blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
e9d2989735d55c509fc024da40cf942046683a44
SHINE1607/coding
/problems/introductory/palindrome_reorder.py
849
3.796875
4
from collections import Counter def palindrome_reorder(string): if len(string) == 1: print(string) return counter = Counter(string) <<<<<<< HEAD freq_arr = list(counter.values()).sort(reverse = True) if freq_arr[-1]%2 == 1 and freq_arr[-2]%2 == 1: print("NO SOLUTION") return ======= freq_arr = list(counter.values()) odd_count = 0 for i in freq_arr: if i%2 == 1: odd_count += 1 if odd_count >= 2: print("NO SOLUTION") return >>>>>>> f55fdab3c6ded2513a158623af13d93c09e5e1a3 res = list(counter.keys())[-1] * freq_arr[-1] for i in list(counter.keys())[:-1]: res += i*int(counter[i]/2) res = i*int(counter[i]/2) + res print(res) return string = input() palindrome_reorder(string)
104a2ee46119baba627d748a98ecc50f65d8757b
SHINE1607/coding
/dynamic_programming/recursive_staircase.py
609
3.671875
4
# given the number of steps we can take at a time howe mkany tyital number of ways to climb given number of steps from collections import defaultdict def find_climb(n, steps): dp = defaultdict(lambda:[0] * (n + 1)) steps = [0] + steps dp[0][0] = 1 for i in range(1, len(steps)): if steps[i] > n: continue dp[i][:steps[i]] = dp[i - 1][:steps[i]] for j in range(steps[i], n + 1): dp[i][j] = dp[i - 1][j] + dp[i][j - steps[i]] print(dp[i][-1]) n = int(input()) steps = [int(x) for x in input().split()] find_climb(n, steps)
fb272460636079c87d718e04c6c404fcc9cbd4b4
SHINE1607/coding
/problems/introductory/apple_division.py
721
3.546875
4
diff = 0 final_ans = 0 def division_rec(arr, i, s, target): global diff global final_ans if i == -1: return if abs(s - target) < abs(diff): final_ans = s diff = s - target # print(s, diff, i, "check") return division_rec(arr, i - 1, s, target) or division_rec(arr, i - 1, s - arr[i], target) def apple_division(n, arr): s = sum(arr) target = s/2 global diff global final_ans diff = abs(s - min(arr)) division_rec(arr, n - 1, s, target) left_sum = final_ans right_sum = s - final_ans print(abs(right_sum- left_sum)) n = int(input()) weights = [int(x) for x in input().split()] apple_division(n, weights)
2edd67084f46c9f82718aaff7400834c77b3b9de
SHINE1607/coding
/DSA/Tree/test.py
847
3.953125
4
import random def merge(left, right): left_pointer = 0 right_pointer = 0 res = [] while left_pointer < len(left) and right_pointer < len(right): if left[left_pointer] < right[right_pointer]: res.append(left[left_pointer]) left_pointer += 1 else: res.append(right[right_pointer]) right_pointer += 1 if left_pointer < len(left): res += left[left_pointer:] if right_pointer < len(right): res += right[right_pointer:] def merge_sort(arr): if len(arr) <= 1: return arr else: middle = len(arr)//2 left = merge_sort(arr[:middle]) right = merge_sort(arr[middle:]) return merge(left, right) arr = [] for i in range(100): arr.append(random.randint(1, 10)) print(merge_sort(arr))
0a6f3cc34c38e3206bc990fb6871c90c27540c46
jainish008/Python-Tkinter-GUI
/Python Tkinter11.py
692
3.578125
4
import tkinter james_root = tkinter.Tk() james_root.title("Harrison GUI") james_root.geometry("1020x920") #For creating an event where you left click, right click and midddle click on mouse #There will message printed on the screen #Create function for each click def left_click(event): tkinter.Label(text = "Left Click!!!").pack() def middle_click(event): tkinter.Label(text = "Middle Click!!!!").pack() def right_click(event): tkinter.Label(text = "Right Click!!!").pack() #Now bind it james_root.bind("<Button-1>", left_click) james_root.bind("<Button-2>", middle_click) james_root.bind("<Button-3>", right_click) james_root.mainloop()
e43a26b995241c17fa4aa011325e2516e6bf2673
guyrt/teaching
/2017/Com597I/wordplay/exercise2_fancy.py
1,755
4.09375
4
# What is the longest word that starts with a 'q'? # Since more than one word is as long as the longest q word, let's find them all. import scrabble longest_word_length_so_far = 0 longest_words = [] # empty list. for word in scrabble.wordlist: if word[0] == 'q': # If the current q word is longer than the longest q word we've seen so far, then # save it as the longest word. current_word_length = len(word) if current_word_length == longest_word_length_so_far: longest_words.append(word) elif current_word_length > longest_word_length_so_far: # NOTE: I'm comparing length of current word to the stored length. longest_word_length_so_far = len(word) print("New longest word: " + word) longest_words = [word] # overwrite longest_words with a new list that contains one word. print("The longest words are: ") print(longest_words) ''' New longest word: qabala New longest word: qabalah New longest word: qabalahs New longest word: qabalisms New longest word: qabalistic New longest word: quacksalver New longest word: quacksalvers New longest word: quadragenarian New longest word: quadragenarians The longest words are: ['quadragenarians', 'quadringenaries', 'quadripartition', 'quadrisyllables', 'quadrivalencies', 'quadruplicating', 'quadruplication', 'quadruplicities', 'quantifications', 'quarrelsomeness', 'quarterfinalist', 'quartermistress', 'quatercentenary', 'quattrocentisms', 'quattrocentists', 'querulousnesses', 'questionability', 'quicksilverings', 'quincentenaries', 'quincentennials', 'quingentenaries', 'quinquagenarian', 'quinquevalences', 'quintuplicating', 'quintuplication', 'quizzifications', 'quodlibetarians', 'quodlibetically'] '''
5f51862837f6a87aa2428b8dc11a69c217876a61
guyrt/teaching
/2017/Com597I/wordplay/words2.py
348
3.96875
4
import scrabble # Print all letters that never appear doubled in an English word. for letter in "abcdefghijklmnopqrstuvwxyz": exists = False for word in scrabble.wordlist: if letter + letter in word: exists = True break if not exists: print("There are no English words with a double " + letter)
e8b6047ae138cc73b6faf3d02118daff26c6a5f6
Sheetal777/ds-algo
/Codechef/Practice Problems/16_factorial.py
150
3.828125
4
import math t=int(input()) while(t!=0): n=int(input()) if(n==0): print("1") else: print(math.factorial(n)) t=t-1
43643bcae9e44a206b904bfe1e6ca25622a3dc19
YChaeeun/startPython
/problems/TODO_maze_findEVERYpath.py
1,519
3.75
4
# 미로탈출하기 # 그래프 # 다양한 경로를 모두 찾으려면 어떻게 해야 할까??? 흠... def findPath(maze, start,end) : qu = list() visited = set() result = list() qu.append(start) visited.add(start) while qu : path = qu.pop(0) print(path) print('v', visited) v = path[-1] if v == end : result.append(path) # visited 때문에 path 가 최종적으로 한 개 밖에 안 나와 for x in maze[v] : if x not in visited : qu.append(path+x) visited.add(x) # 최단 경로 if result : print(result) shortest = result[0] for idx in range(0, len(result)) : if len(shortest) > len(result[idx]) : shortest = result[idx] return shortest else : return '?' maze = { 'a' :['f'], 'b' : ['c','g'], 'c' :['n', 'd'], 'd' : ['c', 'e'], 'e' :['d'], 'f' : ['a', 'k'], 'g' :['b', 'h', 'l'], 'h' : ['g', 'c', 'i'], 'i' :['n', 'j'], 'j' : ['i', 'o'], 'k' :['f', 'l'], 'l' : ['g', 'm', 'q'], 'm' :['l', 'n', 'r'], 'n' : ['m', 'o', 's'], 'o' :['j', 'n'], 'p' : ['k', 'q'], 'q' : ['l', 'p', 'r'], 'r' :['m', 'q'], 's' : ['n','t', 'x'], 't' :['s', 'y'], 'u' :['p', 'v'], 'v' : ['u'], 'w' :['r'], 'x' : ['s', 'y'], 'y' : ['t', 'x'] } path = findPath(maze, 'a', 'y') print(path)
6d3c696a35a8620f6f23fa3e18b16acc0082cc3a
YChaeeun/startPython
/Algorithm/Search/linear_search_2.py
790
3.9375
4
# 여러 개의 값들의 위치를 찾을 때 O(mn) def linearSearch_2(listofNum, findNumList): numidxList = list() for i in range(0, len(listofNum)): for findNum in findNumList : if listofNum[i] == findNum : numidxList.append(i) findNumList.remove(findNum) return numidxList # 중복된 특정 값의 위치를 모두 찾고 싶을 때 O(n) def linearSearch_3(listofNum, findNum): numidxList = list() for idx in range(0, len(listofNum)): if listofNum[idx] == findNum : numidxList.append(idx) return numidxList listofNum = [12,4,15, 1,6,3,7,9,21,4,5,97,1,33] findNumList = [3, 4, 1, 21] print(linearSearch_2(listofNum, findNumList)) findNum = 1 print(linearSearch_3(listofNum, findNum))
33dd6a8476e08c199627014c1942ba98865f027b
YChaeeun/startPython
/Algorithm/Search/binary_search.py
931
3.859375
4
# Binary Search # O(logN) def binarySearch(listofNum, num) : start = 0 end = len(listofNum)-1 while start <= end : mid = (start+end) //2 if listofNum[mid] == num : return mid elif listofNum[mid] < num : start = mid +1 elif listofNum[mid] > num : end = mid-1 return -1 listofNum = [2,7,6,8,9,3,1,17,5,12,10,25] listofNum.sort() # 이진탐색은 오름차순 정렬이 된 리스트에만 적용 가능 print(listofNum) # 찾고자 하는 숫자 입력받기 num = input('찾고자 하는 정수를 입력하세요: ') if num.isdecimal() : num = int(num) print('num :', num) else : print('잘못된 입력입니다.') foundNum = binarySearch(listofNum, num) # 결과 출력 if foundNum > 0 : print(f'{num} 리스트 인덱스번호는 {foundNum}입니다.') else : print('찾고자 하는 숫자가 없습니다.')
47ae53a54f9ed6a820edeada248a32b26e63c4ad
manishaverma1012/Hackerank_Solution
/hackerrank_subset.py
319
3.53125
4
a = int(input()) for i in range(a): x = int(input()) m = set(map(int,input().split())) y = int(input()) n = set(map(int,input().split())) if(m.intersection(n)==m): print("True") else: print("False")# Enter your code here. Read input from STDIN. Print output to STDOUT
acdf7d7a23f60edc8c40c5fa2a6edf12953b365b
manishaverma1012/Hackerank_Solution
/Prob&Stats_hackerrank/day5_normaldist_I.py
329
3.875
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import math n1=list(map(int,input().split())) n2=float(input()) n3=list(map(int,input().split())) def norm(x): c=0.5+0.5*math.erf((x-n1[0])/(n1[1]*math.sqrt(2))) return c a=norm(n2) print("%.3f"%a) b=norm(n3[1]) d=norm(n3[0]) z=b-d print("%.3f"%z)
2dcb7d75d6413a37b762ba3d6d084970ea19aa6d
huidou74/studypy
/abc_xyz.py
395
3.734375
4
#!/usr/bin/python import itertools #for a in itertools.permutations('abc'): # print a[0], a[1], a[2] # if ( a[0] != 'a' ) and (a[-1] != 'a' ) and (a[-1] != 'c'): # print "x vs %s, y vs %s, z vs %s" % (a[0], a[1], a[2]) for i in itertools.permutations('xyz'): if (i[0] != 'x') and (i[-1] != 'z') and (i[-1] != 'x'): print "a vs %s, b vs %s, c vs %s" % (i[0], i[1], i[2])
43a63cdbe3ae31d0b9fcf463f692314db5caba38
tanksoga/leetcoetraining
/python/Array_List_Dict/E_reverseInteger.py
561
3.546875
4
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if x <= -2**31 or x >= 2**31-1: return 0 xString = str(x) if(x < 0): xString = xString[1:] reserved = "-" + xString[::-1] else: reserved = xString[::-1] result = int(reserved) if result <= -2**31 or result >= 2**31-1: return 0 else: return result print(Solution().reverse(3560745))
eeacf68f45fcd301029696cfed9d296c20b5bdc3
tanksoga/leetcoetraining
/python/Array_List_Dict/M_productOfArrayExceptSelf.py
818
3.5
4
class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ length = len(nums) left = [0]*length right = [0]*length result = [0]*length if(length == 1): return [0] left[0] = 1 right[length - 1] = 1 for i in range(1, length): left[i] = left[i - 1] * nums[i - 1] right[length - 1] = 1 for i in reversed(range(length - 1)): right[i] = right[i + 1] * nums[i + 1] for i in range(length): result[i] = left[i] * right[i] return result print(Solution().productExceptSelf([1,3,5,7,8,10,4]))
1eea2ef3b2e2839b465b3ad53e10db717ac2584e
tanksoga/leetcoetraining
/python/Array_List_Dict/E_isomorphicStrings.py
842
3.59375
4
class Solution(object): def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ exist1 = {} exist2 = {} pattern1 = [] pattern2 = [] for i in range(len(s)): if(s[i] not in exist1): exist1[s[i]] = str(i) pattern1.append(str(i)) else: pattern1.append(exist1[s[i]]) for i in range(len(s)): if(t[i] not in exist2): exist2[t[i]] = str(i) pattern2.append(str(i)) else: pattern2.append(exist2[t[i]]) return pattern1 == pattern2 print(Solution().isIsomorphic("title","paper")) print(Solution().isIsomorphic("title","apple"))
0a7ae1e3382702f86426b0e877c218ec99282ca5
tanksoga/leetcoetraining
/python/LinkedList/E_mergeTwoSortedList.py
1,032
4.0625
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): #def main(): # l1 = [1,2,4] # l2 = [1,3,4] # print(mergeTwoLists(l1,l2)) def mergeTwoLists(self,l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if l1 is None: return l2 elif l2 is None: return l1 elif l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2 l1 = ListNode(1) l1_1 = ListNode(2) l1_2 = ListNode(4) l1.next = l1_1 l1_1.next = l1_2 l1_2.next = None l2 = ListNode(1) l2_1 = ListNode(3) l2_2 = ListNode(4) l2.next = l2_1 l2_1.next = l2_2 l2_2.next = None head = Solution().mergeTwoLists(l1,l2) while head: print(head.val) head = head.next
d4b9a7934d27d1cf86d22569f3ddc5bb048bfaaf
tanksoga/leetcoetraining
/python/Tree/E_symmetricTree.py
1,013
3.9375
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): def isSameTree(self, p, q): if not p and not q: return True if not p or not q: return False #print(str(p.val) + "," + str(q.val)) if p.val != q.val: return False return self.isSameTree(p.right,q.left) and self.isSameTree(p.left, q.right) def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ return self.isSameTree(root,root) root = TreeNode(1) rl = TreeNode(2) rr = TreeNode(2) root.left = rl root.right = rr rll = TreeNode(3) rlr = TreeNode(4) rl.left = rll rl.right = rlr rrl = TreeNode(4) rrr = TreeNode(3) rr.left = rrl rr.right = rrr print(Solution().isSymmetric(root))
8ec6d68bf147723fdd82c755843d96427687d1b1
icyflame/cows-and-bulls
/solutionToRepeatedNumberIssue.py
353
3.53125
4
def digits(number): return [int(d) for d in str(number)] def bulls_and_cows(guess, target): guess, target = digits(guess), digits(target) bulls = [d1 == d2 for d1, d2 in zip(guess, target)].count(True) bovine = 0 for digit in set(guess): bovine += min(guess.count(digit), target.count(digit)) return bulls, bovine - bulls
1ae7cdf0c2e2b51586428e3627ee4244e9650cab
eduardrich/Senai-2.1
/3.py
529
4.1875
4
#Definição da lista Val = [] #Pede para inserir os 20 numeros para a media for c in range(0,20): Val.append ( int(input("Digite aqui os valores para a média: ")) ) #detalhamento da soma e conta dos numeros dentro da lista SomVal = sum(Val) NumVal = len(Val) #Tira a media MedVal = SomVal / NumVal print("Media da lista: ") print(MedVal) #Numero Max dentro da lista MaxVal = max(Val) print("Numero Max da lista:") print(MaxVal) #Numero Min dentro da lista MinVal = min(Val) print("Numero Min da lista") print(MinVal)
346439bc872487e4c174e4fa32c319e42890d673
tokitsubaki/labcode
/exception/exception_python.py
401
3.59375
4
import traceback def main(): try: print("before exception.") raiseException() print("after exception.") except Exception as e: print(traceback.format_exc()) else: print("not exception.") finally: print("finally.") def raiseException(): print("before raise.") raise Exception("Test Exception.") print("after raise") main()
f80d5a2755c78577e7f72af1e800410841b4c1e1
tokitsubaki/labcode
/string/string_python.py
3,239
4.25
4
# coding: utf-8 # +演算子による結合 s1 = "Hello" s2 = "Python" r = s1 + s2 print(r) # HelloPython # 配列を結合 a = ["Python","Hello","World"] r = " ".join(a) print(r) # Python Hello World # printf形式による文字列の埋め込み s1 = "Python" s2 = "Hello" r = "%s %sWorld!!" % (s1, s2) print(r) # Python HelloWorld!! # formatメソッドによる文字列の埋め込み s1 = "Python" s2 = "Hello" r = "{0} {1}World!!".format(s1, s2) print(r) # Python HelloWorld!! # フォーマット済み文字列リテラルによる文字列の埋め込み s1 = "Python" s2 = "Hello" r = f"{s1} {s2}World!!" print(r) # Python HelloWorld!! # 文字列の抽出 s = "Hello Python!!" r = s[6:12] print(r) # Python s = "Hello Python!!" r = s[-8:-2] print(r) # Python # 文字列の長さを求める s = "1234567890" r = len(s) print(r) # 10 s = "あいうえお" r = len(s) print(r) # python2で実行すると10、python3で実行すると5 # findによる検索 s = "Hello Python!!" r = s.find("!") print(r) # 12 # rfindによる検索 s = "Hello Python!!"; r = s.rfind("!"); print(r); # 13 # countによる文字列のカウント s = "Hello Python!!" r = s.count("!") print(r) # 2 # in文による存在確認 s = "Hello Python!!" r = "!" in s print(r) # True # startswithによる存在確認 s = "Hello Python!!" r = s.startswith("Hello") print(r) # True # endswithによる存在確認 s = "Hello Python!!" r = s.endswith("!!") print(r) # True # replaceによる置換 s = "Hello Java!!" r = s.replace("Java", "Python") print(r); # Hello Python!! # translateによる置換 s = "Hello Python!!" r = s.translate(str.maketrans({ '!':'?' })) print(r); # Hello Python?? # replaceによる文字列削除 s = "Hello Python!!" r = s.replace("!", "") print(r); # Hello Python # translateによる文字列削除 s = "Hello Python!!" r = s.translate(str.maketrans({ '!':'' })) print(r); # Hello Python # splitによる分割 s = "JavaScript,Python,Java,Ruby,Go" r = s.split(",") print(r) # [ "JavaScript", "Python", "Java", "Ruby", "Go" ] # stripによるトリミング s = " Hello Python!! " r = s.strip() print("--") print(r) # Hell Pythn!! # lstripによるトリミング s = "Hello Python!!" r = s.lstrip("Hello ") print(r) # Python!! # rstripによるトリミング s = "Hello Python!!" r = s.rstrip("!") print(r) # Hello Python! # zfillによる0埋め s = "123" r = s.zfill(10) print(r) # 0000000123 # ljustによる0埋め s = "123" r = s.ljust(10, "0") print(r) # 1230000000 # centerによる0埋め s = "123" r = s.center(10, "0") print(r) # 0001230000 # rjustによる0埋め s = "123" r = s.rjust(10, "0") print(r) # 0000000123 # formatによる書式変換 s = "123" r = format(s, "0>10") print(r) # 0000000123 # upperによる大文字変換 s = "Python" r = s.upper() print(r) # PYTHON # lowerによる小文字変換 s = "Python" r = s.lower() print(r) # python # intによる文字列からintへの変換 s = "123" r = int(s) print(r) # 123 print(type(r)) # <class 'int'> # strによるintから文字列への変換 n = 123 r = str(n) print(r) # 123 print(type(r)) # <class 'str'> # 文字列の一致確認 s1 = "123" s2 = "123" r = (s1 == s2) print(r) # True
3fa2fe6caf2a0cfda09a745dc8c7fceb7d381e5a
YayraVorsah/PythonWork
/lists.py
1,673
4.4375
4
names = ["John","Kwesi","Ama","Yaw"] print(names[-1]) #colon to select a range of items names = ["John","Kwesi","Ama","Yaw"] print(names[::2]) names = ["John","Kwesi","Ama","Yaw"] names[0] ="Jon" #the list can be appended print(names) numbers = [3,4,9,7,1,3,5,] max = numbers[0] for number in numbers: if number > max: max = number print(max) print("2 D L I S T S") #MACHINE LEARNING AND MATRICS(RECTANGULAR ARRAY OF NUMBERS) #MATRIX = [LIST] matrix = [ # EACH ITEM REPRESENTS ANOTHER LIST [1, 2, 3], [4, 5, 6], [7, 8, 9], ] print(matrix[0]) matrix = [ # EACH ITEM REPRESENTS ANOTHER LIST [1, 2, 3], [4, 5, 6], [7, 8, 9], ] for row in matrix: for item in row: print(item) # list methods # numbers = [3,4,5,9,7,1,3,5,] # numbers.append(20) # TO ADD THE NUMBER TO THE LIST # numbers.insert(0,8) # INSERTED AT THE INDEX YOU DETERMINE # numbers.remove(1) # numbers.clear() #REMOVES EVERYTHING IN THE LIST # # numbers.pop() #LAST NUMBER IS REMOVED FROM THE LIST # #print(numbers.index(3)) #shows what number is set at that index # #print(50 in numbers) # to check if it is present in the list --- generates a boolean # print(numbers.count(5)) # numbers.sort() sorts out the list in ascending order # numbers.reverse() sorts in descending order # numbers.copy() to copy the list numbers = [2,2,4,6,3,4,6,1] uniques = [] for number in numbers: if number not in uniques: uniques.append(number) print(uniques)
f2cacc2f354655e601273d4a2946a2b27258624d
YayraVorsah/PythonWork
/conditions.py
1,769
4.1875
4
#Define variable is_hot = False is_cold = True if is_hot: #if true for the first statement then print print("It's a hot day") print("drink plenty of water") elif is_cold: # if the above is false and this is true then print this print("It's a cold day") print("Wear warm clothes") else: # else you print this if both statements are false print("It's a good day") print("Enjoy your day") print("EXERCISE") house_price = 1000000 good_credit = True bad_credit = False if good_credit: downpay = house_price//10 print("your downpayment : $" + str(downpay)) else : downpay = house_price//20 print("Your downpay is bad ") # if good_credit: # print("Your down payment is " + good_credit) print("LOGICAL OPERATORS") hasHighIncome = True hasGoodCredit = True if hasHighIncome and hasGoodCredit: #Both Conditions need to be true to execute print("Eligible for Loan") #even if one statement is false(It all becomes false due to the AND operator) else: print("Not eligible for Loan") hasHighIncome = True hasGoodCredit = False if hasHighIncome or hasGoodCredit: #At least One condition needs to be true to execute print("Eligible for Loan and other goods") #even if one statement is false it will execute because of the OR operator) else: print("Not eligible for Loan") print("NOT OPERATOR") #has good credit and not a criminal record good_credit = True criminalRecord = False # the not operator would turn this to True if good_credit and not criminalRecord: # and not (criminalRecord = False) === True print("you are good to go")
be1c35404de416884e0f1bb3b7ea274580183d9e
tarunbodapati/sum.c
/67.py
145
3.765625
4
x=int(input()) count = 0 for i in range(1,x//2+1): if(x%i==0): count+=1 if(count==1): print("yes") else: print("no")
bff63a51a92406fc98df5343b90e3e3f1f8a912e
tarunbodapati/sum.c
/72.py
186
3.71875
4
x=list(input()) count=0 for k in x: if((k=='a')or(k=='e')or(k=='i')or(k=='o')or(k=='u')): count=count+1 if(count>0): print("yes") else: print("no")
4193da24dc0234d54099637767c82ec70fba8a94
tarieli-d/vigenere_python
/list.py
1,196
3.859375
4
from src import * def encrypt(start_text, keyword): end_text = [] for e, let in enumerate(start_text): if let.isalpha(): len_sum = char_position(let) + char_position(keyword[e]) end_text.append(pos_to_char(len_sum % 26, let)) else: end_text.append(let) return end_text def decrypt(end_text, keyword): start_text = [] for e, let in enumerate(end_text): if let.isalpha(): start_text.append(pos_to_char((char_position(let) + 26 - char_position(keyword[e])) % 26,let)) else: start_text.append(let) return start_text # lists for plaintext,key and keyword.keyword we will get from from key ListText = list(text) ListKey = list(key) ListKeyword = [] i = 1 # here we get ListKeyword from key,it's the same length as plain text,it's need while encryption and decryption while len_text != 0: ListKeyword.append(ListKey[i-1]) if len_key == i: i = 1 else: i += 1 len_text -= 1 # invoke functions endText = encrypt(ListText, ListKeyword) startText = decrypt(endText, ListKeyword) print("encrypted list:", endText) print("decrypted list:", startText)
c116516eaa8d833f3b7db5b3b52a6718db6bf353
sbowl001/cs-module-project-hash-tables
/applications/histo/histo.py
371
3.578125
4
# Your code here with open("robin.txt") as f: words = f.read() split_words = words.split() cache = {} for word in split_words: if word not in cache: cache[word] = '#' else: cache[word] += '#' items = list(cache.items()) items.sort(key = lambda x: x[1], reverse= True) for key, value in items: print(f'{key: <18} {value}')
8e6a9399680541756605b4d687bf44b7388c5652
Kul0l0/myLeetCode
/algorithms/1221. Split a String in Balanced Strings/Solution.py
425
3.625
4
class Solution: def balancedStringSplit(self, s: str) -> int: stack = [] res = 0 for i in s: if len(stack)>0 and stack[-1]!=i: stack.pop(-1) if len(stack) == 0: res += 1 else: stack.append(i) return res s = "RLRRLLRLRL" # s = "RLLLLRRRLR" # s = "LLLLRRRR" print(Solution().balancedStringSplit(s))
23f02f1df0a5e3cf3f053a220e6482290f657f95
LuisMalave2001/GarryTesting
/school_base/utils/commons.py
559
3.90625
4
# -*- coding: utf-8 -*- def switch_statement(cases, value): """ Simulate a swithc statement """ return cases[value] if value in cases else cases["default"] if "default" in cases else False def extract_value_from_dict(parameter: str, values: dict): """ Extract a value from values dict Args: parameter (str): What we want to extract values(dict): Where we want to extract Return: values[parameter] if is in values, if not return False """ return values[parameter] if parameter in values else False
3dec2822d414f2848e1f2d6bf4e00b71b3e1e0a2
choulilove/Sort__by__python
/DataStructure/排序/基数排序.py
913
4.03125
4
''' 实现基数排序RadixSort, 分为: 最高位优先(Most Significant Digit first)法 最低位优先(Least Significant Digit first)法 ''' # 最低位优先法 def radixSortLSD(alist): if len(alist) == 0: return if len(alist) == 1: return alist tempList = alist maxNum = max(alist) radix = 10 while maxNum * 10 > radix: newArr = [[], [], [], [], [], [], [], [], [], []] for n1 in tempList: testnum = n1 % radix testnum = testnum // (radix / 10) for n2 in range(10): if testnum == n2: newArr[n2].append(n1) tempList = [] for i in range(len(newArr)): for j in range(len(newArr[i])): tempList.append(newArr[i][j]) radix *= 10 return tempList print(radixSortLSD([10, 12, 24, 23, 13, 52, 15, 158, 74, 32, 254, 201, 30, 19]))
cfc689c826196a77c7eb4e0c9873a78a668fc7e6
ronniepereira/python-academy
/modulo_04/exercicio_01.py
112
3.71875
4
nota = int(input("Digite a nota do aluno: ")) if nota >= 60: print("Aprovado") else: print("Reprovado")
1a996993caa0dbcc09e7bd7450c2787d5d9b278f
GauravInprosys/AGS-intern-files
/Sujeet/assinment1.py
309
3.59375
4
import pyodbc #https://towardsdatascience.com/sql-server-with-python-679b8dba69fa conn = pyodbc.connect('Driver={SQL Server};''Server=DESKTOP-CAFAM2K\SUJEETPATIL;''Database=Agsdb;''Trusted_Connection=yes;') mycursor = conn.cursor() mycursor.execute("select * from table1") for row in mycursor: print(row)
dc9b8ab9789c9fa3278a989e467d0e84098f9c71
CodecoolBP20161/a-mentor-s-life-in-an-oo-way-act-1
/story.py
4,761
3.609375
4
from assignment import Assignment from codecool_class import CodecoolClass from electronic import Electronic, Laptop from feedback import Feedback from mentor import Mentor from student import Student from colors import Colors print(Colors.OKBLUE + "\nThe ACT presents an (almost) average day in codecool." + Colors.ENDC) skip = input() miki = Mentor.create_by_csv()[0] dani = Mentor.create_by_csv()[1] tomi = Mentor.create_by_csv()[2] print("Mentors are initialized from CSV.") skip = input() móni = Student.create_by_csv()[0] beru = Student.create_by_csv()[1] beni = Student.create_by_csv()[3] print("Students are initialized from CSV.") skip = input() print("School @ Budapest, in year 2016 is created, with 3 mentors and 4 students.") skip = input() print("Examine a mentor.. for example Dani.") skip = input() print("Nickname: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( dani.nickname, dani.knowledge_level, dani.energy_level, dani.joy_level)) print("He has more attributes, but it's not necessary for now.") skip = input() l = Laptop("HP", False, True) print("Edina has brought a {} laptop.".format(l.name)) skip = input() print("Then she tries to turn on. But...") skip = input() l.tool_switcher() print("So she's looking for a mentor...") skip = input() print("... she finds Dani and asks him to repair the laptop.") skip = input() l.tool_repair(dani) skip = input() print("These are Dani's attributes...") skip = input() print("Nickname: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( dani.nickname, dani.knowledge_level, dani.energy_level, dani.joy_level)) skip = input() print("So now she can turn on the laptop.") skip = input() l.tool_switcher() skip = input() print("Finally Edina can use the laptop... So she starts coding.") skip = input() print("Before she starts coding:\nName: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( beru.first_name, beru.knowledge_level, beru.energy_level, beru.joy_level)) skip = input() l.coding(beru) skip = input() print("After she finished coding:\nName: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( beru.first_name, beru.knowledge_level, beru.energy_level, beru.joy_level)) skip = input() print("Meanwhile Beni plays a quick game...") skip = input() print("Before playing:\nNickname: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( beni.nickname, beni.knowledge_level, beni.energy_level, beni.joy_level)) skip = input() l.playing(beni) skip = input() print("After playing:\nNickname: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( beni.nickname, beni.knowledge_level, beni.energy_level, beni.joy_level)) skip = input() print("And he wins!") skip = input() print("During the day Móni needs a feedback...") skip = input() print("So she finds Tomi and asks for his help.") f = Feedback("Tomi") print("\nBefore feedback:\nNickname: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( móni.nickname, móni.knowledge_level, móni.energy_level, móni.joy_level)) skip = input() f.give_feedback(móni) skip = input() print("After feedback:\nNickname: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( móni.nickname, móni.knowledge_level, móni.energy_level, móni.joy_level)) skip = input() print("Sometimes a mentor needs a feedback too, even if his name is Miki...") skip = input() print("Tomi is the mentor who always ready to help to his friends.") print("\nBefore feedback:\nNickname: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( miki.nickname, miki.knowledge_level, miki.energy_level, miki.joy_level)) skip = input() f.get_feedback(miki) skip = input() print("Before feedback:\nNickname: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( miki.nickname, miki.knowledge_level, miki.energy_level, miki.joy_level)) skip = input() print("At the end of the day, Tomi checks CANVAS.") skip = input() a = Assignment("OOP project", 24) a.check_assignment(tomi) skip = input() print("He forgets that the deadline hour doesn't come yet. But now he knows.") skip = input() print("And he checks an other assignment.") skip = input() print("Before checking:\nNickname: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( tomi.nickname, tomi.knowledge_level, tomi.energy_level, tomi.joy_level)) skip = input() b = Assignment("Inventory", 3) b.check_assignment(tomi) skip = input() print("After checking:\nNickname: {}\nKnowledge level: {}\nEnergy level: {}\nJoy level: {}".format( tomi.nickname, tomi.knowledge_level, tomi.energy_level, tomi.joy_level)) skip = input() print(Colors.OKBLUE + "So the day is over, and everybody goes to home and rests.\n" + Colors.ENDC)
eef2feeea33fd5b39b671f35d889b85306e8eb41
colinsongf/SpellCheck
/test.py
384
3.640625
4
def find_common_distinct_letters (word1, word2): letters_word1 = [] letters_word2 = [] for i in range(0,len(word1)): letters_word1.append(word1[i]) for i in range(0,len(word2)): letters_word2.append(word2[i]) common_distinct_letters = list(set(letters_word1).union(set(letters_word2))) return len(common_distinct_letters) print find_common_distinct_letters('cat','bat')
881a8e4b1aa1eaed9228782eef2440097c2cb301
siyangli32/World-City-Sorting
/quicksort.py
1,439
4.125
4
#Siyang Li #2.25.2013 #Lab Assignment 4: Quicksort #partition function that takes a list and partitions the list w/ the last item #in list as pivot def partition(the_list, p, r, compare_func): pivot = the_list[r] #sets the last item as pivot i = p-1 #initializes the two indexes i and j to partition with j = p while not j == r: #function runs as long as j has not reached last object in list if compare_func(the_list[j], pivot): #takes in compare function to return Boolean i += 1 #increments i before j temp = the_list[i] #switches i value with j value the_list[i] = the_list[j] the_list[j] = temp j += 1 #increments j temp = the_list[r] #switches pivot with the first object larger than pivot the_list[r] = the_list[i+1] the_list[i+1] = temp return i+1 #returns q = i+1 (or pivot position) #quicksort function takes in the partition function and recursively sorts list def quicksort(the_list, p, r, compare_func): if p < r: #recursive q = partition(the_list, p, r, compare_func) quicksort(the_list, p, q-1, compare_func) quicksort(the_list, q+1, r, compare_func) return the_list #sort function sorts the entire list using quicksort def sort(the_list, compare_func): return quicksort(the_list, 0, len(the_list)-1, compare_func)
cd549e08ba3133720ce4e75ba416c4388c2a2e2c
sharanya-code/Basic-number-programs
/NUMBER GUESSING GAME.py
513
4.03125
4
#RANDOM NUMBER GUESSING GAME import random#GETTING RANDOM IMPORT n = random.randint(1, 99) g = int(input("ENTER A NUMBER FROM 1-99: "))#INPUT A NUMBER while n != g: print if g < n:#GUESS APPROXIMATION print ("guess is low") g = int(input("ENTER A NUMBER FROM 1-99: ")) elif g > n: print ("guess is high") g = int(input("ENTER A NUMBER FROM 1-99: ")) else: print ("YOU GUESSED IT! YAY!") break print("THANKS FOR PLAYING THE GAME")
5d686400257697cabfc20345ea4aa52c6a5cfc88
sharanya-code/Basic-number-programs
/SUM OF DIGITS.py
229
3.9375
4
def sod(): #SUM OF DIGITS n=int(input("Enter a number:")) tot=0 while(n>0): dig=n%10 tot=tot+dig#GETTING THE LAST DIGIT n=n//10 print("The total sum of digits is:",tot) sod()
08b37f326f0d4ab6dae5f95dd655ea2d9ef3f711
mlobf/LogicRoutinePython
/logicTest/test9.py
306
4.03125
4
''' Faça um Programa que peça a temperatura em graus Farenheit, transforme e mostre a temperatura em graus Celsius. C = (5 * (F-32) / 9). ''' temperatura_celsus = 0 def convert_celsus(temperatura_celsus): celsus = ((temperatura_celsus - 32) / 1.8) return celsus print(convert_celsus(100))
415ae0cde3c5b6057f8bf2539d29917a253856ed
abhishekghz/Python-_Pygame-
/tut9..py
625
3.65625
4
import pygame pygame.init() # Colors white = (255, 255, 255) red = (255, 0, 0) black = (0, 0, 0) # Creating window screen_width = 900 screen_height = 600 gameWindow = pygame.display.set_mode((screen_width, screen_height)) # Game Title pygame.display.set_caption("SnakesWithSunny") pygame.display.update() # Game specific variables exit_game = False game_over = False # Game Loop while not exit_game: for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game = True gameWindow.fill(white) pygame.display.update() pygame.quit() quit()
150810f760c409533200b7252912130cc72e792b
aiman88/python
/Introduction/case_study1.py
315
4.1875
4
""" Author - Aiman Date : 6/Dec/2019 Write a program which will find factors of given number and find whether the factor is even or odd. """ given_number=9 sum=1 while given_number>0: sum=sum*given_number given_number-=1 print(sum) if sum%10!=0: print("odd number") else: print("Even number")
ae7a9048dc6ab92cd5327423dadc83826494502f
aiman88/python
/Introduction/name.py
143
4.125
4
name = "Nurul Iman" if len(name) < 3: print("Less than 3") elif len(name) > 50: print("More than 50") else: print("Name look good")
96737e27981019e448f1eb5916ca21a80804f461
igorlealantunes/APA
/diversos/prim/min_heap.py
2,556
3.75
4
class Min_heap: def __init__(self): self.list = [0] self.size = 0 self.map = {} """ def fix_up(self, i): while i // 2 > 0: # enquanto nao chegar na raiz if self.list[i].v < self.list[i//2].v: # se pai for menor => troca self.swap(i, i//2) i = i // 2 def insert(self, k): self.list.append(k) self.size = self.size + 1 self.fix_up(self.size) # depois de inserir => corrige o heap a partir do valor inserido ate a raiz """ def fix_down(self, i): while i * 2 < self.size: # enquanto estiver nos limites da arvore mc = self.min_child(i) # retorna o menor filho if self.list[i].v > self.list[mc].v: # se pai for maior que menor filho => troca self.swap(i, mc) i = mc def min_child(self,i): if i * 2 + 1 > self.size: # se so tiver 1 filho return i * 2 else: # com dois filhos if self.list[i*2].v < self.list[i*2+1].v: return i * 2 else: return i * 2 + 1 def pop_min(self): retval = self.list[1] del self.map[retval.k] # remove from dic self.list[1] = self.list[self.size] self.map[self.list[1].k] = 1 self.size = self.size - 1 self.list.pop() self.fix_down(1) # refaz o heap return retval def swap(self, i1, i2): # i1 e i2 sao INT para posicoes no array temp = self.list[i1] self.list[i1] = self.list[i2] self.list[i2] = temp # atualiza mapa tambem self.map[self.list[i1].k] = i1 self.map[self.list[i2].k] = i2 def build_heap(self, alist): i = len(alist) // 2 self.size = len(alist) root = Heap_obj(0, "") self.list = [root] + alist[:] while (i > 0): self.fix_down(i) i = i - 1 for y in range(1, len(self.list)): # build map self.map[self.list[y].k] = y def contains(self, k): if int(k) in self.map: return True else: return False def print_heap(self): for i in xrange(1, len(self.list)): print "[" + str(i) + "]: " + self.list[i].to_string() class Heap_obj : def __init__(self, v, k, f = None): self.v = v self.k = k self.father = f def to_string(self): stre = "V = " + str(self.v) + " K = " + str(self.k) return stre
a58b824da4b39594b99e05879c82a1e7bae54afd
mtoce/Intro-Python-I
/src/03_modules.py
772
3.890625
4
""" In this exercise, you'll be playing around with the sys module, which allows you to access many system specific variables and methods, and the os module, which gives you access to lower- level operating system functionality. """ import sys # See docs for the sys module: https://docs.python.org/3.7/library/sys.html print("sys.argv command line arguments, one per line:") print(sys.argv, '\n') print("OS platform:") print(sys.platform, '\n') print("Python version:") print(sys.version, '\n') import os # See the docs for the OS module: https://docs.python.org/3.7/library/os.html print("current process ID:") print(os.getpid(), '\n') print("current working directory (cwd):") print(os.getcwd(), '\n') print("machine's login name:") print(os.getlogin(), '\n')
6724d61cc018556e22ea88f0617f66c72697aa35
phoomct/Comprohomework
/combineString.py
268
3.609375
4
""" combineString """ def main(): """ Write a Python program to get a single string from two given strings, s eparated by a space and swap the first two characters of each string. """ data = input() data2 = input() print(data2 +" " + data) main()
1556d0ba32be359ed8f6955bd3957eb08bc6c6a2
phoomct/Comprohomework
/Coffee Shop.py
1,169
4.03125
4
""" Coffee Shop """ def main(): """The IT coffee shop sells 3 different types of coffess as follows: Robusta coffee 390 baht per kg, ***Promotion Free 2 kg of Robusta coffee, every 15 kg Robusta coffee order. Liberica coffee 380 baht per kg, ***Promotion Free 2 kg of Liberica coffee, every 15 kg Liberica coffee order. Arabica coffee 440 baht per kg, ***Promotion Free 1 kg of Arabica coffee, every 15 kg Arabica coffee order. For each transaction, customer need to pay 5% shipping cost. IF the total amount is more than 5,000 baht, the shipping cost is free. Write a program that calculate the cost of an order.""" data = input() rob, lib, arab = data.split(',') rob, lib, arab = int(rob), int(lib), int(arab) if rob >= 17: rob = rob-((rob//15)*2) robc = 390 * rob if lib >= 17: lib = lib - ((lib // 15) * 2) libc = 380*lib if arab >= 16: arab = arab-(arab // 15) arabc = 440 * arab total = robc + libc + arabc ship = 5 * total / 100 if total >= 5000: ship = 0 print('Coffee cost: %.2f'%total) print('Shipping cost: %.2f'%ship) main()
42a3298e1978dfb8bc8e57114f4b1146a0389356
phoomct/Comprohomework
/dayOfWeek.py
276
3.953125
4
""" dayOfWeek """ def main(): """ dayOfWeek """ import datetime date = input() day, month, year = date.split(":") day, month, year = int(day), int(month), int(year) dayofweek = datetime.date(year, month, day).strftime("%A") print(dayofweek) main()
3606dd083e4d948470fab5a3b2825a20140206a5
SenthilKumar009/100DaysOfCode-DataScience
/Python/Pattern/equilateralTriangle.py
214
3.953125
4
line = int(input("Enter the total line to print:")) for i in range(1,line+1): for j in range (i,line): print(' ', end='') for k in range (0, 2*i-1): print('*', end='') print()
40df24e8679f2f9f829621c4c0672f8f1989c0a0
SenthilKumar009/100DaysOfCode-DataScience
/Python/Concepts/List/zip.py
329
4.0625
4
names = ['Bruce', 'Art', 'Peter', 'Tony', 'Steve'] heros = ['Batman', 'Joker', 'Spiderman', 'Iron Man', 'Captain America'] print(list(zip(names, heros))) my_dict = {} #for name, hero in zip(names, heros): # my_dict[name] = hero my_dict = {name: hero for name, hero in zip(names, heros) if name != 'Peter'} print(my_dict)
ee60de3bbeeee63f6d5ed498a09f85f06c522a14
SenthilKumar009/100DaysOfCode-DataScience
/Python/Pattern/leftTriangle.py
145
3.9375
4
line = int(input("Enter the total line to print:")) for x in range(1,line+1): for y in range(1, x+1): print('* ', end="") print()
3c0c83f6815358e853c8a01c1cbe2c5659870969
SenthilKumar009/100DaysOfCode-DataScience
/Python/Concepts/returnfun.py
1,845
3.703125
4
''' def greet(lang): if(lang == 'es'): return('Holo') elif(lang == 'fr'): return('Bonjur') else: return('Hello') print(greet('en'), 'Maxwell') print(greet('es'), 'Steffy') print(greet('fr'), 'Senthil') list = ['a', 'b', 'c', 'd', 'e'] def list(lst): del lst[3] lst[3] = 'x' print(list(list)) def fun(x): x += 1 return x x = 2 x = fun(x+1) print(x) tup = (1,2,3,4) tup[1] = tup[1] + tup [0] #tup = tup[0] print(tup) def fun(x): global y y = x * x return y fun(2) print(y) dct = {} dct['1'] = (1,2) dct['2'] = (2,1) for x in dct.keys(): print(dct[x][1], end='') def fun(x): if x % 2 == 0: return 1 else: return 2 print(fun(fun(2))) x = float(input()) y = float(input()) print(y ** (1/x)) print(1//5 + 1/5) lst = [[x for x in range(3)] for y in range(3)] for r in range(3): for c in range(3): print(lst[r][c]) if lst[r][c] % 2 != 0: print('#') lst = [1,2] for v in range(2): lst.insert(-1, lst[v]) print(lst) def fun(inp=2, out=2): return inp * out print(fun(out=2)) x = 1 y = 2 x,y,z = x,x,y z,y,z = x,y,z print(x,y,z) i = 0 while i < i + 2: i += 1 print('*') else: print('*') a = 1 b = 0 a = a^b b = a^b c = a^b print(a,b) def fun1(a): return None def fun2(a): return fun1(a) * fun1(a) #print(fun2(2)) print(1//2) nums = [1,2,3] vals = nums del vals[:] print(nums) print(vals) lst = [i for i in range(-1,-2)] print(lst) dd = {'1':'0', '0':'1'} for x in dd.values(): print(x, end='') def func(a,b=0): return a**b print(func(b=2)) lst = [x*x for x in range(5)] def fun(lst): del lst[lst[2]] return lst print(fun(lst)) tup = (1,2,4,8) tup[1] = tup[1] + tup[0] #print(tup) #tup = tup[-1] print(tup) ''' #print(float("1, 3")) print(len('\''))
1dcd53777bbc5a41491d94db126568aeb489dffb
SenthilKumar009/100DaysOfCode-DataScience
/Python/Functions/packing.py
136
3.578125
4
def packing(*args): sum = 0 for x in range (0, len(args)): sum += args[x] return sum print(packing(1,2,3,4,5))
7aeea96916dbb1a0e22a6542b0472888a450cd7f
SenthilKumar009/100DaysOfCode-DataScience
/Python/OOP/classIntro.py
451
3.78125
4
class Dog(): species = 'Mammal' myDogBreed = ['Lab', 'German', 'Country'] def __init__(self, breed, name): self.breed = breed self.name = name def bark(self): for breed in Dog.myDogBreed : if self.breed == breed: print('Woof!!!') break else: print('LOL!!!') break my_dog = Dog(breed = 'Lab', name = 'Tony') my_dog.bark()
f05174829075d9ae7eafb2cd345c3b2278e782cb
SenthilKumar009/100DaysOfCode-DataScience
/Python/Programs/CollatzSequence.py
131
3.78125
4
def collatz(number): if number % 2 == 0: print(number/2) else: print(number * 3 + 1) collatz(3) collatz(4)
9a1122730c0a44c5f9d19df4eb0cbc2b5ef04379
SenthilKumar009/100DaysOfCode-DataScience
/Python/Programs/minoftwoArray.py
381
3.90625
4
pair = int(input('Enter the total pair of numbers:')) list1 = [] list2 = [] for i in range(0,pair): number1, number2 = input().split() list1.append(int(number1)) list2.append(int(number2)) min = [] for i in range(0,pair): if list1[i] > list2[i]: min.append(list2[i]) else: min.append(list1[i]) for val in min: print(val, end=' ') print()
436c848fe2a78858ee2b6b5528d9bfc1280ad837
SenthilKumar009/100DaysOfCode-DataScience
/Python/File/file_pass_runtime.py
263
3.640625
4
from sys import argv script, fileName = argv txt = open(fileName) print('The opened file {}', fileName) print(txt.read()) fileAgain = input('Enter the file name again:') print('The opened file {}', fileAgain) txt_again = open(fileAgain) print(txt_again.read())
5e2e9fb18dea2910c67e397f0bcf97046caf2a03
SenthilKumar009/100DaysOfCode-DataScience
/Python/Strings/string_format.py
481
4.09375
4
myName = 'SKK' myJob = 'Data Scientist' print('My name is ', myName) print('My Name is {}, and Im working as a {}'.format(myName, myJob)) x = 10 y = 20 print('The given value is:%i' % x) print('The Values are: %i %i' % (x,y)) print('The Values are: %d %d' % (x,y)) for i in range(11): print('Number:{:.2f}'.format(i)) import datetime my_date = datetime.datetime(2020, 2, 7, 12, 30, 45) print('{:%B %d, %Y}'.format(my_date)) x = 'There are %d types of people' % 10 print(x)
211009d3cd13c00e93323588d1b77a18bd14593d
SenthilKumar009/100DaysOfCode-DataScience
/Python/Programs/make_bricks.py
148
3.5625
4
def make_bricks(small, big, goal): # return (goal%5)<=small and (goal-(big*5))<=small print(make_bricks(3,1,8)) print(make_bricks(3, 2, 9))
0ec23c68dd87a2a2fab51238a6f26eb1d492fcc8
SenthilKumar009/100DaysOfCode-DataScience
/Python/OOP/class_cons.py
384
3.71875
4
class ExampleClass: def __init__(self, val = 1): self.first = val def setSecond(self, val): self.second = val exampleObject1 = ExampleClass() exampleObject2 = ExampleClass(2) exampleObject2.setSecond(3) exampleObject3 = ExampleClass(4) exampleObject3.third = 5 print(exampleObject1.__dict__) print(exampleObject2.__dict__) print(exampleObject3.__dict__)
e840b77ca8e9fe15e8d6717d546ef49641db3243
SenthilKumar009/100DaysOfCode-DataScience
/Python/Concepts/Set/setComp.py
123
3.9375
4
nums = [1,1,1,2,2,2,2,3,3,4,4,4,5,5,5,5] print(set(nums)) mySet = set() for num in nums: mySet.add(num) print(mySet)
0a6d7c918c741bf87ede054baa62685b2f9d480c
SenthilKumar009/100DaysOfCode-DataScience
/Python/Programs/suminLoopPair.py
315
3.8125
4
pair = int(input('Enter the total pair of numbers:')) list1 = [] list2 = [] for i in range(0,pair): number1, number2 = input().split() list1.append(int(number1)) list2.append(int(number2)) sum = [] for i in range(0,pair): sum.append(list1[i]+list2[i]) for i in sum: print(i, end=' ') print()
351f5b25fda523a7d07897159e7ec4c4642c9d1a
SenthilKumar009/100DaysOfCode-DataScience
/Python/Programs/date_month_year.py
692
3.84375
4
def isYearLeap(year): if year % 4 == 0 and year % 100 != 0: return True elif year%100 == 0 and year%400 == 0: return True else: return False def daysInMonth(year, month): if month in (1,3,5,7,8,10,12): return 31 elif month in (4,6,9,11): return 30 elif month == 2 and isYearLeap(year): return 29 else: return 28 testYears = [1900, 2000, 2016, 1987] testMonths = [2, 2, 1, 11] testResults = [28, 29, 31, 30] for i in range(len(testYears)): yr = testYears[i] mo = testMonths[i] print(yr, mo, "->", end="") result = daysInMonth(yr, mo) if result == testResults[i]: print("OK") else: print("Failed")
2937f1c3d3cd5f3b96981d4658ef6e688966592a
SenthilKumar009/100DaysOfCode-DataScience
/Python/Concepts/generatorExp.py
133
3.578125
4
nums = [1,2,3,4,5,6,7,8,9,10] def gen_func(nums): for n in nums: yield n*n my_gen = gen_func(nums) print(list(my_gen))
c9432a9c83d802bab1735c10df0cd8ae3899c4f5
adilkhash/yandex-webinar-decorators
/method_decorators.py
720
3.6875
4
def method_decorator(name, func): def wrapper(cls): def _dec(*args, **kwargs): instance = cls(*args, **kwargs) if hasattr(instance, name): method = getattr(instance, name) setattr(instance, name, func(method)) return instance return _dec return wrapper def decorator(func): def wrapper(*args, **kwargs): print(f'calling method: {func.__name__}') return func(*args, **kwargs) return wrapper @method_decorator(name='hello', func=decorator) class MyClass: def say(self, msg): print(msg) def hello(self): return f'{self.__class__.__qualname__}' x = MyClass() print(x.hello())
cfe68b3f68c5b9b66d4599de2548ac5a8903b08d
enmorse/com.pythoncrashcourse2ndedition.favorite_languages.py
/main.py
476
3.703125
4
favorite_languages = { 'jen': ['python', 'ruby'], 'sarah': ['c'], 'edwin': ['ruby', 'go'], 'phil': ['python', 'haskel'], } for name, languages in favorite_languages.items(): if len(languages) > 1: print(f"\n{name.title()}'s favorite languages " f"are: ") elif len(languages) <= 1: print(f"\n{name.title()}'s favorite language " f"is: ") for language in languages: print(f"\t{language.title()}")
5830c5044839f32b6b548d814d400ed01f537d01
gabrielmusker/UrGame
/UrGame.py
1,088
3.9375
4
""" This is a Python script for running the ancient game of Ur. As I write this on 05/07/2020, before actually coding anything, I hope it's not going to be too complicated, but then again, you never know... """ from numpy.random import binomial def roll_dice(): """ In Ur, instead of rolling one die (such as a D6, for example), you roll four D4s, each of which has two dotted corners and two blank corners. Your roll is then the sum of the number of dotted corners that land upwards. Probabilistically, this is the equivalent of flipping four fair coins and taking your roll to be the number of heads; in other words, the dice rolls follow a Binomial(4, 0.5) distribution (as opposed to a normal D6 dice roll, which follows a Uniform(1/6) distribution). Explicitly, the distribution is as follows: P(X = 0) = 0.0625 P(X = 1) = 0.25 P(X = 2) = 0.375 P(X = 3) = 0.25 P(X = 4) = 0.0625 Note here that X represents the roll outcome, which this function returns. """ return int(binomial(4, 0.5, 1))
9f228d157b8e58b9ff30e15d19b08a4256c31e5d
xeki/MITx--Paython-1
/creditPayment.py
1,070
3.609375
4
def creditPayment(b,ai,mr): b = b/1.0 annualInterestRate = ai monthlyPaymentRate = mr monthlyInterestRate = ai / 12.0 for i in range(12): minimumMonthlyPayment = monthlyPaymentRate*b b = b - minimumMonthlyPayment b = b + b*monthlyInterestRate print ("Remaining Balance: "+ str(i) + " " + str(round(b,2))) return b def fixedMonthlyPayment(b,ai,mp): b = b/1.0 annualInterestRate = ai monthlyPayment = mp monthlyInterestRate = ai / 12.0 for i in range(12): b = b - monthlyPayment b = b + b*monthlyInterestRate #print ("Remaining Balance: " + str(i) + " " + str(round(b,2))) return b def findMinimumFixedPayment(b,ai): lb = b/12.0 ub = (b*((1.0+ai/12.0)**12)/12.0) mp = (lb + ub)/2.0 rb = fixedMonthlyPayment(b,ai,mp) while rb!=0: if rb > 0: lb = mp mp = (lb + ub)/2.0 elif rb < 0: ub = mp mp = (lb + ub)/2.0 rb = fixedMonthlyPayment(b,ai,mp) print("Minimum Fixed Payment : " + str(round(mp,2))) b = 42 ai = 0.2 mr = 0.04 creditPayment(b,ai,mr) findMinimumFixedPayment(320000,0.2) findMinimumFixedPayment(999999,0.18)
05c85616cc19ed986ec786b4ceda06ccbbc14263
Vlad-Kornev/PythonApplication12
/Strings.py
142
3.578125
4
str = input() substr = 'G' substr1 = 'C' p = str.upper().count(substr) p1 = str.upper().count(substr1) print (((p + p1) / len(str)) * 100)
cd9115ae031759129dd043eb92e61de58039d591
Vlad-Kornev/PythonApplication12
/Compare numbers 1.py
438
3.984375
4
a = int(input('введите первое число')) b = int(input('введите второе число')) c = int(input('введите третье число')) m = a if (m < b): m = b elif (m < c): m = c l = a if (l > b): l = b elif (l > c): l = c if (l < a < m) or (l < a <= m): ml = a elif (l <= b < m) or (l < b <= m): ml = b elif (l <= c < m) or (l < c <= m): ml = c print (m,'\n',l,'\n',ml)
d91cf3c448ab2e39430749f822e8a7c81e009648
Vlad-Kornev/PythonApplication12
/Cycle for.py
216
3.90625
4
a = int(input('укажите ширину квадрата из звездочек')) b = int(input('укажите длину квадрата из звездочек')) for i in range(b + 1): print ('*' * a)
764b1f8af7fee5c6d0d1707ab6462fc1d279be36
dadheech-vartika/Leetcode-June-challenge
/Solutions/ReverseString.py
863
4.28125
4
# Write a function that reverses a string. The input string is given as an array of characters char[]. # Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. # You may assume all the characters consist of printable ascii characters. # Example 1: # Input: ["h","e","l","l","o"] # Output: ["o","l","l","e","h"] # Example 2: # Input: ["H","a","n","n","a","h"] # Output: ["h","a","n","n","a","H"] # Hide Hint #1 # The entire logic for reversing a string is based on using the opposite directional two-pointer approach! # SOLUTION: class Solution(object): def reverseString(self, s): def helper(left,right): if left < right: s[left], s[right] = s[right], s[left] helper(left + 1, right - 1) helper(0, len(s) - 1)
fb89d7c5bf753cd3998c6622ef47610068b14f0e
majkelmichel/rock_paper_scissors
/game.py
2,476
3.953125
4
import random default_options = ['paper', 'scissors', 'rock', 'paper', 'scissors', 'rock'] def game(points, possible_inputs, lenght = 3): user_option = '' while user_option != '!exit': user_option = input() computer_option = possible_inputs[random.randint(0, len(possible_inputs)-1)] # print(possible_inputs) if user_option == "!exit": break if user_option == "!rating": print(f"Your rating: {points}") continue if user_option not in possible_inputs: print("Invalid input") continue ind_user = possible_inputs.index(user_option) # print(possible_inputs[ind_user + 1:ind_user + lenght // 2 + 1]) if computer_option == user_option: print(f"There is a draw ({user_option})") points += 50 elif possible_inputs[possible_inputs.index(computer_option)] in possible_inputs[ind_user + 1:ind_user + lenght // 2 + 1]: print(f"Sorry but computer chose {computer_option}") else: print(f"Well done. Computer chose {computer_option} and failed") points += 100 print("Bye!") return points def read_file(): rf = open('rating.txt') rate_list = rf.readlines() names = list() scores = list() for score in rate_list: names.append(score.split(' ')[0]) scores.append(score.split(' ')[1].rstrip('\n')) rf.close() return names, scores def write_file(sco, na): to_file = list() for i in range(len(na)): to_file.append(f'{na[i]} {sco[i]} \n') file = open('rating.txt', 'w') file.writelines(to_file) file.close() def append_file(name, points): file = open("rating.txt", 'a') file.write(f'{name} {points} \n') file.close() name = input("Enter your name: ") options = input() print("Okay, let's start") names, scores = read_file() if name in names: current_score = int(scores[names.index(name)]) print(f'Your current score is: {current_score}') new_player = False else: current_score = 0 new_player = True if len(options) == 0: current_score = game(current_score, default_options) else: options = options.split(",") len_op = len(options) options += options current_score = game(current_score, options, len_op) if new_player: append_file(name, current_score) else: scores[names.index(name)] = current_score write_file(scores, names)
ca042af11712f32c4b089da67c4a9dcfecd6000d
darkblaro/Python-code-samples
/strangeRoot.py
1,133
4.25
4
import math ''' getRoot gets a number; calculate a square root of the number; separates 3 digits after decimal point and converts them to list of numbers ''' def getRoot(nb): lsr=[] nb=math.floor(((math.sqrt(nb))%1)*1000) #To get 3 digits after decimal point ar=str(nb) for i in ar: lsr.append(int(i)) return lsr ''' getPower gets a number; calculate a power of the number; and converts the result to list of numbers ''' def getPower(num): lsp=[] num=int(math.pow(num,2)) ar=str(num) for i in ar: lsp.append(int(i)) return lsp ''' isStrange gets a number; calls to two functions above and gets from them two lists of numbers; after that compares two lists ''' def isStrange(nb): ls1=getRoot(nb) ls2=getPower(nb) for i1 in ls1: for i2 in ls2: if i1==i2: return True return False if __name__ == '__main__': number=int(input("Enter a number")) if isStrange(number): print(f'{number} has strange root') else: print(f'{number} doesn\'t have strange root')
a49eb3130dd7c87fda205c47b9f37efae061bdd3
darkblaro/Python-code-samples
/scientificNotation.py
578
3.8125
4
''' Created on Oct 12, 2018 Scientific Notation input: 9000 output: 9*10^3 @author: Roman Blagovestny ''' def scinotdown(n): cz=0 n=float(n) if n<1 and n>-1: while n<1 and n>-1: cz+=1 n*=10 return str(n)+"*10^-"+str(cz) if n>1 or n<-1: while n>=1 or n<-1: cz+=1 n/=10 return str(n*10)+"*10^"+str(cz-1) if __name__ == '__main__': try: inp=float(input("Enter a number: ")) print(scinotdown(inp)) except ValueError: print("Wrong input.")
3952065cb4a9111433a2cf9752df296c7b8d1483
Momo916/PythonFirst
/input&output.py
381
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- print('hello world!') print('Count', 'of 100 + 200 is:', 100 + 200) print('Hi, %s! You have %d emails!' % ('Momo', 8)) print('please type your name:') name = raw_input() print('hello,', name) abc = raw_input('hey, please type something') print('[format] your type is: {0}, another type {1}'.format(abc, 999)) print('I\'m \"OK\"!')
4af0217c44bbc9c8d997b772b2c3b4da410f31a7
Momo916/PythonFirst
/ifelse.py
346
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- age = 10 if age > 18: print('your age is', age) elif age > 10 and age <= 18: print('teenager') else: print('child') l = [] if l: print(True) else: print(False) str = input('please input a integer:') birth = int(str) if birth > 2000: print('00后') else: print('00前')
4e94792683d6e758ede916d8fce49f9e75c8f6a1
LuisC137/Python
/02_AI/01_Explore_Exploit_Dilema/comparing_epsilons.py
1,677
3.6875
4
""" Author: Luis_C-137 First example to compare epsilon greedy """ import numpy as np import matplotlib.pyplot as plt class Bandit: def __init__(self,m): self.m = m self.mean = 0 self.N = 0 def pull(self): return np.random.rand() + self.m def update(self, x): self.N += 1 self.mean = (1 -1.0/self.N) * self.mean + 1.0 / self.N * x def run_experiment(m1,m2,m3,eps,N): bandits = [Bandit(m1), Bandit(m2), Bandit(m3)] data = np.empty(N) for i in range(N): # epsilon greedy p = np.random.random() if p < eps: j = np.random.choice(3) else: j = np.argmax([b.mean for b in bandits]) x = bandits[j].pull() bandits[j].update(x) # for the plot data[i] = x cumulative_average = np.cumsum(data) / (np.arange(N) + 1) # plot moving average ctr plt.title('Epsilon = '+str(eps)) plt.plot(cumulative_average) plt.plot(np.ones(N) * m1) plt.plot(np.ones(N) * m2) plt.plot(np.ones(N) * m3) plt.legend() plt.xscale('log') plt.show() for b in bandits: print(b.mean) return cumulative_average def main(): print("\n\n---------------------") print("And so it begins...\n\n\n") c1 = run_experiment(1.0,2.0,3.0,0.1,10000) c05 = run_experiment(1.0,2.0,3.0,0.05,10000) c01 = run_experiment(1.0,2.0,3.0,0.01,10000) plt.title('Log scale plot') plt.plot(c1,label='eps = 0.1') plt.plot(c05,label='eps = 0.05') plt.plot(c01,label='eps = 0.01') plt.legend() plt.xscale('log') plt.show() plt.title('Linear plot') plt.plot(c1, label='eps = 0.1') plt.plot(c05, label='eps = 0.05') plt.plot(c01, label='eps = 0.01') plt.legend() plt.show() if __name__ == '__main__': main() else: print("Importing module {}".format(__name__))
dab8cc7bf07b1298e550097e94f6c9b9b31457be
ImmanuelXIV/med_cnn
/train_cnn.py
6,288
3.5
4
# Main draft to run the CNN on the medical data set from sklearn.cross_validation import KFold import utils import tensorflow as tf import random import pickle # ToDo: # implement more text pre-processing (see utils.py -> check which words are not recognized by word2vec model) # experiment with network architecture (e.g. number and size of layers, to get feeling what works) # implement final grid-search with diff. hyper parameters # report best setup for data and store results # Set parameters num_iter = 2000 # number of iterations per k-fold cross validation n_gram = 3 # try different n-grams: 1, 2, 3, 4, 5 batch_size = 2 # how many sentences to feed the network at once num_folds = 2 # how many folds in k-fold-cross-validation data_subset = 8 # create a subset of size data_subset (get results faster) eval_acc_every = 10 # in the training: evaluate the test accuracy ever X steps num_classes = 5 # how many different classes exist? keep_probability = 0.5 # this is the dropout (keep) value for the training of the CNN # ToDo: Download the German word2vec model (700MB, link) and set the path accordingly # https://tubcloud.tu-berlin.de/public.php?service=files&t=dc4f9d207bcaf4d4fae99ab3fbb1af16 model = "/home/immanuel/ETH/data/german.model" diagnoses = "/home/immanuel/ETH/med_cnn/sample10.txt" # this is a txt file, where each line is a diagnosis labels = "/home/immanuel/ETH/med_cnn/sample10_lables.txt" # this is the corresponding txt file, 1 class in each line # Since padding='VALID' for the filter, dimensionality has to be reduced reduce_dim = n_gram - 1 # Pre-process (clean, shuffle etc.) and load the medical data (respectively a subset of size data_subset) data, labels, sequence_length = utils.load_data(model, diagnoses, labels, data_subset, num_classes) # Initiate Tensorflow session sess = tf.InteractiveSession() # Create placeholders # sequence_length = max word length of diagnoses (if diagnose is shorter -> augmented to max size with "PAD" word) # 300 is dimensionality of each word embedding by pre-trained word2vec model on German Wikipedia data x = tf.placeholder("float", shape=[None, sequence_length, 300, 1]) y_ = tf.placeholder("float", shape=[None, num_classes]) # Initialize variables sess.run(tf.initialize_all_variables()) def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='VALID') # do not change VALID # First Convolutional Layer W_conv1 = weight_variable([n_gram, 300, 1, 32]) b_conv1 = bias_variable([32]) # Convolve with the weight tensor, add the bias, apply the ReLU function h_conv1 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1) # Densely Connected Layer # reduce_dim = 3-gram -1 = 2 W_fc1 = weight_variable([(sequence_length-reduce_dim)*32, 1024]) b_fc1 = bias_variable([1024]) # Reshape input for the last layer h_pool2_flat = tf.reshape(h_conv1, [-1, (sequence_length-reduce_dim)*32]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # Dropout keep_prob = tf.placeholder("float") h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) # Readout Layer (FC -> 5 neurons) W_fc2 = weight_variable([1024, num_classes]) b_fc2 = bias_variable([num_classes]) # Apply softmax y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # Train and Evaluate the Model cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) sess.run(tf.initialize_all_variables()) print('Perform cross-validation...') data_size = len(labels) print("Data Size: %d" % data_size) kf = KFold(data_size, n_folds=num_folds, shuffle=False) # Store final accuracy of different folds count = 0 train_accuracy_fold = [] train_accuracy_total = [] test_accuracy_final = [] for train_index, test_index in kf: # Initialize variables sess.run(tf.initialize_all_variables()) train_accuracy_fold = [] # Split in train and test set count += 1 print("TRAIN and TEST in Fold: %d" % count) x_train, x_test = data[train_index], data[test_index] y_train, y_test = labels[train_index], labels[test_index] # Check shape of arrays # print("Shape of arrays: ") # print(x_train.shape) # print(y_train.shape) # Start training loop for i in range(num_iter): # Set batch size (how many diff. diagnoses presented at once) indices = random.sample(xrange(len(x_train)), batch_size) batch = x_train[indices] ybatch = y_train[indices] if i % eval_acc_every == 0: # evaluate every X-th training step to monitor overfitting # run the evaluation step train_accuracy = accuracy.eval(feed_dict={ x: batch, y_: ybatch, keep_prob: 1.0}) # in evaluation dropout has to be 1.0 # save value train_accuracy_fold.append(train_accuracy) print("step %d, training accuracy %g" % (i, train_accuracy)) # run the training step train_step.run(feed_dict={x: batch, y_: ybatch, keep_prob: keep_probability}) # in training dropout can be set test_acc = accuracy.eval(feed_dict={ x: x_test, y_: y_test, keep_prob: 1.0}) # Store train_accuracy_total.append(train_accuracy_fold) test_accuracy_final.append(test_acc) print("TEST ACCURACY %g" % test_acc) print("\nFINAL TEST ACCURACY per k-fold: ") print(test_accuracy_final) print("\nTRAIN ACCURACIES all: ") print(train_accuracy_total) # Store TRAIN results in pickle files """ f = open('./Results/' + str(data_subset) + '_' + str(NIter) + '_' + str(N_gram) + '_' + str(NFolds) + '_results_Train.pckl', 'w') pickle.dump(train_accuracy_total, f) f.close() # Store TEST results in pickle files f = open('./Results/' + str(data_subset) + '_' + str(NIter) + '_' + str(N_gram) + '_' + str(NFolds) + '_results_Test.pckl', 'w') pickle.dump(test_accuracy_final, f) f.close() """
2733446c456f17e625f3bbe5ceab76b39697bf46
namancg/LineComparisonPython
/LineComparison.py
608
3.921875
4
import math import random import cmp def getLength(x1, x2, y1, y2): val = ((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)) result = math.sqrt(val) return result x1 = random.random() * 100 x2 = random.random() * 100 y1 = random.random() * 100 y2 = random.random() * 100 x11 = random.random() * 100 x12 = random.random() * 100 y11 = random.random() * 100 y12 = random.random() * 100 l1 = getLength(x1, x2, y1, y2) l2 = getLength(x11, x12, y11, y12) print(l1) print(l2) if l1==l2: print("BOTH ARE EQUAL") elif l1 > l2: print("LINE 1 IS GREATER") else: print("LINE 2 IS GREATER")
0659a2fc05253f54b53a201848fc055ff2388c5d
jezhang2014/2code
/leetcode/LongestCommonPrefix/solution.py
571
3.5
4
# -*- coding:utf-8 -*- class Solution: # @return a string def longestCommonPrefix(self, strs): if not strs: return '' prefix = [] first = strs[0] if not first: return '' strs = strs[1:] for i, c in enumerate(first): for s in strs: if not s or i >= len(s): break if s[i] != c: break else: prefix.append(c) continue break return ''.join(prefix)
4b09c65f9d5c4ccf5e3b80a277e88e263c85ed99
jezhang2014/2code
/leetcode/LengthofLastWord/solution.py
241
3.515625
4
# -*- coding:utf-8 -*- class Solution: # @param s, a string # @return an integer def lengthOfLastWord(self, s): w_list = filter(None, s.split()) if not w_list: return 0 return len(w_list[-1])
b9340da85f495cf9813c4b6d49f76629236aa83d
chskof/HelloWorld
/chenhs/module/demo3_fromImport.py
1,125
3.515625
4
""" Python 的 from 语句让你从模块中导入一个指定的部分到当前命名空间中: from modname import name1[, name2[, ... nameN]] """ from myModule import myPrint, myPrint2 myPrint("abc") myPrint2("def") """ 把一个模块的所有内容全都导入到当前的命名空间也是可行的,只需使用如下声明: from modname import * 一个模块只会被导入一次,不管你执行了多少次import。这样可以防止导入模块被一遍又一遍地执行 """ """ __name__属性: 一个模块被另一个程序第一次引入时,其主程序将运行。如果我们想在模块被引入时,模块中的某一程序块不执行, 我们可以用__name__属性来使该程序块仅在该模块自身运行时执行。 每个模块都有一个__name__属性,当其值是'__main__'时,表明该模块自身在运行 if __name__ == '__main__': print('程序自身在运行') else: print('我来自另一模块') dir() 函数 内置的函数 dir() 可以找到模块内定义的所有名称: dir(myModule) dir() #得到当前模块中定义的属性列表 """ print(dir())
4b98478ef980e2ca1c207d4e1814e2d3f92071a0
chskof/HelloWorld
/chenhs/variable_test.py
3,045
4.1875
4
""" 变量就像一个小容器,变量保存的数据可以发生多次改变,只要程序对变量重新赋值即可 Python是弱类型语言,弱类型语言有两个典型特征: 1、变量无须声明即可直接赋值:对一个不存在的变量赋值就相当于定义了一个新变量 2、变量的数据可以动态改变:同一个变量可以一会儿被赋值为整数值,一会儿可以赋值为字符串 """ a = 5 b = "hello" a = "mike" c = 100 # 数字的类型是int 字符串的类型是str # 如果想查看变量的类型,可以使用python内置函数type() type(c) type(b) print("c的类型:", type(c)) print("b的类型:", type(b)) """ 变量(标识符)的命名规则: Python语言的变量必须以字母、下划线_开头,不能以数字开头,后面可以跟任意数目的字母、数字和下划线 变量不可以是Python关键字 变量不能包含空格 变量可以用驼峰命名法或者下划线区分每个单词首字母 变量区分大小写 """ abc_xyz = 1 abc2 = "hello" userName = "Jack" _teachName = "chen" userFirstName = "chen" # 驼峰命名法 第一个单词首字母小写 后面单词首字母大写 user_first_name = "chen" # abc#xyz 不合法 变量名不能出现井号 # 1abc 不合法 变量名不能以数字开头 """ Python还包含一系列关键字和内置函数,避免使用他们作为变量名 如果开发者尝试使用关键字作为变量名,python解释器会报错 如果开发者使用内置函数名字作为变量名,Python解释器不会报错,但是会把该内置函数覆盖导致该内置函数无法使用 Python关键字: 'False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield' 保留字即关键字,我们不能把它们用作任何标识符名称。Python 的标准库提供了一个 keyword 模块,可以输出当前版本的所有关键字: >>> import keyword >>> keyword.kwlist python内置函数: abs() str() print() type() input() open() divmod() all() enumerate() int() ord() staticmethod() any() eval() isinstance() pow() sum() basestring() execfile() issubclass() super() bin() file() iter() property() tuple() bool() filter() len() range() bytearray() float() list() raw_input() unichr() callable() format() locals() reduce() unicode() chr() frozenset() long() reload() vars() classmethod() getattr() map() repr() xrange() cmp() globals() max() reverse() zip() compile() hasattr() memoryview() round() __import__() complex() hash() min() set() delattr() help() next() setattr() dict() hex() object() slice() dir() id() oct() sorted() ... """
c0c9303b5127be01a420a033e2d0b6dcbc9e1f2d
chskof/HelloWorld
/chenhs/object/demo7_Override.py
470
4.21875
4
""" 方法重写(覆盖): 如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法 """ # 定义父类 class Parent: def myMethod(self): print('调用父类方法') class Child(Parent): def myMethod(self): print('调用子类方法') c = Child() # 创建子类对象 c.myMethod() # 调用子类重写的方法 super(Child, c).myMethod() # 用子类对象调用父类已被覆盖的方法
c0ae62b93519caa0ba33234b88721dd5800301e0
GSvensk/OpenKattis
/MediumDifficulty/Union-find/__init__.py
1,433
3.84375
4
class Node: def __init__(self, nummer): self.nummer = int(nummer) self.friends = set() def merge(self, b): #self.friends = self.friends.union(b.get_friends()) self.friends = self.friends|b.friends b.friends = self.friends self.friends.add(b) b.friends.add(self) def friends_with(self, b): return b in self.friends def print_friends(self): print("node: {}".format(self.nummer)) for i in self.friends: print(i.nummer) tmp = input().split() noofelements = int(tmp[0]) operations = int(tmp[1]) nodes = [] numbers = set() for i in range(0, operations): tmp = input().split() query = tmp[0] if int(tmp[1]) in numbers: for j in nodes: if j.nummer == int(tmp[1]): a = j else: numbers.add(int(tmp[1])) a = Node(int(tmp[1])) nodes.append(a) if int(tmp[2]) in numbers: for k in nodes: if k.nummer == int(tmp[2]): b = k else: numbers.add(int(tmp[2])) b = Node(int(tmp[2])) nodes.append(b) if query == '?': if a.friends_with(b): print('yes') elif b.friends_with(a): print('yes') elif a == b: print('yes') else: print('no') else: #a.add_friend(b) #b.add_friend(a) a.merge(b)
845388d14e5b586b358933391fdc9db6e3431363
GSvensk/OpenKattis
/LowDifficulty/cups.py
400
3.515625
4
class Cup: def __init__(self, color, size): self.color = color self.size = size cases = int(input()) cups = [] for i in range(cases): tmp = input().split() if tmp[0].isnumeric(): cups.append(Cup(tmp[1], float(tmp[0])/2)) else: cups.append(Cup(tmp[0], float(tmp[1]))) cups.sort(key=(lambda x: x.size)) list(map((lambda x: print(x.color)), cups))
1a467f18bb89c8d1228d6aa2462ba8df7df87bef
pnll/Natural-Language-Processing-with-Python-Cookbook
/Chapter02/recipe2.py
486
3.875
4
str = 'NLTK Dolly Python' print('다음의 인덱스에서 끝나는 부분 문자열:',str[:4]) print('다음의 인덱스에서 시작하는 부분 문자열:',str[11:] ) print('부분 문자열:',str[5:10]) print('복잡한 방식의 부분 문자열:', str[-12:-7]) if 'NLTK' in str: print('NLTK를 찾았습니다.') replaced = str.replace('Dolly', 'Dorothy') print('대체된 문자열:', replaced) print('각 문자(character) 액세스:') for s in replaced: print(s)
1b63ffbac749549831c596f5c0864124e7546407
pnll/Natural-Language-Processing-with-Python-Cookbook
/Chapter04/recipe3.py
635
3.703125
4
import re #search for literal strings in sentence patterns = [ 'Tuffy', 'Pie', 'Loki' ] text = 'Tuffy eats pie, Loki eats peas!' for pattern in patterns: print('"%s"에서 "%s" 검색 중 ->' % (text, pattern),) if re.search(pattern, text): print('찾았습니다!') else: print('찾을 수 없습니다!') #search a substring and find it's location too text = 'Diwali is a festival of lights, Holi is a festival of colors!' pattern = 'festival' for match in re.finditer(pattern, text): s = match.start() e = match.end() print('%d:%d에서 "%s"을(를) 찾았습니다.' % (s, e, text[s:e]))
078f5695b9b0db0027ae3ce9cdd059d0c2e93e78
knowledgeftw/twitter_cli
/oauth_helpers.py
2,583
3.78125
4
#!/usr/bin/python # # Contains code taken from the python-oauth2 README.md here: # # import urlparse import oauth2 import os class OauthToken(object): """ This is a simple class which we can pickle and restore. """ def __init__(self, key, secret): self.key = key self.secret = secret class OauthUrls(object): """ Represents the three URLs that you need to perform an oauth exchange. """ def __init__(self, request_token_url, auth_token_url, access_token_url): self.request_token_url = request_token_url self.auth_token_url = auth_token_url self.access_token_url = access_token_url def authenticate(urls, consumer_key, consumer_secret): consumer = oauth2.Consumer(consumer_key, consumer_secret) client = oauth2.Client(consumer) # Step 1: Get a request token. This is a temporary token that is used for # having the user authorize an access token and to sign the request to obtain # said access token. resp, content = client.request(urls.request_token_url, "GET") if resp['status'] != '200': raise Exception("Invalid response %s." % resp['status']) request_token = dict(urlparse.parse_qsl(content)) # Step 2: Redirect to the provider. Since this is a CLI script we do not # redirect. In a web application you would redirect the user to the URL # below. print "Go to the following link in your browser:" print "%s?oauth_token=%s" % (urls.auth_token_url, request_token['oauth_token']) print # After the user has granted access to you, the consumer, the provider will # redirect you to whatever URL you have told them to redirect to. You can # usually define this in the oauth_callback argument as well. accepted = 'n' while accepted.lower() == 'n': accepted = raw_input('Have you authorized me? (y/n) ') oauth_verifier = raw_input('What is the PIN? ') # Step 3: Once the consumer has redirected the user back to the oauth_callback # URL you can request the access token the user has approved. You use the # request token to sign this request. After this is done you throw away the # request token and use the access token returned. You should store this # access token somewhere safe, like a database, for future use. token = oauth2.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(oauth_verifier) client = oauth2.Client(consumer, token) resp, content = client.request(urls.access_token_url, "POST") access_token = dict(urlparse.parse_qsl(content)) token = OauthToken(access_token['oauth_token'], access_token['oauth_token_secret']) return token
46b20781f3cf77eb9716479f61c3b2b4034ee96f
CodingPanda93/Full_Portfolio
/PythonStack/Fundamentals/stars.py
191
3.640625
4
x = [4, 6, 1, 3, 5, 7, 25] char = '' i = 0 def draw_stars(num_list): for num in num_list: char = '' for i in range(num): char += '*' print char y = draw_stars(x) print y
cba7bb8aacc820c0fd03675aefc9e2bcfd411a1e
jtagoeASC/Allstar-Code
/list.py
364
3.546875
4
myList=[10,11,12,13,14,15,16,17,18,19,20] myOtherList=[0,0,0,0,0] myEmptyList=[] myOtherList=[] i=0 while i<5: myOtherList print(myOtherList) i=i+1 theFifthList=["a",5,"doodle",3,10] print(len(theFifthList)) theFifthList.append(90) print(theFifthList) theFifthList[0]=8.4 print(theFifthList) theFifthList.insert(0,98) print(theFifthList)
37bcf019ef4658abd5629a3d9cf8ad22cd70cf39
ioef/PyLinuxTools
/wc.py
632
3.921875
4
#!/usr/bin/env python ''' Creation of the word count Linux utility in python ''' import sys def printStats(filename): #data = sys.stdin.read() with open(filename,'r') as data: data = data.read() chars = len(data) words = len(data.split()) lines = len(data.split('\n')) print "\nThe file includes {0} characters, {1} words and {2} lines".format(chars,words,lines) def main(): if len(sys.argv) !=2: print "Wrong number of arguments. Exiting..." print "usage: wc.py filename" sys.exit(1) printStats(sys.argv[1]) if __name__ =='__main__': main()
11169db02f6dd002ea98668b9c15bfcc44686693
DiegoTc/ProyectoCompiladoresI
/MiniPython/Ejemplos/sample2.py
111
3.671875
4
class ciclos: def main: for x in 1 ... 10+a: if (x + 2): y = y + x print y else: print x
535e5ec1eb19d397ebad276759074ae847627f7a
nikky1731/spell-corrector
/spellcorrector.py
2,341
3.96875
4
#A simple spelling corrector python program using tkinter module from tkinter import * from textblob import TextBlob from tkinter.messagebox import * def select(event): inputword.get() def clearall(): inputword.delete(0,END) correctedword.delete(0,END) def correction(): input_word = inputword.get() blob_obj = TextBlob(input_word) corrected_word = str(blob_obj.correct()) correctedword.insert(10,corrected_word) if input_word == '' : correctedword.delete(0,END) def exit(): res = askyesno('Confirm', 'Are you sure you want to exit?') if res: root.destroy() else: pass root =Tk() root.configure(bg = 'BLACK') root.title("spell corrector") root.resizable() root.geometry("500x450+0+0") headlabel =Label(root, text ="Welcome to spell corrector application",font=("arial",12,"bold"),bd=2,bg ='whitesmoke',fg='black') headlabel.grid(row=0,column=1,padx=10,pady=10) fakelabel = Label(root,bg ='black',width =40) fakelabel.grid(row=1,column = 1,padx=10,pady=10) inputlabel = Label(root,text = "Input word",bg='white',fg="black",font=("arial",10,"bold"),bd=2,relief = "flat") inputlabel.grid(row=2,column = 0,padx=5,pady=5) correctedwordlabel = Label(root, text ="corrected word",bg="white",fg="black",font=("arial",10,"bold"),bd = 2, relief = "flat") correctedwordlabel.grid(row=4,column=0,padx=10,pady=5) inputword = Entry(root, font=('arial', 18, 'bold'), bd=8, relief= 'flat', width=10) inputword.grid(row=2,column = 1,padx=10,pady=10) correctedword = Entry(root, font=('arial', 18, 'bold'), bd=8, relief= 'flat', width=10) correctedword.grid(row=4,column = 1,padx=10,pady=10) buttoncorrection = Button(root,text = "correction",fg="black",bg = "red",relief = GROOVE,width=12,command = correction) buttoncorrection.grid(row=3,column =1,padx=5,pady=5) buttonclear = Button(root,text = "clear",fg="black",bg = "red",relief = GROOVE,width=10,command = clearall) buttonclear.grid(row=5,column =1,padx=5,pady=5) buttonexit = Button(root,text = "exit",fg="black",bg = "red",relief = GROOVE,width=8,command = exit) buttonexit.grid(row=6,column =1,padx=5,pady=5) def enter_function(event): buttoncorrection.invoke() def enter_delete(event): buttonclear.invoke() root.bind('<Return>', enter_function) root.bind('<Delete>', enter_delete) root.mainloop()
af3c29d2b624127b718f1be930ceb82566b898fc
arfu2016/nlp
/nlp_models/algorithm/longestPalinDromicSubstring/LongestPalindromicSubstring.py
2,146
3.734375
4
""" @Project : text-classification-cnn-rnn @Module : LongestPalindromicSubstring.py @Author : Deco [[email protected]] @Created : 5/31/18 1:16 PM @Desc : 5. Longest Palindromic Substring Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example: Input: "cbbd" Output: "bb" 自己写的代码: 遍历字符串,从中间往两边查找,如果遇到字符不一致的情况则停止查找,跳入下一个字符串。 运行时间1262 ms """ class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ n = len(s) res = "" for i, char in enumerate(s): tmp1 = tmp2 = "" #odd left = right = i while 1: if left is -1 or right == n or s[left] is not s[right]: tmp1 = s[left+1:right] break else: left -= 1 right += 1 #even left = i right = i + 1 while 1: if left is -1 or right == n or s[left] is not s[right]: tmp2 = s[left+1:right] break else: left -= 1 right += 1 #compare odd and even str if len(tmp2) > len(tmp1): tmp = tmp2 else: tmp = tmp1 #compare res and tmp str if len(tmp) > len(res): res = tmp return res ''' 受讨论区启发后写的代码: 其实思路是一样的,但是用helper函数把代码变得更加简洁 ''' class Solution2: def longestPalindrome1(self, s): res = "" for i in range(len(s)): res = max(self.helper(s,i,i), self.helper(s,i,i+1), res, key=len) return res def helper(self,s,l,r): while 0<=l and r < len(s) and s[l]==s[r]: l-=1; r+=1 return s[l+1:r]
19cce1157ae01ec838eeb6f290081681339c6f7e
eminetuba/7.hafta-odevler
/1. soru.py
3,026
3.96875
4
# telefon rehberi uygulamasi # Bu odevde bir telefon rehberi simulasyonu yapmanizi istiyoruz. # Program acildiginda kullaniciya, rehbere kisi ekleme, kisi silme, kisi isim ya da tel bilgisi guncelleme, # rehberi listeleme seceneklerini sunun. Kullanicinin secimine gore gerekli inputlarla programinizi sekillendirin. # Olusturulan rehberi bir dosyaya kaydedin. # Rehberi olustururken sozlukleri kullanin. menu = ("""\nTELEFON REHBERIM 1. Rehbere isim ekle 2. Rehberden Kisi Sil 3. Rehber Guncelleme 4. Rehberi Listele 5. Cikis """) rehber = {} while True: print(menu) secim = input("Seciminiz:\t") if secim == "1": print("Not: Rehberde tekrarlayan isim olmamaktadir.") ad_soyad = input("Rehbere eklemek istediginiz kisinin adi soyadi:") tel = input("Rehbere eklemek istedigini kisinin tel numarasi ") rehber[ad_soyad.lower()] = tel continue elif secim == "2": sil = (input("Silmek istediginiz kisinin adini-soyadi :")).lower() for k in rehber.keys(): if k == sil: rehber.pop(sil) print(sil.upper(), " adli kisi silindi...") break else: print("Bu ad-soyad bulunamadi..") break continue elif secim == '3': guncelle = (input("Guncellemek istediginiz \nKisinin adi soyadi ise 1,\nTelefon numarasi ise 2'ye basiniz: ")) if guncelle == "1": ad_soyad = input("Rehberde guncellemek istediginiz kisinin adi soyadi:").lower() for k in rehber.keys(): if k == ad_soyad: tel = rehber[ad_soyad] rehber.pop(ad_soyad) ad_soyad2 = input("Guncel adi-soyadini giriniz: ").lower() rehber[ad_soyad2] = tel print("Basariyla guncellendi...\n") break else: print("Yanlis giris yaptiniz..\n") break continue elif guncelle == "2": ad_soyad = input("Rehberde guncellemek istediginiz kisinin adi soyadi:").lower() for k in rehber.keys(): if k == ad_soyad: tel = input("Kisinin guncel tel numarasi: ") rehber[ad_soyad] = tel print("Basariyla guncellendi...\n") break else: print("Yanlis giris yaptiniz..\n") break continue elif secim == '4': for k, v in rehber.items(): print("\nAdi-Soyadi: {}\t\tTelefon Numarasi:{}".format(k.upper(), v)) elif secim == "5": print("Cikis Yapiliyor...") break else: print("Yanlis secim yaptiniz lutfen tekrar deneyin...\n") continue dosya = open("telefonrehberi.txt", "w") dosya.write("Ad-Soyad\tTelefon Numarasi\n") for k, v in rehber.items(): a = "{}\t{}\n".format(k.upper(), v.upper()) dosya.write(a) dosya.close()
a0c30fce1801dfc18ce77ce4cce562962dcd6cfa
ayoolaao/school-projects-2017
/AyoolaAbimbola_HW6.py
3,407
3.703125
4
# Ayoola Abimbola ''' List of functions: index(fname, letter) - accepts filename and letter as args rollDice() and crap() STUDENT() ''' ### Problem 1 from string import punctuation def index(fname, letter): totalLines = len(open(fname, 'r').readlines()) - 1 infile = open(fname, 'r') wordCount = 0 lineNumber = 0 storageDict = {} letter = letter.lower() space = ' ' * len(punctuation) transTable = str.maketrans(punctuation, space) while lineNumber <= totalLines: line = infile.readline() line = line.lower() line = line.translate(transTable) lineNumber += 1 line = line.split() for word in line: if word[0] == letter: if word not in storageDict: wordCount += 1 storageDict[word] = [lineNumber] else: wordCount += 1 storageDict[word] = storageDict[word] + [lineNumber] infile.close() for key, value in sorted(storageDict.items()): value = set(value) value = list(value) value = sorted(value) print('{:20}{}'.format(key, str(value)[1:-1])) print() print('There are {} lines in the book.'.format(lineNumber)) print('There are {} words that begin with "{}".'.format(wordCount, letter)) return ''' #filename = 'Pride_and_Prejudice.txt' filename = 'The_Tempest.txt' let = 'a' index(filename, let) ''' ### Problem 2 from random import randint def rollDice(): die1 = randint(1, 6) die2 = randint(1, 6) return die1 + die2 def crap(): status = { 'I win': (7, 11), 'I lose': (2, 3, 12) } initialRoll = rollDice() print(initialRoll) for k, v in status.items(): if initialRoll in v: print(k) return status['I win'] = initialRoll status['I lose'] = 7 while True: # print(status) roll = rollDice() print(roll) for k, v in status.items(): if roll == v: print(k) return #crap() ### Problem 3 def STUDENT(): studentRecords = {} while True: firstName = input('First name: ') if firstName == '': break lastName = input('Last name: ') if lastName == '': lastName = input('Last name is required. (return again to quit program):') if lastName == '': break name = (lastName, firstName) if name in studentRecords: update = input('{} has ID {}. Update? (y or n): '.format(name, studentRecords[name])) if update == 'y' or update == 'Y' or update == 'yes' or update == 'YES' or update == 'Yes': studentRecords[name] = input('Student ID: ') else: continue else: studentID = input('Student ID: ') if len(studentID) != 7: studentID = input('Re-enter Student ID (must be 7-digits): ') if studentID == '': break studentRecords[name] = studentID print('\nContents of dictionary:') if studentRecords == {}: print('There is no record') else: for k, v in studentRecords.items(): print('{}, {} has studentID {}'.format(k[0], k[1], v)) return #STUDENT()
5141b2f70ee8ff1528ea633940007712c4d64b71
Ortovoxx/NCC2019
/Functions/Function - Key mapping.py
1,021
3.828125
4
def substitionKeyCipher(userCipherText,userKey): #maps a ciphertext to plaintext according to the key given to it cipherText = convertToASCII(list(userCipherText)) #Converting cipher to numbers key = convertToASCII(list(userKey)) #Converting key to numbers def switchChar(cipherChar): #Switches a single character from its chiphertext to its plaintext alphaPerm = 0 newChar = 0 while alphaPerm < len(alphabetASCII): #as it goes through a letter it changes it if cipherChar == key[alphaPerm]: newChar = alphabetASCII[alphaPerm] alphaPerm = alphaPerm + 1 return newChar textPerm = 0 switchedCipher = [] while textPerm < len(cipherText): #Goes through each character one by one and sends to the function which converts cipher to plain switchedCipher.append(switchChar(cipherText[textPerm])) textPerm = textPerm + 1 switchedCipherStr = "".join(convertToCHARACTER(switchedCipher)) return switchedCipherStr
1c4439c0dd9e504071d15a7ea8154b0f31e8bb59
jarthurj/Python
/bankaccount.py
778
3.8125
4
class BankAccount: def __init__(self, int_rate=.01, balance=0): self.balance = balance self.int_rate = int_rate def deposit(self, amount): self.balance += amount return self def withdraw(self, amount): self.balance -= amount return self def display_account_info(self): print("Balance:",self.balance,"Interest Rate:",self.int_rate) return self def yield_interest(self): if self.balance > 0: interest = self.balance * self.int_rate self.balance += interest return self account1 = BankAccount() account2 = BankAccount() account1.deposit(100).deposit(100).deposit(100).withdraw(100).yield_interest().display_account_info() account2.deposit(200).deposit(200).withdraw(50).withdraw(50).withdraw(50).withdraw(50).yield_interest().display_account_info()