blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
1bf90175e9c394376b1d84a207e058edcc882f0a
TianrunCheng/LeetcodeSubmissions
/clone-graph/Runtime Error/6-28-2021, 11:05:40 PM/Solution.py
1,320
3.59375
4
// https://leetcode.com/problems/clone-graph """ # Definition for a Node. class Node: def __init__(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else [] """ class Solution: def cloneGraph(self, node: 'Node') -> 'Node': seen = {} ...
3daecba99fffd6b3a191882a7c2bbea6d57b5b63
TianrunCheng/LeetcodeSubmissions
/daily-temperatures/Accepted/6-28-2021, 5:39:28 PM/Solution.py
972
3.515625
4
// https://leetcode.com/problems/daily-temperatures class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: # process from the right end # information we need to determine arr[i] have seen # record it in a stack # a "76" earlier than "73" will make the lat...
d5481dbcb73bb1954c25f672544af3da4824cbe8
TianrunCheng/LeetcodeSubmissions
/min-stack/Accepted/6-28-2021, 4:36:15 PM/Solution.py
701
3.765625
4
// https://leetcode.com/problems/min-stack class MinStack: def __init__(self): """ initialize your data structure here. """ self.__data = [] def push(self, val: int) -> None: self.__data.append(val) def pop(self) -> None: self.__data.pop() de...
6de44c76d3458f6abe6be39912ba72130670f0fa
TianrunCheng/LeetcodeSubmissions
/longest-palindromic-substring/Compile Error/10-13-2019, 11:38:31 PM/Solution.py
408
3.5
4
// https://leetcode.com/problems/longest-palindromic-substring class Solution: def longestPalindrome(self, s: str) -> str: if (s=="") or (len(set(list(s)))==1): return s m = s[0] for i in range(len(s)): if len(s)-i<len(m): break for j in range(len(s), i,-1): if s[i:j]==s[i:j][::-1]: ...
b22c31d30c743ad469ff69e3dfee5d9d3a6d3795
TianrunCheng/LeetcodeSubmissions
/merge-intervals/Wrong Answer/1-29-2021, 11:22:18 PM/Solution.py
518
3.75
4
// https://leetcode.com/problems/merge-intervals class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: # intervals.sort(key = lambda intervals: intervals[0]) result = [intervals[0]] for interval in intervals: if interval[1] <= result[-1][1]: ...
861b86669573b739121d414562e0418a2d48a594
TianrunCheng/LeetcodeSubmissions
/distribute-candies/Accepted/3-2-2021, 2:27:12 AM/Solution.py
344
3.71875
4
// https://leetcode.com/problems/distribute-candies class Solution: def distributeCandies(self, candyType: List[int]) -> int: types = set() n = len(candyType) for c in candyType: types.add(c) t = len(types) if t < n//2: return t else: ...
9598e636d851bb42e2e1975a9d4ffa6042f496e5
TianrunCheng/LeetcodeSubmissions
/binary-tree-postorder-traversal/Accepted/5-28-2021, 5:23:27 PM/Solution.py
1,948
3.875
4
// https://leetcode.com/problems/binary-tree-postorder-traversal # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def postorderTraversal(self, root: TreeNo...
83bd9639a021800068cd25c25605f399403b5f81
TianrunCheng/LeetcodeSubmissions
/third-maximum-number/Accepted/6-24-2021, 12:29:31 AM/Solution.py
1,723
3.78125
4
// https://leetcode.com/problems/third-maximum-number class Solution: def thirdMax(self, nums: List[int]) -> int: # # this code repeats itself, could be written into a function # maximum = nums[0] # for k in nums: # if k > maximum: # maximum = k # ...
1cec15fbebf712325dcb82ad116a97329f9c8398
vspaz/pythonkatas
/brain_teasers/math/arithmetics/permutations.py
582
3.75
4
num = int(input("please input num: \n")) m = int(input("please input m: \n")) nums = [None for _ in range(num)] used = [False for _ in range(num)] def union(idx): if idx == num: print(nums) return for i in range(m): nums[idx] = i union(idx + 1) union(0) print("============...
84c510fa6c72001e4ed3172d6a8efdfc76ebf8cb
vspaz/pythonkatas
/datastructures/stack/postfix_calculator.py
607
3.578125
4
from datastructures.stack.stack import StackList OPERATIONS = { "*": lambda x, y: x * y, "-": lambda x, y: x - y, "/": lambda x, y: x / y, "+": lambda x, y: x + y, } def postfix_calculator(expression): tokens = expression.split() stack = StackList() for token in tokens: if token...
9bc4ad9ce725ea58996517d2c760c28e71f9c017
vspaz/pythonkatas
/datastructures/queue/queue.py
1,159
3.578125
4
from datastructures.lists.singly_linked_list import LinkedList from datastructures.lists.node import SingleLinkedNode class QueueList: def __init__(self): self._items = LinkedList() def is_empty(self): return 0 == self._items.count def enqueue(self, item): self._items.add_last(Si...
f00d55c54196eeceec781366669dc593dd18e321
Danielmiercalmchaves/Daniel-Miercalm-Chaves-EDB2-2018-2
/arvorecontinua/arvorebi.py
3,740
3.71875
4
arvore = [] altura = 0 recente = 0 choose = 0 def swap(x, y): temp = arvore[x] arvore[x] = arvore[y] arvore[y] = temp def subir(ref): if ref>0: pai = int((ref-1)/2) if int(arvore[ref])<int(arvore[pai]): swap(pai, ref) return subir(pai) def descer(ref): alt = haltura(ref) if ref==0: alt = 0 if ...
f715d1aa429301ce1c428d7e76a02ca6d2a13f0b
neelkela007/python_iant
/ab.py
310
3.8125
4
from abc import ABC, abstractclassmethod class a(ABC): @abstractclassmethod # decorator def n(self): pass @abstractclassmethod def shakur(self): pass class b(a): def n(self): print("i am from n") def shakur(self): pass obj = b() obj.n() obj.shakur()
b3a9b9517fc34cfe121ff18536ce9f7701eef0b7
aksh0001/algorithms-journal
/questions/trees_graphs/SortedArrayToBST.py
2,049
4.125
4
""" Given an array where elements are sorted in ascending order, convert it to a height balanced BST. A height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10...
4013a2f8ea31ae42c8775bf276565b5220e62e65
aksh0001/algorithms-journal
/questions/trees_graphs/MergeTrees.py
1,888
4.21875
4
""" Given two binary trees and imagine that when you put one of them to cover the other; some nodes of the two trees are overlapped while the others do not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise,...
c33b3a4779a87d6fd71f9c33e1b024c222c778a7
aksh0001/algorithms-journal
/questions/arrays_strings/StringRotation.py
1,113
4
4
""" Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1? (eg given s1 = ABCD and s2 = CDAB, return true, given s1 = ABCD, and s2 = ACBD , return false) @author a.k """ def solution(s1: str, s2: str) -> bool: """ Returns whether s2 is a rotation of s1 (using only one call ...
eb81552d033f47437209322a7e6e5aa2b45c317b
aksh0001/algorithms-journal
/questions/trees_graphs/FlattenTree.py
1,847
4.25
4
""" Given a binary tree, flatten it to a linked list in-place. For example, given the following tree: 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 @author a.k """ from data_structures.trees.BinaryTree import...
f6065041f30ddef4c37f56805cd1f16216e50ad0
aksh0001/algorithms-journal
/questions/arrays_strings/TwoSum.py
2,411
4.09375
4
""" This module implements the popular 2-sum problem. Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. @author a.k """ def two_sum(nums, target, skip=0)...
4819fab77767bf35353d5f992ba7e0edd5e0c4ea
aksh0001/algorithms-journal
/questions/arrays_strings/FlipImage.py
1,808
4.5
4
""" Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. To invert an image means that each 0 is replaced by 1, a...
f1a18c1ad0b745bb32079892b8b22545beeaab98
aksh0001/algorithms-journal
/questions/python/Multithreading.py
1,256
4.28125
4
""" Demonstrate multithreading. https://www.youtube.com/watch?v=PJ4t2U15ACo @author a.k """ from threading import Thread import time from typing import List def calc_square(nums: List[int]): for n in nums: time.sleep(0.5) print('square:', n * n) return def calc_cube(nums: List[int]): f...
066fcef6ebc83254d29a31b999cdc6842dc243c9
aksh0001/algorithms-journal
/questions/trees_graphs/MaxDifferenceNodeAncestor.py
1,733
3.90625
4
""" Given the root of a binary tree, find the maximum value V for which there exists different nodes A and B where V = |A.val - B.val| and A is an ancestor of B. (A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.) Input: [8,3,10,1,6,null,14,null,null,4,7,13] ...
5acdf8699801cbcf82c5dc882cec5589c9a16e88
aksh0001/algorithms-journal
/questions/backlog/SquareRoot.py
981
4.09375
4
""" Given an integer x, find square root of it. If x is not a perfect square, then return floor(√x). You cannot use in-built function. Approaches: 1) Naive O(√x) 2) BinarySearch (log(x)) """ def naive(x: int) -> int: """ Naive solution: try numbers starting from 1, until the square of the number becomes >= x...
38872e2ad7ed9bc306ec372a8c20e59bdb096d1e
aksh0001/algorithms-journal
/questions/linkedlists/CycleDetection.py
5,755
3.90625
4
""" Implements the linked list cycle detection problem. Given a linked list, which may or may not be circular, implement an algorithm that returns the node at the start of the cycle. Approaches: Naive + Floyd's Cycle detection algorithm @author a.k """ from data_structures.LinkedList import SinglyLinkedList, ListNode...
712e6df2351659dc9cee028a56b79fb738c2f7e5
aksh0001/algorithms-journal
/questions/trees_graphs/TreeSort.py
1,602
3.921875
4
""" Sort a list of numbers using trees in O(Nlog(N)) N.B. numbers must be unique since BSTs and AVL Trees by definition do not allow duplicates Approach: - Construct AVL tree using list - Inorder traverse tree @author a.k """ from typing import List from data_structures.trees.AVLTree import AVLTree, TreeNode...
cf71b542a12f28d9e5094bbc0af56392f71641e5
aksh0001/algorithms-journal
/questions/arrays_strings/PalindromePermutation.py
1,892
4.1875
4
""" Given a string, write a function to check if it is a permutation of a palindrome. E.g. "tactcoa" => True (permutation: "tacocat", "atcocta, etc.) Approach: Simple arithmetic based on character occurrences @author a.k """ def check(s: str) -> bool: """ Returns true if s is a permutation of a palindrome....
27bb90b8f38549a20006288462fc8169b6b9041e
aksh0001/algorithms-journal
/questions/recursion_dp/LetterCasePermutation.py
1,349
4.25
4
""" Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create. Examples: Input: S = "a1b2" Output: ["a1b2", "a1B2", "A1b2", "A1B2"] Input: S = "3z4" Output: ["3z4", "3Z4"] Input: S = "12345" Output: ["1234...
ae0832e60289771cffeb2fb0737b51a43a59649b
wilbert-abreu/GH-Scrape
/gh_data_analysis.py
874
3.8125
4
import pandas as pd import matplotlib.pyplot as plt gh_frame = pd.read_csv('gh_data.csv') # .value_counts = # Anuj Adhiya 1118 # Nichole Elizabeth DeMeré 546 # Morgan Brown 411 # group by and get count user_counts = gh_frame['Who_Posted'].value_counts() x_axis = range(len(us...
62f5831475a06f8834dc3ff9d95997e047d429ea
clipklop/pythonProgrammingForTheAbsoluteBeginner
/08/television.py
2,506
4.46875
4
### Televsion control emulation ## # # 2. Write a program that simulates a television by creating it as an object. # The user should be able to enter a channel number and raise or lower the volume. # Make sure that the channel number and volume level stay within valid ranges. # ## ### class Television(object): ...
e1c6a4292579550e3facc50e8dfa36022e9ca853
jhashuva/ptython_lab
/sqrt.py
70
3.625
4
import math a = int(input("Enter a number")) print(math.sqrt(a))
496035f2d8dd8d9995c3d5a545eb42b0a2a24b25
DredgeMonkey/CS_Examples
/Sal's_shipping.py
1,222
3.765625
4
flat_charge = 20 premium_ground_charge = 125.00 def ground_shipping_cost(weight): if weight <= 2: return weight * 1.50 + flat_charge elif weight >= 2 and weight <= 6: return weight * 3.00 + flat_charge elif weight >= 6 and weight <= 10: return weight * 4.00 + flat_charge else: return weight * 4....
2805a7cac808e560bf113383f9eea48c55e4ba17
PendyalaHarshita/Python-short-programs
/Exception_handling.py
297
3.96875
4
n= int(input(Enter the number)) try: if(n<0): raise ValueError("Number should not be negative") elif(n<=20): raise ValueError("Number should be above 20") else: res = 1 while(n>0): res = resn n = n-1 print(res) except Exception as e: print(e)
29f8401943420e80deda4a2dd2967db714022162
FernandoFigueroa14/Tarea-02
/cuenta.py
382
3.65625
4
#encoding: UTF-8 # Autor: Luis Fernando Figueroa Rendon, A01746139 # Descripcion: Pedir el costo de la comida para sacar la propina, el IVA y el total. # A partir de aquí escribe tu programa costo= input("Costo de la comida: ") costo= int(costo) propina= costo*0.12 iva= costo*0.16 total= costo + propina + iva p...
a81d1b0af85e1eaf90cca1ba0d7fa5c07f554932
SdtAslan/python-assignments
/Fibonacci.py
129
3.625
4
fibonacci = [] x = 0 y = 1 while y <= 55: x, y = y, x+y fibonacci.append(x) print(fibonacci)
b47ce03e39387356d4a0da5da0bc3d57b81a5042
huzaifak98/assignment1
/func.py
663
3.984375
4
'''def arithmetic_operations(oprn1,oprn2,oper): if oper=="+": print(oprn1+oprn2) arithmetic_operations(2,3,"+") def func_with_var_arg(**Ali_imran): print(Ali_imran) func_with_var_arg(Name='Huzaifa') func_with_var_arg(Name='Huzaifa',Fname='Jawed') func_with_var_arg(Name='Huzaifa',Fname='Jawed',Age=44) '...
7e5abbe9bb934bd7326ed6e42b4d8c2496c33094
amonsap/dataStructre
/LabSorting.py
1,188
4.125
4
def bubblesort(list): for K in range(len(list) - 1, 0, -1): for idx in range(K): if list[idx] > list[idx + 1]: temp = list[idx] list[idx] = list[idx + 1] list[idx + 1] = temp def insertionsort(list): for i in range(1,len(list)): j = i ...
7bee0a86197a72c435e4153fde9be9348b5776bd
disassembly/pltable
/plsolution.py
6,650
3.75
4
#! /usr/bin/python # -*- coding: utf-8 -*- import argparse import fileinput import locale import re import sys class MatchResult(object): """Soccer match result.""" def __init__(self, line): """Parse a match result string into teams and scores.""" self.teams = () self.scores = () ...
18761f314adc254efb7dbb29fe07bfc86ef4ebc0
akihikoy/ay_test
/python/basic/exception/my_exception.py
1,321
3.59375
4
#!/usr/bin/python #\file my_exception.py #\brief certain python script #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Mar.16, 2016 from except_forward import PrintException class MyException(Exception): def __init__(self, msg): self.msg= msg def __str__(self): return repr(self....
b13eea71e0d24ce510fbd83a81a6820cb8780967
akihikoy/ay_test
/python/basic/structure/inherited_list.py
1,203
3.859375
4
#!/usr/bin/python class TKeys(list): #Ver1: NOTE: this is the best way to wrap a general list #def __init__(self,v): #list.__init__(self,v) #Ver2: NOTE: usage is not intuitive (see examples below) #def __init__(self,*v): #list.__init__(self,v) #Ver3: NOTE: this will fail to create like [[1,2]]; only...
1e30293d51e71b93b442dc9b84cba077d44dc7ad
akihikoy/ay_test
/python/geometry/splines/vel_ctrl.py
4,347
3.625
4
#!/usr/bin/python import numpy as np import numpy.linalg as la def Sign(x): if x==0.0: return 0 elif x>0.0: return +1 elif x<0.0: return -1 #Modify the velocity of a given trajectory (base routine). #t0: Current internal time maintaining a playing point of the trajectory #v: Target speed #traj: Function to ...
ed73ad2a36783df955642830ef248c14ecbdbefb
akihikoy/ay_test
/python/basic/lambda_local.py
3,788
3.515625
4
#!/usr/bin/python #\file lambda_local.py #\brief test lambda with local variable. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Feb.21, 2017 import time,threading locker= threading.RLock() def func(i, obj): while obj['count']>0: with locker: print 'thread',i,obj,id(obj) o...
8d76bca351e1a3530eb61a3e33bbae9febde09e2
akihikoy/ay_test
/python/basic/file/yaml_test3.py
752
3.5
4
#!/usr/bin/python import yaml #Print a dictionary with a nice format def PrintDict(d,indent=0): for k,v in d.items(): if type(v)==dict: print ' '*indent,'[',k,']=...' PrintDict(v,indent+1) else: print ' '*indent,'[',k,']=',v if indent==0: print '' #Insert a new dictionary to the base d...
657bf85d90b04f50b31995676c55717421b46322
akihikoy/ay_test
/python/algorithms/loop_combination.py
555
3.671875
4
#!/usr/bin/python #Apply operation for every combination in collection. def ForEachCombination(collection, operation, pre_seq=[]): if len(collection)==0: return if len(collection)==1: operation(pre_seq+list(collection)) return for item in collection: ForEachCombination(set(collection)-set([item])...
c7f14bbfca890d05fecbc552743e7d395b9733b7
akihikoy/ay_test
/python/ml/statistics/median.py
471
3.859375
4
#!/usr/bin/python import copy def Median(array): if len(array)==0: return None a_sorted= copy.deepcopy(array) a_sorted.sort() return a_sorted[len(a_sorted)/2] array= [2,10,5,1,55,7,48,103,22,6,3,99,45,99] print "median:",Median(array) print " in:",array array= [[2,2],[10,8],[5,3],[1,1],[55,0],[7,55],[48,1...
78c5dc70b64c45b143e398e036db00dbc72c59c4
akihikoy/ay_test
/python/geometry/polygon/polygon_point_in_out2.py
3,572
3.828125
4
#!/usr/bin/python #ref. http://stackoverflow.com/questions/11716268/point-in-polygon-algorithm #Ray-casting algorithm (http://en.wikipedia.org/wiki/Point_in_polygon) #with considering point on an edge of polygon. def PointInPolygon2D2(points, point, include_on_edge=True): if PointOnPolygon2D(points, point): return ...
8ec3b82fe7e68711155812760eab49dbe8523e53
akihikoy/ay_test
/python/basic/reference_var.py
681
3.71875
4
#!/usr/bin/python ##x does not change: #def Test1(x): #x*= 10.0 #def Test2(x): #x= 20.0 #class TTest: #def __init__(self): #self.x= 0.0 #def Test1(self): #self.x*= 10.0 #def Test2(self): #self.x= 20.0 #x changes: def Test1(x): x[0]*= 10.0 def Test2(x): x[0]= 20.0 class TTest: def __init__(...
9a289ce7dfee2f76ac918acff25514a0cd315c5e
akihikoy/ay_test
/python/algorithms/tree_parse.py
1,231
3.625
4
#!/usr/bin/python def Test1(tree): def sub_parse(sub_tree): name= sub_tree[0] if sub_tree[1]=='x': return [name, sub_parse(sub_tree[2][-1])] else: return name print 'last names=', sub_parse(tree) def Parser(tree_struct, op): name= tree_struct[0] kind= tree_struct[1] op(name,kind) i...
8c602fea4a9af86dead3229bc19592da9128fb82
akihikoy/ay_test
/python/time/time_str_py3.py
926
3.75
4
#!/usr/bin/python3 #\file time_str_py3.py #\brief Time to string. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Apr.21, 2022 import time def TimeStr(fmt='short2', now=None): if now is None: now= time.localtime() if fmt=='normal': return f'{now.tm_year:04d}.{now.tm_mon:02d}.{now.tm_m...
9c5c72e6e14586af0e2e51df00359cbc87cc736d
akihikoy/ay_test
/python/geometry/line_line_intersect.py
3,008
3.546875
4
#!/usr/bin/python #\file line_line_intersect.py #\brief Get intersection of two line segments. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Aug.20, 2020 import math import numpy as np #Return an intersection between line seg (p1,p2) and line seg (pA,pB). #Return None if there is no inter...
014a875d0eb4e0ee1dd780c6e039552d660e0e61
akihikoy/ay_test
/python/basic/namedtuple.py
633
3.953125
4
#!/usr/bin/python import collections Point= collections.namedtuple('Point', ['X','Y'], verbose=True) a= Point(2.5,-0.5) #a.X= 2.9 #a.Y= -0.5 b= Point(0,0) #b.X= 1.1 #b.Y= 0.0 print 'a=',a print 'b=',b print 'a.X=',a.X print 'a[1]=',a[1] print 'list(a)=',list(a) print 'a+b=',a+b #NOTE: it's impossible to assign to...
e7f1ab18cb508ccc42768caaa757b3c0baefe06f
akihikoy/ay_test
/python/optimization/find_changept.py
925
3.671875
4
#!/usr/bin/python #\file find_changept.py #\brief Find a change point of a function. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Mar.27, 2021 import scipy.optimize ''' Find a change point of a function. Assume a function func(x)={True,False} which has only one change point x0 where func...
33dfad57747ce95b31ffab8835944a9ef816fe8c
akihikoy/ay_test
/python/geometry/3d/box_ray_intersection.py
3,258
3.609375
4
#!/usr/bin/python #\file box_ray_intersection.py #\brief Get an intersection between a ray and a cube. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Sep.09, 2019 ''' Based on the Ray-box intersection algorithm described in: Amy Williams, Steve Barrus, R. Keith Morley, and Peter Shirle...
5ddcb87d6a31ff613d2400816405dc27d12bb421
Kimsangwon0509/python_study
/chapter03_04.py
947
3.671875
4
#값 비교 #선언 a =[] b = list() c = [70, 78, 75, 76] #len 가능 d = [1000, 10000, "Ace", 'bear', ' 서로다른 자료형을 한 리스트 안에 담을수 있다.'] e = [1000, 10203023, ['asd', 'asfasf', 'qwqwewww']] f = [21.42, 'foobar', 3, 4, False, 3.1234] print(c == c[:3] + c[3:]) #Identity(id) temp = c print(temp, c) print(id(temp)) print(id(c)) c[0] = 4 ...
521b681813c32b38c0ff6f980657cfb0544f37e1
Kimsangwon0509/python_study
/chapter08_01.py
1,088
3.984375
4
#While 구문 #for문과는 조금 다름 #if, for, while을 흐름 제어문으로 씀 . # while <expression> 표현식이 들어감 # <statement(s)> # 조건에 만족할떄 까지 반복을 한다. # 예제1 n = 5 while n > 0: print(n) n = n - 1 # 예제 2 a = ['abc', 'bar', 'bax'] while a: print(a.pop()) a = ['abc', 'bar', 'bax'] while a: print(a.pop(-1)) # 예제 3 # break ...
840e09c548b201e4c16c5ef3a3740c4d45d9b342
Kimsangwon0509/python_study
/hangman_final.py
2,046
3.5
4
# 행맨 미니 게임 제작 import time import csv import random # 사운드 처리 import winsound # 처음 인사 하기 name = input("이름을 입력하세요 : ") print('Hi, ' + name, "게임을 시작할 시간입니다." ) print() time.sleep(1) print('로딩중......') print() time.sleep(0.5) # CSV의 단어의 리스트를 선언 (CSV 파일은 추후에 추가) words = [] # 문제 CSV 파일 로드 with open('./src/file.csv','...
8b44940ca2b29b5a5cfbc0eb5babcaa3c90ed2f6
kunallanjewar/python-class
/lab4_3.py
1,065
3.90625
4
print("Method 1") n1 = input("Enter the first number: ") ops = input("Enter the operator: ") n2 = input("Enter the second number: ") if (ops == '+') : print(float(n1) + float(n2)) if (ops == '-') : print(float(n1) - float(n2)) if (ops == '*') : print(float(n1) * float(n2)) if (ops == '/') : print(fl...
ab2e6832370dce97a0bf76c2dcd67f01bb0a074a
kunallanjewar/python-class
/ex11.py
480
3.75
4
# Student: Kunal Lanjewar # Programming Ex: 11 class Division(object): def __init__(self,dept, fullTime, partTime): self.dept=dept self.fullTime = fullTime self.partTime = partTime def getList(self): print ("The {0} department has {1} full-time and {2} part-ti...
f22c7bf120f43bb16605529dc9e63a853be35642
kunallanjewar/python-class
/exam_1_1.py
124
3.609375
4
#student: Kunal Lanjewar #FileName: exam1_1.py s = input("Enter your Name: "); for i in range(len(s)) : print((i+1) * s[i])
0d84d6ef629e8b96350fe0602971ed5a1038cd3b
kunallanjewar/python-class
/lab08_4.py
956
3.578125
4
def acct2Number(): s = input("Enter the dollar amount: ") result = "" for i in range(len(s)): if (s[i] == '$') : pass elif (s[i] == ',') : pass else : result = result + s[i] print(result) def number2Acct(): s = input("Enter a large number: ") ...
b3321359f55179fed91632d7d7a456fd67b74817
kunallanjewar/python-class
/ex05.py
248
4.03125
4
#Student: Kunal Lanjewar #Programming: Exercise 05 #---------------------For Loop-------------------------------# print("\nFOR LOOP\n") s = input("Enter your First name: "); for i in range(len(s)-1, -1, -1): print((i+1) * s[i])
76cc29ecf6675f106d4e617fbc4dd3b2142fd970
kunallanjewar/python-class
/lab7_1.py
1,096
3.671875
4
def showCPU(): import platform print(platform.processor()) def showOS(): import os; print(os.name) def getSysInfo(): # function declaration import platform # function body print("System Info: \n", "system: ", platform.system(), "\n", "machine: ", platform.mac...
8ef173e1f54e8a368235760fbb25e8ebe56f3462
kunallanjewar/python-class
/ex06.py
355
3.65625
4
#Student: Kunal Lanjewar #Programming Exercise: 06 weekday = ["Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday","Sunday"]; print("Day 1: ", weekday[0]); print("Day 2: ", weekday[1]); print("Day 3: ", weekday[2]); print("Day 4: ", weekday[3]); print("Day 5: ", weekday[4]); print("Day 6: ", ...
1c672085111595f6d8fb1bfbb7d2e4e2ca355ea2
kunallanjewar/python-class
/lab3_2.py
773
3.9375
4
x = 5 #example 1 x += 4 print(x) x = 7 x -= 4 print(x) x = 3 x *= 2 print(x) x = 5 x /= 4 print(x) x = 15 x %= 7 print(x) x = 2 x **= 3 print(x) x = 2 # example 2 x *= 5 x *= 5 x *= 5 print(x) x = 17.9 x /= 3.5 x /= 2.1 print(x) ...
81ea4a80500b9d26f41f4b3d72c609b6c3f02020
AaronDasani/Python
/insertion_sort.py
400
4.1875
4
def insertion_sort(a_list): for index in range(1,len(a_list)): currentvalue = a_list[index] position = index while position>0 and a_list[position-1]>currentvalue: a_list[position]=a_list[position-1] position = position-1 a_list[position]=currentvalue r...
dc099a3555ac9a7e89d357606e5946a6cb45e702
yahiaakkazi/python
/jour 3 - job 1.py
316
3.546875
4
class Personne: def __init__(self, name, prenom): self.name = name self.prenom = prenom def sePrésenter(self): print(self.name,self.prenom) p1=Personne("John","Smith") p2=Personne("Alex","alex") p3=Personne("Jogn","John") for i in [p1,p2,p3]: i.sePrésenter()
f433af33c3a98be30b29269da592c81aa13f8cbf
hayoungleee/algorithmstudy
/baekjoon_9498.py
517
3.8125
4
#시험 점수를 입력받아 90 ~ 100점은 A, 80 ~ 89점은 B, 70 ~ 79점은 C, 60 ~ 69점은 D, # 나머지 점수는 F를 출력하는 프로그램을 작성하시오 # 입: 첫째 줄에 시험 점수가 주어진다. 시험 점수는 0보다 크거나 같고, 100보다 작거나 같은 정수이다 point = int(input("시험 점수를 입력하세요 :: ")) if point >= 90 : print("A") elif point >=80: print("B") elif point >=70: print("C") elif point >=60: prin...
591bcedf852e9e50f4549236db594d7a536f1b05
hayoungleee/algorithmstudy
/programmerCT/Same_num.py
697
3.515625
4
#배열 arr가 주어집니다. 배열 arr의 각 원소는 숫자 0부터 9까지로 이루어져 있습니다. #이때, 배열 arr에서 연속적으로 나타나는 숫자는 하나만 남기고 전부 제거하려고 합니다. # 단, 제거된 후 남은 수들을 반환할 때는 배열 arr의 원소들의 순서를 유지해야 합니다. def samenum(arr): answer = [] answer.append(arr[0]) for i in range(1,len(arr)): if arr[i] != arr[i-1]: answer.append(arr[i]) r...
e745781e20aa4f37216127d5fcef001e708e99c9
hayoungleee/algorithmstudy
/programmerCT/numOfsum.py
392
3.546875
4
#자연수 N이 주어지면, N의 각 자릿수의 합을 구해서 return 하는 solution 함수를 만들어 주세요. #예를들어 N = 123이면 1 + 2 + 3 = 6을 return 하면 됩니다. def solution(n): answer = 0 str_n = str(n) for i in range(len(str_n)): answer += int(str_n[i]) return answer print(solution(987)) #return sum([int(i) for i in str(number)])
573ccd82c0823f0ea14b68c6bacb7f35d4a997c6
hayoungleee/algorithmstudy
/programmerCT/reverse.py
429
3.53125
4
#자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요. 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다. def solution(n): answer = [] n = list(str(n)) len_n = len(n) for i in range(len_n): answer.append(int(n[i])) answer.reverse() return answer print(solution(12345)) #def digit_reverse(n): # return list(map(...
35d3b631f98bd079d0784165e40e45d930389e4e
stevejackson/Game2Text
/dictionary.py
828
3.515625
4
import zipfile import json dictionary_map = {} def load_dictionary(dictionary): archive = zipfile.ZipFile(dictionary, 'r') result = list() for file in archive.namelist(): if file.startswith('term_bank'): with archive.open(file) as f: data = f.read() ...
12f6ccbff18479dac20aacbf24cd53b8575db791
krsign/PyProject
/Guess The Number/guess__the__number__win__or__lose.py
406
4.125
4
# -*- coding: utf-8 -*- """ 1. Get the random number 2. guess the number 3. if random number equal to guessed number then 'You win!' and if not then 'You Lose!' @krsign """ import random random_number = random.randint(0, 20) guessed_number = int(input('Guess The Number : ')) if random_...
9c9b9c7d39d821ef75171999e938885528a83b0e
alv2017/Ignitis
/analytics/analytics_functions.py
1,210
3.5625
4
from etl.db_operations import select_data def get_regions(conn): """ Function connects to SQLite DB and returns regions iterator. Input Parameters: conn - connection to SQLite DB Output: returns regions iterator """ query = """ SELECT DISTINCT region FROM hourly_...
5b6733a78d9b74671d0ddca8ed3df16619ad6e40
johnruiz24/Sudoku-GA
/run.py
1,009
3.578125
4
import pandas as pd from plot import Draw from setup import Setup from sudoku import Sudoku from create import Generator draw = Draw() setup = Setup() sudoku = Sudoku() generator = Generator() #Scrapping the data #========================== #1.Download the data from internet #2.Save the data into the 'data' folder ge...
38aecc297ea14c5179d0368ec75e3b97a9745d47
jupmarsat/labs_scripts
/AnyRotation.py
2,778
4.71875
5
#!/usr/#!/usr/bin/python3 #Have a string with each letter of the alphabet alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #Get user input if they want to decrpyt or encrypt a word answer = input("Would you like to encrypt or decrypt a word? ('e' for \n" "encrypt, 'd' for decrypt): ").lower() #create a whil...
23e49c61b12aa3ca4464fd8d0df5afa3e6a942f8
amdp-chauhan/python-opencv-exp
/Starting/6. draw-shapes-on-image.py
1,072
3.75
4
import cv2 as cv import numpy as np blank_img = np.zeros((600, 600, 3)) cv.imshow('Blank Image', blank_img) # 1. Colour a rectangular part of the image blank_img[100:150, 250:300] = 0, 0, 150 blank_img[150:200, 300:350] = 0, 123, 150 blank_img[200:250, 350:400] = 130, 23, 140 cv.imshow('Colour patches', blank_img) #...
26d7c702c3cc10840d549e131a18d14f76e6caea
Lanlanshi/hello_coding
/month_1/input.py
519
3.921875
4
''' username=input('请输入用户名') password=input('请属于密码') print('您输入的用户名是:',username) print('您输入的密码是',password) ''' price = input('请输入单价') number=input('请输入密码') print('price 的类型是:',type(price)) print('number的数据类型是: ', type(number)) print('输入商品的总价是',int(price)*int(number)) print('='*20) # ==================== print(' '*2+'...
7a0b47f30e52024534cee56d58d1881f0ee5ca03
Bruno81930/EDAN20-Labs
/Assignment2/Assignment 2 - Normalization.py
824
4.03125
4
# coding: utf-8 # # Assignment 2 # ## Normalizing a Corpus # 1) Write a program to insert < s > and < /s > tags to delimit sentences. You can start from the tokenization and modify it. Use a simple heuristics such as: a sentence starts with a capital letter and ends with a period. Estimate roughly the accuracy of y...
46f7ca5e9a79b26ffbcfcfe5d66d0747c900544b
TurarAbishev/-Web-Development-2020
/Week7/loop/whie/22.py
62
3.71875
4
a = int(input()) i = 2 while i <= a: print(i) i =i * 2
10b85d517b6ac752204c99a7abcd9bcc1ad577d5
AILARON/active-learning
/query_strategies/bayesian_utils/acs/baselines/kcenter_greedy.py
3,232
3.53125
4
# Taken from active-learning (https://github.com/google/active-learning/blob/master/sampling_methods/kcenter_greedy.py) """Returns points that minimizes the maximum distance of any point to a center. Implements the k-Center-Greedy method in Ozan Sener and Silvio Savarese. A Geometric Approach to Active Learning for C...
ab6a06789e522c931a112187525d40f544afcd3c
handykasdi/HandyKasdi_ITP2017_FinalProject
/Blackjack3.py
2,118
3.71875
4
# with the help of Titan and David also Georgious from Classes import Card, Hand import random print("Welcome to Black Jack Gameroom") hand=Hand() dhand=Hand() suits="cdsh" print("Want to Play ??") def maingame(): x=input("press y/n") if x == "Y" or x == "Yes" or x == "yes" or x == "y": card = [] ...
de8d496e9be695b61d596bb31c43a571f1694d82
Brainiac-BV/Udacity_Fullstack
/Python_Stuff/concept_demos.py
1,928
4.375
4
#tuple demo #can contain multple data types t = ('string', 1, True, [1,2,3]) print(t) print(len(t)) print(type(t)) #str demo #format example n = "The age of {0} is {1}".format('keith', '32') print(n) #range demo #list creation with range samp_list = list(range(10,21)) print(samp_list) #itera...
ee8edfdf8a66353145166dd6e94c894693f85365
alexanderganderson/site-freq-spectrum
/src/random_queue.py
525
3.515625
4
# random queue import random from math import floor class RandomQueue: def __init__(self): self.a = [] def size(self): return len(self.a) def is_empty(self): return self.size() == 0 def add(self, key): self.a.append(key) def rand_pop(self): i = random.randran...
c12c4778dab245d8bbde5bc18101b250a281edeb
clemsciences/ohcr
/point_group.py
3,196
3.640625
4
""" """ import math __author__ = "Clément Besnier" class Point: def __init__(self, x, y): self.x = x self.y = y def distance(self, autre_point): return math.sqrt((self.x - autre_point.x)**2 + (self.y - autre_point.y)**2) class PointGroup: """ Point cluster """ def...
164d9b72a945b1a1a16c618d5da61045644c1a4c
Nikita9409/python_lesson
/hw_8.py
8,919
3.609375
4
# Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата «день-месяц-год». # В рамках класса реализовать два метода. Первый, с декоратором @classmethod, должен извлекать число, # месяц, год и преобразовывать их тип к типу «Число». Второй, с декоратором @staticmethod, должен п...
a57d083527003bfcb99970ac61358089d537820a
ankitmaini/learning_classes
/OrderedDict usage.py
558
3.53125
4
# The dictionaries don't keep track of the oreder in which the key-value pairs are added. So, in order to track the order in which the key value pairs are added, we use OrderedDict class from collections module from collections import OrderedDict favorite_languages = OrderedDict() favorite_languages['jen'] = 'python' ...
543147908c88d930abe4b41f43497a1a55ba0545
ankitmaini/learning_classes
/dice.py
316
3.53125
4
class Die(): '''Modelling a die.''' def __init__(self, sides = 6): self.sides = sides def roll_die(self): from random import randint print(randint(1, self.sides)) six_side_die = Die(6) for i in range(10): six_side_die.roll_die() import time time.sleep(2)
ace27eefda9306adae615cc5fd9e3ed24ca9dbe3
Cher99/LearnLog
/Python/fullConnection_DL/bp_1.py
9,502
3.625
4
#!/usr/bin/env/python # -*- coding: UTF-8 -*- ''' #if net = Network([8,3,8]),there be a network model: 3 layers : net.layers[0] has 8 nodes / net.layers[1] has 3 nodes / net.layers[2] has 8 nodes 2 connections: net.connections[0].downstream_nodes = [node_0_0,node_0_1,node_0_2,...] net.connections[1].... # trai...
6a03e021b0881e0382af5b17b2f7ba07773e6b78
abdulawwal/MITx-IntroductionToCSandPython
/ProblemSet2-1.py
659
3.96875
4
# Problem Set 2 - Problem 1 balance = 4842 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 minMonthlyPayment = 0 totalPaid = 0 i = 1 while (i <= 12): minMonthlyPayment = monthlyPaymentRate * balance unpaidB = balance - minMonthlyPayment interest = annualInterestRate/12.0 * unpaidB balance = unpaidB...
0429c1ead7435eac49b8704975002c9f5a89ebc7
UlisesBrunoLozano/programacion_python
/laboratorio_2/Ejercicio_3.py
323
3.640625
4
#!/usrbin/env python # _*_ coding: utf-8 _*_ #Tarea 2 Ejercicio 3 #Ulises Bruno Lozano #25/11/16 import matplotlib.pyplot as plt cx=input("Introduce la magnitud del lado de un triangulo rectangulo: ") def juegodelcaos(x): x=cx triangulo=[[0,0],[0,x],[x/2,x],[0,0]] plt.plot(triangulo) plt.show() salida=j...
258700f602af3af1868db6e2693505efed9924c5
UlisesBrunoLozano/programacion_python
/Laboratorio_1/E2.py
321
3.859375
4
#!/usrbin/env python # _*_ coding: utf-8 _*_entrada=input("Introduzca un entero positivo ") #Ulises Bruno Lozano def e2(x): Interes_por_ano=0.04 Saldo_inicial=input("Cantidad a depositar: ") Nuevo_saldo=Saldo_inicial*0.04 Saldo_final=Nuevo_saldo+Saldo_inicial print "Usted tendra en un año",+Saldo_fi...
037339660c02618dac7b2c00fb8a50215df6c682
UlisesBrunoLozano/programacion_python
/Laboratorio_1/E1.py
262
3.890625
4
#!/usrbin/env python # _*_ coding: utf-8 _*_ #Ulises Bruno Lozano entrada=input("Introduzca un entero positivo: ") def funcion1(x): suma=0 listax=[x for x in range(0,x+1)] for x in listax: suma=x+suma return suma salida=funcion1(entrada) print salida
f11961f697bef6be129af8eeeaf5c9bf7220505a
aymanfatima/Python-s-Assignment-
/assignment 03/task6.py
206
4
4
test_string = input("Enter sentence with number: ") print("The original string : " + test_string) res = [int(i) for i in test_string.split() if i.isdigit()] print("The numbers list is : " + str(res))
2370c9d9cbbe2d3a677363bd920cffb5e229dbd4
Linsetta/SchoolProjects
/Class41A_Python/HW/TakeHome_C.py
2,523
4.21875
4
""" Nina Demenchukova CIS 41A Fall 2018" Unit C take-home assignment """ print("Example output:\n") #Create an empty list called list1. Populate list1 with the values 1,3,5 list1 =[] list1 =[1, 3, 5] # Create list2 and populate it with the values 1,2,3,4 list2 = [1, 2, 3, 4] #Create list3 by combining list1 and l...
e4f153a0965bd8e68fe64387ef8a6453a096806f
chen-gan-ga/pythonProject
/leet-code/递归/递归实例模板.py
457
4.03125
4
#Recursion 递归 # 计算 n! def Fac(n): #终止条件/recursion terminator if n<=1: return n return n*Fac(n-1) print(Fac(5)) # 模板 def recursion(leve,param1,param2): #递归终结条件 if leve>Max_level: process_result return #process logic in current level/处层当前层逻辑 process(leve,data....) ...
11615d3e0eb16f70756c02d2dcfee7bf9e8ec151
chen-gan-ga/pythonProject
/leet-code/array/26删除数组中的重复项.py
287
3.640625
4
class Solution: def removeDuplicates(self, nums) -> int: i=0 while i+1 <len(nums): if nums[i]==nums[i+1]: nums.pop(i+1) else: i=i+1 return nums nums=[1,1,1,1,1,1,2] answer=Solution() print(answer.removeDuplicates(nums))
f7946c31ea0296dfa69dac3f7e63c327ac7d4783
chen-gan-ga/pythonProject
/leet-code/Linked_list/21合并两个有序链表.py
856
3.875
4
# 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 # 输入:l1 = [1,2,4], l2 = [1,3,4] # 输出:[1,1,2,3,4,4] class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: hakehead = ListNode...
3109074a49ff32eb8b6b8c41d5b31eb7dbebe9d3
rohit01/multi_logger
/emaillogger.py
5,673
3.609375
4
""" Python module to store logs in string format while the program using it performs its execution. This log can be appended in email body or attached as a file for dubug purpose. """ import logging from base_logger import BaseLoggerClass LOGLEVELS = { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARN':...
c76aea263b4003f2b56e5e84fe57e321d25b9ff9
nilamkurhade/Week1
/AlgorithmPrograms/binaryIntegerSort.py
346
3.890625
4
from util.util_class import binaryIntegerSearch try: arr = [] arr = [10, 20, 30, 40, 20] x = 30 result = binaryIntegerSearch(arr, 0, len(arr) - 1, x) if result != -1: print("Element is present at index % d" % result) else: print("Element is not present in array") except Runt...
a20b0659317fc17ce6ca1da0aa8a8bbfc16be3c2
nilamkurhade/Week1
/FunctionalPrograms/InsertionSort.py
355
3.703125
4
from util.util_class import insertionSort try: """=======Integer array===""" arr = [] arr = [64, 34, 25, 12, 22, 11, 90] print(insertionSort(arr)) """=======String array===""" my_list = [] my_list = ['a', 'd', 'c', 'f', 'e'] print(insertionSort(my_list)) except RuntimeError: prin...
6a01c0d7e095deaee00056c3c829e166ffb8ca1a
nilamkurhade/Week1
/FunctionalPrograms/windChill.py
199
3.734375
4
import math t = int(input("Enter value")) v = int(input("Enter value")) if t < 50 or v < 120 or v > 3: w = 34.74 + 0.6215 * t + (0.4275 * t - 35.75) * math.pow(v, 0.16) print('WindChill is:', w)
6630c0bfc4f1d029acd467d33c3e52e6d31b0a88
zafarali/experiments
/python/calgpa.py
1,870
3.796875
4
from sys import argv script_name, user = argv print "Calculating GPA for ",user f = open(user+".txt", "r") summation = 0 total_credits = 0 def parsegrade(letter): if letter=="A": return 4.0 elif letter=="A-": return 3.7 elif letter=="B+": return 3.3 elif letter=="B": retu...