blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
5fbb6fad65cab887d9a8061f108bba0631388b8d
DMarchezini/UriOnlineJudge-Python
/Uri1036.py
543
3.84375
4
""" Exemplos de Entrada Exemplos de Saída 10.0 20.1 5.1 R1 = -0.29788 R2 = -1.71212 0.0 20.0 5.0 Impossivel calcular 10.3 203.0 5.0 R1 = -0.02466 R2 = -19.68408 10.0 3.0 5.0 Impossivel calcular """ variaveis = input().split(" ") a, b, c = variaveis a = float(a) b = float(b) c = float(c) if a == 0 or (b ** 2 - (4*a*c)) < 0: print('Impossivel calcular') else: R1 = (- b + (b ** 2 - 4 * a * c) ** (1/2))/(2 * a) R2 = (- b - (b ** 2 - 4 * a * c) ** (1/2))/(2 * a) print(f'R1 = {format(R1, ".5f")}\nR2 = {format(R2, ".5f")}')
440ce870c626ba92489478877535f03bfc88943d
Mahedi250/Artificial-Intelligence
/Encryption/Encryption.py
2,217
3.890625
4
securityCode = {} matrixList = [] encodedMatrix = [] pattern = [ [1,2,3], [1,1,2], [0,1,2] ] #This method with Initialize the securityCode like 'A':1, 'B':2... 'Z':26 def initializeCode(): code = 1 for i in range(65,91): securityCode[chr(i)] = code code += 1 #This method will find the character against a values def findChar(value): for key in securityCode: if securityCode[key] is value: return key #This method will find the value against a character def findValue(keyvalue): for key in securityCode: if key is keyvalue: return securityCode[key] #Matrix Multiplication def matrixMultiplication(mat1,mat2): mat = [] for i in range(len(mat1)): total = 0 for j in range(len(mat2)): total += mat1[i][j]*mat2[j] mat.append(total) return mat def isInvertable(): # total = 0 # total += pattern[0][0]* (pattern[1][1]*pattern[2][2] - pattern[2][1]*pattern[1][2]) # total -= pattern[0][1]* (pattern[1][0]*pattern[2][2] - pattern[2][0]*pattern[1][2]) # total += pattern[0][2]* (pattern[1][0]*pattern[2][1] - pattern[2][0]*pattern[1][1]) # if total is not 0: # return True # else: # return False for i in range(len(pattern)): for j in range(len(pattern[i])): if i is 0: print(pattern[i][j], '', end='') print() #Encryption def encryption(word): print('Message:',word) counter = 3 start = 0 end = 3 matrix = [] for c in word: matrix.append(findValue(c)) #print(matrix) while start < len(matrix): temp = matrix[start:end] if len(temp) is counter: matrixList.append(temp) else: for i in range(0,counter-len(temp)): temp.append(0) matrixList.append(temp) start += 3 end += 3 for mat in matrixList: encodedMatrix.append(matrixMultiplication(pattern,mat)) print('Original Matrix:',matrixList) print('Encrypted Matrix:',encodedMatrix) #decryption def decryption(): isInvertable() #MAIN FUNCTION initializeCode() encryption('CRYPTOGRAPHY') decryption()
d00c5dd8c996aaed2784a30a925122bee2a4ac9d
rafaeljordaojardim/python-
/basics/exceptions.py
1,891
4.25
4
# try / Except / Else / Finally for i in range(5): try: print(i / 0) except ZeroDivisionError as e: print(e, "---> division by 0 is not allowed") for i in range(5): try: print(i / 0) except NameError: # it doesn't handle ZeroDivisionError print("---> division by 0 is not allowed") for i in range(5): try: print(i / 1) except ZeroDivisionError: # it doesn't handle ZeroDivisionError print("---> division by 0 is not allowed") except NameError: print("---> division by 0 is not allowed") except ValueError: print("---> division by 0 is not allowed") # if it doesn't raise any exception try: print(4 / 2) except NameError: # it doesn't handle ZeroDivisionError print("---> division by 0 is not allowed") else: print("if it doesn't raise any exception") try: print(4 / 2) except NameError: # it doesn't handle ZeroDivisionError print("---> division by 0 is not allowed") finally: print("it executes anyway if it raises error or not") #Try / Except / Else / Finally - handling an exception when it occurs and telling Python to keep executing the rest of the lines of code in the program try: print(4/0) #in the "try" clause you insert the code that you think might generate an exception at some point except ZeroDivisionError: print("Division Error!") #specifying what exception types Python should expect as a consequence of running the code inside the "try" block and how to handle them else: print("No exceptions raised by the try block!") #executed if the code inside the "try" block raises NO exceptions finally: print("I don't care if an exception was raised or not!") #executed whether the code inside the "try" block raises an exception or not #result of the above block # Division Error! # I don't care if an exception was raised or not!
20bfa38708e9d8d75096cf8e60b48874eb9030f1
rafaeljordaojardim/python-
/advanced/itertools.py
703
3.65625
4
from itertools import * list1 = [1, 2, 3, 'a', 'b', 'c'] list2 = [101,102, 103, 'X', 'Y'] # chain get sequences and chains then together a = chain(list1, list2) for i in chain(list1, list2): print(i) list(chain(list1, list2)) # first value is the starting and the second is the step count(10, 2.5) for i in count(10, 2.5): if i <= 50: print(i) else: break # cycle - and it will print with no limit the sequence 11, 12, 13, 14, 15 a = range(11, 16) for i in cycle(a): print(i) # filterfalse - it is the oposite of filter, it print the false result filterfalse(lambda x: x < 5, [1, 2, 3, 4, 5, 6, 7]) # islice -> a = range(10) list3 = list(a) islice(a, 2, 9, 2)
700af91613cd9a2ee6667615f5a08e59f9d2da62
MrPer4ik/pythoniasa19fall
/assignment01a.py
1,490
4
4
""" Assignment 1-A ============== Write fuction that generates the text below; use at least variables and f-strings. For those who are already familiar with Python – write the best code you can to conform to the Zen of Python. """ def poem(): result = '' base = [["the house that Jack built", "lay in"], ["the malt", "ate"], ["the rat", "killed"], ["the cat", 'worried'], ["the dog", "tossed"], ["the cow with the crumpled horn", "milked"], ["the maiden all forlorn", "kissed"], ["the man all tattered and torn", 'married'], ["the priest all shaven and shorn", "waked"], ["the cock that crowed in the morn", "kept"], ["the farmer sowing his corn", 'is']] for i in range(len(base)): for j in range(i, 0, -1): if j == i: # print(f'This is {base[j][0]}', end='') result += f'This is {base[j][0]}' else: # print(f'That {base[j][1]} {base[j][0]}', end='') result += f'That {base[j][1]} {base[j][0]}' # print(',' if j > 1 else '') result += ',\n' if j > 1 else '\n' #print(f'This is {base[i][i]}.' if i == 0 else f'That {base[0][1]} {base[0][0]}.', end='\n\n') result += f'This is {base[i][i]}.\n\n' if i == 0 else f'That {base[0][1]} {base[0][0]}.\n\n' return result[:-1] if __name__ == '__main__': print(poem())
b5920d757099c82a445968a3ec820256906846e3
Ericmanh/cac_ham_python
/CacHamToanHoc/ham_time.py
235
3.796875
4
# Hàm time gồm clock và time from time import clock print("enter your name:", end="") start_time =clock() name = input() print("nhập name") elapsed = clock() - start_time print(name, "it took you", elapsed ,"second to repond")
7521cbf4b76c785fe8d0b78e837fba5cdf41cce1
evanlihou/msu-cse231
/clock.py
1,436
4.4375
4
""" A clock class. """ class Time(): """ A class to represent time """ def __init__(self, __hour=0, __min=0, __sec=0): """Constructs the time class. Keyword Arguments: __hour {int} -- hours of the time (default: {0}) __min {int} -- minutes of the time (default: {0}) __sec {int} -- seconds of the time (default: {0}) """ self.hour = __hour self.min = __min self.sec = __sec def __repr__(self): """Creates the shell representation of a time with proper formatting Returns: string -- the representation of the time """ outstr = "Class Time: {:0>2d}:{:0>2d}:{:0>2d}" return outstr.format(self.hour, self.min, self.sec) def __str__(self): """Creates the string representation of a time with proper formatting Returns: string -- the representation of the time """ outstr = "{:0>2d}:{:0>2d}:{:0>2d}" return outstr.format(self.hour, self.min, self.sec) def from_str(self, time_str): """Updates the Time in place with a given str Arguments: time_str {str} -- Time to convert with format hh:mm:ss """ time_lst = time_str.split(":") self.hour = int(time_lst[0]) self.min = int(time_lst[1]) self.sec = int(time_lst[2])
f5d77a708522b6febacc4c1e43704d1c63a2d07d
evanlihou/msu-cse231
/proj01.py
1,123
4.3125
4
########################################################### # Project #1 # # Algorithm # Prompt for rods (float) # Run conversions to other units # Print those conversions ########################################################### # Constants ROD = 5.0292 # meters FURLONG = 40 # rods MILE = 1609.34 # meters FOOT = 0.3048 # meters WALKING_SPEED = 3.1 # miles per hour # Take input and convert to float inline, then print rods = float(input("Input rods: ")) print("You input", rods, "rods.\n") # Run conversions, but don't round yet for accuracy meters = rods * ROD feet = meters / FOOT miles = meters / MILE furlongs = rods / FURLONG walking_hours = miles / WALKING_SPEED walking = walking_hours * 60 # Converts hours to minutes of walking # Round all floats for prettier printing meters = round(meters, 3) feet = round(feet, 3) miles = round(miles, 3) furlongs = round(furlongs, 3) walking = round(walking, 3) # Print conversions print("Conversions") print("Meters:", meters) print("Feet:", feet) print("Miles:", miles) print("Furlongs:", furlongs) print("Minutes to walk", rods, "rods:", walking)
9578905a36441641c14596aa6d262cb1be5fa3cd
hazalozbey/python
/modüller.py
928
3.96875
4
#def selamla(): # print("merhaba") # print("nasılsınız") # print(selamla()) # def selamla1(isim): # print("isminiz:",isim) # print(selamla1("hazal")) #def toplama(a,b,c): # print("toplamları",a+b+c) #print(toplama(1,2,3)) #def faktöriyel(sayi): # faktöriyel=1 # if(sayi==0 or sayi==1): # print("faktöriyel",faktöriyel) # else: # while(sayi>=1): # faktöriyel *=sayi # sayi -=1 # print("faktöriyel",faktöriyel) #print(faktöriyel(1)) #def toplama(a,b,c): # return a+b+c #def ikiylecarp(a): # return a*2 #toplam=toplama(2,3,4) #print(ikiylecarp(toplam)) def ücleçarp(a): print("1.fonksiyon çalıştı") return a*3 def ikiyletopla(a): print("2.fonksiyon çalıştı") return a+2 def dördeböl(a): print("3.fonksiyon çalıştı") return a/4 print(dördeböl(ikiyletopla(ücleçarp(5))))
3d6946467c554af43e10a93431ef883565fd72cf
mtmmy/Leetcode
/Python/0149_MaxPointsOnALine/maxPoints.py
1,425
3.5625
4
import unittest class Point: def __init__(self, a=0, b=0): self.x = a self.y = b class Solution: def maxPoints(self, points): """ :type points: List[Point] :rtype: int """ result, n = 0, len(points) for i in range(n): dic = {} duplicate = 1 for j in range(i + 1, n): ix, jx, iy, jy = points[i].x, points[j].x, points[i].y, points[j].y if ix == jx and iy == jy: duplicate += 1 continue dx = jx - ix dy = jy - iy d = self.gcd(dx, dy) tupleD = (dx // d, dy // d) dic[tupleD] = dic.setdefault(tupleD, 0) + 1 result = max(result, duplicate) for key, val in dic.items(): result = max(result, val + duplicate) return result def gcd(self, a, b): return a if b == 0 else self.gcd(b, a % b) class TestFunc(unittest.TestCase): """Test fuction""" def test(self): target = Solution() #self.assertEqual(3, target.maxPoints([Point(1, 1), Point(2, 2), Point(3, 3)])) self.assertEqual(4, target.maxPoints([Point(1,1), Point(3,2), Point(5,3), Point(4,1), Point(2,3), Point(1,4)])) if __name__ == '__main__': unittest.main()
aa08c36318b4408b995ce281c712eb84b2c1fbd7
mtmmy/Leetcode
/Python/0941_ValidMountainArray/validMountainArray.py
555
3.546875
4
class Solution: def validMountainArray(self, A): """ :type A: List[int] :rtype: bool """ if not A or len(A) < 3: return False if A[0] > A[1] or A[-2] < A[-1]: return False peak = False for i in range(0, len(A) - 1): if A[i] == A[i + 1]: return False elif not peak and A[i] > A[i + 1]: peak = True elif peak and A[i] <= A[i + 1]: return False return True
d03418d26f95655d92cfa4116a826b8e9ecedd33
mtmmy/Leetcode
/Python/0316_RemoveDuplicateLetters/removeDuplicateLetters.py
542
3.53125
4
from collections import Counter class Solution: def removeDuplicateLetters(self, s): """ :type s: str :rtype: str """ freq = Counter(s) visited, stack = set(), [] for c in s: freq[c] -= 1 if c not in visited: while stack and c < stack[-1] and freq[stack[-1]] > 0: visited.remove(stack.pop()) stack.append(c) visited.add(c) return "".join(stack)
11e2f25abb2ac470a3c9b11fe41735fd2e3fc8aa
mtmmy/Leetcode
/Python/0426_ConvertBinarySearchTreeToSortedDoublyLinkedList/treeToDoublyList.py
864
3.734375
4
class Node: def __init__(self, val, left, right): self.val = val self.left = left self.right = right class Solution: def __init__(self): self.cur = None def treeToDoublyList(self, root: 'Node') -> 'Node': if not root: return None head = Node(-1, None, None) def dfs(node): if not node: return dfs(node.left) if not self.cur: head.right = node self.cur = node else: self.cur.right = node node.left = self.cur self.cur = node dfs(node.right) dfs(root) first = head.right last = self.cur first.left = last last.right = first return first
4751e0618f128de48568312d32e7c346715b682a
mtmmy/Leetcode
/Python/0059_SpiralMatrix2/generate_matrix.py
1,102
3.59375
4
class Solution: def generateMatrix(self, n): """ :type n: int :rtype: List[List[int]] """ result = [[0] * n for _ in range(n)] nowWidth = n nowHeight = n x = 0 y = 0 num = 1 while nowWidth > 0 and nowHeight > 0: if nowWidth == 1: result[x][y] = num for i in range(nowWidth - 1): result[x][y] = num y += 1 num += 1 for i in range(nowHeight - 1): result[x][y] = num x += 1 num += 1 for i in range(nowWidth - 1): result[x][y] = num y -= 1 num += 1 for i in range(nowHeight - 1): result[x][y] = num x -= 1 num += 1 nowWidth -= 2 nowHeight -= 2 x += 1 y += 1 return result if __name__ == "__main__": target = Solution() result = target.generateMatrix(1)
c2237fb7188c293ecff36d8874cd7aa3cc336e12
mtmmy/Leetcode
/Python/0721_AccountsMerge/accountsMerge.py
3,210
3.65625
4
import unittest class Solution: def accountsMerge(self, accounts): """ :type accounts: List[List[str]] :rtype: List[List[str]] """ def find(s, root): return s if root[s] == s else find(root[s], root) result = [] root = {} owner = {} dic = {} for account in accounts: for i in range(1, len(account)): root[account[i]] = account[i] owner[account[i]] = account[0] for account in accounts: p = find(account[1], root) for i in range(2, len(account)): q = find(account[i], root) root[q] = p for account in accounts: for i in range(1, len(account)): p = find(account[i], root) if p in dic: dic[p].add(account[i]) else: dic[p] = set([account[i]]) for key, val in dic.items(): v = list(val) v.sort() v.insert(0, owner[key]) result.append(v) return result def accountsMerge2(self, accounts): n = len(accounts) acc2per = [-1] * n # initial: acc2per[i] = i def findSet(x): if acc2per[x] < 0: return x acc2per[x] = findSet(acc2per[x]) return acc2per[x] def union(x, y): # union the 2 sets of x & y xx = findSet(x) yy = findSet(y) if xx < yy: acc2per[xx] += acc2per[yy] acc2per[yy] = xx elif yy < xx: acc2per[yy] += acc2per[xx] acc2per[xx] = yy # merge accounts to persons email2acc = {} for acc, emails in enumerate(accounts): for i in range(1, len(emails)): e = emails[i] if e not in email2acc: email2acc[e] = acc else: union(acc, email2acc[e]) # collect emails for each person per2emails = {} for acc, emails in enumerate(accounts): per = findSet(acc) if per not in per2emails: per2emails[per] = set() for i in range(1, len(emails)): per2emails[per].add(emails[i]) # process each person & corresponding info res = [] for per, emails in per2emails.items(): info = [accounts[per][0]] # fetch person name info.extend(sorted(list(emails))) res.append(info) return res class TestFunc(unittest.TestCase): """Test fuction""" def test(self): target = Solution() test = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]] expected = [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]] self.assertEqual(expected, target.accountsMerge2(test)) if __name__ == '__main__': unittest.main()
54499ce3bff30fe820f3656956695b8f1d18dfb8
mtmmy/Leetcode
/Python/0535_EncodeAndDecodeTinyURL/Codec.py
866
3.5625
4
import string import random class Codec: def __init__(self): self.shortToLong = {} self.longToShort = {} def randomString(self): return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(6)) def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str """ while True: randomUrl = self.randomString() if randomUrl not in self.shortToLong: self.shortToLong[randomUrl] = longUrl self.longToShort[longUrl] = randomUrl return randomUrl def decode(self, shortUrl): """Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str """ return self.shortToLong[shortUrl]
618959b86074b58d1d86d9ed8ffcf1cac0ecb7b6
mtmmy/Leetcode
/Python/0075_SortColors/sortColors.py
635
3.890625
4
class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ red, blue = 0, len(nums) - 1 i = 0 while i <= blue: if nums[i] == 0: nums[red], nums[i] = nums[i], nums[red] red += 1 elif nums[i] == 2: nums[blue], nums[i] = nums[i], nums[blue] blue -= 1 i -= 1 i += 1 if __name__ == "__main__": target = Solution() colors = [1,2,0] target.sortColors(colors)
000577b788c7e90def08197606d74da889e05165
mtmmy/Leetcode
/Python/0716_MaxStack/MaxStack.py
1,327
4.09375
4
class MaxStack: def __init__(self): """ initialize your data structure here. """ self.stack = [] self.stackMax = [] def push(self, x): """ :type x: int :rtype: void """ if not self.stackMax or self.stackMax[-1] <= x: self.stackMax.append(x) self.stack.append(x) def pop(self): """ :rtype: int """ pop = self.stack.pop() if self.stackMax and pop == self.stackMax[-1]: self.stackMax.pop() return pop def top(self): """ :rtype: int """ return self.stack[-1] def peekMax(self): """ :rtype: int """ return self.stackMax[-1] def popMax(self): """ :rtype: int """ maximum = self.stackMax.pop() stackTemp = [] while self.stack[-1] != maximum: stackTemp.append(self.stack.pop()) self.stack.pop() while stackTemp: self.push(stackTemp.pop()) return maximum if __name__ == '__main__': target = MaxStack() target.push(5) target.push(1) print(target.popMax()) print(target.peekMax())
544e3de907f65094f0a055633046d3e974afa171
mtmmy/Leetcode
/Python/0482_LicenseKeyFormatting/licenseKeyFormatting.py
1,323
3.6875
4
import unittest class Solution: def licenseKeyFormatting(self, S, K): """ :type S: str :type K: int :rtype: str """ S = S.replace("-", "").upper() rem = len(S) % K return "-".join([S[:rem]] + [S[i:i+K] for i in range(rem, len(S), K)]).strip("-") # S = S.upper() # i, kCounter = len(S) - 1, 0 # while i >= 0: # if S[i] == "-": # S = S[:i] + S[i + 1:] # i -= 1 # continue # else: # if kCounter == K: # kCounter = 0 # S = S[:i + 1] + "-" + S[i + 1:] # kCounter += 1 # i -= 1 # return S class TestFunc(unittest.TestCase): """Test fuction""" def test(self): target = Solution() #self.assertEqual("2-5G-3J", target.licenseKeyFormatting("2-5g-3-J", 2)) self.assertEqual("5F3Z-2E9W", target.licenseKeyFormatting("5F3Z-2e-9-w", 4)) #self.assertEqual("5F-3Z2-E9W", target.licenseKeyFormatting("5F3Z-2e-9-w", 3)) self.assertEqual("AA-AA", target.licenseKeyFormatting("--a-a-a-a--", 2)) if __name__ == '__main__': unittest.main()
60bb9cb8ebe071f65f531dd18debe941b51532bf
mtmmy/Leetcode
/Python/0683_KEmptySlots/kEmptySlots.py
1,591
3.5625
4
import unittest class Solution(object): def kEmptySlots(self, flowers, k): """ :type flowers: List[int] :type k: int :rtype: int """ # result, left, right, n = 20001, 0, k + 1, len(flowers) # days = [0] * n # for i in range(n): # days[flowers[i] - 1] = i + 1 # i = 0 # while right < n: # if days[i] < days[left] or days[i] <= days[right]: # if i == right: # result = min(result, max(days[left], days[right])) # left = i # right = k + i + 1 # i += 1 # return -1 if result == 20001 else result garden = [[i - 1, i + 1] for i in range(len(flowers))] garden[0][0], garden[-1][1] = None, None ans = -1 for i in range(len(flowers) - 1, -1, -1): cur = flowers[i] - 1 left, right = garden[cur] if right != None and right - cur == k + 1: ans = i + 1 if left != None and cur - left == k + 1: ans = i + 1 if right != None: garden[right][0] = left if left != None: garden[left][1] = right return ans class TestFunc(unittest.TestCase): """Test fuction""" def test(self): target = Solution() self.assertEqual(2, target.kEmptySlots([1,3,2], 1)) self.assertEqual(-1, target.kEmptySlots([1,2,3], 1)) if __name__ == '__main__': unittest.main()
7420bd985c73f537922441476ed61b9bcaccb668
mtmmy/Leetcode
/Python/0153_FindMinimuminRotatedSortedArray/findMin.py
944
4
4
import unittest class Solution: def findMin(self, nums): """ :type nums: List[int] :rtype: int """ left, right = 0, len(nums) - 1 if nums[left] > nums[right]: while left != right - 1: mid = (left + right) // 2 if nums[left] < nums[mid]: left = mid else: right = mid return min(nums[left], nums[right]) return nums[left] class TestFunc(unittest.TestCase): """Test fuction""" def test(self): target = Solution() self.assertEqual(1, target.findMin([1,2,3])) self.assertEqual(1, target.findMin([3,1,2])) self.assertEqual(0, target.findMin([4,5,6,7,8,0,1,2,3])) self.assertEqual(0, target.findMin([7,8,0,1,2,3,4,5,6])) if __name__ == '__main__': unittest.main()
1dc2ec1b376662d3d96389de1c7d0ce136a3df35
mtmmy/Leetcode
/Python/0843_GuessTheWord/findSecretWord.py
1,816
3.609375
4
import unittest class Master: def __init__(self, secretWord): self.secretWord = secretWord def guess(self, word): """ :type word: str :rtype int """ if word == self.secretWord: return 6 else: return sum(c1 == c2 for c1, c2 in zip(word, self.secretWord)) class Solution: def findSecretWord(self, wordlist, master): """ :type wordlist: List[Str] :type master: Master :rtype: None """ def pairMatches(word1, word2): return sum(c1 == c2 for c1, c2 in zip(word1, word2)) def mostSimilarWord(): counts = [[0] * 26 for _ in range(6)] for word in candidates: for i, c in enumerate(word): counts[i][ord(c) - ord("a")] += 1 bestScore = 0 for word in candidates: score = 0 for i, c in enumerate(word): score += counts[i][ord(c) - ord("a")] if score > bestScore: bestScore = score bestWord = word return bestWord candidates = wordlist[:] while candidates: simWord = mostSimilarWord() matches = master.guess(simWord) if matches == 6: return 6 candidates = [word for word in candidates if pairMatches(simWord, word) == matches] class TestFunc(unittest.TestCase): """Test fuction""" def test(self): master = Master("acckzz") target = Solution() test = ["acckzz","ccbazz","eiowzz","abcczz"] self.assertEqual(6, target.findSecretWord(test, master)) if __name__ == '__main__': unittest.main()
f53d7fbdfc35414a09506739f28234839859e806
jplineb/OOP_Refresher
/Lessons/OOP_lesson3.py
594
4
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 17 17:48:08 2019 @author: jline """ class Car: ## defining a class variable wheels = 4 def __init__(self): self.mil = 10 # Instance variable self.com = "BMW" # Instance variable c1 = Car() c2 = Car() c1.mil = 8 print(c1.com, c1.mil, c1.wheels) print(c2.com, c2.mil, c2.wheels) ## Class variables are shared so if you change the class varibles it effects ## Both instances of Car() Car.wheels = 5 print(c1.com, c1.mil, c1.wheels) print(c2.com, c2.mil, c2.wheels)
0e2ccea00baf8be2324ae4b38a3366ed30969705
javiipzo/Ejercicios-del-tema-3
/ejercicio1.py
595
3.546875
4
class Animal: def __init__(self, age, name): self.age = age # public attribute self.name = name # public attribute def saluda(self, saludo='Hola', receptor = 'nuevo amigo'): print(saludo + " " + receptor) @staticmethod def add(a, b): if isinstance(a, int) and isinstance(b, int): return a + b elif isinstance(a, str) and isinstance(b, str): return " ".join((a, b)) else: raise TypeError def mostrarNombre(self): print(self.nombre) def mostrarEdad(self): print(self.edad)
84beba21cfcac0fc8a99b945fdc72ab1a5f578e4
luxroot/baekjoon
/old/2609/main.py
180
3.765625
4
def gcd(a,b): while b > 0: a, b = b, a % b return a def lcm(a, b): return a * b / gcd(a, b) (a,b) = map(int,raw_input().split()) print gcd(a,b) print lcm(a,b)
4fc1e7a055c830baa4ea154de82a4568a60b3bdf
alicevillar/python-lab-challenges
/conditionals/conditionals_exercise1.py
1,058
4.46875
4
####################################################################################################### # Conditionals - Lab Exercise 1 # # Use the variable x as you write this program. x will represent a positive integer. # Write a program that determines if x is between 0 and 25 or between 75 and 100. # If yes, print the message:_ is between 0 and 25 or 75 and 100, where the blank would be the value of x. # The program should do nothing if the value of x does not fit into either range. # #Expected Output # If x is 8, then the output would be: 8 is between 0 and 25 or 75 and 100. # If x is 80, then the output would be: 80 is between 0 and 25 or 75 and 100. # If x is 50, then the output would be blank (your program does not print anything). ####################################################################################################### x = 8 if x <= 25: print(str(x) + " is between 0 and 25") elif x > 75 and x < 100: print(str(x) + " is between 75 and 100") # Output => 8 is between 0 and 25
807516283f0b9c85fdf4912375af203a8dd50e22
Shilpaumarji/FST-M1
/Python/Activities/Activity1.py
214
4.03125
4
username = input("Enter your name: ") Age = int(input("Enter your age: ")) print("your name is: " + username) year = str( (2021-Age) + 100) print(username + " will be 100 years old in the year " + year)
08c92a58eaaeed99f8211b1965f9a2e605008147
WaffleKing631/Curso_Python
/adivina_un_numero.py
305
3.84375
4
number_to_guess = 5 a = int(input("dime un numero?")) b = int(input("dame otro numero?")) c = int(input("solo uno mas")) if a == number_to_guess: print("acertaste") if b == number_to_guess: print("acertaste") if c == number_to_guess: print("acertaste") else: print("no has acertado :(")
2d02d9e158ab16e20c7705bcb3e6785e22ec33ac
WaffleKing631/Curso_Python
/encontrar_numero.py
737
3.71875
4
n_usuario = [] n_del_usuario = "" while len(n_usuario) < 10: while not n_del_usuario.isdigit(): n_del_usuario = input("Dime un numero: ") n_usuario.append(int(n_del_usuario)) n_del_usuario = "" print("numero añadido") print("la lista es {}".format(n_usuario)) n_grande = n_usuario[0] for numero in n_usuario: if numero > n_grande: n_grande = numero print("El numero mas grande es {}".format(n_grande)) n_peque = n_usuario[0] for numero in n_usuario: if numero < n_peque: n_peque = numero print("El numero mas pequeño es {}".format(n_peque)) cantidad_numeros = 0 for numero in n_usuario: cantidad_numeros += 1 print("La cantidad de numeros es {}".format(cantidad_numeros))
bb9270be02394d04551d1c05e582eb781c27a3b9
madelinelyons/CrackingTheCodingInterview
/interviewChapter7blackJack.py
941
3.546875
4
class Card: def __init__(self, num, suit): self.num = num self.suit = suit available = True def getNum(self): return self.num def getSuit(self): return self.suit class DeckOfCards: def __init__(self): self.min = 2 self.max = 14 self.deck = [] self.suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] self.dealtIndex = 0 def populateDeck(self): deck = [] for x in self.suits: for i in range(self.min, self.max+1): newCard = Card(i, x) deck = deck + [newCard] self.deck = deck def printDeck(self): for x in self.deck: print(x.getNum(), x.getSuit()) def shuffle(self) def remainingCards(self): return len(self.deck) - dealtIndex def main(): deck = DeckOfCards() deck.populateDeck() deck.printDeck() main()
731a4ae9b656ffeba8417e4c166e0be86fe28c2c
Dhinacse/codekata
/guvi_strings_190.py
143
3.671875
4
n=input() y=input() l="ABCDEFGHIJKLMNOPQRSTUVWXYZ" if(sorted(l)==sorted(n+y)): print("complementary") else: print("non-complementary")
ddb15108ec263e7096efde366bd5a2bb3fb2e7e6
IanGSalmon/hackerrank_python_challenges
/python_challenges/string_validator.py
1,026
4
4
'''Task You are given a string . Your task is to find out if the string contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters. Input Format A single line containing a string . Output Format In the first line, print True if has any alphanumeric characters. Otherwise, print False. In the second line, print True if has any alphabetical characters. Otherwise, print False. In the third line, print True if has any digits. Otherwise, print False. In the fourth line, print True if has any lowercase characters. Otherwise, print False. In the fifth line, print True if has any uppercase characters. Otherwise, print False.''' str = raw_input() print any(c.isalnum() for c in str) print any(c.isalpha() for c in str) print any(c.isdigit() for c in str) print any(c.islower() for c in str) print any(c.isupper() for c in str) # Using comprehension #for method in [str.isalnum, str.isalpha, str.isdigit, str.islower, str.isupper]: # print any(method(c) for c in s)
56870e9f3f322e09042d9e10312ed054fa033fa2
rghosh96/projecteuler
/evenfib.py
527
4.15625
4
#Define set of numbers to perform calculations on userRange = input("Hello, how many numbers would you like to enter? ") numbers = [0] * int(userRange) #print(numbers) numbers[0] = 0 numbers[1] = 1 x = numbers[0] y = numbers[1] i = 0 range = int(userRange) #perform fibonacci, & use only even values; add sums sum = 0 while x < int(userRange): if x % 2 == 0: #print (x, end=", ") sum = sum + x z = x + y x = y y = z #i = i + 1 print("The total sum of the even-valued terms is:", sum)
311fb982387df43a1c79a90d48a477cb58ad3856
silviajlee/MC102
/lab10.py
1,553
3.796875
4
#"Roteiro do Lab. 10: https://www.ic.unicamp.br/~mc102/mc102-1s2020/labs/roteiro-lab10.html" import copy #entrada padrao = [] quadros = 0 while True: leitura =list(input("")) if(leitura[0].isnumeric()): quadros = int("".join(leitura)) break else: padrao.append(leitura) def imprimir_matriz (M): for i in M: print("".join(i)) #matriz def matriz (M): c = copy.deepcopy(M) for i in range (1, len(M)-1): for j in range (1, len(M[i])-1): vizinho = 0 if (M[i-1][j])== "@": vizinho = vizinho + 1 if (M[i-1][j-1]) == "@": vizinho = vizinho + 1 if (M[i-1][j+1]) == "@": vizinho = vizinho + 1 if (M[i][j-1]) == "@": vizinho = vizinho + 1 if (M[i][j+1]) == "@": vizinho = vizinho + 1 if (M[i+1][j]) == "@": vizinho = vizinho + 1 if (M[i+1][j-1]) == "@": vizinho = vizinho + 1 if (M[i+1][j+1]) == "@": vizinho = vizinho + 1 if M[i][j] == "@" and 2<=vizinho<=3: c[i][j] = "@" else: c[i][j] = " " if M[i][j] == " " and (vizinho == 3): c[i][j] = "@" return c imprimir_matriz(padrao) for _ in range(quadros): padrao = matriz(padrao) imprimir_matriz(padrao)
f87bafd4dbf5b69b9eda0f1baa5a87543b881998
biniama/python-tutorial
/lesson4_list_tuple_dictionary/dictionary.py
953
4.375
4
def main(): # dictionary has a key and a value and use colon (:) in between # this is a very powerful and useful data type dictionary = {"Book": "is something to read"} print(dictionary) biniam_data = { "name": "Biniam", "age": 32, "profession": "Senior Software Engineer", "spouse": { "name": "Kidan", "age": 29 } } print(biniam_data) hareg_data = { "name": "Hareg", "age": "26", "profession": "Junior Programmer and Business Manager" } print(hareg_data) # Using for loop to iterate/repeat over a dictionary # Exercise: print Hareg's data in capital letter and as a statement for key in hareg_data: #print(key.upper() + ' IS ' + hareg_data.get(key).upper()) # alternative way of writing print(f'{key.upper()} IS {hareg_data.get(key).upper()}') if __name__ == '__main__': main()
3c21bd12834e39d8fd1c53bb5d9885c2cc75a360
biniama/python-tutorial
/lesson6_empty_checks_and_logical_operators/logical_operators.py
490
4.1875
4
def main(): students = ["Kidu", "Hareg"] name = input("What is your name? ") if name not in students: print("You are not a student") else: print("You are a student") # if name in students: # print("You are a student") # else: # print("You are not a student") # Second example value = False if not value: print("Value is false") else: print("Value is true") if __name__ == '__main__': main()
bac2a9c57de523788893acc83ddfb37a2e10ce0d
biniama/python-tutorial
/lesson2_comment_and_conditional_statements/conditional_if_example.py
1,186
4.34375
4
def main(): # Conditional Statements( if) # Example: # if kidu picks up her phone, then talk to her # otherwise( else ) send her text message # Can be written in Python as: # if username is ‘kiduhareg’ and password is 123456, then go to home screen. # else show error message # Conditional statement example # Assumption # child is someone who is less than 10 years old # young is someone who is between 10 - 30 years old # adult is someone who is between 30 - 50 years old # accepting input from the user ageString = input('Please enter your age ') age = int(ageString) # converts string to integer if age < 10: print('child') elif age >= 10 and age < 30: # T and F = F, T and T = T print('young') elif age > 30 and age <= 50: print('adult') else: print('old - sheba') # another example with ‘if’ only # TODO: Un comment it to execute # if age < 10: # print('child') # if age >= 10 and age <= 30: # T and F = F, T and T = T # print('young') # if age > 30: # print('adult') if __name__ == "__main__": main()
48cff82b645be0f551882888338d76f180fda1ce
aiperi2021/pythonProject
/day_7/home.py
187
3.703125
4
# num = [1, 2, 3, 4] # for i in num: # if i%2==0: # print(i*2) # else: # print(i*3) # box = 0 # num = [1, 2, 3, 4] # for i in num: # box+=i # print(box)
f8c60b72937991f86a2bb8ae0ceaace784dea55f
aiperi2021/pythonProject
/day_7_test/test.py
849
3.984375
4
#1 create program which will ask input from user, # ex: "please enter your name " it will accept the inserted name and display #2 create variable name(string),age(number), isCold(boolean) and print #3a create list of cars, loop and print #3b create list of cars print last car #3c create list of cars and count how many cars have letter "s" or "a" #4 create tuple of number and count how many elements in tuple #5 create if statement ex: if cold stay homme, if warm go out #6 create nested if statement ex:if snowing and warm go walk if snowing and cold stay home # if sunny and warm play golf if sunny and cold stay coding #7 create while loop # ex: given integer number 10, print if nuumber bigger than 5, if less than 5 stop printing #8 create dictionary of book and loop it #9 create method and explain signaute and why we need it
62ac86c00c6afcbb16dcc58a1a12bc426070001a
aiperi2021/pythonProject
/day_4/if_statement.py
860
4.5
4
# Using true vs false is_Tuesday = True is_Friday = True is_Monday = False is_Evening = True is_Morning = False if is_Monday: print("I have python class") else: print("I dont have python class") # try multiple condition if is_Friday or is_Monday: print("I have python class") else: print("I dont have python class") if is_Friday and is_Evening: print("I have python class") else: print("I dont have python class") if is_Friday and is_Morning: print("I have python class") else: print("I dont have python class") if is_Friday and not is_Morning: print("I have python class") else: print("I dont have python class") if is_Friday and is_Morning: print("I dont have python class") elif is_Monday and is_Evening: print("I have python class") else: print("I dont have python class in any of this time ")
f6c60e2110d21c44f230ec710f3b74631b772195
aiperi2021/pythonProject
/day_7/dictionar.py
298
4.3125
4
# Mapping type ## Can build up a dict by starting with the the empty dict {} ## and storing key/value pairs into the dict like this: ## dict[key] = value-for-that-key #create dict dict = {} dict['a'] = 'alpha' dict['g'] = 'gamma' dict['o'] = 'omega' for key in dict: print(key, '->', dict[key])
75c79eabc067d4703398e1a8870c1b6e9034bffb
yasaj/boston_data
/boston_data.py
2,287
3.703125
4
# coding: utf-8 # In[334]: # First let's import all the packages that wer will need in order to analyze and visualize our data import seaborn as sns from sklearn.datasets import load_boston import matplotlib.pyplot as plt import pandas as pd import numpy as np boston_dataset = load_boston() # In[341]: # We will try to make a Linear Regression model on the Boston data. boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names) boston['MEDV'] = boston_dataset.target boston.head() # In order to know more about the data's features we can use the DESCR: print(boston_dataset.DESCR) # In[340]: # The correlation matrix will help us see if there are any strong correlations between the features and the target: correlation_matrix = boston.corr().round(2) sns.heatmap(data=correlation_matrix, annot=True) # We can see that there is a strong correlation (0.7) between the variables MEDV and RM. # We will try to predict the median price (MEDV) using the variable RM (average number of rooms). # In[373]: # Splitting our data into train and test sets: from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error X = boston['RM'] X = X.values.reshape(-1, 1) y = boston['MEDV'] X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=0.2, random_state=23) print(X_train.shape) print(X_test.shape) print(Y_train.shape) print(Y_test.shape) # Starting our linear regression model: regr = LinearRegression() plt.scatter(X_train, Y_train) regr.fit(X_train, Y_train) y_predicted = regr.predict(X_train) print(regr.coef_) print(regr.intercept_) y_line = [9.14438088*x-34.75540260183401 for x in X] plt.plot(X, y_line, c='r') # In[377]: # Let's evaluate our model using RMSE: Y_train_predict = regr.predict(X_train) rmse = (np.sqrt(mean_squared_error(Y_train, Y_train_predict))) print("The model performance for training set") print("-----------------") print('RMSE is {}'.format(rmse)) print("\n") # model evaluation for testing set Y_test_predict = regr.predict(X_test) rmse = (np.sqrt(mean_squared_error(Y_test, Y_test_predict))) print("The model performance for testing set") print("-----------------") print('RMSE is {}'.format(rmse))
390a08b879439751866c6caa458fee0235df3387
cpe202fall2018/lab0-asayani1
/planets.py
309
3.796875
4
def weight_on_planets(): # write your code here earth = int (input("What do you weigh on earth? ")) #print (earth) #print("\n") print ("\nOn Mars you would weigh", earth*0.38, "pounds.") print ("On Jupiter you would weigh", earth*2.34, "pounds.") if __name__ == '__main__': weight_on_planets()
0949dfc3c4efa0badea19992482ee2d616315f59
kafelka/phonebook_project
/phonebook_personal_engine.py
2,450
3.59375
4
import sqlite3 import json from pprint import pprint def get_db(db_name): try: if db_name != "phonebook_database.db": raise OSError('Wrong database name!') #connects to db conn = sqlite3.connect(db_name) #link to db with cursor c = conn.cursor() print('Yay! A none is not returned') return c #conn except Exception as e: print(e) return None def create_table(db_name): c, conn = get_db(db_name) c.execute("DROP TABLE IF EXISTS phonebook_personal") c.execute("CREATE TABLE phonebook_personal(first_name TEXT, last_name TEXT, addressline1 TEXT, addressline2 TEXT, addressline3 TEXT, postcode TEXT, country TEXT, telephone_number REAL)") conn.commit() #create_table() #"with" creates a temporary resource access and closes it after "with" ends with open("mock_data_people.json") as f: data = json.load(f) #pprint(data) def personal_data_entry(db_name): c, conn = get_db(db_name) for item in data: # method1 # values_list = list(item.values()) # print(values_list) # c.execute('''INSERT INTO phonebook_personal(first_name, last_name, addressline1, addressline2, addressline3, postcode, country, telephone_number) VALUES(?, ?, ?, ?, ?, ?, ?, ?)''', (values_list)) # #method2 c.execute('''INSERT INTO phonebook_personal(first_name, last_name, addressline1, addressline2, addressline3, postcode, country, telephone_number) VALUES(?, ?, ?, ?, ?, ?, ?, ?)''', (item["first_name"], item["last_name"], item["address_line_1"], item["address_line_2"], item['address_line_3'], item['postcode'],item['country'], item['telephone_number'])) print(item["first_name"], item["last_name"], item["address_line_1"], item["address_line_2"], item['address_line_3'], item['postcode'],item['country'], item['telephone_number']) conn.commit() #remove data from db in order to avoid duplicate #c.execute("DELETE FROM phonebook_personal") #personal_data_entry() def addColumnsToDb(db_name): c, conn = get_db(db_name) c.execute('''ALTER TABLE phonebook_personal ADD x_coordinate REAL''') c.execute('''ALTER TABLE phonebook_personal ADD y_coordinate REAL''') conn.commit() #addColumnsToDb() #c, conn = get_db() ##closing cursor #c.close() ##closing connection to db #conn.close()
d42487928b8129a69ee49145646347e4230f8e40
dzeinali/11411-QA-Project
/asking/simpleBinary.py
7,023
3.578125
4
import warnings warnings.filterwarnings("ignore") import nltk from nltk.tokenize import word_tokenize from nltk.corpus import wordnet as wn from nltk.tag import pos_tag import string # after tokenize the input is a list of strings # each string is a complete sentence ''' create a list of all "to be" verbs Sentence: A 'to_be' B eg. KT is tired. Question: 'to_be' A B? eg. Is KT tired? Rules: - pull out 'to_be' verb and insert to the front - Adjust 1st letter of "to_be" & 1st letter of original sentence ''' to_be = ['am', 'is', 'are', 'was', 'were'] ''' create a list of aux_verb Sentence: A "aux_verb" infinitive_verb_phase eg. KT must sleep. Question: "aux_verb" A infinitive_verb_phase? eg. Must KT sleep? * The question could also be "What must KT do?", but for the sake of simplicity we do binary first Rules: - pull out 'aux_verb' and insert to the front - Adjust 1st letter of "aux_verb" & 1st letter of original sentence ''' aux_verb = ['must', 'can', 'could', 'shall', 'should', 'will', 'would', 'may', 'might'] def ask_simple_binary(input): result = [] for sentence in input: words = sentence.split() # check "to_be" verbs # ignore complex sentence structure first # find at most 1 question for each sentence for beV in to_be: # "to_be" case if beV in words: words.remove(beV) # edge case: words that must be capitalized # need to add more, such as name entities if words[0] not in ["I"]: words[0] = words[0][0].lower() + words[0][1:] beVCap = beV[0].upper() + beV[1:] newSentence = beVCap + ' ' + ' '.join(words) # remove existing punctuation newSentence = newSentence[:(len(newSentence)-1)] # directly return here, hence will only produce 1 question for each sentence for now result.append((newSentence + "?", sentence)) ''' wordNetQns = useWordNet(newSentence) for qn in wordNetQns: result.append((qn + "?", sentence)) ''' for auxV in aux_verb: if auxV in words: words.remove(auxV) # edge case: words that must be capitalized # need to add more, such as name entities if words[0] not in ["I"]: words[0] = words[0][0].lower() + words[0][1:] auxVCap = auxV[0].upper() + auxV[1:] newSentence = auxVCap + ' ' + ' '.join(words) # directly return here, hence will only produce 1 question for each sentence for now ''' result.append((newSentence + "?", sentence)) wordNetQns = useWordNet(newSentence) for qn in wordNetQns: result.append((qn + "?", sentence)) ''' return result ''' def useWordNet(newSentence): ss = nltk.tokenize.sent_tokenize(newSentence) tokenized_sent=[nltk.tokenize.word_tokenize(sent) for sent in ss] pos_sentences=[nltk.pos_tag(sent) for sent in tokenized_sent] result = [] for i in pos_sentences[0]: word = i[0] # https://opensenselabs.com/blog/tech/entity-extraction-using-nlp-python if i[1] == 'NN': hypernyms = [] for syn in wn.synsets(word): if syn.hypernyms(): hypernyms.append(syn.hypernyms()[0].name().split(".")[0]) if hypernyms != []: hyper = hypernyms[0] if hyper.lower() != word.lower(): temp = newSentence.replace(word, hyper) result += [temp] if i[1] in ['NN', 'JJ', 'RBR', 'RBS', 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ'] and word.lower() not in to_be: synonyms = [] antonyms = [] for syn in wn.synsets(word): for l in syn.lemmas(): synonyms.append(l.name()) if l.antonyms(): antonyms.append(l.antonyms()[0].name()) # Only get the TOP ONE synonyms and antonyms and create questions. # If top synonym is the word itself, ignore; if no antonym, ignore. if synonyms != []: syn = synonyms[0] if syn.lower() != word.lower(): temp = newSentence.replace(word, syn) result += [temp] if antonyms != []: ant = antonyms[0] temp = newSentence.replace(word, ant) result += [temp] return result ''' ''' things to do: - add in name entity to distinguish which are the word that needs to keep capitalized - process punctuation (QUESTION: HOW IS PUNCTUATION PROCESSED IN TOKENIZE?) - if punctuation is treated as an individual word with space on both sides: - detect punction, delete the space before punctuation, leave the space after punctuation - else...? ''' ''' s1 = "Gyarados (Gyaradosu) is a Pokémon species in Nintendo and Game Freak's Pokémon franchise." s2 = "Created by Ken Sugimori, Gyarados first appeared in the video games Pokémon Red and Pokemon Green and subsequent sequels, later appearing in various merchandise, spinoff titles and animated and printed adaptations of the franchise. " s3 = "Lesley should be doing her homework." s4 = "This is a good idea." s5 = "Just a random sentence." s6 = "I must go." s7 = "My dog is cute." input = [s1, s2, s3, s4, s5, s6, s7] result = ask_simple_binary(input) print(result) [("Is gyarados (Gyaradosu) a Pokémon species in Nintendo and Game Freak's Pokémon franchise?", "Gyarados (Gyaradosu) is a Pokémon species in Nintendo and Game Freak's Pokémon franchise."), ("Is gyarados (Gyaradosu) a Pokémon species in Nintendo and Game Freak's Pokémon concession?", "Gyarados (Gyaradosu) is a Pokémon species in Nintendo and Game Freak's Pokémon franchise."), ('Should lesley be doing her homework.?', 'Lesley should be doing her homework.'), ('Should lesley be make her homework.?', 'Lesley should be doing her homework.'), ('Should lesley be unmake her homework.?', 'Lesley should be doing her homework.'), ('Should lesley be doing her school_assignment.?', 'Lesley should be doing her homework.'), ('Is this a good idea?', 'This is a good idea.'), ('Is this a evil idea?', 'This is a good idea.'), ('Is this a good content?', 'This is a good idea.'), ('Must I go.?', 'I must go.'), ('Must I stay_in_place.?', 'I must go.'), ('Is my apple red?', 'My apple is red.'), ('Is my edible_fruit red?', 'My apple is red.'), ('Is my apple gain?', 'My apple is red.')] '''
0e223753f3974b262b4c45ab87e886a6f3a3731c
Xwartu/E02a-Control-Structures
/main10.py
3,178
4.375
4
#!/usr/bin/env python3 import sys, random assert sys.version_info >= (3,7), "This script requires at least Python 3.7" print('Greetings!') # A customary hello to the user, prints in terminal colors = ['red','orange','yellow','green','blue','violet','purple'] # Listing all the possible colors in a list format that Python intrepreter can read. play_again = '' # Sets up the varaible to be called later. best_count = sys.maxsize # the biggest number, is set up to be called later. while (play_again != 'n' and play_again != 'no'): # Creates a while loop that will not end until play_again == "no" or "n" match_color = random.choice(colors) # Runs a function through the random module to select a color/string at random from the aforementioned list. count = 0 # Sets up the count varaible for the attempts to be counted. color = '' # Sets up the color variable to be called in the input. while (color != match_color): #Creates another while loop within a while loop that won't end till the color inputed matches the rnadomly picked color from the list. color = input("\nWhat is my favorite color? ") #\n is a special code that adds a new line, input()will collect an input from the user through the terminal. color = color.lower().strip() #Takes the user's input and removes any extra characters that isn't text and makes it lowercase. count += 1 # Another way to write count = count + 1, will count each time the loop runs through since the line will be called repeatedly. if (color == match_color): # An if statement being used to break the loop and reward the user print('Correct!') # Prints the string in the terminal. else: # A corresponding else statement to the previous statement to create a second set of code if the first condition is not met in the fi statement. print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count)) # Prints in terminal, uses the curly braces to input a string repeatedly after the fact, differentiated from count varaivle for human coder's sake. print('\nYou guessed it in {} tries!'.format(count)) # Creates a new line, prints in the terminal and uses the same plug in string structure as in line 23 if (count < best_count): # A second if statment that keeps track of the highest count variable that comes through the loop. print('This was your best guess so far!') # Prints string in terminal best_count = count # If the count was higher than best_count the if statement will run and then best_count will become the value stored in count. play_again = input("\nWould you like to play again (yes or no)? ").lower().strip() # Asks the user to say yes or no to see if they would like to break the loop or continue through it, lower and .strip to standarnize the answers that could come in. print('Thanks for playing!') # A customary end message for user, prints in terminal.
274a5c9b306e62950c8e70aeb7f237ab08521966
mergitto/word-similarity-python
/replace.py
869
3.5
4
# -*- coding: utf-8 -*- def change_word(word): word = word.replace('it', 'ict') word = word.replace("ウェブ", "web") word = word.replace("gd", "グループディスカッション") word = word.replace("pg", "プログラマー") word = word.replace("openes", "エントリーシート") word = word.replace("es", "エントリーシート") word = word.replace("oes", "エントリーシート") word = word.replace("se", "システムエンジニア") return word def decode_word(word): word = word.replace('ict', 'it') word = word.replace("web", "ウェブ") word = word.replace("グループディスカッション", "gd") word = word.replace("プログラマー", "pg") word = word.replace("エントリーシート", "es") word = word.replace("システムエンジニア", "se") return word
a6a89acec433c34ff3c0905890dd7ac2304eceb7
Vaspe/Coursera_Python_3_Programming_Michigan
/Python_Classes_and_Inheritance_Mod4/Ch20_classes_Ass.py
996
3.90625
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 17 00:25:14 2020 @author: Vasilis """ #%% Ass 1 class Bike: def __init__ (self,color,price): self.color = color self.price = price testOne = Bike('blue',89.99) testTwo = Bike('purple', 25.0) print(testOne.color) #%% Ass2 class AppleBasket: def __init__ (self,apple_color,apple_quantity): self.apple_color = apple_color self.apple_quantity = apple_quantity def increase(self): self.apple_quantity = self.apple_quantity + 1 def __str__(self): return "A basket of {} {} apples.".format(self.apple_quantity,self.apple_color) TestOne = AppleBasket('red',4) print(TestOne) #%% Ass3 class BankAccount: def __init__(self,name,amt): self.name = name self.amt = amt def __str__ (self): return "Your account, {}, has {} dollars.".format(self.name,self.amt) t1 = (BankAccount('Bob',100)) print(t1) #%%
9809e48a7efbe7447455e8bd136b609c55ddb53c
Vaspe/Coursera_Python_3_Programming_Michigan
/Python_Basics_Mod1/listsAndStrings.py
6,561
3.796875
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 29 18:20:46 2020 @author: Vasilis """ #%% Definitions """ string: A single variable which is a concatenation of single strings (nubers,letters, symbols, etc,,,). Empty string is also a single character. They are marked with quotes Example: 'I am a string'. "I'm also a string", '''She said, "I 'm also a string" and left''' Strings are immutable, cannot be changed after creation list: A list of any data type (string,int,float,list, etc...). All can be mixed in there although is not recommended as best practice they are marked with [] and the (possibly mixed) variables are comma separated Example: ["hello", 2.0, 5, [10, 20]] Lists are mutable, CAN be changed after creation tuples: It is the same idea with the list and can contain any type of comma separated elements. They are marked with (). Tuples can contain lists Example ("hello", 2.0, 5, [10, 20]) Tuples are immutable, CANNOT be changed after creation. Although internal elements like list mainteain their mutable nature """ #%% String definition examples aa = 'I am a string' print(aa) bb = "I'm also a string" print(bb) cc = '''She said, "I 'm also a string" and left''' print(cc) dd = ''' I am a multiple line string defined with 3' ''' print(dd) ee = """ I am a second multiple line string defined with triple " """ print(ee) ff =" " print (ff) gg="" print(gg) #%% List definition examples hh = ["Hello", " ", "I", 'am', 'a random list', "of strings only"] print (hh) ii = ["hello", 2.0, 5, [10, 20], "I am a random list which includes another random list"] print(ii) ii1 = [5] print(ii1) #%% Tuples definition examples jj = ("hello", 2.0, 5, [10, 20], "I am a random tuple which includes a random list") print(jj) kk=(5,) print(kk) #%% INDEXING OPERATOR IN PYTHON IS [] (same to () in matlab...) # Indexing starts at 0!!!! # Last value is not inclusive when defining a range!!!! print("-----------------------------") sString = 'Pyhton' lList = ['one',2,'three'] tTuple = ("hello", 2.0, 5, [10, 20], "I am a random tuple which includes a random list") for i in range (len(sString)): print('The character i = '+str(i) +' in the string is ' +(sString[i])) for i in range (len(tTuple)): print ('The item i = '+str(i) +' in the tuple is ' + str(tTuple[i]) ) for i in range (len(lList)): print ('The item i = '+str(i) +' in the list is ' + str(lList[i])) print("-----------------------------") L = [0.34, '6', 'SI106', 'Python', -2] print ('L is the list:'+ str(L)) print('the length of L[1:-1] is '+str(len(L[1:-1])) + ' beacuse the first element is ncluded but the last one is excluded. Python FTW!') print('Return of L[:4] is '+str((L[:4])) + ' .This the slice operator property where blank in the beginning means 0') print('Return of L[-3:] is '+str((L[-3:])) + ' .This the slice operator property where blank at the end means start from last value (-1)') print('The symbol : means take all. Return of L(:) is ' + str(L[:])) L[3]='Takis' print("Changing an elment works with L[3]='Takis' is " + str(L[:])) print("-----------------------------") T = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia") print ('T is the tuple:'+ str(T)) print ('T[2:4] is: '+ str(T[2:4])) T=T[:4] + ('Takis',) + T[5:] print("As we cannot mutate a tuple we have to reassign the whole thing in order to change the values. E.g. T=T[:4] + ('Takis',) + T[5:] gives:" +str(T)) print("-----------------------------") #%% concatenation and repetition print ("Using + we can concatenate lists. With * we can repaeat items. Combining bith also works") fruit = ["apple","orange","banana","cherry"] print('the list fruit contains: ' + str(fruit)) a = fruit +[1,32,666,69] print([1,2] + [3,4]) print('Concataning two list like a = a = fruit +[1,32,666,69] gives a new list a: ' + str(a)) b =a[1:5]*2 print('Repeating selected values of a list like eg b =[a[1:5]*2] gives: ' +str(b) ) print("-----------------------------") #%% Count and index # Look here for an overview of list class methods: https://www.w3schools.com/python/python_ref_list.asp # Look here for an overview of string class methods: https://www.w3schools.com/python/python_ref_string.asp print('Count is a method of strings and lists that counts the occurence of a character or set of characters appear in a string/list') SS = "This is my test string that I have created. Ha ha ha!" SSha = SS.count("ha") print('my string is: '+ SS + ' the count of ha is SS.count("ha"): ' + str(SSha) ) print('If the character/string we are looking does not exist count returns 0') print("-----------------------------") SSindha = SS.index('ha') print('Index is a method of strings and lists that find the first index where a character or set of characters appear in a string/list') print('my string is: '+ SS + ' the count of ha is SSindha = SS.index("ha"): ' + str(SSindha) ) print('If the character/string we are looking does not exist python gives an error instead of empty output...') print("-----------------------------") L2 = [0.34, '6', 'SI106', 'Python', -2,6] L2_6 = L2.count(6) print('my list is: '+ str(L2) + ' the count of 6 is L2.count(6): ' + str(L2_6) ) print('If the character/string we are looking does not exist count returns 0') print("-----------------------------") L2_ind6 = L2.index(6) print('my list is: '+ str(L2) + ' the first index of 6 is L2.index(6): ' + str(L2_ind6) ) print('If the character/string we are looking does not exist index throws errror!') print("-----------------------------") #%% Split and join strings print ('The split method of strings breaks a string to smaller strings based on space') Ssplit = 'I have this string that I want to splitin words' Sspl= Ssplit.split() print('My string is:<' +Ssplit +'> and S.split() gives: ' + str(Sspl) ) Sspl2= Ssplit.split('i') print('If the input of split is not empty I can define a special delimite. E.g: S.split("i"): ' + str(Sspl2)) print('The deliiter DOES NOT appear in the result!') print("-----------------------------") print ('The join method of strings concatenates strings based on specific glue character') wds = ["red", "blue", "green"] glue = ';' s = glue.join(wds) #print(s) Sjoined = " ".join(wds) print( 'My list of strings is:' + str(wds)) print ('I can join my list by defining the connection character " ".join(wds): '+Sjoined) print('Or using any other character like "***".join(wds): ' + "***".join(wds)) #print("".join(wds))
4c58f3e5799dd7de38c26d14cdaf2ca9ebd8dd5c
Vaspe/Coursera_Python_3_Programming_Michigan
/Python_Classes_and_Inheritance_Mod4/Ch18_Test_Cases.py
3,893
4.03125
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 18 00:03:34 2020 @author: Vasilis Important resouces not covered in the course abut modules unittest and doctest: https://docs.python.org/3/library/unittest.html https://docs.python.org/3/library/doctest.html#module-doctest Asser statement: https://docs.python.org/3/reference/simple_stmts.html#assert Other good docs: https://realpython.com/python-testing/ """ #%% assert 5==5 print('I passd') #%% checking the type assert type(9//5) == int #assert type(9.0//5) == int #%% checking if list elements are the same lst = ['a', 'b', 'c'] first_type = type(lst[0]) for item in lst: assert type(item) == first_type lst2 = ['a', 'b', 'c', 17] first_type = type(lst2[0]) #for item in lst2: # assert type(item) == first_type #%% check length of a variable lst = ['a', 'b', 'c'] assert len(lst) < 10 #%% function test def accumulator(lst): accum = 0 for w in lst: accum = accum + w return accum assert accumulator([1,2,3]) == 6 # assert accumulator([]) == None # gives 0 instead og the expected 0!!!! #%% Testing possible combination of outputs of functions """ #1 Functionality with 'normal' expec ted inputs #2 Testing edge cases like numbers or types of inputs that are extreme #3 Testing side effects like mutations of lists or other stuf that are not directly # connected to the functionality #4 Test outputs like files written outside the environment """ # functionality and edge tests def square(x): return x*x assert square(3) == 9 assert square(4) ==16 assert square(0) ==0 assert square(-3)==9 # side effect tests: def update_counts(letters, counts_d): for c in letters: if c not in counts: counts_d[c] = 0 if c in counts_d: counts_d[c] = counts_d[c] + 1 counts = {'a': 3, 'b': 2} update_counts("aaab", counts) # 3 more occurrences of a, so 6 in all assert counts['a'] == 6 # cretes an error! # 1 more occurrence of b, so 3 in all assert counts['b'] == 3 # The same for optional parametrs. assert sorted([1, 7, 4]) == [1, 4, 7] assert sorted([1, 7, 4], reverse=True) == [7, 4, 1] #%% When doing development unit test for each increment change should be done # before the implementation itself. This is a good practice to make sure # we have a clear scope and added functionality does not break the previous def distance(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 dsquared = dx**2 + dy**2 result = dsquared**0.5 return result assert distance(1, 2, 1, 2) == 0 assert distance(1,2, 4,6) == 5 assert distance(0,0, 1,1) == 2**0.5 """ 1. Make sure you know what you are trying to accomplish. Then you can write appropriate unit tests. 2. Start with a working skeleton program and make small incremental changes. At any point, if there is an error, you will know exactly where it is. 3. Use temporary variables to hold intermediate values so that you can easily inspect and check them. 4. Once the program is working, you might want to consolidate multiple statements into compound expressions, but only do this if it does not make the program more difficult to read. """ #%% In the same way we can also create test cases for classes! class Point: """ Point class for representing and manipulating x,y coordinates. """ def __init__(self, initX, initY): self.x = initX self.y = initY def distanceFromOrigin(self): return ((self.x ** 2) + (self.y ** 2)) ** 0.5 def move(self, dx, dy): self.x = self.x + dx self.y = self.y + dy #testing class constructor (__init__ method) p = Point(3, 4) assert p.y == 4 assert p.x == 3 #testing the distance method p = Point(3, 4) assert p.distanceFromOrigin() == 5.0 #testing the move method p = Point(3, 4) p.move(-2, 3) assert p.x == 1 assert p.y == 7
00e3304a1b6216c18d5cd8fc9ea5c266ed72149e
Vaspe/Coursera_Python_3_Programming_Michigan
/Python_Project_pillow_tesseract_and_opencv_Mod5/Week2_Tesseract/ipywidgets_stuff.py
2,172
4.15625
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 30 19:49:51 2020 @author: Vasilis """ # In this brief lecture I want to introduce you to one of the more advanced features of the # Jupyter notebook development environment called widgets. Sometimes you want # to interact with a function you have created and call it multiple times with different # parameters. For instance, if we wanted to draw a red box around a portion of an # image to try and fine tune the crop location. Widgets are one way to do this quickly # in the browser without having to learn how to write a large desktop application. # # Lets check it out. First we want to import the Image and ImageDraw classes from the # PILLOW package from PIL import Image, ImageDraw # Then we want to import the interact class from the widgets package from ipywidgets import interact # We will use interact to annotate a function. Lets bring in an image that we know we # are interested in, like the storefront image from a previous lecture image=Image.open('readonly/storefront.png') # Ok, our setup is done. Now we're going to use the interact decorator to indicate # that we want to wrap the python function. We do this using the @ sign. This will # take a set of parameters which are identical to the function to be called. Then Jupyter # will draw some sliders on the screen to let us manipulate these values. Decorators, # which is what the @ sign is describing, are standard python statements and just a # short hand for functions which wrap other functions. They are a bit advanced though, so # we haven't talked about them in this course, and you might just have to have some faith @interact(left=100, top=100, right=200, bottom=200) # Now we just write the function we had before def draw_border(left, top, right, bottom): img=image.copy() drawing_object=ImageDraw.Draw(img) drawing_object.rectangle((left,top,right,bottom), fill = None, outline ='red') display(img) # Jupyter widgets is certainly advanced territory, but if you would like # to explore more you can read about what is available here: # https://ipywidgets.readthedocs.io/en/stable/examples/Using%20Interact.html
cf9fcbcad23d70ed863af3f74cbfac22543b5671
Vaspe/Coursera_Python_3_Programming_Michigan
/Python_Basics_Mod1/Mutability_ch9.py
4,943
3.90625
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 2 22:32:44 2020 @author: Vasilis """ #%% Theory # List are mutable we can add, remove or reassign elements # Strings and tuples are immutable we can only reassign or create a new variable to change them #%% Basics # replacing elements alist = ['a', 'b', 'c', 'd', 'e', 'f'] alist[1:3] = ['x', 'y'] print(alist) # squeezing in elemnts alist = ['a', 'b', 'c', 'd', 'e', 'f'] alist[3:3] = ['x', 'y'] print(alist) # deleting elements 1st method alist = ['a', 'b', 'c', 'd', 'e', 'f'] alist[1:3] = [] print(alist) # deleting elements second method alist = ['a', 'b', 'c', 'd', 'e', 'f'] del alist[1:3] print(alist) #%% Check if two variables reference to the same object in python usingis operator a = "banana" b = "banana" print(a is b) b += b # reassign it and check again print(a is b) b = "banana" # we can also check the unique id of each object using the id commnad print(id(a)) print(id(b)) # the immutable strings have the same identifier print(id(alist)) # this is not valid for lists which are always assigned to UNIQUE IDs print("-------------------------------") a = [81,82,83] b = [81,82,83] print(a is b) print(a == b) # they are the same but dont have the same id! print(id(a)) print(id(b)) print("-------------------------------") # If we reassign the varible though the lsit tkes the same id c = b print(c is b) print(c == b) # they are the same but dont have the same id! print(id(c)) print(id(b)) # Now c is alias of b. Practically is the same object with another name. So any mutation # to the object will reflect in all other named variables # Although this behavior can be useful, it is sometimes unexpected or undesirable. # In general, it is safer to avoid aliasing when you are working with mutable objects. #%% # We can clone a list to avoid the alias as explained before. Clone means we assign # a new name and ID to the same mutable object a = [81,82,83] b= a[:] print("-------------------------------") print (a is b) print(a == b) # print(id(a)) print(id(b)) b[0] = 5 print(a) print(b) print("-------------------------------") #%% Mutability of METHODS # remeber: https://www.w3schools.com/python/python_ref_list.asp mylist = [] mylist.append(5) mylist.append(27) mylist.append(3) mylist.append(12) print(mylist) mylist.insert(1, 12) # inserts stuff in the list permanently print(mylist) print(mylist.count(12)) # only counts occurencies print(mylist.index(3)) # only finds the first index of a nelement print(mylist.count(5)) mylist.reverse() # reverses the order of the list permanently print(mylist) mylist.sort() # sorts the list from low to high permanently! print(mylist) mylist.remove(5) # removes the lement with value 5 (not the fifth!) print(mylist) lastitem = mylist.pop() # pop removes an element from a specific position if empty removes the last print(lastitem) print(mylist) print("-------------------------------") #%% ''' methods like append, sort, and reverse all return None !!!! Dont use them to create new lists ''' mylist = mylist.sort() #probably an error print(mylist) print("-------------------------------") #%% STRING METHODS #remember: https://www.w3schools.com/python/python_ref_string.asp ss = "Hello, World" print(ss.upper()) tt = ss.lower() print(tt) ss = " Hello, World " print (ss) els = ss.count("l") print(els) print("***"+ss.strip()+"***") news = ss.replace("o", "***") print(news) name = "Vasilis" score = 5 str_form = "Hello {}. Your score is {}".format(name,score) print (str_form) origPrice = 100 discount = 17 newPrice = (1 - discount/100)*origPrice # number format calculation = '${:.2f} discounted by {}% is ${:.2f}.'.format(origPrice, discount, newPrice) print(calculation) # overview of fstrinmg formatting types are here: # https://www.w3schools.com/python/ref_string_format.asp print("-------------------------------") a = 5 b = 9 setStr = 'The set is {{ {}, {} }}.'.format(a, b) print(setStr) print("-------------------------------") #%% #Append vs Concatenate origlist = [45,32,88] print("origlist:", origlist) print("the identifier:", id(origlist)) #id of the list before changes newlist = origlist + ['cat'] print("newlist:", newlist) print("the identifier:", id(newlist)) #id of the list after concatentation origlist.append('cat') print("origlist:", origlist) print("the identifier:", id(origlist)) #id of the list after append is used print("-------------------------------") origlist = [45,32,88] print("origlist:", origlist) aliaslist = origlist print("aliaslist:", aliaslist) origlist += ["cat"] print(origlist) print (aliaslist) origlist = origlist + ["cow"] print("origlist:", origlist) print("aliaslist:", aliaslist) print("-------------------------------") winners = ['Alice Munro', 'Alvin E. Roth', 'Kazuo Ishiguro', 'Malala Yousafzai', 'Rainer Weiss', 'Youyou Tu'] print(str(winners)) winners.reverse() z_winners =winners print(str(z_winners))
0229eae841f5fec0563ad643a508650a3b1b235c
nadiiia/cs-python
/extracting data with regex.py
863
4.15625
4
#Finding Numbers in a Haystack #In this assignment you will read through and parse a file with text and numbers. #You will extract all the numbers in the file and compute the sum of the numbers. #Data Format #The file contains much of the text from the introduction of the textbook except that random numbers are inserted throughout the text. #Handling The Data #The basic outline of this problem is to read the file, look for integers using the re.findall(), looking for a regular expression of '[0-9]+' and then converting the extracted strings to integers and summing up the integers. import re name = raw_input("Enter file:") if len(name) < 1 : name = "regex_sum_212308.txt" handle = open(name) sum=0 for line in handle: stuff=re.findall('[0-9]+',line) #list of strings for str in stuff: num=int(str) sum=sum+num print 'Summ', sum
7b0da6770e7e68abc8b52de20229e4b8ff77ba76
mrcabellom/django-api-disney
/app/utils.py
306
3.71875
4
from datetime import datetime def parse_date(string_date): try: d = datetime.strptime(string_date, "%Y-%m-%d %H") except ValueError: d = datetime.strptime(string_date, "%Y-%m-%d") return d def date_to_string(date): d = datetime.strftime(date, "%Y-%m-%d %H") return d
255fd794666d6dc504c261877489e3b7ee872bbe
saharul/csa_ver3
/carinfo_db.py
4,096
3.515625
4
import pandas as pd class CarInfoDb: def __init__( self, filename="/home/saharul/Projects/csa_ver3/data/carinfo_master.csv" ): self.dbfilename = filename def GetModelId(self, model): if type(model) != str: raise TypeError("Car Model must be in str") if len(model) == 0: raise ValueError("Car Model cannot be empty") # read file car_info.csv df = pd.read_csv(self.dbfilename) # check model name contains the given string and to ignore case # df1 = df[df['Model'].str.contains("(?i)" + model)] df1 = df[df["Model"] == model] if df1.empty or len(model) == 0: return 1 else: # get the id value return df1.iloc[0]["Id"] # function to get car information by is id in the db def GetCarInfoById(self, car_id): carinfolist = self.ListCarInfo() if type(car_id) != str: raise TypeError("car id must be type str") for car in carinfolist: if car[0] == str(car_id): return car # function to view all the car model in the csv file """ will return car informatio i.e ['2', 'EXORA 1.6 (A)', 'AGU4004', '', '', '', 'SILVER', 'SAHARUL'] """ def ListCarInfo(self): carinfolist = [] with open(self.dbfilename, "r") as f: for line in f: line = line.rstrip() carinfo = line.split(",", 8) if not line: continue if carinfo[0] == "Id": continue carinfolist.append(carinfo) # add car information return carinfolist # function to ask user for model to choose from # and return back the car info of the chosen model def SelectCarInfo(self, defmodel=""): carinfolist = self.ListCarInfo() # get default model id defid = self.GetModelId(defmodel) print("\nCHOOSE YOUR CAR MODEL: ") for car in carinfolist: print(car[0] + ". " + car[1]) choice = "" while True: try: # ask user to make choice and show the default value as well choice = int( input("\nSelect your car model (1,2), default [%s]: " % defid) ) # choice is assigned to user choice or default value choice = choice or defid carinfo = carinfolist[choice - 1] except IndexError: print("\nInvalid Selection!") continue except ValueError: if not choice: # check if choice empty string (user press 'Enter') carinfo = carinfolist[int(defid - 1)] break else: print("\nInvalid Input!") continue else: # print(carinfo) return carinfo return carinfo # function to view all the car model in the csv file def ListCarInfoShort(self): carinfolist = [] with open(self.dbfilename, "r") as f: for line in f: line = line.rstrip() if not line: continue carinfo = line.split(",", 8) if carinfo[0] == "Id": continue # skip the header carinfolist.append(carinfo[1]) return carinfolist # def get_record(self, record_id): # with open("service_master.csv","r") as f: # for line in f: # line = line.rstrip() # line = line.split(",", 9) # if (line[0] == str(record_id)): # return line # main function for running the program def main(): ci = CarInfoDb() print(type(ci.GetModelId("EXORA 1.6 (A)"))) # print(ci.ListCarInfoShort()) # print(ci.GetCarInfoById("2")) # print(ci.GetCarInfoById(2)) # print(ci.GetModelId("EXORA 1.6 (A)")) if __name__ == "__main__": main()
45e7a9010b5dd5c64c2806a33cac78e7892519bc
pascal19821003/python
/study/tutorial/if.py
105
4.03125
4
x=1 if x<1: print("greater than 1") elif x==1: print("equal to 1") else: print("less than 1")
a1cf305f838642ef9d1c17a626952e89e65753c9
pascal19821003/python
/study/tutorial/runoob/1.py
1,237
4.0625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- # https://www.runoob.com/python/python-variable-types.html counter=100 # 赋值整型变量 miles = 1000.0 # 浮点型 name = "John" # 字符串 print(counter) print (miles) print (name) print("----------------------------") a = b = c = 1 print(a) print(b) print(c) print("----------------------------") a, b, c = 1, 2, "john" print(a) print(b) print(c) print("----------------------------") s="abcdef" print(s[5]) print(s[3:5]) print(s[-1]) print(s[-3:]) print("----------------------------") list = [ 'runoob', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print (list) # 输出完整列表 print (list[0]) # 输出列表的第一个元素 print (list[1:3] ) # 输出第二个至第三个元素 print ( list[2:] ) # 输出从第三个开始至列表末尾的所有元素 print (tinylist * 2) # 输出列表两次 print ( list + tinylist) # 打印组合的列表 print("----------------------------") dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print (dict['one']) print (dict[2]) print (tinydict) print (tinydict.keys()) print (tinydict.values())
c2636f45f0515cf761426c0aea37ba3eaadfda09
jasonDBA/pythonApp
/Read_Write_A_Text_File/Read_Write_A_Text_File.py
1,598
3.640625
4
# Read / Write files in Python # Project: Read / Write 'Let it be' lylics # Name: Jason(Jabin) Choi # Date: June 8, 2020 # Reference: https://docs.python.org/3/tutorial/inputoutput.html import os # import os module script_dir = os.getcwd() odd_path = "oddlines.txt" even_path = "evenlines.txt" output_path = "output.txt" abs_odd_path = os.path.join(script_dir, odd_path) abs_even_path = os.path.join(script_dir, even_path) abs_output_path = os.path.join(script_dir, output_path) fodd = open(abs_odd_path, 'r', encoding='utf-8') # open a oddlines text file (r: read mode) feven = open(abs_even_path, 'r', encoding='utf-8') # open a evenlines text file (r: read mode) if os.path.isfile(abs_output_path): # if output text file is written something, os.remove(abs_output_path) # remove the content foutcome = open(abs_output_path, 'w', encoding='utf-8') # open an output text file (w: write mode) else: foutcome = open(abs_output_path, 'w', encoding='utf-8') while True: # Loop through the odd and even line til input lines do not exist any more oddSentence = fodd.readline() foutcome.writelines(oddSentence) evenSentence = feven.readline() foutcome.writelines(evenSentence) if not oddSentence: break foutcome.writelines('\n\n===================================================') foutcome.writelines('\nName: Jason(Jabin) Choi, Date: June 8, 2020') foutcome.writelines('\n===================================================') foutcome.close() # close the output file feven.close() foutcome.close()
4e8ad87dcc310d0b2dc8ec15dadb325cdae597f6
dmi3s/stepik-512-py
/Hierarchy.py
1,098
3.890625
4
import string class Hierarchy(dict): def is_derived_from(self, derived: string, base: string) -> bool: if derived not in self: return False if derived == base: return True for p in self[derived]: if p == base or self.is_derived_from(p, base): return True return False def is_base_of(self, base: string, derived: string) -> bool: return self.is_derived_from(derived, base) def parse_definition(definition: string) -> (string, []): if ":" not in definition: return definition.strip(), [] name, bases = definition.split(":", 1) return name.strip(), bases.strip().split(" ") def main(): h = Hierarchy() for _ in range(int(input())): name, bases = parse_definition(input()) h[name] = bases prev = [] for _ in range(int(input())): ex = input().strip() for p in prev: if h.is_derived_from(ex, p): print(ex) break prev.append(ex) main() if __name__ == '__main__': main()
85268e65ca2eefeec04a1501f96479be569f23bd
fshi7418/hack-the-north-2018
/digital_recognition.py
3,794
3.65625
4
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) #the following is a RandomForest training program for a model training_data = pd.read_csv("train.csv") # Any results you write to the current directory are saved as output. from sklearn.metrics import * from sklearn.model_selection import train_test_split # Our y will be the survived column so we'll add it then drop it from our X set y = training_data['label'] X = training_data.drop(['label'], axis=1) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42) #display(X_train) #display(X_test) #display(y_test) #display(y_train) # First we'll tryout the basic Random Forest algorithm #from sklearn.ensemble import RandomForestClassifier # rfc = RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=40, n_jobs=-1, oob_score=True, random_state=42, verbose=0, warm_start=False) rfc.fit(X_train, y_train) preds = rfc.predict(X_test) #display(preds) #The accuracy is usually quite high for RandomForest -- 90+% print(accuracy_score(y_test, preds)) #the following draws the first 20 entries of the test file; the result will # be compared to the visually confirmed answers later test_data = pd.read_csv("test.csv") preds2 = rfc.predict(test_data.head(20)) display(preds2) #the following code draws from the test.csv file to extract the first 20 # entries, each entry representing a written number # from PIL import Image, ImageDraw # image1 = Image.new('RGB', (28, 28), (255, 255, 255)) # a white canvas test_data = pd.read_csv('test.csv') test_data.drop(['label'], axis = 1) print(test_data.shape) # prints the dimension of the data just to be sure display(test_data.loc[8:8]) # loc[8:8] extracts the 8th row of the table # This is drawing the number on the white canvas by the data count = 1 for count in range(20): image1 = Image.new('RGB', (28, 28), (255, 255, 255)) for x in range(28): for y in range(28): if test_data.iat[count, x * 28 + y] > 0: image1.putpixel((x,y),(0,0,0)) draw = ImageDraw.Draw(image1) image1.save('image{0}.png'.format(count)) # Note that RGB value == 0 means it's black; RGB==255 means it's white # The following uses another algorithm called K-Nearest Neighbour from sklearn.neighbors import KNeighborsClassifier df0 = pd.read_csv('train.csv') df = df0[0:15000] df.head() from sklearn.model_selection import train_test_split X = np.array(df.iloc[:, 2:785]) y = np.array(df['label']) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=42) # split into train and test for i in range(5): # instantiate learning model (k = 2) knn = KNeighborsClassifier(n_neighbors=2) # fitting the model knn.fit(X_train, y_train) # predict the response pred = knn.predict(X_test) # evaluate accuracy print('\nThe percentage of correct estimate (for the training data)is %' + str(accuracy_score(y_test, pred) * 100) + '') df1 = df0[15001:40000] df2 = df1.sample(n=10000) new_X = np.array(df2.iloc[:, 2:785]) new_y = np.array(df2['label']) new_pred = knn.predict(new_X) print('\nThe new percentage of correct estimate (for the testing data)is %' + str(accuracy_score(new_y, new_pred) * 100) + '')
c5bef145b8b46fee27bd38b53f39f93985a5588a
aanyag/15112-Clue
/clueAI.py
3,700
3.703125
4
from cmu_112_graphics import * import math, random class MyApp(App): def appStarted(self): self.doorsList = [(3,6),(4,9),(5,17),(6,11),(6,12),(8,6),(9,17),(10,3), (12,1),(12,16),(15,5),(17,9),(17,14),(18,19),(19,4),(19,8),(19,15)] #I used this website (https://www.raywenderlich.com/3016-introduction-to-a-pathfinding) #only to learn how the A* algorithm, however I wrote all of the following code myself def pathfinding(self, start, end): #finds the shortest path from the user's position to where they wish to go openList = [start] scoreList = [0] closedList = [] gScore = 0 parentDict = {} #will keep running until the end location is in the final path list or #there are no more possible squares while True: #finds the square with the lowest f-score minScore = min(scoreList) minIndex = len(scoreList) - 1 - scoreList[::-1].index(minScore) currSquare = openList[minIndex] closedList += [currSquare] openList.pop(minIndex) scoreList.pop(minIndex) #break out of the loop if the end destination is in the closed list if end in closedList: break #find all eligible squares adjacent to the current location adjacentSquares = [] (row, col) = currSquare for direction in [(-1,0), (0,-1), (1,0), (0,+1)]: (newRow, newCol) = (row + direction[0], col + direction[1]) #square must be in the grid, and not a room, stair, or in the center room if (newRow >= self.rows or newRow < 0 or newCol >= self.cols or newCol < 0 or (newRow, newCol) in self.roomsList or (newRow, newCol) in self.stair1list or (newRow, newCol) in self.stair2list or (newRow, newCol) in self.centerRoomList): pass else: adjacentSquares.append((newRow, newCol)) gScore += 1 #for all adjacent squares, find the f-score for item in adjacentSquares: if item in closedList: continue hScore = abs(end[0] - item[0]) + abs(end[1] - item[1]) fScore = gScore + hScore #add square to the open list if item not in openList: parentDict[item] = currSquare openList += [item] scoreList += [fScore] #if already in the open list, update list if new f-score is lower than old f-score else: itemIndex = openList.index(item) oldFScore = scoreList[itemIndex] if fScore < oldFScore: openList.remove(item) scoreList.pop(itemIndex) parentDict[item] = currSquare openList += [item] scoreList += [fScore] #if the open list is empty, there is no path if (openList == []): break #determine the shortest path by traversing the parent dictionary backwards path = [end] currParent = parentDict[end] currPoint = end while currParent != start: path += [currParent] currPoint = currParent currParent = parentDict[currPoint] path += [start] return path def main(): MyApp(width=1440, height=801) if __name__ == '__main__': main()
ec44cec6454308cf50228aba28e85d23687d3ded
erisantiagodev/SimplePythonCarInsuranceApp
/PythonApplication1/PythonApplication1/PythonApplication1.py
1,177
3.984375
4
import os import sys, time def TicketsCalculation(): print("How many tickets do you have?") num_tickets = int(input()) if num_tickets < 4: print("We are able to proceed") else: print("We are unable to insure customers with more than 3 tickets") print("Thank you for your time") time.sleep(5) os._exit(1) return num_tickets def AccidentsCalculation(): print("How many accidents do you have?") num_accidents = int(input()) if num_accidents < 4: print("We are able to proceed") else: print("We are unable to insure customers with more than 3 accidents") print("Thank you for your time") time.sleep(5) os._exit(1) return num_accidents def AddingPoints(): num_tickets = TicketsCalculation() num_accidents = AccidentsCalculation() #total_points = int(num_tickets) + int(num_accidents) #print(f'We can insure you because you only have {total_points} points.') print(f'We can insure you because you only have {int(num_tickets) + int(num_accidents)} points.') print("Hello, and welcome to Eri's car insurance app!") AddingPoints()
554b6a60f0ce12acadbc4ed27d349fb4c37f04b1
Soist/waste_sorter
/Activity2/Milestone1.py
1,823
3.65625
4
import cv2 import numpy as np uppLeft = None lowLeft = None uppRight = None def mouseResponse(event, x, y, flags, param): """This function is a callback that happens when the mouse is used. event describes which mouse event triggered the callback, (x, y) is the location in the window where the event happened. The other inputs may be ignored.""" global uppLeft, lowLeft, uppRight if event == cv2.EVENT_LBUTTONDOWN: cv2.circle(workImg, (x, y), 5, (255, 0, 255), -1) if uppLeft is None: uppLeft = [x, y] print("uppLeft is " + str(uppLeft)) elif lowLeft is None: lowLeft = [x, y] print("lowLeft is " + str(lowLeft)) elif uppRight is None: uppRight = [x, y] print("uppRight is " + str(uppRight)) # read in an image origImg = cv2.imread("SampleImages/snowLeo1.jpg") (height, width, depth)= origImg.shape # make a copy and set up the window to display it workImg = origImg.copy() cv2.namedWindow("Working image") # assign mouse_response to be the callback function for the Working image window cv2.setMouseCallback("Working image", mouseResponse) # Keep re-displaying the window, and look for user to type 'q' to quit while True: cv2.imshow("Working image", workImg) x = cv2.waitKey(20) ch = chr(x & 0xFF) if ch == 'q': break if (uppLeft is not None) and (uppRight is not None) and (lowLeft is not None): origPts = np.float32([uppLeft, lowLeft, uppRight]) newPts = np.float32([[0, 0], [0, height - 1], [width - 1, 0]]) mat = cv2.getAffineTransform(origPts, newPts) warpImg = cv2.warpAffine(workImg, mat, (width, height)) cv2.imshow("Warped", warpImg) if ch == 'q': break cv2.destroyAllWindows()
779f35f7c879f19b76f34ac1c613a9a9293eb790
muskan121/code-example
/sample09.py
117
3.96875
4
def string_length(str1): count=0 for char in str1: count = count+1 return count print(string_length("muskaan"))
08122e08dcda056d55f018213db1082b01492827
DarkDivision4/CrackCaesar
/crackcaesar.py
402
3.90625
4
KEY = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ciphertext = input('Enter Cipher Text? ') def decrypt(x, ciphertext): result = '' for l in ciphertext: try: index = KEY.index(l) i = (index - x) % 26 result += KEY[i] except ValueError: result += l return result for x in range(0,27): dec = decrypt(x, ciphertext) print("[+] Shift: %d - %s" % (x,dec))
c0eea93b3e10fd8afd3abddc0869da07ad7a47d5
Yaz015/EjerciciosPython
/Guia2/E6.py
640
4.03125
4
#Escribir un programa que seleccione una operación de cuatro operaciones numéricas disponibles, # una vez seleccionada la operación, introducir dos números y ejecutar la operación. elegir_operacion = int(input("""Seleccionar la operación que desea realizar: 1 - Suma 2 - Resta 3 - Producto 4 - División Opcion: """ )) numero1 = int(input("Elegir un numero: ")) numero2 = int(input("Elegir otro numero: ")) if elegir_operacion == 1: print(numero1 + numero2) elif elegir_operacion == 2: print(numero1 - numero2) elif elegir_operacion == 4: print(numero1 / numero2) else: print(numero1 * numero2)
5a012ca3c16c00425e65c1c2414a70f6f7254e81
Yaz015/EjerciciosPython
/Guia1/Ejercicio4.py
164
3.84375
4
#Ejercicio 4: Crear un programa que pregunte al usuario su nombre y devuelva "¡Hola {nombre}!" nombre = input("Cual es su nombre?: ") print("Hola "+ nombre +"!")
b86aed3a1e2423a694aeed07db31085f8632993f
Yaz015/EjerciciosPython
/Guia1/Ejercicio8.py
316
3.59375
4
# Ejercicio 8: Crear un programa que almacene en una lista las siguientes materias: Historia, Matemática, Lengua y Geografía. # Luego devolver por pantalla la última materia almacenada. lista_materias = ['Historia' ,'Matemática', 'Lengua', 'Geometria'] ultimaMateria = lista_materias[-1] print(ultimaMateria)
38144f2e286a1ef7b1c997c0cad7a55e2174f7ba
astroteo/OptimizationExperiments
/genetic_boxes.py
4,988
3.65625
4
#!/usr/bin/python2.7 # -*-coding:Utf-8 -* import numpy as np import random #step-1: create a fitness function def fitness (password, test_word): if (len(test_word) != len(password)): print "taille incompatible" return else: score = 0 i = 0 while (i < len(password)): if ( test_word[i] == password[i] ): score+=1 i+=1 return score * 100 / len(password) #step-2: create individuals # individual ==> word {!! fitness evaluates one individual at once !! } # population ==> words ={w1,w2,...wn } def generateAWord (length): i = 0 result = "" while i < length: letter = chr(97 + int(26 * random.random())) result += letter i +=1 return result def generateFirstPopulation(sizePopulation, length): population = [] i = 0 while i < sizePopulation: population.append(generateAWord(length)) i+=1 return population #step-3: from one population to the next # 3a) evaluate the population ==> sort evaluated individuals by score # 3b) select best individual(s) ==> HyperParameter: HOW MANY INDIVIDUALS TO BE KEPT AFTER SORTING # key-point1: shuffle after sorting !! Don't be soooo stupid !! def computePerfPopulation(population, password): populationPerf = {} for individual in population: populationPerf[individual] = fitness(password, individual) return sorted(populationPerf.items(), key=lambda kv: kv[1],reverse=True) def selectFromPopulation(populationSorted, best_sample, lucky_few): nextGeneration = [] for i in range(best_sample): nextGeneration.append(populationSorted[i][0]) for i in range(lucky_few): nextGeneration.append(random.choice(populationSorted)[0]) random.shuffle(nextGeneration)# CRUCIAL: shuffle after sorting. return nextGeneration #step-4: mutations & Child def createChild(individual1, individual2): child = "" for i in range(len(individual1)): if (int(100 * random.random()) < 50): child += individual1[i] else: child += individual2[i] return child def createChildren(breeders, number_of_child): nextPopulation = [] for i in range(len(breeders)/2): for j in range(number_of_child): nextPopulation.append(createChild(breeders[i], breeders[len(breeders) -1 -i])) return nextPopulation def mutateWord(word): index_modification = int(random.random() * len(word)) if (index_modification == 0): word = chr(97 + int(26 * random.random())) + word[1:] else: word = word[:index_modification] + chr(97 + int(26 * random.random())) + word[index_modification+1:] return word def mutatePopulation(population, chance_of_mutation): for i in range(len(population)): if random.random() * 100 < chance_of_mutation: population[i] = mutateWord(population[i]) return population #step-5: compute next population def nextGeneration (firstGeneration, password, best_sample, lucky_few, number_of_child, chance_of_mutation): populationSorted = computePerfPopulation(firstGeneration, password) nextBreeders = selectFromPopulation(populationSorted, best_sample, lucky_few) nextPopulation = createChildren(nextBreeders, number_of_child) nextGeneration = mutatePopulation(nextPopulation, chance_of_mutation) return nextGeneration #get best individual def getBestIndividualFromPopulation (population, password): return computePerfPopulation(population, password)[0] if __name__ =='__main__': d ={'a':3, 'bb':5, 'z': 1} print d ds = sorted(d.items(), key = lambda kv: kv[1]) print ds password = 'aeiouuoiea' length = len(password) print len('clwhovboyd') print len(password) print '------------------------FIRST ITERATION------------------------' firstPopulationTest = generateFirstPopulation(1000,length); selectedAndSortedPopulation = computePerfPopulation(firstPopulationTest, password) bestIndividuals = selectFromPopulation(selectedAndSortedPopulation, 10, 2)# keep best 10, and 2 lucky bastards print bestIndividuals print '---------------------------------------------------------------' print '------------------------ OPTIMIZATION ------------------------' generation =400; nFirstPopulation = 100; safeIndividuals =20 #nFirstPopulation/10; luckyBastards = 20 #nFirstPopulation/100; firstPopulation = generateFirstPopulation(nFirstPopulation,length); population = firstPopulation number_of_child = 5 chance_of_mutation = 5 # SUPER-KEY_POINT: ((best_sample + lucky_few) / 2 * number_of_child = size_population) while generation >0 or password_got == password: population = nextGeneration (population, password, safeIndividuals, luckyBastards, number_of_child, chance_of_mutation) #safeIndividuals /= 2; #luckyBastards /=2; #print population[1:3] print generation password_got = getBestIndividualFromPopulation(population, password) generation -=1; print '---------------------------------------------------------------' print password_got
0e236cdd26114b7f59f5b0b713931790a54145fd
arnoldfini/namra
/recommendations_algorithm/input_related/cs50.py
1,158
3.8125
4
import re import sys def get_string(prompt) -> object: """ Read a line of text from standard input and return it as a string, sans trailing line ending. Supports CR (\r), LF (\n), and CRLF (\r\n) as line endings. If user inputs only a line ending, returns "", not None. Returns None upon error or no input whatsoever (i.e., just EOF). Exits from Python altogether on SIGINT. """ try: if prompt is not None: print(prompt, end="") s = sys.stdin.readline() if not s: return None return re.sub(r"(?:\r|\r\n|\n)$", "", s) except KeyboardInterrupt: sys.exit("") except ValueError: return None def get_int(prompt): """ Read a line of text from standard input and return the equivalent int; if text does not represent an int, user is prompted to retry. If line can't be read, return None. """ while True: s = get_string(prompt) if s is None: return None if re.search(r"^[+-]?\d+$", s): try: return int(s, 10) except ValueError: pass
59bb55684bffde3abd337b0617af2117a9e4abb4
jinwei15/java-PythonSyntax-Leetcode
/LeetCode/src/FindAllAnagramsinaString.py
2,464
4.1875
4
# 438. Find All Anagrams in a String # Easy # 1221 # 90 # Favorite # Share # Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. # Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. # The order of output does not matter. # Example 1: # Input: # s: "cbaebabacd" p: "abc" # Output: # [0, 6] # Explanation: # The substring with start index = 0 is "cba", which is an anagram of "abc". # The substring with start index = 6 is "bac", which is an anagram of "abc". # Example 2: # Input: # s: "abab" p: "ab" # Output: # [0, 1, 2] # Explanation: # The substring with start index = 0 is "ab", which is an anagram of "ab". # The substring with start index = 1 is "ba", which is an anagram of "ab". # The substring with start index = 2 is "ab", which is an anagram of "ab". # Accepted # 94,870 # Submissions # 268,450 # my first idea is that to remain a hashtable window and keep looping the the long string form 0 to len(long string) - len(short string) class Solution: def findAnagrams(self, s, p): """ :type s: str :type p: str :rtype: List[int] """ block = dict() winBlock = dict() returnList = list() for ch in p: block[ch] = block.get(ch, 0) + 1 for i in range(0, len(s)): if i - len(p) >= 0: occur = winBlock.get(s[i - len(p)]) - 1 if occur == 0: del winBlock[s[i - len(p)]] else: winBlock[s[i - len(p)]] = occur winBlock[s[i]] = winBlock.get(s[i], 0) + 1 # print(winBlock) # print(i+1-len(p)) if winBlock == block: returnList.append(i + 1 - len(p)) return returnList # def findAnagrams(self, s, p): # """ # :type s: str # :type p: str # :rtype: List[int] # """ # block = dict() # returnList = list() # for ch in p: # block[ch] = block.get(ch,0)+1 # for i in range(0,len(s)-len(p) + 1): # winBlock = dict() # window of length len(p) # for ch in s[i:i+len(p)]: # winBlock[ch] = winBlock.get(ch,0)+1 # if winBlock == block: # returnList.append(i) # return returnList
3b45f252180ac6e85fdf1e94f783542378efd2de
jinwei15/java-PythonSyntax-Leetcode
/LeetCode/src/CountUnivalueSubtrees.py
1,443
3.578125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def countUnivalSubtrees(self, root: TreeNode) -> int: self.count = 0 def dfs(root): if root == None: return True left = dfs(root.left) right = dfs(root.right) if (left == right): if (root.left != None and root.left.val != root.val): return False if (root.right != None and root.right.val != root.val): return False self.count += 1 return True else: return False dfs(root) return self.count # public class Solution { # public int countUnivalSubtrees(TreeNode root) { # int[] arr = new int[1]; # postOrder(arr, root); # return arr[0]; # } # public boolean postOrder (int[] arr, TreeNode node) { # if (node == null) return true; # boolean left = postOrder(arr, node.left); # boolean right = postOrder(arr, node.right); # if (left && right) { # if (node.left != null && node.left.val != node.val) return false; # if (node.right != null && node.right.val != node.val) return false; # arr[0]++; # return true; # } # return false; # } # }
041f21360e8762ff26a339ef28e8891df72e5951
jinwei15/java-PythonSyntax-Leetcode
/LeetCode/src/TrappingRainWater.py
2,064
3.859375
4
# Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. # The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! # Example: # Input: [0,1,0,2,1,0,1,3,2,1,2,1] # Output: 6 # class Solution: # def trap(self, height): # """ # :type height: List[int] # :rtype: int # """ # # below is a brute force method this will lead to time limit exceeded: # # this is very boring. need to think a smarter way. # length = len(height) # ans = 0 # for i in range(1, length-1): # leftIndex = 0 # rightIndex = 0 # for j in range(i,-1,-1): # leftIndex = max(leftIndex, height[j]) # for j in range(i,length,1): # rightIndex = max(rightIndex,height[j]) # ans += min(leftIndex, rightIndex) - height[i] # return ans class Solution: def trap(self, height): """ :type height: List[int] :rtype: int """ if height == []: return 0 ans = 0 length = len(height) leftMax = [0 for i in range(length)] rightMax = [0 for i in range(length)] leftMax[0] = height[0] for i in range(1,length): leftMax[i] = max(height[i],leftMax[i-1]) rightMax[length - 1] = height[length - 1] for i in range(length-2,-1,-1): rightMax[i] = max(height[i], rightMax[i+1]) for i in range(1, length-1): ans += min(leftMax[i],rightMax[i]) - height[i] return ans
fa550f5026cc16f1dc02ef204fc352e79d027f57
jinwei15/java-PythonSyntax-Leetcode
/LeetCode/src/StringToInteger.py
1,972
3.796875
4
# mplement atoi which converts a string to an integer. # # The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. # # The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. # # If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. # # If no valid conversion could be performed, a zero value is returned. # # Note: # # Only the space character ' ' is considered as whitespace character. # Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned. class Solution: def myAtoi(self, s: 'str') -> 'int': """ :type str: str :rtype: int """ ###better to do strip before sanity check (although 8ms slower): ls = list(s.strip()) if len(ls) == 0: return 0 if len(s) == 0: return 0 if ls[0] == '-': sign = -1 else: sign = 1 if ls[0] in {'-', '+'}: del ls[0] ret, i = 0, 0 while i < len(ls) and ls[i].isdigit(): ret = ret * 10 + ord(ls[i]) - ord('0') # ret = ret*10 + int(ls[i]) i += 1 if sign * ret > 2 ** 31 - 1: return 2 ** 31 - 1 elif sign * ret < -2 ** 31: return -2 ** 31 return sign * ret # return max(-2**31, min(sign * ret, 2**31-1))
17dfc714163d95c66f05278ffc62b2b69ec0b967
jinwei15/java-PythonSyntax-Leetcode
/LeetCode/src/FindtheDuplicateNumber.py
1,020
3.53125
4
# # import collection # class Solution: # def findDuplicate(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # a = collections.Counter(nums) # return a.most_common(1)[0][0] # class Solution: # def findDuplicate(self, nums: List[int]) -> int: # dic = dict() # for i in nums: # if dic.get(i) != None: # return i # else: # dic[i] = dic.get(i,0) + 1 # return -1 class Solution: def findDuplicate(self, nums: List[int]) -> int: if (len(nums) > 1): slow = nums[0] fast = nums[0] while (fast != None and slow != None): slow = nums[slow] fast = nums[nums[fast]] if fast == slow: break print(slow) fast = nums[0] while (fast != slow): fast = nums[fast] slow = nums[slow] return slow return -1
5e2f86e03c300b8c89217e1402e66901514951c6
jinwei15/java-PythonSyntax-Leetcode
/LeetCode/src/LongestSubstringwithAtMostTwoDistinctCharacters.py
2,760
4.09375
4
import sys # Given a string s , find the length of the longest substring t that contains at most 2 distinct characters. # Example 1: # Input: "eceba" # Output: 3 # Explanation: t is "ece" which its length is 3. # Example 2: # Input: "ccaabbb" # Output: 5 # Explanation: t is "aabbb" which its length is 5. # https://www.geeksforgeeks.org/count-number-of-substrings-with-exactly-k-distinct-characters/ class Solution: def lengthOfLongestSubstringTwoDistinct(self, s): """ :type s: str :rtype: int """ # if s == '': return 0 # # this is the initial sol lution is using a hashmap: # longest = -sys.maxsize-1 # # longest = float('-inf') # resultNum = 0 # checkTable = [0]*56 # n = len(s) # for i in range(n): # count = 0 # checkTable = [0]*56 # for j in range(i,n): # if checkTable[ord(s[j]) - ord('a')] == 0: # count += 1 # checkTable[ord(s[j]) - ord('a')] += 1 # if count <= 2: # resultNum += 1 # else: # break; # if count <= 2 and j-i + 1 > longest: # longest = j-i+1 # return longest # Initialize sliding window and counts of chars in the window # Worst case time and space complexity: # Time: O(N), Space: O(W) where N is size of string and W is size of max window left = 0 right = 0 counts = dict() maxlength = 0 # Slide the window down the string until we reach the end # # Loop invariant: # (1) The previously seen window is s[left:right] # (2) The right index - left index of window is always the length # of the longest substring with <= 2 distinct characters while right < len(s): # Slide the right end up and update counts such that the window is now s[left:right+1] counts[s[right]] = counts.get(s[right],0) + 1 right += 1 # If the window has more than 2 characters, slide the left end of # the window up and update counts such that the window is now s[left+1:right+1] if len(counts) > 2: counts[s[left]] -= 1 if counts[s[left]] == 0: del counts[s[left]] left += 1 # print(right - left, " sep", left, right) # The length of the window is the length of the longest valid substring return right - left
fbc9f13538fa5ff7d4ed03965ee844c23d2cd6e4
jinwei15/java-PythonSyntax-Leetcode
/LeetCode/src/MiddleoftheLinkedList.py
477
3.875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def middleNode(self, head: ListNode) -> ListNode: pointer1 = head pointer2 = head while (pointer2 != None and pointer2.next != None): pointer1 = pointer1.next pointer2 = pointer2.next.next return pointer1 # this is the runner technique which is the two pointer technique.
9b552a95d0405e484c6b53ab2ce6d97d96f83daa
jinwei15/java-PythonSyntax-Leetcode
/LeetCode/src/AddDigits.py
293
3.6875
4
class Solution: def addDigits(self, num): """ :type num: int :rtype: int """ sum = 0 for ch in str(num): sum = sum + int(ch) if sum<10: return sum else: return self.addDigits(sum)
d784762141d91432fde3d91b904d9d2faa909dec
HelenaZanini/python_design_patterns
/strategy_pattern/strategy.py
396
3.75
4
from abc import ABC, abstractmethod class ImpostosAbstrato(ABC): @abstractmethod def calcula(self): pass class ICMS(ImpostosAbstrato): def calcula(self, valor): return valor * 0.11 class ISS(ImpostosAbstrato): def calcula(self, valor): return valor * 0.05 class PIS(ImpostosAbstrato): def calcula(self, valor): return valor * 0.025
154ed2e640f90b554e3e3750371211592e1ae30e
xheniscoba/XRating
/client/result/result.py
1,653
3.671875
4
class Result: """ A class used to represent a rated task. Attributes ---------- checkbox_results : list list of the rated attributes using Yes/No chekboxes slider_results : list list of the rated attributes using a slider with values in [0,100] Methods ------- add_checkbox_result(checkbox): Adds the result of the checked box to the attribute checkbox_results. add_slider_result(slider): Adds the value of the slider to the attribute slider_results. """ def __init__(self): self.checkbox_results = [] self.slider_results = [] self.toggle_button_results = [] def __str__(self): return 'the checkbox results: ' + str(self.checkbox_results) +'\nthe slider results: ' + str(self.slider_results) +'\nthe toggle button results: ' + str(self.toggle_button_results) def add_checkbox_result(self, checkbox): """ Adds the result of the checked box to the attribute checkbox_results Parameters ---------- checkbox: a MyCheckbox object, whose result we want to store """ self.checkbox_results.append(checkbox.get_checkbox_result()) def add_slider_result(self, slider): """ Adds the value of the slider to the attribute slider_results Parameters ---------- slider: a MySlider object, whose value we want to store """ self.slider_results.append(slider.get_slider_result()) def add_toggle_button_result(self, toggle_button): self.toggle_button_results.append(toggle_button.get_toggle_button_result())
0cd4fbd232f8b0d85ff333b2111e0a70826aec41
dhydrated/pgconn
/pgconn/menu_builder.py
522
3.515625
4
class MenuBuilder: """Menu builder""" menu="" selection=None def __init__(self, logger, items): self.logger = logger self.logger.name = self.__class__.__name__ self.items = items def display(self): index = 1 self.menu = "Please select a connection:\n" for item in self.items: self.menu += str(index) + ") " + item.getName() + "\n" index+=1 self.menu += "q) Quit." + "\n" self.menu += "Your selection: " self.selection = raw_input(self.menu) def getSelection(self): return self.selection
24a6d25c1621d6beda9926c9e11d510c7f7f6f1f
JobStoker/ProgrammingCourseHU
/2-6.InputAndOutput.py
303
3.609375
4
uurloon = input('Uurloon: ') werkuren = input('Aantal werkuren: ') int(uurloon) int(werkuren) salaris = int(werkuren)*int(uurloon) print('Je verdient: ' + str(uurloon) + ' per uur') print('Je hebt: ' + str(werkuren) + ' uren gewerkt') print(str(werkuren) + ' uur levert ' + str(salaris) + ' Euro op')
537fbef2767aed8a86d85cba69ff0ca8d1f8fcb6
JobStoker/ProgrammingCourseHU
/3-5.ForIfNumbers.py
85
3.84375
4
numbers = [3, 6, 4, 1, 7, -2] for i in numbers: if i % 2 == 0: print(i)
c3e814f8455d25a6b3d6279167f5a84578debf74
veenaGangi/serviceportal
/mapreduce/wordcount.py
1,260
3.859375
4
#!/usr/local/bin/python3.8 from mapreduce import MapReduce class WordCount(MapReduce): def mapper(self, _, line): for word in line.split(" "): yield (word.strip(),1) def combiner(self, key, values): yield key, sum(values) def reducer(self, key, values): yield key, sum(values) # input = [ # "this is an example of this line", # "this is an example of some example text", # "this is another example", # "and this is some more text and text and text" # ] with open("alice.txt","r") as f: input = f.read().lower().split() output = WordCount().run(input) max_key = "" max_value = 0 uniques = [] for word in input: if word not in uniques: uniques.append(word) counts = [] for unique in uniques: count = 0 for word in input: if word == unique: count += 1 counts.append((count, unique)) counts.sort() counts.reverse() for i in range(min(10, len(counts))): count, word = counts[i] print(i+1,'Most Common Word used---->',word,',Count--->', count) counts.sort() print('_______________________________________________________________') for i in range(min(10, len(counts))): count, word = counts[i] print(i+1,'least Word used---->',word,',Count--->', count)
94953f4e3009292aa5af210633ef280b0bc02725
abishekbalaji/hundred_days_of_code_python
/day_25/main.py
1,390
3.828125
4
# import csv # # with open(file="weather_data.csv") as data_file: # data = csv.reader(data_file) # temperatures = [] # for row in list(data)[1:]: # temperatures.append(int(row[1])) # print(temperatures) import pandas # data = pandas.read_csv('weather_data.csv') # print(data["temp"]) # temp_list = data["temp"].to_list() # print(round(sum(temp_list) / len(temp_list), 2)) # OR # print(round(data["temp"].mean(), 2)) # print(data["temp"].max()) # print(data.condition.to_list()) # print(data[data.day == "Monday"]) # print(data[data.temp == data.temp.max()]) # # monday = data[data.day == "Monday"] # mon_temp = int(monday.temp) # fahren = mon_temp * (9 / 5) + 32 # print(fahren) squirrel_data = pandas.read_csv('2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv') print(squirrel_data) gray_squirrels_count = len(squirrel_data[squirrel_data["Primary Fur Color"] == "Gray"]) red_squirrels_count = len(squirrel_data[squirrel_data["Primary Fur Color"] == "Cinnamon"]) black_squirrels_count = len(squirrel_data[squirrel_data["Primary Fur Color"] == "Black"]) print(gray_squirrels_count) print(red_squirrels_count) print(black_squirrels_count) data_dict = { "Fur Color": ["Gray", "Cinnamon", "Black"], "Count": [gray_squirrels_count, red_squirrels_count, black_squirrels_count] } df = pandas.DataFrame(data_dict) print(df) df.to_csv('squirrel_count.csv')
01046b00459e9344c53d1d3f4872e7cea3355d1e
abishekbalaji/hundred_days_of_code_python
/day-26-1/main.py
1,541
3.84375
4
nums = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] squared_nums = [num ** 2 for num in nums] print(squared_nums) # Filter even nums numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] even_nums = [num for num in numbers if num % 2 == 0] print(even_nums) # Common nums with open('file1.txt') as file1: list1 = file1.read().split('\n') with open('file2.txt') as file: list2 = file.read().split('\n') new_list = [int(num) for num in list1 if num in list2] print(new_list) # Number of letters in each word of a sentence sentence = "What is the Airspeed Velocity of an Unladen Swallow?" num_of_letters = {word: len(word) for word in sentence.split()} print(num_of_letters) # Weather in c to weather in f weather_c = { "Monday": 12, "Tuesday": 14, "Wednesday": 15, "Thursday": 14, "Friday": 21, "Saturday": 22, "Sunday": 24, } weather_f = {day: (temp_c * 9 / 5) + 32 for (day, temp_c) in weather_c.items()} print(weather_f) student_dict = { "student": ["Angela", "James", "Lily"], "score": [56, 76, 98] } # Looping through dictionaries: for (key, value) in student_dict.items(): # Access key and value pass import pandas student_data_frame = pandas.DataFrame(student_dict) print(student_data_frame) # Loop through rows of a data frame for (index, row) in student_data_frame.iterrows(): # Access index and row print(index, row) # Access row.student or row.score print(row.student, row.score) # Keyword Method with iterrows() # {new_key:new_value for (index, row) in df.iterrows()}
f32d4eafb08ee037e0e9637638db9d1b5c43b693
abishekbalaji/hundred_days_of_code_python
/CoffeeMachine1/main.py
2,196
3.9375
4
import menu items = menu.MENU resources = menu.resources money = 0 def report(): print(f"Water: {resources['water']}\nMilk: {resources['milk']}\nCoffee: {resources['coffee']}\nMoney: {money}") def is_sufficient(req): return req['water'] <= resources['water'] and req['milk'] <= resources['milk'] and req['coffee'] <= resources[ 'coffee'] def get_money(): return { "quarters": int(input("Enter no. of quarters: ")), "dimes": int(input("Enter the no. of dimes: ")), "nickles": int(input("Enter the no. nickles: ")), "pennies": int(input("Enter the no. pennies: ")) } def process_payment(cost, paid): global money denominations = { "quarters": 0.25, "dimes": 0.10, "nickles": 0.05, "pennies": 0.01 } amount = 0 for x in paid: amount += paid[x] * denominations[x] if amount < cost: return None elif amount == cost: return 0 money += cost return amount - cost def make_coffee(req): global resources for x in resources: resources[x] -= req[x] def machine(): served = False choice = input("What would you like: (espresso/latte/cappuccino): ") if choice == "report": report() elif choice in ("espresso", "latte", "cappuccino"): if is_sufficient(items[choice]["ingredients"]): print("Payment time!") paid = get_money() cost = items[choice]["cost"] payment = process_payment(cost, paid) if payment is None: print("Sorry that's not enough money. Money refunded.") elif payment == 0: print(f"Enjoy your {choice}") served = True else: print(f"Here is your ${round(payment, 2)} in change.\nEnjoy your {choice}") served = True else: print(f"Sorry. We are out of ingredients for {choice}.\nTry something else.") if served: make_coffee(items[choice]["ingredients"]) elif choice == "off": print("Bye!") return else: print("Check your input.") machine() machine()
b99d753d1130578e2305ddca338afb294f978715
abishekbalaji/hundred_days_of_code_python
/five_percent.py
137
3.921875
4
import math def five_percent(num): return math.ceil(num + (num * 0.05)) while True: print(five_percent(int(input("num: "))))
444d702ca4a6f39db57afab2acecfddf50e1a677
MenacingManatee/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/9-multiply_by_2.py
202
3.890625
4
#!/usr/bin/python3 def multiply_by_2(a_dictionary): new_dict = {} keys = a_dictionary.keys() for key in keys: new_dict.update({key: a_dictionary.get(key) * 2}) return (new_dict)
795cbf40f98ad3a775af177e11913ce831752854
MenacingManatee/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
504
4.21875
4
#!/usr/bin/python3 '''Prints a string, adding two newlines after each of the following: '.', '?', and ':' Text must be a string''' def text_indentation(text): '''Usage: text_indentation(text)''' if not isinstance(text, str): raise TypeError('text must be a string') flag = 0 for char in text: if flag is 1 and char is ' ': continue print(char, end="") flag = 0 if char in ['.', ':', '?']: print('\n') flag = 1
1ee074079729475b25368a84a39006e5306aec28
MenacingManatee/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
571
4.375
4
#!/usr/bin/python3 '''Adds two integers If floats are sent, casts to int before adding''' def add_integer(a, b=98): '''Usage: add_integer(a, b=98)''' if (a == float("inf") or (not isinstance(a, int) and not isinstance(a, float)) or a != a): raise TypeError('a must be an integer') elif (b == float("inf") or (not isinstance(b, int) and not isinstance(b, float)) or b != b or b is float("inf")): raise TypeError('b must be an integer') return (int(a) + int(b))
0979d91394847fbe8ff9edd49d6bb1e2d0fc451e
MenacingManatee/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/8-uppercase.py
319
3.921875
4
#!/usr/bin/python3 def islower(a): a = ord(a) if a > 96: return(a - (ord("a") - ord("A"))) else: return(a) def uppercase(s1): s2 = list(s1) for i in range(len(s2)): check = islower(s2[i]) s2[i] = chr(check) print("{:s}".format(s2[i]), end="") print("")
d5d557f24d2e74375e95cf22f7df5d2ed5587e8c
MenacingManatee/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
321
4.3125
4
#!/usr/bin/python3 '''Defines a function that appends a string to a text file (UTF8) and returns the number of characters written:''' def append_write(filename="", text=""): '''Usage: append_write(filename="", text="")''' with open(filename, "a") as f: f.write(text) f.close() return len(text)
d91f8e862b939ab0131fab2bf97c96681fba005a
MenacingManatee/holbertonschool-higher_level_programming
/0x0B-python-input_output/100-append_after.py
595
4.1875
4
#!/usr/bin/python3 '''Defines a function that inserts a line of text to a file, after each line containing a specific string''' def append_after(filename="", search_string="", new_string=""): '''Usage: append_after(filename="", search_string="", new_string="")''' with open(filename, "r") as f: res = [] s = f.readline() while (s != ""): res.append(s) if search_string in s: res.append(new_string) s = f.readline() f.close() with open(filename, "w") as f: f.write("".join(res)) f.close()
faefe53c66424e822ce06109fc4d095f013e64c0
MenacingManatee/holbertonschool-higher_level_programming
/0x06-python-classes/102-square.py
1,442
4.40625
4
#!/usr/bin/python3 '''Square class''' class Square: '''Defines a square class with logical operators available based on area, as well as size and area''' __size = 0 def area(self): '''area getter''' return (self.__size ** 2) def __init__(self, size=0): '''Initializes size''' self.__size = size @property def size(self): '''size getter''' return (self.__size) @size.setter def size(self, value): '''size setter''' if (type(value) is int): if (value >= 0): self.__size = value else: raise ValueError('size must be >= 0') else: raise TypeError('size must be an integer') def __eq__(self, other): '''Sets __eq__ to check area''' return (self.area() == other.area()) def __lt__(self, other): '''Sets __lt__ to check area''' return (self.area() < other.area()) def __gt__(self, other): '''Sets __gt__ to check area''' return (self.area() > other.area()) def __ne__(self, other): '''Sets __ne__ to check area''' return (not (self.area() == other.area())) def __le__(self, other): '''Sets __le__ to check area''' return (self.area() <= other.area()) def __ge__(self, other): '''Sets __ge__ to check area''' return (self.area() >= other.area())
55ea45a451bca133710791cb21e86bb40f5a85d3
MenacingManatee/holbertonschool-higher_level_programming
/0x06-python-classes/testfiles/6-main.py
544
3.5
4
#!/usr/bin/python3 Square = __import__('6-square').Square my_square_1 = Square(3) my_square_1.my_print() print("--") my_square_2 = Square(3, (1, 1)) my_square_2.my_print() print("--") my_square_3 = Square(3, (3, 0)) my_square_3.my_print() print("--") try: my_square_4 = Square(0, (0)) my_square_4.my_print() except Exception as e: print(e) print("--") try: my_square_5 = Square(1, (2, -3)) my_square_5.my_print() except Exception as e: print(e) print("--") my_square_6 = Square(3, (3, 3)) my_square_6.my_print()
5d5fc3a5e07ea8c85394024194ebbb62b4a49a56
higher68/Introduction_to_Algorithms_and_Data_Structures
/ALDS1_7_A.py
3,691
4.03125
4
# ouput:parent, depth, type, 子の節点番号をそれぞれのノードに対してアウトプット # pythonはnullじゃなくてNonce class Node: ''' leftは子ノード rightは同depthのノード ''' def __init__(self): self.parent = None self.left = None self.right = None # def getDepth(u): # ''' # depthを入力した番号のノードに対して求める # ''' # d = 0 # while Nodes[u].parent is not None: # u = Nodes[u].parent # d += 1 # return d # # # def printChild(u): # c = Nodes[u].left # while c is not None: # print(c) # c = Nodes[c] def printNode(u): print("node {}: ".format(u), end="") print("parent = {}, ".format(Nodes[u].parent), end="") print("depth = {}, ".format(Depth[u]), end="") if Nodes[u].parent == -1: print("root, ", end="") elif Nodes[u].left is None: print("leaf, ", end="") else: print("internal node, ", end="") print("[", end="") c = Nodes[u].left i = 0 while c is not None: if i == 0: print("{}".format(c), end="") else: print(", {}".format(c), end="") c = Nodes[c].right i += 1 # if i == 5: # exit() print("]") def rec(u, p): # print(u) Depth[u] = p if Nodes[u].right is not None: # print('right-hoge') rec(Nodes[u].right, p) if Nodes[u].left is not None: # print("left-hoge") rec(Nodes[u].left, p+1) n = int(input()) # print(n) Nodes = [[] for i in range(n)] for i in range(n): Nodes[i] = Node() # classを宣言するときは、()がないとおかしなことになる # print(type(Nodes)) # print("len", len(Nodes)) # for i in range(n): # Nodes[i].left, Nodes[i].right, Nodes[i].parent = i, i, i # for i in range(n): # print(i, Nodes[i].left, Nodes[i].right, Nodes[i].parent) # exit() Depth = [""] * n # for i in range(n): # print(i, Nodes[i].parent, Nodes[i].left, Nodes[i].right) # Nodes[i].parent, Nodes[i].left, Nodes[i].right = 1, 1, 1 # print(i, Nodes[i].parent, Nodes[i].left, Nodes[i].right) # exit() for i in range(n): q_in = [int(_) for _ in input().split()] # print(q_in) dimention = q_in[1] # 親の場合分け if dimention >= 1: Nodes[q_in[0]].left = q_in[2] # print(Node_number, dimention) # 子ノードの処理 if dimention >= 1: for j in range(0, dimention): # print(j, '-' x*20) # print('hoge', j+2, q_in[j+2], Node_number) # print(Node_number) if dimention > 1 and j <= dimention-2: Nodes[q_in[j+2]].right = q_in[j+3] # print(type(Nodes[q_in[j+2]].parent)) # print("Node_number2", Node_number, q_in[j+2]) # print("Nodes[q_in[j+2]].parent, Nodes[0].parent", Nodes[q_in[j+2]].parent, Nodes[0].parent) Nodes[q_in[j+2]].parent = q_in[0] # print("Nodes[q_in[j+2]].parent", q_in[0], q_in[j+2]) # print("Nodes[0].left, Nodes[0].parent, Nodes[0].right", Nodes[0].left, # Nodes[0].parent, Nodes[0].right) # print("Nodes[0].left, Nodes[0].parent, Nodes[0].right", Nodes[0].left, Nodes[0].parent, Nodes[0].right) # exit() # print("hoge") # exit() # exit() for i in range(n): if Nodes[i].parent is None: Nodes[i].parent = -1 r = -11 for i in range(n): if Nodes[i].parent == -1: r = i break if r != -11: rec(r, 0) # for i in range(n): # print(i, Nodes[i].parent, Depth[i]) # print(n) for i in range(n): # print("i", i) printNode(i)
774a96446d5fe9f8d4539871c36ab489d1531262
akhileshkaushal/annotation-refinery
/utils.py
4,259
3.640625
4
import os import tempfile import shutil import requests import urllib from urlparse import urlsplit import logging logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) def check_create_folder(folder_name): """ Small utility function to check if a folder already exists, and create it if it doesn't. """ logger.info('Creating folder ' + folder_name + '...') if not os.path.exists(folder_name): os.mkdir(folder_name) logger.info(folder_name + ' folder created.') else: logger.info('Folder ' + folder_name + ' already exists. ' + 'Saving downloaded files to this folder.') def download_from_url(url, download_folder, file_name=None): """ In case the downloading process gets interrupted, a dummy tempfile is created in the download_folder for every file that is being downloaded. This tempfile is then erased once the file finishes downloading. Arguments: url -- The URL string where the annotation file must be downloaded from. download_folder -- Path of folder where annotation file from URL will be downloaded to. This is a string. file_name -- Optional string argument for the name the downloaded file will will have in download_folder. If this is None, it will be assigned the last part of the url. Returns: True if file did not already exist and was able to be downloaded. Otherwise, return False. """ if file_name: filename = file_name else: filename = os.path.basename(urlsplit(url).path) target_filename = os.path.join(download_folder, filename) if os.path.exists(target_filename): logger.warning('Not downloading file ' + filename + ', as it already' ' exists in the download_folder specified.') return False try: if url.startswith('ftp'): urllib.urlretrieve(url, target_filename) # Because this is an FTP connection, we need to clear the # cache from previous calls. For more info, see: # https://stackoverflow.com/questions/44733710/downloading-second-file-from-ftp-fails # https://docs.python.org/2/library/urllib.html#urllib.urlcleanup urllib.urlcleanup() return True else: temp = tempfile.NamedTemporaryFile(prefix=filename + '.', dir=download_folder) download_request = requests.get(url, stream=True) # chunk_size is in bytes for chunk in download_request.iter_content(chunk_size=4096): if chunk: temp.write(chunk) temp.flush() # Go back to the beginning of the tempfile and copy it to # target folder temp.seek(0) target_fh = open(target_filename, 'w+b') shutil.copyfileobj(temp, target_fh) temp.close() # This erases the tempfile return True except: logger.error('There was an error when downloading the file "' + filename + '" - downloading could not be completed.') return False def translate_gene_ids(tribe_url, gene_list, from_id, to_id): payload = {'gene_list': gene_list, 'from_id': from_id, 'to_id': to_id} response = requests.post(tribe_url + '/api/v1/gene/xrid_translate', data=payload) return response def build_tags_dictionary(tag_mapping_file, geneset_id_column, geneset_name_column, tag_column, header): tags_dict = {} tag_file_fh = open(tag_mapping_file, 'r') if header: tag_file_fh.next() for line in tag_file_fh: toks = line.strip().split('\t') gs_id = toks[geneset_id_column] gs_name = toks[geneset_name_column] # Underscores may be used in files in place of spaces gs_name = gs_name.replace('_', ' ') gs_tag = toks[tag_column] if gs_id not in tags_dict: tags_dict[gs_id] = {'gs_name': gs_name, 'gs_tags': [gs_tag]} else: tags_dict[gs_id]['gs_tags'].append(gs_tag) tag_file_fh.close() return tags_dict
8c7829926b918d3cfce2b4eba919b84c0d4b4da3
MilesTide/Tree
/BinaryTree.py
1,691
4
4
#二叉树类 class BinaryTree(object): # 初始化,传入根节点的值 def __init__(self, root_value): self.root = root_value self.leftchild = None self.rightchild = None # 插入左子树 def insert_left(self, left_value): if self.leftchild == None : self.leftchild = BinaryTree(left_value) else: left_subtree = BinaryTree(left_value) left_subtree.leftchild = self.leftchild self.leftchild = left_subtree # 插入右子树 def insert_right(self, right_value): if self.rightchild == None : self.rightchild = BinaryTree(right_value) else: right_subtree = BinaryTree(right_value) right_subtree.rightchild = self.rightchild self.rightchild = right_subtree # 设置根节点的值 def set_root(self, root_value): self.root = root_value # 获取根节点的值 def get_root(self): return self.root # 获取左子树 def get_leftchild(self): return self.leftchild # 获取右子树 def get_rightchile(self): return self.rightchild # 前序遍历二叉树 def pre_traversal(tree): if tree != None: print(tree.root) pre_traversal(tree.leftchild) pre_traversal(tree.rightchild) # 中序遍历二叉树 def in_traversal(tree): if tree != None: in_traversal(tree.leftchild) print(tree.root) in_traversal(tree.rightchild) # 后序遍历二叉树 def post_traversal(tree): if tree != None: post_traversal(tree.leftchild) post_traversal(tree.rightchild) print(tree.root)
0e53f01af5ec7831f99804d3973a11052cf98426
shea7073/More_Algorithm_Practice
/bubble_sort.py
356
3.984375
4
# Implement bubble sort def bubble(arr): for j in range(len(arr)): for i in range(len(arr)-1): first = arr[i] second = arr[i+1] if first > second: temp = arr[i+1] arr[i+1] = arr[i] arr[i] = temp print(arr) bubble([9, 4, 3, 8, 6, 1, 2])