blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
a2d8eb1fdbaf7d9142e714096c61d533abdda077
chengdg/Lib
/site-packages/eaglet/utils/string_util.py
2,142
3.78125
4
# -*- coding: utf-8 -*- __author__ = 'chuter' import binascii def __is_hex_char(char): assert (char is not None) char = char.upper() return (ord(char) >= ord('0') and ord(char) <= ord('9')) or\ (ord(char) >= ord('A') and ord(char) <= ord('F')) def is_hax_str(hex_str): if hex_str is None or len(hex_str) == 0: return False if len(hex_str) % 2 != 0: return False for char in hex_str: if not __is_hex_char(char): return False return True def byte_to_hex(byte_str, join_with=''): """ Convert a byte string to it's hex string representation e.g. for output. """ if byte_str is None or len(byte_str) == 0: return byte_str if isinstance(byte_str, unicode): byte_str = byte_str.encode('utf-8') if is_hax_str(byte_str): return byte_str else: return binascii.b2a_hex(byte_str).upper() # Uses list comprehension which is a fractionally faster implementation than # the alternative, more readable, implementation below # # hex = [] # for aChar in byte_str: # hex.append( "%02X " % ord( aChar ) ) # # return ''.join( hex ).strip() # return ''.join( [ "%02X%s" % (ord(x), join_with) for x in byte_str ] ).strip() #------------------------------------------------------------------------------- def hex_to_byte(hex_str): """ Convert a string hex byte values into a byte string. The Hex Byte values may or may not be space separated. """ # The list comprehension implementation is fractionally slower in this case # # hex_str = ''.join( hex_str.split(" ") ) # return ''.join( ["%c" % chr( int ( hex_str[i:i+2],16 ) ) \ # for i in range(0, len( hex_str ), 2) ] ) if hex_str is None or len(hex_str) == 0: return hex_str if not is_hax_str(hex_str): return hex_str bytes = [] hex_str = ''.join(hex_str.split(" ")) for i in range(0, len(hex_str), 2): bytes.append(chr(int(hex_str[i:i+2], 16 ))) return ''.join(bytes)
b06e9ca5d69e2dd30c6ae3bacff41e698405444a
anna-kapitonova/PythonCourse
/hw_C2.py
192
3.765625
4
a=input() b=[int(symbol) for symbol in a] summ=0 pr=1 for i in range(len(b)): summ+=b[i] pr=pr*b[i] print('Сумма цифр:', summ) print('Произведение цифр:', pr)
c13bc0ed243e9ad020196d16a50592ceaee11120
FunkyMcMilker/Discret-Maths-is-4x4-sodoku-solved
/WS02_Kaiah_Miller_4124708.py
6,502
4.0625
4
#function bellow is for question 1 def p(grid,row,col,n): print("Checking if ", n, " can be placed at possition, grid[",row, "] [",col, "]") #checking if the value of n is equal to the value is the given possiton if grid[row-1][col-1] == n: print("True, the given value, ", n , "IS found at the given possition, grid[ ",row, "] [",col, "]" ) #prints output, and returns true return True else: #first checking if the space contains zero #if it does, then there IS a possibility of value n being placed there #returns true, however we dont know for sure if the value can be placed there tey #the check row and check grid functions can confirm or deny this possibility if grid[row-1][col-1] == 0: print("The given possition, grid[",row, "] [",col, "] is EMPTY" ) print("There IS a possibility of value ", n, " being placed here") return False #if the value is not zero, and not equal to n then it is not possible that n #can be placed in the given possition else: value = grid[row-1][col-1] print("False, The given possition, grid[",row, "] [",col, "] contains the value, ",value ) print("The value ", n, " cannot be placed here") return False #this function checks if a row contains all numbers 1 - 4 def check4rows(grid): row = 4 col = 4 trueCount = 0 #iterate through every row for r in range(row): #iteratre through every col #counter to shote the number of times p function returns true counter = 0 for c in range(col): num = 1 #while loop applies a check for each number 1 - 4 in a given possition while num <= 4: #check if the number is contained in that specific location if p(grid,r,c,num): num += 1 counter += 1 else: num +=1 #check if p function returns true 4 times if counter == 4: print("The row contains all numbers 1 - 4, True") print("\n") #add a counter for trueCount saying the row was satisfied trueCount += 1 else: print("The row does NOT contains all numbers 1 - 4, False") print("\n") if trueCount == 4: print("Every row satisfies numbers 1 - 4") print("\n") return True else: print("Every row does NOT satisfy numbers 1 - 4") print("\n") return False #this function checks each block of the puzzle for containing numbers 1-4 def check4blocks(grid): blockFoundcounter = 0 print("\n") print("Checking block 1") blockTwor = 1 blockTwoc = 1 c = 0 r = 0 counter = 0 while r <= blockTwor: while c <= blockTwoc: num = 1 while num <= 4: if p(grid,r,c,num): num += 1 counter += 1 else: num +=1 c += 1 r += 1 c = 0 if counter == 4: print("This block contains numbers 1 - 4, True") print("\n") blockFoundcounter += 1 else: print("This block does NOT contain numbers 1 - 4, False") print("\n") print("\n") print("Checking block 2") blockTwor = 1 blockTwoc = 3 c = 2 r = 0 counter = 0 while r <= blockTwor: while c <= blockTwoc: num = 1 while num <= 4: if p(grid,r,c,num): num += 1 counter += 1 else: num +=1 c += 1 r += 1 c = 2 if counter == 4: print("This block contains numbers 1 - 4, True") print("\n") blockFoundcounter += 1 else: print("This block does NOT contain numbers 1 - 4, False") print("\n") print("\n") print("Checking block 3") blockTwor = 3 blockTwoc = 1 c = 0 r = 2 counter = 0 while r <= blockTwor: while c <= blockTwoc: num = 1 while num <= 4: if p(grid,r,c,num): num += 1 counter += 1 else: num +=1 c += 1 r += 1 c = 0 if counter == 4: print("This block contains numbers 1 - 4, True") print("\n") blockFoundcounter += 1 else: print("This block does NOT contain numbers 1 - 4, False") print("\n") print("\n") print("Checking block 4") blockTwor = 3 blockTwoc = 3 c = 2 r = 2 counter = 0 while r <= blockTwor: while c <= blockTwoc: num = 1 while num <= 4: if p(grid,r,c,num): num += 1 counter += 1 else: num +=1 c += 1 r += 1 c = 2 if counter == 4: print("This block contains numbers 1 - 4, True") print("\n") blockFoundcounter += 1 else: print("This block does NOT contain numbers 1 - 4, False") print("\n") if blockFoundcounter == 4: print("\n") print("All blocks contain numbers 1 - 4") return True else: print("\n") print("All blocks do NOT contain numbers 1 - 4") return False grid = [] grid.append([2,1,0,0]) grid.append([0,3,2,0]) grid.append([0,0,0,4]) grid.append([1,0,0,0]) grid2 = [ [2, 1, 4, 3], [4, 3, 2, 1], [3, 2, 1, 4], [1, 4, 3, 2] ] print("\n") print("This is my grid :") print(grid) print("\n") print("This is the output of my p function :") print( p(grid,2,2,0) ) print("\n") print("This is the output of my check4rows function :") check4rows(grid) print("\n") print("This is the output of my check4blocks function :") check4blocks(grid) print("\n") print("This is my grid :") print(grid2) print("\n") print("This is the output of my p function :") print( p(grid2,2,2,0) ) print("\n") print("This is the output of my check4rows function :") check4rows(grid2) print("\n") print("This is the output of my check4blocks function :") check4blocks(grid2)
944b91b606f47ffc5ec48f6df6836a6a6998b449
Jokrrr/Python-Playground
/Write To File/write-to-file.py
246
3.984375
4
print("-----Write To A File-----") data = input("Please input that data you want written to a file:\n") f = open("Info_Output.txt","w") f.write(" " +data) f.close() print("Printing Input") r = open("Info_Output.txt","r") print(r.read()) r.close()
ee8d78347b62c66f285a746034dbd0ff23e90510
ekjellman/interview_practice
/epi/8_4.py
1,167
3.921875
4
### # Problem ### # Given the head of a linked list, determine if there is a cycle. If there # is, return the start of the cycle. If not, return None. ### # Work ### # Questions: # Length of list # Can I use a set? (assume no) # Why does your linked list have cycles, anyway. def cycle_test(head): fast = head slow = head while True: slow = slow.next_node fast = fast.next_node if fast: fast = fast.next_node if not fast: return None if slow == fast: break fast = head while fast != slow: slow = slow.next_node fast = fast.next_node return fast # Test: from linked_list import ListNode ll = ListNode.make_list([1, 2, 3, 4, 5, 6, 7, 8]) start = ll.find(3) end = ll.find(8) end.next_node = start result = cycle_test(ll) print result == start, result, start ll = ListNode.make_list(range(15)) start = ll.find(6) end = ll.find(14) end.next_node = start result = cycle_test(ll) print result == start, result, start ll = ListNode.make_list(range(15)) result = cycle_test(ll) print result, "None" # Time: 10 minutes ### # Mistakes / Bugs / Misses ### # Made some mistakes making find(), which I wrote for this problem's tests
9a5df42f950c08cc5285e15a9d7d31c3b30b62c2
Harryonismyname/CodingDojoProjects
/python_stack/_python/OOP/UsersWithBankAccounts/UsersWithBankAccounts.py
2,082
3.796875
4
class BankAccount: def __init__(self, int_rate=0.01, balance=0, name=""): self.int_rate = int_rate self.balance = balance self.name = name def deposit(self, amount): self.balance += amount return self def withdraw(self, amount): self.balance -= amount return self def display_account_info(self): print("{}\nBalance: ${}\nIntrest Rate: {}".format(self.name,self.balance, self.int_rate)) return self def yield_intrest(self): if self.balance > 0: self.balance+=self.int_rate*self.balance return self class User: def __init__(self, name): self.name = name self.accounts = {} def open_an_account(self, account): self.accounts[account.name] = account return self def make_deposit(self,account_name, amount): self.accounts[account_name].deposit(amount) return self def make_withdrawl(self,account_name, amount): self.accounts[account_name].withdraw(amount) return self def display_user_balance(self): print("\n",self.name,"Accounts:") for k in self.accounts: print("\n") self.accounts[k].display_account_info() return self def transfer_money(self, other_user, amount, account_name, other_user_account_name): print("Transferring:", amount, "from", account_name, "to", other_user_account_name) self.accounts[account_name].withdraw(amount) other_user.accounts[other_user_account_name].deposit(amount) return self pen = User("Pen") pen.open_an_account(BankAccount(0.25, 100, "Niran Mercenaries Official Account")).make_deposit("Niran Mercenaries Official Account", 700).make_deposit("Niran Mercenaries Official Account",1000).display_user_balance().make_withdrawl("Niran Mercenaries Official Account", 350).display_user_balance().open_an_account(BankAccount(0.15,100,"Pen's Personal Account")).transfer_money(pen, 50,"Niran Mercenaries Official Account","Pen's Personal Account").display_user_balance()
d8473cc08aaea8bb2f8a8fdcfa0d6541dbcd3beb
yashhR/competitive
/Edyst/antiDiagonals.py
405
3.671875
4
def Solution(A): result = [] diagonal = [] n = len(A) if n == 0: return result for d in range((2*(n-1))+1): for i in range(d+1): j = d - i if i >= n or j >= n: continue diagonal.append(A[i][j]) result.append(diagonal) diagonal = [] return result print(Solution([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
85a0b743384d3c84e4cde439cc9ef17b85a3ff89
svs144/forITEA
/hw_3_1.py
2,008
3.953125
4
a = input('Введите число a: ').strip() b = input('Введите число b: ').strip() # Валидация входного числа def validate_numbers(input_num): num_ok = True cnt_point = 0 cnt_minus = 0 for x in input_num: if (x.isdigit()): pass elif (x.isalpha()): num_ok = False elif (x == '.'): cnt_point += 1 elif (x == '-'): cnt_minus += 1 else: num_ok = False if cnt_minus > 1 or cnt_point > 1 or input_num == '': num_ok = False return num_ok # Расчет суммы натуральных чисел def sum_natural_numbers(a, b): summ = 0 # сумма всех натуральных чисел if float(a) < float(b): start = int(a) if a.isdigit() else float(a) end = int(b) if b.isdigit() else float(b) elif float(a) > float(b): start = int(b) if b.isdigit() else float(b) end = int(a) if a.isdigit() else float(a) else: if not a.isdigit(): if float(a) == int(float(a)): return int(float(a)) else: return 0 else: return a rez_isset = False # если не найдены числа, то дописываем '0' show_float = False end = int(end) + 1 while start < end: if show_float or start == int(start): if start > 0: summ += int(start) rez_isset = True else: show_float = True start += 1 if not rez_isset: return 0 else: return summ # Вызов функций if validate_numbers(a) and validate_numbers(b): print('Сумма натуральных чисел в диапазоне от ', a, ' до ', b, '>>> ', sum_natural_numbers(a, b)) else: print('Неверный формат ввода данных!')
952341523840a106bd21562d54db38b489b25afe
Chibi-Shem/python-exercises
/PE8.py
263
3.84375
4
def remove_duplicate(lst): """Removes duplicate objects in lst.""" new_list = [] for x in range(len(lst)): if new_list.count(lst[x]) < 1: new_list.append(lst[x]) return new_list print(remove_duplicate([1, 2, 3, 4, 1, 2]))
2c7b8169bd9a6cb87e1ca3619db5221f5b906922
cemar-ortiz/coding_challenges
/challenges/is_unique.py
1,169
4.15625
4
# Implement an algorithm to determine if a string has all unique characters. def task(string: str) -> (str, str): # 1 Pass input string into a list str_list = list(string) # O(n) # 2 Define a function that removes all instances of an item from a list # and checks its length before and after the operation. def remove_task(in_list): len_before = len(in_list) i = in_list[0] str_list = [char for char in in_list if char != i] # O(n) len_after = len(str_list) # If the difference is bigger than -1, then repeated characters were removed diff = len_after - len_before if diff < -1: ans = 'not unique' return ans # If a total length of 0 has been reached, no repeated characters were found if len_after == 0: ans = 'unique' return ans # If length is still not 0, call remove_task(str_list) again ans = remove_task(str_list) return ans # Recursion start. It will be called a max of n times ans = remove_task(str_list) # All operations not specified otherwise are estimated as constant time # Estimated total time complexity of O(n²) # Estimated space complexity of O(n) + O(n) = O(n) return (string, ans)
0f1e167a1dc20867139517ab5413b29b86742dae
bossjoker1/algorithm
/pythonAlgorithm/Practice/hard/6032得到要求路径的最小带权子图.py
1,182
3.5625
4
# 求三个点的最小值 # 枚举两条路中间的交汇点 # 需要建立反图 class Solution: def minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int: def dijkstra(g:List[List[tuple]], src:int) -> List[int]: dis = [inf] * n dis[src] = 0 # 堆优化 q = [(0, src)] while q: d, x = heappop(q) if dis[x] < d: continue for y, wt in g[x]: newd = wt + dis[x] if newd < dis[y]: dis[y] = newd heappush(q, (newd, y)) return dis g = [[] for _ in range(n)] rg = [[] for _ in range(n)] for x, y, wt in edges: g[x].append((y, wt)) rg[y].append((x, wt)) d1 = dijkstra(g, src1) d2 = dijkstra(g, src2) d3 = dijkstra(rg, dest) # 将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表 ans = min(sum(d) for d in zip(d1, d2, d3)) return ans if ans < inf else -1
c5bf83ac28d01abcd69880f8fa6b1ad2a5bebebf
rishabhgargdps/python_for_finance
/green_line_breakout.py
1,145
3.59375
4
import yfinance as yf import datetime as dt import pandas as pd from pandas_datareader import data as pdr yf.pdr_override() start = dt.datetime(1980,12,1) now = dt.datetime.now() stock = "" stock = input("Enter the stock symbol: ") while stock != "quit": df = pdr.get_data_yahoo(stock, start, now) dfmonth = df.groupby(pd.Grouper(freq="M"))["High"].max() glDate=0 lastGLV=0 currentDate="" currentGLV=0 for index, value in dfmonth.items(): if value > currentGLV: currentGLV=value currentDate=index counter=0 if value < currentGLV: counter+=1 if (counter==3 and (index.month!=now.month or index.year!=now.year)): if currentGLV!=lastGLV: print(currentGLV) glDate=currentDate lastGLV=currentGLV counter=0 print(str(lastGLV)) if lastGLV==0: message=stock+"has not formed a green line yet" else: message="Last Green line: "+str(lastGLV)+" was formed on "+str(glDate) print(message) stock = input("Enter the stock symbol: ")
98ab10674fe48fa9fe59417ee6b8c550aa919013
atm1992/nowcoder_offer_in_Python27
/p6_find_sort/a1_minNumberInRotateArray.py
2,911
3.734375
4
#-*- coding: UTF-8 -*- """ 旋转数组的最小数字。 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如:数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。 解题思路:若直接遍历整个数组,则时间复杂度为O(n),并未使用到数组有序后旋转的特性。 因为数组刚开始是有序的,然后经过了一次旋转,因此这里可以使用二分查找的变体,将时间复杂度降为O(logn) 可将旋转数组看作两个非递减的子数组,前一个子数组中的所有元素均大于等于后一个子数组中的元素,这两个子数组的分界点就是所需查找的最小元素 使用两个指针:头指针刚开始指向第一个元素;尾指针指向最后一个元素。 头指针始终在前一个子数组内,结束时指向前一个数组的最大元素;尾指针始终在后一个子数组中,结束时指向后一个数组的最小元素。 退出循环的条件是尾指针索引比头指针大于1 """ class Solution: def minNumberInRotateArray(self, rotateArray): if not rotateArray or len(rotateArray) < 1: return 0 low = 0 high = len(rotateArray) - 1 # 说明原有序数组没有旋转。若旋转了,数组的最后一个元素应该小于等于第一个元素 if rotateArray[low] < rotateArray[high]: return rotateArray[low] # 原有序数组经过了旋转 else: # 退出循环时,high等于low+1 while high > low + 1: mid = (low+high) // 2 # 特殊情况:low、mid、high所指向的值相等,此时退回顺序查找。例如:[1,1,1,0,1] if rotateArray[low] == rotateArray[mid] == rotateArray[high]: min_val = rotateArray[low + 1] for i in range(low + 2, high): if rotateArray[i] < min_val: min_val = rotateArray[i] return min_val # 二分查找,右半部分 elif rotateArray[mid] >= rotateArray[low]: low = mid # 二分查找,左半部分 else: high = mid return rotateArray[high] if __name__ == '__main__': s = Solution() arr = [ 6501, 6828, 6963, 7036, 7422, 7674, 8146, 8468, 8704, 8717, 9170, 9359, 9719, 9895, 9896, 9913, 9962, 154, 293, 334, 492, 1323, 1479, 1539, 1727, 1870, 1943, 2383, 2392, 2996, 3282, 3812, 3903, 4465, 4605, 4665, 4772, 4828, 5142, 5437, 5448, 5668, 5706, 5725, 6300, 6335 ] print(s.minNumberInRotateArray(arr))
c68f28f79164d4204359c24bcb9c85d8c2e280c6
Horlawhumy-dev/.py-projects
/PYTHON CLASS/PY tutorial/looping/user.py
88
3.734375
4
x = float(input("Enter the number: ")) print(type(x)) input("press any key to exit...")
b6e12b4b95e1ee0c881e37f5bd1234a4ac085433
skywhat/leetcode
/Python/75.py
424
3.625
4
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ color = [0]*3 for n in nums: color[n] +=1 i = j = 0 while i<=2: while color[i] != 0: nums[j] = i color[i] -= 1 j+=1 i+=1
ef775a3c380b838b7573fa0511414e3d12a6cb98
xmonkee/JackCompiler
/compiler/compiler.py
987
3.59375
4
#Author: Mayank Mandava #The main compiler function #Calls the tokenizer, parser and code generator from tokenizer import tokenize from parser import parse_class from codegenerator import codegen import pprint def compile(intext): tokens = tokenize(intext) ast = parse_class(tokens) vmcode = codegen(ast) return vmcode; def py2xml(data, dist=0): """Converts nested python lists and dictionaries to XML""" if isinstance(data, dict): out = "" for k in data.keys(): out += "<%s>"%k if isinstance(data[k], list): out += "\n" out += py2xml(data[k], dist+2) out += " "*dist + "</%s>"%k else: out += py2xml(data[k], dist) out += "</%s>"%k return out elif isinstance(data, list): out = "" for item in data: out += " "*dist + py2xml(item, dist) + '\n' return out else: return data
84ed092bb1cc7b1f8b2e2ae250a124662f070e92
huiyanglu/My_Ideas
/File_processing/batch_file_rename.py
1,696
3.5625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Huiyang Lu """批量重命名指定文件的后缀名""" import os import argparse def batch_rename(work_dir, old_ext, new_ext): files = os.listdir(work_dir) print(os.listdir(work_dir)) print("Start!") for filename in files: portion = os.path.splitext(filename) #文件名以点为分割点被分开 file_ext = portion[1] if old_ext == file_ext: new_file_ext = portion[0]+new_ext os.rename(os.path.join(work_dir,filename),os.path.join(work_dir,new_file_ext)) print('Rename is done!') print(os.listdir(work_dir)) def get_parser(): parser = argparse.ArgumentParser(description='change extension of files in a working directory') parser.add_argument('work_dir', metavar='WORK_DIR', type=str, nargs=1, help='the directory where to change extension') parser.add_argument('old_ext', metavar='OLD_EXT', type=str, nargs=1, help='old extension') parser.add_argument('new_ext', metavar='NEW_EXT', type=str, nargs=1, help='new extension') return parser def main(): parser = get_parser() args = vars(parser.parse_args()) work_dir = args['work_dir'][0] old_ext = args['old_ext'][0] if old_ext[0] != '.': old_ext = '.' + old_ext new_ext = args['new_ext'][0] if new_ext[0] != '.': new_ext = '.' + new_ext batch_rename(work_dir,old_ext,new_ext) if __name__ == '__main__': main() """ 测试:terminal输入,位置切换至Python文件所在位置 python3 batch_file_rename.py ./test_1 .txt .txt2 参考自:https://github.com/geekcomputers/Python/blob/master/batch_file_rename.py """
8416f4502d3b38efd5dc91a8106fb2187fd96fef
ivancmartin/python_repaso
/ejercicios.py
387
3.78125
4
print("Introduce los siguientes datos") nombre=input("Dime tu nombre: ") direccion=input("Dime tu direccion: ") tlfno=input("Dime tu teléfono: ") def guardarDatos(nombre,direccion,tlfno): datusUsu=[nombre,direccion,tlfno] return datusUsu datos=guardarDatos(nombre,direccion,tlfno) print('los datos son: nombre: '+ datos[0] + '; direccion' + datos[1] + '; telefono: ' + datos[2])
ed79c31d2fbd32215731cbf45f67b92455ab2d81
Liav8/Games.cards2
/Card.py
998
3.96875
4
class Card: #מקבל ערך וצורה של קלף def __init__(self, value, suit): if type(value) is int and type(suit) is str: self.value = value self.suit = suit else: raise Exception("The inputs aren't valid") # פונקציה שמדפיסה את קלף def __str__(self): return f"This card's number is: {self.value} and it's suit is: {self.suit}" # פונקציה שמדפיסה את קלף def __repr__(self): return f"\nCard's number: {self.value}, Card's suit: {self.suit}" # מחזירה צורה של הקלף def card_name(self): names = {1: "Ace", 11: "Jack", 12: "Queen", 13: "King"} if self.value == 1 or self.value > 10: return names[self.value] else: return False def __eq__(self, other): if type(other) is Card: return self.value == other.value and self.suit == other.suit else: return False
d21d2a8588735b9aed9cd1508dbd5a8cd1b7b07c
piersonscarborough/Exercises
/letter_histogram.py
209
4.0625
4
#dictionary = {} word = input('Please enter a word ') counter = 0 for letter in word: if letter == i: counter += 1 print(counter) #print(single_letter_count('asjghisueHGIsehfiSBEifhef', 'e'))
4c568ac8c6da7dc6a78cd825de7ce0a7266cf76f
bhunkeler/DataScienceCoursera
/Reinforcement_Learning - University of Alberta/003_Prediction_and_Control_with_Function_Approximation/week_2/assignment/sgd.py
921
3.65625
4
from assignment import BaseOptimizer import numpy as np class SGD(BaseOptimizer): def __init__(self): pass def optimizer_init(self, optimizer_info): """Setup for the optimizer. Set parameters needed to setup the stochastic gradient descent method. Assume optimizer_info dict contains: { step_size: float } """ self.step_size = optimizer_info.get("step_size") def update_weights(self, weights, g): """ Given weights and update g, return updated weights """ for i in range(len(weights)): for param in weights[i].keys(): ### update weights # weights[i][param] = None weights[i][param] = weights[i][param] + self.step_size * g[i][param] # ---------------- return weights
5ed6c92135aec2aae3967af449cd2480e2404114
benjamincampbell/cs4310-hw3
/priorityqueue.py
2,283
3.859375
4
class QueueNode(object): def __init__(self, node): self.node = node self.parent = None self.child = None def __str__(self): return "{{{}}}".format(self.node) class PriQueue(object): def __init__(self): self.head = None self.size = 0 def __str__(self): temp = self.head ret = "head: " while temp != None: ret += "{}->".format(temp) temp = temp.child return ret def add(self, new_node): newnode = QueueNode(new_node) if not self.head: # No head node, make head. self.head = newnode else: # head node exists, start comparing. found = False temp = self.head while not found: if (temp.node.count < newnode.node.count): # current node's count is lower, new node # needs to go further down if temp.child: # if the current node has a child, move # to it temp = temp.child else: # current has no child, make the new node # the child temp.child = newnode newnode.parent = temp found = True else: # (temp.count >= newnode.count): # current node's count is the same or # higher, new node can go here. if temp.parent: # current is not head: temp.parent.child = newnode newnode.parent = temp.parent else: self.head = newnode temp.parent = newnode newnode.child = temp found = True self.size += 1 def get_min(self): ret = self.head if self.head.child: self.head.child.parent = None self.head = self.head.child else: self.head = None self.size -= 1 return ret
3bb5627b4ca558895bf4098c9bb06ab1edb015d9
thesmigol/python
/1009.py
501
3.71875
4
salario = None vendas = None funcionario = None def read_string(): try: # read for Python 2.x return raw_input() except NameError: # read for Python 3.x return input() def read_numeric(): try: # read for Python 2.x return float(raw_input()) except NameError: # read for Python 3.x return float(input()) funcionario = read_string() salario = read_numeric() vendas = read_numeric() print(str("TOTAL = R$ ") + str("{:0.2f}".format((vendas * 0.15 + salario))))
0cc23b2d8febd5aca46ce19dc48c03c9f106ab4f
Fimics/FimicsPy
/base/StaticAndClassMethed.py
2,073
4.21875
4
""" 类方法 是类对象所拥有的方法,需要用修饰器@classmethod来标识其为类方法,对于类方法,第一个参数必须是类对象, 一般以cls作为第一个参数(当然可以用其他名称的变量作为其第一个参数 ,但是大部分人都习惯以'cls'作为第一个参数的名字,就最好用'cls'了),能够通过实例对象和类对象去访问。 """ class People(object): country = 'china' # 类方法,用classmethod来进行修饰 @classmethod def getCountry(cls): return cls.country p = People() print(p.getCountry()) # 可以用过实例对象引用 print(People.getCountry()) # 可以通过类对象引用 # 类方法还有一个用途就是可以对类属性进行修改: class People(object): country = 'china' # 类方法,用classmethod来进行修饰 @classmethod def getCountry(cls): return cls.country @classmethod def setCountry(cls, country): cls.country = country p = People() print(p.getCountry()) # 可以用过实例对象引用 print(People.getCountry()) # 可以通过类对象引用 p.setCountry('japan') print(p.getCountry()) print(People.getCountry()) # 静态方法 需要通过修饰器@staticmethod来进行修饰,静态方法不需要多定义参数 class People(object): country = 'china' @staticmethod # 静态方法 def getCountry(): return People.country print(People.getCountry()) """ 从类方法和实例方法以及静态方法的定义形式就可以看出来,类方法的第一个参数是类对象cls, 那么通过cls引用的必定是类对象的属性和方法;而实例方法的第一个参数是实例对象self, 那么通过self引用的可能是类属性、也有可能是实例属性(这个需要具体分析), 不过在存在相同名称的类属性和实例属性的情况下,实例属性优先级更高。 静态方法中不需要额外定义参数,因此在静态方法中引用类属性的话,必须通过类对象来引用 """
c7a8451d218f3565e1613451b2a5e43e6d0c931f
TStasio/Python_S20
/lab5_ts.py
832
3.921875
4
""" Name: Tanya Stasio IDCE 302 - Lab 5 Python 2.7.16 Due: 02/2/2020 """ #Create Dictionary for Refugee Camp and Number of Refugees #Year chosen: 2006 refugee={"Chad - Am Nabak": 16504,"Yemen - Al Kharaz": 9298, "Sudan - Girba": 8996, "Malawi - Dzaleka": 4950, "Thailand - Mae La": 46148} #There are multiple camps per country so I am adopting the function to return country/camp combination #Camps only def country_camp(dicInput): for key in dicInput: print(dicInput.keys()) country_camp(refugee) #Values only def country_camp_values(dicInput): for value in dicInput: print(dicInput.values()) country_camp_values(refugee) def sentence(dicInput): for (key,value) in dicInput.items(): print(key,"has",value,"refugees") sentence(refugee)
b6aee006dca9c74058d8fedd13530ddcc1d99bb5
jpeinado/structure
/Win32/Figuras2d.py
998
3.84375
4
# importacion de la libreria Tkinter from tkinter import * # Implementacion de la clase grafica dibujar class Dibujar(object): # Metodo que instancia la clase dibujo e inicializa el modo grafico def __init__(self,master): self.master = master self.inicializar_gui() self.lienzo = Canvas(self.master,width=100,height=100) # creamos los widget dentro del canvas def inicializar_gui(self): Button(self.master,text='Dibujar',command=lambda: self.rectangulo()).pack() def rectangulo(self): self.lienzo.pack(expand=YES,fill=BOTH) self.lienzo.create_rectangle(10,10,100,100,width=5,fill='red') def linea(self): self.lienzo.pack(expand=YES,fill=BOTH) self.lienzo.create_line(0, 200, 200, 0, width=5, fill='green') def main(): master = Tk() master.title("Mis dibujos") master.geometry('300x300') ventana = Dibujar(master) master.mainloop() if __name__ == "__main__": main()
3ba1048da78d2a36b4ef093eaa12b81b423bdad7
Bayaz/PyStuff
/tempconverter.py
1,110
4.59375
5
#this script is a temperature converter #this script is a good candidate for a beginner gui application #this defines the functions used in the script, use'm like legos! def convert_f_to_c(x): f_converted = (x-32) * (5 / 9) return f_converted def convert_c_to_f(y): c_converted = y * (9 / 5) + 32 return c_converted #starting point of the program def start(): cels_or_fahr = input("""Enter 'c' for celcius to fahrenheit or 'f' for fahrenheight to celcius: > """) if cels_or_fahr == 'f': celsius_temp = input("""Input the temp in fahrenheit and press RETURN to see celsius value : > """) celsius_temp = float(celsius_temp) celsius_temp = convert_f_to_c(celsius_temp) print(celsius_temp) elif cels_or_fahr == 'c': fahr_temp = input("""Input the temp in celsius and press RETURN to see fahrenheight value : > """) fahr_temp = float(fahr_temp) fahr_temp = convert_c_to_f(fahr_temp) print(fahr_temp) else: print("Input not valid, please input 'c' or 'f' ('' not required)") start() start()
34bef8ca232fc02be6577a2e22d56b3f1a495b5b
PeterCookDev/LearningPython
/Lists.py
749
3.734375
4
def nested_sum(numbers): currentTotal = 0 for i in numbers: if(isinstance(i, list)): currentTotal += nested_sum(i) else: currentTotal += i return currentTotal def capitalize_all(sentence): res = [] for word in sentence: res.append(word.capitalize()) return res def only_upper(t): res = [] for s in t: if s.isupper(): res.append(s) return res def cumulative_sum(numbers): res = [] cumsum = 0 for number in numbers: cumsum += number res.append(cumsum) return res print(nested_sum([1,2,3,[4,5,[6,7],[8]]])) print(cumulative_sum([10,20])) print(only_upper('ABcdEfGhI')) print(capitalize_all(['lorem','ipsum'])) print(capitalize_all('lorem ipsum'))
e2db5308cb61ebcd8ed99189e1720980e3db16c5
bahybintang/cryptography
/Subtitution and Transposition/subandtrans.py
916
4.125
4
#!/usr/bin/python3 letters = "abcdefghijklmnopqrstuvwxyz " def generateKey(key): # subKey is the key for subtitutions # transKey is the key for transposition subKey = {} transKey = 0 # To keep track of index in letters cur = 0 for ch in key: # Generate transKey by xor and modulo 4 transKey = transKey ^ ord(ch) % 4 # Generate subKey if the key character # not already exists in subKey value if ch not in subKey.values(): subKey[letters[cur += 1]] = ch # Generate key for unmapped letter while cur < len(key): subKey[letters[cur]] = letters[cur += 1] return subKey, transKey def substitute(plaintext, key): return [key[ch] for ch in plaintext] if __name__ == '__main__': plaintext = input("Plaintext: ") subKey, transKey = generateKey(input("Key: ")) print(substitute(plaintext, subKey))
3d30abd12438ab07b9784e2f19fb855c1c3f9a96
jimmylin1991619/guess_number
/guess_number.py
624
3.796875
4
#讓使用者重複輸入數字去猜 #猜對的話 印出"終於猜對了!" #猜錯的話要告訴他 比答案大/小 import random #載入random模組 r = random.randint(1, 100) #隨機正整數 random int = randint(start, end) #print(r) count = 0 while True: count = count + 1 # count += 1 等同 count =count + 1 guess = input('請猜猜數字: ') guess = int(guess) if r == guess: print('終於猜對了!') print('這是你猜的第', count, '次') break else: if r != guess and r > guess: print('比答案小') else: print('比答案大') print('這是你猜的第', count, '次')
f5e9c2842541cbb81edeebd043478b43fce9e5bf
bunnybryna/Coursera_MIT_Intro_To_CS
/Code/wk6l11class.py
1,126
4.1875
4
import math def sq(x): return x*x class Coordinate(object): def __init__(self,x,y): self.x = x self.y = y # __str__ method will return a str # __ and __ is for not overriding the other string method # it will convert any instance into a string def __str__(self): return '<' + str(self.x) + ',' + str(self.y) + '>' # create method in a class that will apply to any instance def distance(self,other): return math.sqrt(sq(self.x - other.x)+sq(self.y-other.y)) c = Coordinate(3,4) # without __str__ method, it will print out like <__main__.Coordinate instance at 0x0000000002632E08> # now <3,4> print c # <class '__main__.Coordinate'> # means the name of class is Coordinate and c is an instance of class Coordinate print type(c) # <class '__main__.Coordinate'> <type 'type'> # means that Coordinate is a class, type is a version of 'type' print Coordinate, type(Coordinate) # use isinstance() to check if an object is an instance of a particular type # check if c is an instance of Coordinate # print True print isinstance(c, Coordinate)
a95afa7baffb3a7f948009da1700f4ddcc760ba0
cmiles1/QuantumZetaZeros
/zetafunc.py
572
3.53125
4
from itertools import islice # Zetafunc.py # Calculates Zeta function in terms of Eta(s), where Re(s) > 0, Re(s) != 1 def count(firstval=0, step=1): x = firstval while 1: yield x x += step # Calculates Eta(s) of a complex/real positive number, s def eta(s,t=100000): if s ==1: return float("inf") term = (((-1) **(n-1))/(n**s) for n in count(1)) return sum(islice(term,t)) # Calculates Zeta(s) in terms of Eta(s) def zeta(s,t=100000): if s == 1: return float("inf") else: return eta(s)/ (2**(1-s)-1)
8d6dc74761ffba13192fc1fca830ae1f360f2187
wpy-111/python
/DataAnalysis/day06/demo01_vec.py
335
3.859375
4
""" 函数矢量化 """ import numpy as np import math def func(x,y): return math.sqrt(x**2 + y**2) a,b = np.array([4,3,3]),np.array([4,4,6]) #使用vectorize,对func函数执行函数矢量化,这样就可以处理矢量数据 fun_vec= np.vectorize(func) print(fun_vec(a,b)) print(fun_vec(a,4)) print(np.sqrt([9+16,9+16]))
31e70872bdc5e27b6212f6fb5d9bd563a5cc5446
UPIMAN73/LCC-Arduino-Code
/python/packet.py
2,222
3.671875
4
class Packet: def __init__(self, header, size, msg): """ Message packet - MSG Data packet - DAT CMD Packet - CMD Timestamp will be added to othe msg part of the packet like so TYPE_SIZE_|TIMESTAMP|MSG Timestamps are always 26 letters/bytes """ self.header = header # Same with message if (len(msg) < 257): self.msg = msg else: self.msg = "" self.size = len(self.msg) # print out the packet format def packetFormat(self): return str(self.header) + "_" + str(self.size) + "_" + str(self.msg) # Reformat the packet from a given string def packetReformatString(self, s): p = s.split("_") if (len(p) == 3): self.header = p[0] self.size = int(p[1]) self.msg = p[2] return [self.header, self.size, self.msg] else: return ["CMD", 4, "quit"] # reformat the packet information def packetReformat(self, header, message): if (self.checkHeader(header)): if (self.checkMessage(message)): self.setHeader(header) self.setMessage(message) self.size = len(self.msg) else: print("Failed Message") print(message) """ Setting and checking valid headers and message data """ def setHeader(self, header): if self.checkHeader(header): self.header = header else: print("ERROR: Cannot have that type as a header, it is unrecognizable") def setMessage(self, message): if self.checkMessage(message): self.msg = message else: print("ERROR: Cannot have data be more than 256 characters (bytes)") def checkHeader(self, header): if header == "MSG" or header == "CMD" or header == "DAT" or header == "TST": return True else: return False def checkMessage(self, message): if (len(message) < 257): return True else: return False
075d42472223792fad7a9639f7eb45dd8924bc27
agladman/python-exercises
/small-exercises/generators.py
709
4.1875
4
#!/usr/bin/env python3 """Playing with generators to figure out how they work once and for all.""" def spellout(text): for ch in text: yield ch def addone(my_int): """Not veru useful as a generator, no iteration required so better as a normal function returning a value.""" yield my_int + 1 def countup(my_int): for _ in range(my_int): yield _ + 1 def countdown(my_int): for _ in range(my_int, 0, -1): yield _ def main(): print('\nspell out "bumhole"') string = ', '.join(c for c in spellout('bumhole')) print(string) print('\ncount up to 5') for _ in countup(5): print(_) print('\ncount down from 5') for _ in countdown(5): print(_) if __name__ == '__main__': main()
a6cd2cf05d186c06f00b94dee55377a41363b7c9
artbohr/codewars-algorithms-in-python
/7-kyu/check-vowel.py
523
4.03125
4
def check_vowel(string, position): if position < 0: return False try: return string[position].lower() in 'aeiou' except IndexError: return False ''' Check if it is a vowel(a, e, i, o, u,) on the n position in a string (the first argument). Don't forget about uppercase. A few cases: { checkVowel('cat', 1) -> true // 'a' is a vowel checkVowel('cat', 0) -> false // 'c' is not a vowel checkVowel('cat', 4) -> false // this position doesn't exist } P.S. If n < 0, return false '''
a0e7e0d6210b34b55b776ab295aaa80920cd0578
240-coding/2020-winter-python
/0111 - 함수2/2-answer.py
608
3.8125
4
def average(score1, score2, score3, score4) : if score1 < 0 or score1 > 100 : print('Invalid parameter') return elif score2 < 0 or score2 > 100 : print('Invalid parameter') return elif score3 < 0 or score3 > 100 : print('Invalid parameter') return elif score4 < 0 or score4 > 100 : print('Invalid parameter') return score_list = [score1, score2, score3, score4] score_list.sort() score_list.reverse() sum = 0 for i in range(0, 3) : sum += score_list[i] result = sum / 3 return result
6920cf467c6a8712edfb0aa72b96e3cb30b30f73
repotudou/pyTrade
/testSql.py
864
3.828125
4
''' Created on @author: Admin ''' import sqlite3 print (sqlite3.version) # conn=sqlite3.connect('test.db') # conn.execute('''CREATE TABLE COMPANY # (ID INT PRIMARY KEY NOT NULL, # NAME TEXT NOT NULL, # AGE INT NOT NULL, # ADDRESS CHAR(50), # SALARY REAL);''') # conn.close() conn=sqlite3.connect('test.db') conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 )"); conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Allen', 25, 'Texas', 15000.00 )"); conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )"); conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )"); conn.commit() print "Records created successfully"; conn.close() if __name__ == '__main__': pass
5ac0da32daefa66911521ab6a22b398e43834ad5
parths-ca/VM
/vm.py
241
3.921875
4
a = 55 b = 48 addition = a + b subtraction = a - b multiplication = a * b division = a / b print("Addition is : ", addition) print("Subtracting is : ", subtraction) print("Multiplication is : ", multiplication) print("Division : ", division)
1f8ac31ec32c7d4ee320eb712b880ee1e3f0bbc2
arushipandit/python-class-labwork
/datatypes.py
347
3.890625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: name= input('what is ur name') age=input(Enter age”) print(name + “you are” + age +”years old”) # In[6]: n=7 type(n) # In[7]: n='hi' type(n) # In[11]: print(format('hello', '<30’)) print(format('hello', '>30')) # In[12]: print(format('hello', '^30')) # In[ ]:
bedebc20923b11fc3325d52fdf63f6772aebc05d
PlumpMath/sicpy-1
/streams.py
990
3.71875
4
"""Play with Section 3.5""" def isprime(n): """The method of section 1.2.6. Soon to be outsted by the sieve of Eratosthenes. """ return n == smallest_divisor(n) def smallest_divisor(n): return find_divisor(n, 2); def find_divisor(n, test_divisor): if square(test_divisor) > n: return n elif divides(test_divisor, n): return test_divisor else: return find_divisor(n, test_divisor + 1) def square(n): return n * n def divides(a, b): return b % a == 0 def sum_primes_iter(a, b): """Sum primes in range iteratively.""" def loop(n, accum): if n > b: return accum elif isprime(n): return loop(n + 1, accum + n) else: return loop(n + 1, accum) return loop(a, 0) from functools import reduce from operator import add def sum_primes_seqs(a, b): """Sum primes using sequence transformations.""" return reduce(add, filter(isprime, range(a, b)))
0bfc29657bd3864a30057f65fe4338b7a1a9113f
selmeczia/heller-advanced-python
/Ex_1/main.py
240
4.25
4
# creating numbers into list from 1 to 100 numbers = list(range(1, 100)) # creating empty list num_3 = list() # for cycle for every number divisible by 3 for num in numbers: if num % 3 == 0: num_3.append(num) # print return print(num_3)
1fb9fa26fe359538413cfffd01e70981f16fcf6f
Jonathan-aguilar/DAS_Sistemas
/Ago-Dic-2019/NoemiEstherFloresPardo/Practica1/FavoriteNumbers2.py
525
4.28125
4
"""6-10. Favorite Numbers: Modify your program from Exercise 6-2 (page 102) so each person can have more than one favorite number. Then print each person’s name along with their favorite numbers.""" favorite_numbers = { 'Lupita': [10,17], 'Reynaldo': [24,42], 'Samuel': [7,14], 'Teresa': [21,26], 'Rosendo': [12,24] } for name, numbers in favorite_numbers.items(): print("\nA " + name.title() + " le gustan los siguientes numeros:") for number in numbers: print(" " + str(number))
f655aab73a90a8e6914018bf0b66092f929badbf
PhillipLeeHub/python-algorithm-and-data-structure
/leetcode/124_Binary_Tree_Maximum_Path_Sum.py
1,556
3.984375
4
''' 124. Binary Tree Maximum Path Sum Hard A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any path. Example 1: Input: root = [1,2,3] Output: 6 Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. Example 2: Input: root = [-10,9,20,null,null,15,7] Output: 42 Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. Constraints: The number of nodes in the tree is in the range [1, 3 * 104]. -1000 <= Node.val <= 1000 ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxPathSum(self, root: TreeNode) -> int: self.max_sum = float("-inf") self.find_max(root) return self.max_sum def find_max(self, node): if node == None: return 0 max_right_sum = max(self.find_max(node.right), 0) max_left_sum = max(self.find_max(node.left), 0) self.max_sum = max(node.val + max_right_sum + max_left_sum, self.max_sum) return node.val + max(max_right_sum, max_left_sum)
62e612dbc6a73804609ede9ecb22ed361790064d
jesus-rod/algorithms-python
/recursiveAverage.py
389
3.765625
4
def average(testVariable, currentIndex=0): if currentIndex == len(testVariable) - 1: return testVariable[currentIndex] if currentIndex == 0: return ((testVariable[currentIndex] + average(testVariable, currentIndex + 1)) / len(testVariable)) return (testVariable[currentIndex] + average(testVariable, currentIndex + 1)) print(average([1, 2, 3, 4, 5, 6], 0))
cd547c0d9ef4504800b27b846dfae93433f402ad
chyidl/chyidlTutorial
/root/os/DSAA/DataStructuresAndAlgorithms/python/queue_circular_linked_list_implement.py
5,166
4.21875
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # # queue_circular_linked_list_implement.py # python # # 🎂"Here's to the crazy ones. The misfits. The rebels. # The troublemakers. The round pegs in the square holes. # The ones who see things differently. They're not found # of rules. And they have no respect for the status quo. # You can quote them, disagree with them, glority or vilify # them. About the only thing you can't do is ignore them. # Because they change things. They push the human race forward. # And while some may see them as the creazy ones, we see genius. # Because the poeple who are crazy enough to think thay can change # the world, are the ones who do." # # Created by Chyi Yaqing on 03/03/19 11:00. # Copyright © 2019. Chyi Yaqing. # All rights reserved. # # Distributed under terms of the # MIT """ Circular Queue is a linear data structure in which the operations are performed based on FIFO(First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer" Operations on Circular Queue: Front: Get the front item from queue. Rear: Get the last item from queue. enQueue(value): This function is used to insert an element into the circular queue. In a circular queue. the new element is always inserted at Rear position. Steps: 1. Check whether queue is Full - Check ( (rear == SIZE-1 && front == 0)||(rear == front-1)) 2. If it is full then display Queue is full. If queue is not full then, check if (rear == SIZE-1 && font != 0) if it is true then set rear=0 and insert element. deQueue(): This function is used to delete an element from the circular queue.In a circular queue, the element is always deleted from front position. Steps: 1. Check whether queue is Empty means check (front == -1). 2. if it is empty then display Queue is empty, If queue is not empty then step3 3. Check if (front == rear) if it is true then set front=rear=-1 else check if (front==size-1), if it is true then set front 0 and return the element. Time Complexity: Time complexity of enqueue(), dequeue() operation is O(1) as there is no loop in any of the operation. Applications: 1. Memory Management: The unused memory locations in the case of ordinary queues can be utilized in circular queues. 2. traffic system: In computer controlled traffic system, circular queue are used to switch on the traffic lights one by one repeatedly as per the time set. 3. CPU Scheduling: Operating systems often maintain a queue of process-es that are ready to execute or that are waiting for a particular envent to occur """ class CircularQueue(): # constructor def __init__(self, size): # initializing the class self.size = size # initializing queue with none self.queue = [None for i in range(size)] self.front = self.rear = -1 def enqueue(self, data): # condition if queue is full if ((self.rear + 1) % self.size == self.front): print("Queue is Full\n") # condition if queue is empty elif (self.front == -1): self.rear = self.front = 0 self.queue[self.rear] = data else: # next position of rear self.rear = (self.rear + 1) % self.size self.queue[self.rear] = data def dequeue(self): if (self.front == -1): # condition for empty queue print("Queue is Empty\n") # condition for only one element elif (self.front == self.rear): temp = self.queue[self.front] self.front = self.rear = -1 return temp else: temp = self.queue[self.front] self.front = (self.front + 1) % self.size return temp def display(self): # condition for empty queue if (self.front == -1): print("Queue is Empty") elif (self.rear >= self.front): print("Elements in the circular queue are:", end=" ") for i in range(self.front, self.rear + 1): print(self.queue[i], end=" ") print() else: print("Elements in Circular Queue are:", end=" ") for i in range(self.front, self.size): print(self.queue[i], end=" ") for i in range(0, self.rear + 1): print(self.queue[i], end=" ") print() if ((self.rear + 1) % self.size == self.front): print("Queue is Full") if __name__ == '__main__': circularq = CircularQueue(5) circularq.enqueue(14) circularq.enqueue(22) circularq.enqueue(13) circularq.enqueue(-6) circularq.display() print("Deleted value = ", circularq.dequeue()) print("Deleted value = ", circularq.dequeue()) circularq.display() circularq.enqueue(9) circularq.enqueue(20) circularq.enqueue(5) circularq.display()
bed44c86473d02acb585e7ad8be48970e5da7f07
bentd/think-python
/18.py
2,328
3.90625
4
import random import sys class Card(object): """ Author Represents a standard playing card.""" def __init__(self,suit=0,rank=2): " Author " self.suit = suit self.rank = rank suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] def __str__(self): " Author " return '%s of %s' % (Card.rank_names[self.rank], Card.suit_names[self.suit]) def __repr__(self): return '%s of %s' % (Card.rank_names[self.rank], Card.suit_names[self.suit]) def __cmp__(self,other): return cmp((self.suit,self.rank), (other.suit,other.rank)) class Deck(object): def __init__(self): self.cards = [] for suit in [0,1,2,3]: for rank in [1,2,3,4,5,6,7,8,9,10,11,12,13]: self.cards.append(Card(suit,rank)) def __str__(self): string=[] for card in self.cards: string.append(str(card)) return ', '.join(string) def add_card(self,card): self.cards.append(card) def deal_card(self): return self.cards.pop() def shuffle(self): random.shuffle(self.cards) def sort(self): self.cards.sort() def move_cards(self, hand, num): self.shuffle() for card in range(num): hand.add_card(self.deal_card()) def deal_hands(self, hands, num): assert hands * num <= len(self.cards), "Not enough cards..." allhands = [] for hand in range(hands): hand = Hand() self.move_cards(hand, num) allhands.append(hand) return allhands class Hand(Deck): " Represents a players hand (their cards) " def __init__(self, label = ''): self.cards = list() self.label = label def find_defining_class(obj, meth_name): " Author " for ty in type(obj).mro(): if meth_name in ty.__dict__: return ty if __name__ == '__main__': print sys.argv
da50e04cdeaa57f602ae964a238b55788c2dd653
ElizabethFoley/IntroProgramming-Labs
/madlib.py
480
3.890625
4
def promptForWords(): 'global noun, verb, adjective, place' promptForWords() def makeAndPrintSentence(): noun = input("Enter a noun: ") verb = input("Enter a verb: ") adjective = input("Enter an adjective: ") place = input("Enter a place: ") print("Take your " + adjective + " " + noun + " and " + verb + " to the " + place + "!") makeAndPrintSentence() def main(promptForWords, makeAndPrintSentence): return promptForWords + makeAndPrintSentence
f97d2d1f2e0eeb7bd50bc53b19adccff73b1b6eb
candyer/leetcode
/2020 June LeetCoding Challenge/07_change.py
1,246
3.796875
4
# https://leetcode.com/explore/featured/card/june-leetcoding-challenge/539/week-1-june-1st-june-7th/3353/ # Coin Change 2 # You are given coins of different denominations and a total amount of money. # Write a function to compute the number of combinations that make up that amount. # You may assume that you have infinite number of each kind of coin. # Example 1: # Input: amount = 5, coins = [1, 2, 5] # Output: 4 # Explanation: there are four ways to make up the amount: # 5=5 # 5=2+2+1 # 5=2+1+1+1 # 5=1+1+1+1+1 # Example 2: # Input: amount = 3, coins = [2] # Output: 0 # Explanation: the amount of 3 cannot be made up just with coins of 2. # Example 3: # Input: amount = 10, coins = [10] # Output: 1 # Note: # You can assume that # 0 <= amount <= 5000 # 1 <= coin <= 5000 # the number of coins is less than 500 # the answer is guaranteed to fit into signed 32-bit integer from typing import List def change(amount: int, coins: List[int]) -> int: dp = [0] * (amount + 1) dp[0] = 1 for coin in coins: for i in range(1, amount + 1): if coin <= i: dp[i] += dp[i - coin] return dp[-1] assert(change(5, [1, 2, 5]) == 4) assert(change(3, [2]) == 0) assert(change(10, [10]) == 1) assert(change(10, [1, 2, 5, 7]) == 12)
2572c4f49dafcbcfa09b9792a78bd164a0393f79
johnlin0228/30_Days_of_Code_Hackerrank
/Day 6/Let_Us_Review.py
256
3.625
4
N = int(input()) for i in range(0, N): str = input() evenStr = "" oddStr = "" for j in range(0, len(str)): if (j % 2 == 0): evenStr += str[j] else: oddStr += str[j] print(evenStr + " " + oddStr)
e625a7b8ad6cfe9e3ad61da12d5ae1cf0c939014
shub0/algorithm-data-structure
/python/range_sum_2D.py
2,140
3.78125
4
''' Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). [3,0,1,4,2], [5,6,3,2,1], [1,2,0,1,5], [4,1,0,1,7], [1,0,3,0,5] Range Sum Query 2D The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8 ''' class NumMatrix(object): def __init__(self, matrix): """ initialize your data structure here. :type matrix: List[List[int]] """ row = len(matrix) self.empty = False if row < 0: self.empty = True col = len(matrix[0]) self.dp = [ [0] * col for _ in range(row) ] for r in range(row): for c in range(col): if r == 0 and c == 0: self.dp[r][c] = matrix[r][c] elif r == 0: self.dp[r][c] = matrix[r][c] + self.dp[r][c-1] elif c == 0: self.dp[r][c] = matrix[r][c] + self.dp[r-1][c] else: self.dp[r][c] = self.dp[r-1][c] + self.dp[r][c-1] + matrix[r][c] - self.dp[r-1][c-1] def sumRegion(self, row1, col1, row2, col2): """ sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtype: int """ if row1 == 0 and col1 == 0: return self.dp[row2][col2] elif row1 == 0: return self.dp[row2][col2] - self.dp[row2][col1-1] elif col1 == 0: return self.dp[row2][col2] - self.dp[row1-1][col2] else: return self.dp[row2][col2] + self.dp[row1-1][col1-1] - self.dp[row2][col1-1] - self.dp[row1-1][col2] # Your NumMatrix object will be instantiated and called as such: matrix = [[3,0,1,4,2], [5,6,3,2,1], [1,2,0,1,5], [4,1,0,1,7], [1,0,3,0,5] ] numMatrix = NumMatrix(matrix) print numMatrix.dp print numMatrix.sumRegion(1, 0, 2, 3) print numMatrix.sumRegion(1, 2, 3, 4)
2f2dd1a8d4c193ee2109df9600a026e8804cd4af
dimaprokopiv/Dima_Prokopiv
/reverse.py
466
4.71875
5
#You need to write a function that reverses the words in a given string. #A word can also fit an empty string. #If this is not clear enough, here are some examples: #reverse('Hello World') == 'World Hello' #reverse('Hi There.') == 'There. Hi' #As the input may have trailing spaces, you will also need to ignore unneccesary whitespace. def reverse(st): result="" my_string= st.split() my_string.reverse() result=" ".join(my_string) return result
19f5c825e17efa1c377a9ca7e0d5d67bbf659d78
coderNamedPaul/science-project
/поляков/chapter1/параграф13/пример5.py
223
3.5625
4
from graph import * penColor("brown") penSize(5) x1 = 100 x2 = 300 y1 = 100 y2 = 200 rectangle(x1, y1, x2, y2) N = 10 h = round((x2-x1)/N) for x in range(x1+h, x2, h): penColor("black") line(x, y1, x, y2) run()
85b61ebb629a2c1c560f20759ec035565d97fdd5
ixpwn/code
/code/iplane-grouper.py
1,562
3.640625
4
import sys import fileinput ''' This script runs through the ip_to_pop_with_latlons.txt file from iPlane and tries to fill in missing location entries by checking to see if there are any IPs in the same POP for which we already know the location (i.e., if we don't know A's location, but it's in the same POP as some address B for which we know the location, we can set A's location to that of B). It also checks to see if we have conflicting locations for a particular POP (which would be "bad"). ''' bubba = {} # a queensland grouper famous as the first fish to undergo chemo def fix_single_pop(item, lat, lng): if item[2] > 180: # fix unknown entries #print "fixing %s" % pop item[2] = lat item[3] = lng else: if item[2] != lat or item[3] != lng: print "error! mismatch of lat/long! existing: %s, %s new: %s, %s" % (item[0],item[1],ip,pop) exit() for line in fileinput.input(): entries = line.rstrip().split(' ') if not len(entries) == 4: continue ip, pop, lat, lng = entries try: # make sure all of bubba[pop] has same lat/long bubba[pop].append([ip, pop, lat, lng]) if not lat > 180 and not lng > 180: map(lambda x: fix_single_pop(x, lat, lng), bubba[pop]) except KeyError: # we haven't seen this pop before bubba[pop] = list() bubba[pop].append([ip, pop, lat, lng]) for pop, lines in bubba.iteritems(): for l in lines: print "%s %s %s %s" % (l[0], l[1], l[2], l[3]) #print l
6b9f3de46b70a1e26c636d5ba43c0203d6f847a3
farfromhome/learn
/python_魔法方法.py
27,096
3.515625
4
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> class Rectangle: def __init__(self,x,y): self.x=x self.y=y >>> class Rectangle: def __init__(self,x,y): self.x=x self.y=y def getPeri(self): return (self.x+self.y)*2 def getArea(self): return self.x *self.y >>> rect=Rectangle() Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> rect=Rectangle() TypeError: __init__() missing 2 required positional arguments: 'x' and 'y' >>> rect=Rectangle(3,4) >>> rect.getPeri() 14 >>> rect.getArea() 12 >>> class A : def __init__(self): return 'A fo A-Cup' >>> a=A() Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> a=A() TypeError: __init__() should return None, not 'str' >>> >>> class CapStr(str): def __new__(cls,string): string = string.upper() return str.__new__(cls,string) >>> a=CapStr('i love owen') >>> a 'I LOVE OWEN' >>> >>> class C: def __init__(self): print('我是__init__方法,我被调用了...') def __init__(self): print('我是__del__方法,我被调用了...') >>> c1=C() 我是__del__方法,我被调用了... >>> class C: def __init__(self): print('我是__init__方法,我被调用了...') def __del__(self): print('我是__del__方法,我被调用了...') >>> c2=C() 我是__init__方法,我被调用了... >>> c3=c2 >>> c4=c3 >>> del c3 >>> del c2 >>> del c4 我是__del__方法,我被调用了... >>> #对象生成以后,所有对它的引用被删除以后,才会启动垃圾回收机制 >>> #就是没有了映射对应过去,就删除了 >>> >>> >>> #魔法方法 >>> type(len) <class 'builtin_function_or_method'> >>> type(dir) <class 'builtin_function_or_method'> >>> type(int) <class 'type'> >>> type(list) <class 'type'> >>> class C: pass >>> type(C) <class 'type'> >>> a=int('123') >>> a 123 >>> b=int('457') >>> a+b 580 >>> >>> class New_init(int): def __add__(self,other): return int.__sub__(self,other) def __sub__(self,other): return int.__add__(self,other) >>> a=New_int(3) Traceback (most recent call last): File "<pyshell#68>", line 1, in <module> a=New_int(3) NameError: name 'New_int' is not defined >>> a=New_int() Traceback (most recent call last): File "<pyshell#69>", line 1, in <module> a=New_int() NameError: name 'New_int' is not defined >>> class Newinit(int): def __add__(self,other): return int.__sub__(self,other) def __sub__(self,other): return int.__add__(self,other) >>> a=New_int(3) Traceback (most recent call last): File "<pyshell#72>", line 1, in <module> a=New_int(3) NameError: name 'New_int' is not defined >>> class Newinit(int): def __add__(self,other): return int.__sub__(self,other) def __sub__(self,other): return int.__add__(self,other) >>> a=New_int(3) Traceback (most recent call last): File "<pyshell#75>", line 1, in <module> a=New_int(3) NameError: name 'New_int' is not defined >>> a=Newint(3) Traceback (most recent call last): File "<pyshell#76>", line 1, in <module> a=Newint(3) NameError: name 'Newint' is not defined >>> class New_int(int): def __add__(self,other): return int.__sub__(self,other) def __sub__(self,other): return int.__add__(self,other) >>> a=New_int(3) >>> b=New_int(5) >>> a+b -2 >>> a-b 8 >>> >>> class Try_int(int) SyntaxError: invalid syntax >>> class Try_int(int): def __add__(self,other): return self + other def __sub__(self,other): return self - other >>> a=Try_int(3) >>> b=Try_int(4) >>> a+b Traceback (most recent call last): File "<pyshell#93>", line 1, in <module> a+b File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other File "<pyshell#90>", line 3, in __add__ return self + other RecursionError: maximum recursion depth exceeded >>> class Try_int(int): def __add__(self,other): return int(self) + int(other) def __sub__(self,other): return int(self) - int(other) >>> a=Try_int(3) >>> b=Try_int(5) >>> b+a 8 >>> >>> #魔法方法 >>> class int(int): def __add__(self,other): return int.__sub__(self,other) >>> a=int('5') >>> a 5 >>> b = int(3) >>> a+b 2 >>> =============================== RESTART: Shell =============================== >>> class Nint(int): def __radd__(self,other): return int.sub__(self,other) >>> a=Nint(5) >>> b=Nint(3) >>> a+b 8 >>> 1+b Traceback (most recent call last): File "<pyshell#116>", line 1, in <module> 1+b File "<pyshell#112>", line 3, in __radd__ return int.sub__(self,other) AttributeError: type object 'int' has no attribute 'sub__' >>> class Nint(int): def __radd__(self,other): return int.__sub__(self,other) >>> 1+b Traceback (most recent call last): File "<pyshell#119>", line 1, in <module> 1+b File "<pyshell#112>", line 3, in __radd__ return int.sub__(self,other) AttributeError: type object 'int' has no attribute 'sub__' >>> b=Nint(3) >>> a=Nint(5) >>> a+b 8 >>> 1+b 2 >>> =============================== RESTART: Shell =============================== >>> class Nint(int): def __rsub__(self,other): return int.__sub__(self,other) >>> a=Nint(5) >>> 3=a SyntaxError: can't assign to literal >>> 3-a 2 >>> class Nint(int): def __rsub__(self,other): return int.__sub__(other,self) >>> a=Nint(4) >>> 6-a 2 >>>
a6c84f5627ac87cd944d85bc2d6370a33b1858e9
brianrice2/advent-of-code-2020
/day09/day09.py
1,840
3.515625
4
# Load input data with open('day09/input.txt', 'r') as file: encodings = list(map(int, file.read().split('\n'))) preamble_length = 25 # Helper functions def binary_search(arr, low_index, high_index, base_num, sum_to): # Given `base_num`, find some other number in `arr` which together sum to `sum_to` if high_index >= low_index: mid = (high_index + low_index) // 2 if base_num + arr[mid] == sum_to: return mid elif base_num + arr[mid] > sum_to: return binary_search(arr, low_index, mid - 1, base_num, sum_to) else: return binary_search(arr, mid + 1, high_index, base_num, sum_to) else: # Element is not present in the array return None def has_counterpart(window, preamble_length, num): for x in range(preamble_length): counterpart = binary_search(window, x + 1, preamble_length - 1, window[x], sum_to=num) if counterpart: return True return False # Part 1 for i in range(preamble_length, len(encodings)): window = sorted(encodings[i - preamble_length:i]) current_num = encodings[i] if not has_counterpart(window, preamble_length, current_num): print('Part 1:', current_num) break # Part 2 target_sum = 257342611 for i in range(len(encodings)): contig_nums = [encodings[i]] contig_sum = sum(contig_nums) # Add neighboring numbers if they don't put sum over the limit next_idx = i + 1 while contig_sum < target_sum: if (next_idx < len(encodings) and contig_sum < target_sum): contig_nums += [encodings[next_idx]] contig_sum = sum(contig_nums) next_idx += 1 # Check for exit condition if contig_sum == target_sum: print('Part 2:', min(contig_nums) + max(contig_nums)) break
eb085d763dcc5f70218326ac982a06d9df2972c4
pzelenin92/learning_programming
/Stepik/Algorithms_theory_and_practice_course_217/2/2.3/2.3.5/Greatest_common_divisor_2.3.5.py
634
3.859375
4
"""Iterative Euclidean algorithm""" def gcd(a, b): """Function that finds greatest common divisor""" if a > b: big_number, remainder = a, b else: big_number, remainder = b, a while remainder > 0: big_number, remainder = remainder, big_number % remainder return big_number # we return big_number because remainder from previous iter was assigned to this big_number # in the last iter remainder = 0, thus we need to get it from previous iter def main(): """input and print func""" a, b = map(int, input().split()) print(gcd(a, b)) if __name__ == "__main__": main()
32d585a519974efd3a03b856926c2f5c07722105
MasakiSakai0305/PythonUI
/EAP_UI/scroll.py
2,183
3.53125
4
import tkinter as tk from PlotSensor import PlotSensor #Show ScrollBar class ScrollBar(): def __init__(self): pass #close window def _quit(self, root): root.quit() root.destroy() #show plot when button is pushed def button_selected(self, lb): #anyone aren't selected if len(lb.curselection()) == 0: return index = lb.curselection()[0] label = lb.get(index) #path = 'resource/NG/12182700604BB524_NG.csv' plot = PlotSensor(label) plot.Plot() #get add data label def data_add(self, data): try: self.data = data except AttributeError: print('error') return #add getting new data label def update(self, lb): lb.delete(0, 'end') try: for data in self.data: lb.insert('end', data) except AttributeError: print('error') return #Show scrollbar def Scroll(self, datalabel): self.datalabel = datalabel root = tk.Tk() root.title(u"ScrollBar") root.geometry("800x500") frame = tk.Frame(root, height=200, width=400, bg="white") frame.place(relwidth=0.9, relheight=0.9) frame.pack(padx=10, pady=10) # Listbox lb = tk.Listbox(frame, selectmode = 'single', height = 5, width = 40) lb.pack(side = 'left') # Scrollbar sb = tk.Scrollbar(frame, command = lb.yview) sb.pack(side = 'left', fill = 'y') lb.configure(yscrollcommand = sb.set) for x in sorted(datalabel): lb.insert('end', x) # button button_quit = tk.Button(root, text="Quit", command=lambda:self._quit(root)) button_quit.pack() button_plot = tk.Button(root, text="Plot", command=lambda:self.button_selected(lb)) button_plot.pack() button_update = tk.Button(root, text="update", command=lambda:self.update(lb)) button_update.pack() tk.mainloop()
b12fe5298e85d6c4745ecd2ea8e237557c6e6fb2
wilbertgeng/LeetCode_exercise
/654.py
816
3.640625
4
"""654. Maximum Binary Tree""" # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def constructMaximumBinaryTree(self, nums): """ :type nums: List[int] :rtype: TreeNode """ ## preorder return self.dfs(nums) def dfs(self, nums): if not nums: return None max_v = float('-inf') idx = 0 for i in range(len(nums)): if nums[i] > max_v: max_v = nums[i] idx = i root = TreeNode(nums[idx]) root.left = self.dfs(nums[0:idx]) root.right = self.dfs(nums[idx+1:]) return root
11cd3b7afe4f81788bedfd8a923e731910700d8e
Shampjeff/Personal_Projects
/development_graph_package/BarPlot.py
3,350
3.578125
4
import matplotlib.pyplot as plt import seaborn as sns from GeneralPlot import PlotRoutine class BarPlot(PlotRoutine): """ Bar plot for categorical data. Arguements: dataframe: dataframe filtered to only columns to plot x_axis: string, x_axis categories for plot y_axis: string, y_axis values for plot x_label: string, label for x axis y_label: string, label for y axis title: string, Plot title Attributes: make_bar_plot: Displays bar plot of sorted values (ascending) make_hist_plot: Display a histogram or univariate data """ def __init__(self, dataframe, x_axis, y_axis, x_label, y_label, title,**kwargs): self.data = dataframe self.x_axis = x_axis self.y_axis = y_axis self.x_label = x_label self.y_label = y_label self.title = title # do I define or re-define the args and kwargs #as self.attributes? Will that make them easier to access?? PlotRoutine.__init__(self, **kwargs) def _add_bar_annotation(self, ax, **kwargs): """ Function to add bar plot annotations. Agruements: ax: axis plot in seaborn of matplotlib Returns: None """ for rect in ax.patches: y_value = rect.get_height() x_value = rect.get_x() + rect.get_width() / 2 va = 'bottom' spacing=2 label = self._make_annotation_format(y_value, **kwargs) ax.annotate( label, (x_value, y_value), xytext=(0, spacing), textcoords="offset points", ha='center', va=va, fontsize=14) def make_bar_plot(self,hue=None, **kwargs): """ Function to produce bar plot from two dataframe columns. Arguements: hue: separate bars for subcategory. This is the same command is seaborn or matplotlib hue call. Returns: None """ df = self.data.sort_values(self.y_axis) plt.figure(figsize=(6,4)) ax = sns.barplot(x=self.x_axis, y=self.y_axis, hue=hue, data=df, ci=None) if 'annot' in kwargs: self._add_bar_annotation(ax, **kwargs) if 'caption' in kwargs: self._make_caption(**kwargs) if 'rotate' in kwargs: ax.tick_params(axis= 'x', labelrotation= kwargs['rotate']) self._add_labels(ax) def make_hist_plot(self, **kwargs): """ Function to display histogram of univariate data from pandas dataframe. Argurments: None Returns: None """ plt.figure(figsize=(6,4)) ax = plt.hist(self.data) if 'annot' in kwargs: self._add_bar_annotation(ax, **kwargs) if 'caption' in kwargs: self._make_caption(**kwargs) self._add_labels(ax)
cafa0891ba5b25fa4cd74a4f855d32f78287405a
luozhaoyu/leetcode
/regular_expression_matching_recursion.py
1,435
3.828125
4
class Solution(object): """Google interview""" def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ if s == p: return True if not p: return not s if not s: return len(p) >= 2 and p[1] == "*" and self.isMatch(s, p[2:]) if p == ".*": return True if p == ".": return len(s) == 1 if len(p) == 1: return s == p # print(s, p) first_match = p[0] == s[0] if p[1] == "*": # match empty or 1 if p[0] == ".": return self.isMatch(s, p[2:]) or self.isMatch(s[1:], p) return self.isMatch(s, p[2:]) or (first_match and self.isMatch(s[1:], p)) if p[0] == ".": return self.isMatch(s[1:], p[1:]) return first_match and self.isMatch(s[1:], p[1:]) solution = Solution() print(solution.isMatch("aa", "a")) print(solution.isMatch("aa", "a*")) print(solution.isMatch("ab", ".*")) print(solution.isMatch("aab", "c*a*b")) print(solution.isMatch("mississippi", "mis*is*p*.")) print(solution.isMatch("mississippi", "mis*is*ip*.")) print(solution.isMatch("a", "ab*a")) print(solution.isMatch("mississippi", "mis*is*p*.")) print(solution.isMatch("bbbba", ".*a*a")) print(solution.isMatch("ab", ".*..")) print(solution.isMatch("bbaa", "a...")) print(solution.isMatch("", "c*c*"))
1bc75abed7dd75d38f3f3a1936e94a02dea1db93
ChengHsinHan/myOwnPrograms
/CodeWars/Python/8 kyu/#088 8kyu interpreters HQ9+.py
1,945
3.765625
4
# You task is to implement an simple interpreter for the notorious esoteric # language HQ9+ that will work for a single character input: # # If the input is 'H', return 'Hello World!' # If the input is 'Q', return the input # If the input is '9', return the full lyrics of 99 Bottles of Beer. It should # be formatted like this: # 99 bottles of beer on the wall, 99 bottles of beer. # Take one down and pass it around, 98 bottles of beer on the wall. # 98 bottles of beer on the wall, 98 bottles of beer. # Take one down and pass it around, 97 bottles of beer on the wall. # 97 bottles of beer on the wall, 97 bottles of beer. # Take one down and pass it around, 96 bottles of beer on the wall. # ... # ... # ... # 2 bottles of beer on the wall, 2 bottles of beer. # Take one down and pass it around, 1 bottle of beer on the wall. # 1 bottle of beer on the wall, 1 bottle of beer. # Take one down and pass it around, no more bottles of beer on the wall. # No more bottles of beer on the wall, no more bottles of beer. # Go to the store and buy some more, 99 bottles of beer on the wall. # For everything else, don't return anything (return null in C#, None in Rust). # (+ has no visible effects so we can safely ignore it.) def HQ9(code): match code: case 'H': return 'Hello World!' case 'Q': return code case '9': return '\n'.join([f"{bottle} bottles of beer on the wall, {bottle} bottles of beer.\nTake one down and pass it around, {bottle - 1} bottle" + "s" * (bottle != 2) + " of beer on the wall." for bottle in range(99, 1, -1)]) + \ "\n1 bottle of beer on the wall, 1 bottle of beer.\nTake one down and pass it around, no more bottles of beer on the wall." + \ "\nNo more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall." case _: return None
fc109ad30ca06b07f4d76312567938173a1082e6
Joachim-Wambua/final_DSA_project_Imali_-_Joachim
/pygame/kim_continuation_build.py
3,010
3.953125
4
import pygame import random # Initialise pygame pygame.init() # Creating the Game window gameWindow = pygame.display.set_mode((800, 600)) # Adding a Game Title pygame.display.set_caption("Alien Shooter Game") # Icon for the game gameIcon = pygame.image.load('rocket.png') pygame.display.set_icon(gameIcon) # Defining Player Image and Starting Position of the player playerIcon = pygame.image.load('space-invaders.png') playerPosX = 360 playerPosY = 480 # Responsible for the change in direction when user presses left of right key playerPosx_change = 0 # Defining Enemy Image and Starting Position of the Enemy enemyIcon = pygame.image.load('rocket.png') # Randomising our enemy start position to the set range enemyPosX = random.randint(0, 800) enemyPosY = random.randint(50, 150) # Responsible for the change in direction of the enemy enemyPosx_change = 0 enemyPosy_change = 0 # Player Character Function # Arguments x_axis and y_axis to take user input for moving the player accordingly def player_character(x_axis, y_axis): # the blit() method is used to draw the player's Image icon at the defined positions for x and y gameWindow.blit(playerIcon, (x_axis, y_axis)) # Enemy Character Function def enemy_character(x_axis, y_axis): # the blit() method is used to draw the player's Image icon at the defined positions for x and y gameWindow.blit(enemyIcon, (x_axis, y_axis)) # Game Loop # Makes sure the game window runs until the Quit button is pressed gameRunning = True while gameRunning is True: # Changing the game screen's background using RGB codes gameWindow.fill((0, 0, 255)) # This for loop checks for the event that the quit button is pressed by the user for event in pygame.event.get(): if event.type == pygame.QUIT: gameRunning = False # This Section Handles player movement input along the a axis. # If key is pressed check whether it is left or right KEYDOWN - Pressing a key if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: playerPosx_change = -0.3 if event.key == pygame.K_RIGHT: playerPosx_change = 0.3 # Check if pressed key has been released KEYUP- Releasing the pressed key if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: playerPosx_change = 0 # This line updates the player's x-axis position according to the above keyboard press conditions playerPosX += playerPosx_change # This part is meant to create boundaries around the screen such that the player does not leave the game window if playerPosX <= 0: playerPosX = 0 elif playerPosX >= 736: playerPosX = 736 # Calling our Player to be displayed player_character(playerPosX, playerPosY) # Calling our Enemy to be displayed enemy_character(enemyPosX, enemyPosY) # constantly updating our game window pygame.display.update()
79031266da6a801d40e108575a669cb9055d3405
sushrut7898/complete_python_mastery
/exercise.py
342
3.671875
4
from pprint import pprint sentence = "This is a common interview question" char_freq = {} for char in sentence: if char in char_freq: char_freq[char] += 1 else: char_freq[char] = 1 pprint(char_freq, width=1) char_freq_sorted = sorted(char_freq.items(), key=lambda kv: kv[1], reverse=True) print(char_freq_sorted[0])
9c6700b823a3e87c2c66f8713f9e160b38b85dfa
shubh-codings/python-again
/new.py
255
3.640625
4
colors = ['red', 'blue', 'white', 'green', 'purple'] bases = ['delhi','mumbai','agra','dehradun'] for o ,color in enumerate(colors): print( o ,' : ', colors[o]) for base ,color in zip(bases,colors): print(base,' : ',color) print(type(zip(bases,colors)))
344fb9ff782b912caec80a4f2e1416b092a7e739
yoo-s/LearnPython
/ex33.py
423
4.15625
4
i = 0 numbers = [] maxnum = 5 add = 2 def numlist(letter, num, incr, listing): for letter in range(0, 5): # while letter < num: print "At the top i is %d" % letter listing.append(letter) # letter = letter + incr print "Numbers now: ", listing print "At the bottom i is %d" % letter numlist(i, maxnum, add, numbers) print "The numbers: " for num in numbers: print num
3e88f245a278c5093de4440c074ac4966297bc5d
leandrosilva/IntroGenomicDataScience
/week2_minimum_skew_test.py
1,045
3.59375
4
import unittest from week2 import MinimumSkew class Week2MinimumSkewTest(unittest.TestCase): def test_0(self): output = MinimumSkew("TAAAGACTGCCGAGAGGCCAACACGAGTGCTAGAACGAGGGGCGTAAACGCGGGTCCGAT") self.assertEqual(output, [11, 24]) def test_1(self): output = MinimumSkew("ACCG") self.assertEqual(output, [3]) def test_2(self): output = MinimumSkew("ACCC") self.assertEqual(output, [4]) def test_3(self): output = MinimumSkew("CCGGGT") self.assertEqual(output, [2]) def test_4(self): output = MinimumSkew("CCGGCCGG") self.assertEqual(output, [2, 6]) def test_5(self): output = MinimumSkew("GGG") self.assertEqual(output, [0]) def test_6(self): output = MinimumSkew("CGG") self.assertEqual(output, [1]) def test_7(self): output = MinimumSkew("CCC") self.assertEqual(output, [3]) if __name__ == '__main__': unittest.main()
d21f1453af27805ef9ad9b2ae23c94c5d9e7e647
adh2004/Python
/Lab6/Lab06P2.py
229
3.796875
4
list1 = [4,7,5,8,1,2,6,3] list2 = list1[0:9] list3 = list1[0:4] end_index = len(list1) + 1 start_index = len(list1) - 4 list4 = list1[start_index:end_index] print("List 2: ",list2) print("List 3: ",list3) print("List 4: ",list4)
ea01a6ad12019c0378961014e3caaecf5f81e754
MagdalenaSvilenova/Programming-Basics-Python
/While Loop/Exam preparation.py
636
3.765625
4
threshold = int(input()) times = 0 problems_count = 0 grades_sum = 0 last_problem = '' has_failed = True while times < threshold: problem_name = input() if problem_name == 'Enough': has_failed = False break grade = int(input()) if grade <= 4: times += 1 grades_sum += grade problems_count += 1 last_problem = problem_name if has_failed: print(f"You need a break, {threshold} poor grades.") else: print(f"Average score: {grades_sum / problems_count:.2f}") print(f"Number of problems: {problems_count}") print(f"Last problem: {last_problem}")
2f031a44f2597cfacc61b81d12b66db07ecfde5e
Cytla24/LinkedLists
/MergeLinkedLists.py
1,406
3.96875
4
class node(): def __init__(self, data=None): self.data = data self.next = None class LinkedList(): def __init__(self): self.head = None def printing(self): printval = self.head while printval: print(printval.data) printval = printval.next def merge(self,y): p = self.head q = y.head s = None if p is None: return q if q is None: return p if p.data <= q.data: s = p p = s.next else: s = q q = s.next new_head = s while p and q: if p.data <= q.data: s.next = p s = p p = s.next else: s.next = q s = q q = s.next if not p: s.next = q if not q: s.next = p return new_head x = LinkedList() x.head = node(10) data2 = node(20) data3 = node(59) data4 = node(60) data5 = node(80) data6 = node(120) data7 = node(150) data8 = node(200) x.head.next = data2 data2.next = data3 data3.next = data4 data4.next = data5 data5.next = data6 data6.next = data7 data7.next = data8 y = LinkedList() y.head = node(1) data2 = node(2) data3 = node(59) data4 = node(60) data5 = node(61) data6 = node(90) data7 = node(100) data8 = node(200) y.head.next = data2 data2.next = data3 data3.next = data4 data4.next = data5 data5.next = data6 data6.next = data7 data7.next = data8 x.merge(y) x.printing()
5849623a08115cab7abf5f0bd0472144ceb1979e
Sam-Power/Trials
/Exercises/Statistics/Assignment-2.py
2,014
3.5625
4
import matplotlib.pyplot as plt import numpy as np """years = [2010,2012,2013,2014,2015,2016,2017,2018,2019] number_of_passengers = [5000,7000,13000,10000,20000,22000,17000,16500,27000] plt.bar(years,number_of_passengers) plt.xlabel('years') plt.ylabel('number_of_passengers') plt.xticks(years) plt.yticks(number_of_passengers) plt.grid(True) plt.grid(color='b', ls = '-.', lw = 0.25) plt.show()""" """income = ['16-22','23-29','30-36','37-43','44-50','51-57'] income2 = np.arange(16,57,7) print(income2) families = [2,3,5,8,8,10] plt.bar(income2,families) #plt.xticks(income) #plt.yticks(families) plt.show()""" """x = np.arange(7) families = [2,3,5,8,8,10] plt.bar(families, height=[2,3,5,8,8,10]) plt.xticks(families, ['16-22','23-29','30-36','37-43','44-50','51-57']) plt.show() """ """families = [2,3,5,8,8,10] x = np.arange(16,58,1) plt.hist(families) plt.axis([16, 57, 2, 10]) #axis([xmin,xmax,ymin,ymax]) plt.xlabel('Weight') plt.ylabel('Probability') plt.show() plt.hist""" import numpy as np import matplotlib.pyplot as plt x = np.arange(16,58,7) print(x) families = [2,3,5,8,8,10] #plt.hist(x,bins=10,weights =families,rwidth=6 ) #plt.show() y = [2,3,5,8,8,10] x = ['16-22','23-29','30-36','37-43','44-50','51-57'] #plt.bar(x,y) plt.bar(x, y, 1, color='r') plt.show() """import numpy as np import matplotlib.pyplot as plt alphab = ['16-22','23-29','30-36','37-43','44-50','51-57'] frequencies = [2,3,5,8,8,10] pos = np.arange(len(alphab)) width = 1.0 # gives histogram aspect to the bar diagram ax = plt.axes() ax.set_xticks(pos + (width / 2)) ax.set_xticklabels(alphab) plt.bar(pos, frequencies, width, color='r') plt.show() import numpy as np import matplotlib.pyplot as plt Income = ['16','22', '29', '36', '43', '50', '57'] NumberofFamilies = [0,2, 3, 5, 8, 8, 10] pos = np.arange(len(Income)) width = 1.0 # gives histogram aspect to the bar diagram ax = plt.axes() ax.set_xticks(pos + (width / 2)) ax.set_xticklabels(Income) plt.bar(Income, NumberofFamilies, width) plt.show()"""
f4eb5837ebcd827fd18714f8ca133d581c212ef2
teleamigos/TIR4
/MyNode.py
923
3.890625
4
"""----------------------------------------------------------------------------- ------------------------------Clase mi nodo------------------------------------- 1.- Inicia el nodo 2.- Tiene informacion del nodo 3.- Calcula MPR -----------------------------------------------------------------------------""" from MPR import* class MyNode(MPR): def __init__(self,IP): self.my_address=IP self.Neighbor=[] #self.MPR=False self.tp=dict() self.c=0 self.SoyMPR={} def CreaTopologia(self,Nodo): self.tp[Nodo[0]]=Nodo[1] def AgregaVecino(self,Vecino): if Vecino in self.Neighbor: print("Ya conocido") self.c+=1 else: if Vecino != self.my_address: self.Neighbor.append(Vecino) def Calcula_MPR(self): MPRs=MPR(self.tp) MPRs.Busca_MPRs(self.my_address) return MPRs.MPR
89e61b798725952eb5eb3c0434c2ee6ae49f56f2
Hiromitsu4676/AtCoder
/acbs_product.py
111
3.796875
4
import re vals=input() a,b=re.split(" ",vals) if (int(a)*int(b))%2==0: print("Even") else: print("Odd")
4cced432350757b5c714e4e49a232b5fdd6a6100
thegibster/pythonExamples
/intro python/check_profanity.py
942
3.765625
4
#Example where the text file contents are read in and sent as the search parameter to the specified url import urllib import os def read_text(): current_dir = os.getcwd() # os.getcd() is used to allow the sample file to be run regardless of the location if this folder is copied as is quotes = open(current_dir + "/movie_quotes.txt") contents_of_file = quotes.read() print(contents_of_file) quotes.close() check_profanity(contents_of_file) def check_profanity(text_to_check): connection = urllib.urlopen("http://www.wdylike.appspot.com/?q="+text_to_check) output = connection.read() connection.close() if "true" in output: print("Profanity Alert!") elif "false" in output: print("This document contains no curse words!") else: print("Could not scan the selected document.") read_text()
e03d73d0fd4340e5d844cb3f1f304dd52c9acc4c
ks-99/forsk2019
/week2/day1/book_shop1.py
1,402
3.8125
4
""" Code Challenge Name: Book Shop Filename: book_shop1.py Problem Statement: Imagine an accounting routine used in a book shop. It works on a list with sublists, which look like this: Order Number Book Title Author Quantity Price per Item 34587 Learning Python, Mark Lutz 4 40.95 98762 Programming Python, Mark Lutz 5 56.80 77226 Head First Python, Paul Barry 3 32.95 88112 Einführung in Python3, Bernd Klein 3 24.99 Write a Python program, You need to write a solution without using lambda,map,list comprehension first and then with lambda,map,reduce A) which returns Order Summary as a list with 2-tuples. Each tuple consists of the order number and the product of the price per items and the quantity. The product should be increased by 10 INR if the value of the order is smaller than 100.00 INR. Hint: Write a Python program using lambda and map. """ list1=[] list1=[[34587,'Learning Python','Mark Lutz',4,40.95],[98762,'Programming Python','Mark Lutz',5,56.80],[77226,'Head First Python','Paul Barry',3,32.95],[77226,'Head First Python','Paul Barry',3,32.95]] list2=[] for item in list1: t1=[item[0],item[3]*item[4]] if(t1[1]<100): t1[1]+=10 list2.append(tuple(t1)) t1=map(lambda x:(x[0],x[3]*x[4]),list1) t1=map(lambda x: x if x[1]>=100 else (x[0],x[1]+10),t1)
3016a620662d8aa9cff221df4d33bf5f41818558
leandro-alvesc/estudos_python
/guppe/leitura_escrita_arquivos/seek_cursors.py
1,309
4.53125
5
""" Seek e Cursors seek() -> É utilizada para movimentar o cursor pelo arquivo. Ela recebe um parâmetro que indica onde queremos colocar o cursor. arquivo = open('texto.txt') print(arquivo.read()) # Movimentando o cursor pelo arquivo com a função seek() arquivo.seek(0) print(arquivo.read()) arquivo.seek(57) print(arquivo.read()) readline() -> Ler o arquivo linha a linha. print(arquivo.readline()) ret = arquivo.readline() print(type(ret)) print(ret) print(ret.split(' ')) readlines() -> Coloca as linhas em uma lista linhas = arquivo.readlines() print(linhas) print(len(linhas)) # OBS: Quando abrimos um arquivo com a função open() é criada uma conexão entre o arquivo no disco do computador e o programa. Essa conexão é chamada de streaming. Ao finalizar os trabalhso com o arquivo, devemos fechar a conexão utilizando a função close(). 1- Abrir o arquivo arquivo = open('texto.txt') 2- Trabalhar o arquivo print(arquivo.read()) print(arquivo.closed) # Verifica se o arquivo está aberto ou fechado (False) 3- Fechar o arquivo arquivo.close() print(arquivo.closed) # True # OBS: Se tentarmos manipular o arquivo após seu fechamento, teremos ValueError """ arquivo = open('texto.txt') print(arquivo.read(57)) print(arquivo.read()) # Continua de onde parou o cursor
03084a9ef1a77130cbbf401271743a98850f202c
jianq1994/leetcode
/python/412_fizz_bizz.py
562
3.53125
4
class Solution: def __init__(self): self.memo = [] def fizzBuzz(self, n: int) -> List[str]: L = len(self.memo) if (n <= L): pass else: for i in range(L+1,n+1): if i%3 == 0 and i%5 == 0: self.memo.append('FizzBuzz') elif i%3 == 0: self.memo.append('Fizz') elif i%5 == 0: self.memo.append('Buzz') else: self.memo.append(str(i)) return self.memo[:n]
25afcd439b6ed4c97931ef878c56691fa3a4200a
yanxurui/keepcoding
/python/oop/Person.py
1,669
3.9375
4
#!/usr/bin/env # coding=utf-8 """ >>> sue = Person('sue', 10000) >>> print(sue) [Person: sue, 10000] >>> sue.giveRaise(.1) >>> print(sue) [Person: sue, 11000] >>> Person.giveRaise(sue, .1) >>> print(sue) [Person: sue, 12100] >>> >>> tom = Manager('tom', 20000) >>> tom.giveRaise(.1) >>> print(tom) [Person: tom, 24000] """ class Person(object): # 类属性在class语句中通过赋值语句添加 base = 1000 # 构造函数 def __init__(self, name, pay=0): # 实例属性在方法中通过对self进行赋值添加 self.name = name if pay < self.base: pay = self.base self.pay = pay # 方法,第一个参数自动填充为调用该函数的对象 def giveRaise(self, percent): self.pay = int(self.pay*(1 + percent)) # 运算符重载方法 def __str__(self): return '[Person: %s, %s]' % (self.name, self.pay) # Manager继承Person # Manager是子类,Person是超类 class Manager(Person): def giveRaise(self, percent, bonus=0.1): # self.giveRaise会被解析为Manager.giveRaise,造成死循环 Person.giveRaise(self, percent + bonus) # 一个python文件是一个模块,模块也是对象 # 当作为脚本运行的时候模块的__name__属性的值是__main__ # 而当它作为一个模块被导入的时候__name__是模块名,也就是文件名(不包含后缀) if __name__ == '__main__': sue = Person('sue', 10000) print(sue) sue.giveRaise(.1) print(sue) # 通过类调用实例方法 Person.giveRaise(sue, .1) print(sue) tom = Manager('tom', 20000) tom.giveRaise(.1) print(tom)
5e8fc12b9c74c456c1678eb5e879d6ab4ae92818
dlin94/leetcode
/binary_tree/513_find_bottom_left_tree_value.py
708
3.84375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution(object): def findBottomLeftValue(self, root): """ :type root: TreeNode :rtype: int """ queue = deque() queue.append(root) left = root.val while len(queue) > 0: curr = queue.popleft() if curr.right: left = curr.right.val queue.append(curr.right) if curr.left: left = curr.left.val queue.append(curr.left) return left
9cab03b4525cac3fdf56e3da67962cf6c00bcc7a
akshaysawant/Data-Mining
/Final_Project/Code/Approach 3_Python/MapCompress.py
1,283
3.59375
4
__author__ = 'Aniket' # This program takes the paper author level 3 map. i.e. given a paper get its # authors then for those authors get papers and then again for all those papers # get author. This will be PAP^2 measure. # This program will compress the author names in the map. # e.g. if the author is xyz and it comes 2 time in the level 3 map then the # map will be compressed to XYZ-2 hence the size of the map is reduced from # 6GB to 3GB which is nearly half the size. # This program will write the compress map to pap_compres_level3.txt file in the same # folder. file = open("pap_all_auth_level3_map.txt","r") outfile = open("pap_compres_level3.txt","w") count = 0 for line in file: line = line.strip() content = line.split("\t") paper = int(content[0]) if len(content) > 1: authors = content[1] authors = authors.split(",") comp_map = {} for a in authors: if a in comp_map: comp_map[a] += 1 else: comp_map[a] = 1 string = "" for k in comp_map: string += str(k) + ";" + str(comp_map[k]) + "," string = string[:-1] outfile.write(str(paper) + "\t" + str(string) +"\n") count += 1 print(count) outfile.close()
0443928bb011420b3227486af8c86a400fa1c1aa
SWIN91/codewarspython
/codewarspython/findmultiplesofanumber.py
789
4.46875
4
# In this simple exercise, you will build a program that takes a value, integer , and returns a list of its multiples up to another value, limit . If limit is a multiple of integer, it should be included as well. There will only ever be positive integers passed into the function, not consisting of 0. The limit will always be higher than the base. # For example, if the parameters passed are (2, 6), the function should return [2, 4, 6] as 2, 4, and 6 are the multiples of 2 up to 6. # If you can, try writing it in only one line of code. def find_multiples(integer, limit): return [n for n in range(integer, limit+1, integer) if n%integer == 0] # My solution ^ def find_multiples(integer, limit): return list(range(integer, limit+1, integer)) # Best solution, AND most clever
a54ae5aec8baf7421fbdfb5e2446c4fb849e58f2
deepcpatel/data_structures_and_algorithms
/Dynamic Programming/maximal_square.py
1,125
3.75
4
# Link: https://leetcode.com/problems/maximal-square/ # Approach: At each grid location [i][j], if it is 0 then leave it because it does not form square, if its 1 then look at minimal squares in [i-1][j], [i][j-1], [i-1][j-1] and add 1 to it and update # the current grid [i][j] with that (line 20). The reason to look at neighbours is because if neighbours are part of larger square then we append current 1 and update the bigger square by size 1. # Keep track of maximum square value so far and at last return its square (area) class Solution(object): def maximalSquare(self, matrix): max_dim, d1 = 0, len(matrix) if d1 == 0: return 0 else: d2 = len(matrix[0]) for i in range(d1): for j in range(d2): matrix[i][j] = int(matrix[i][j]) if not (matrix[i][j] == 0 or ((i-1)<0) or ((j-1)<0)): matrix[i][j] = min(matrix[i-1][j], matrix[i][j-1], matrix[i-1][j-1]) + 1 max_dim = max(max_dim, matrix[i][j]) return max_dim*max_dim
3ad85587606d3950470a851d324abc9265e75c0d
wrobcio789/SequentialIndexedFIle
/generator/generator.py
856
3.5625
4
import random f = open("input3.txt", "w") INSERTS_COUNT = 10*1000 READ_COUNT = 10*1000 DELETE_COUNT = 10*1000 MAX_KEY = 50 * 1000 * 1000 allValues = list(range(1, MAX_KEY)) random.shuffle(allValues) allUsedValues = allValues[:INSERTS_COUNT] uninsertedValues = allUsedValues random.shuffle(uninsertedValues) for value in uninsertedValues: f.write(f"insert {value} {value} {value} {value} {value} {value}\n") f.write("statistics\n") f.write("reset_statistics\n") unreadValues = allUsedValues random.shuffle(unreadValues) for value in unreadValues: f.write(f"find {value}\n") f.write("statistics\n") f.write("reset_statistics\n") undeletedValues = allUsedValues random.shuffle(undeletedValues) for value in undeletedValues: f.write(f"delete {value}\n") f.write("statistics\n") f.write("reset_statistics\n") f.write("quit\n") f.close()
82d2ddcb37cc4439450e939985133a7d3931c56a
durgeshsamariya/LearnPython3TheHardWay
/ex4.py
834
4.0625
4
# Exercise 4: Variables and Names #total available cars cars = 100 #how many people can seat in car space_in_a_car = 4.0 #total number of available drivers drivers = 30 #total number of passengers passengers = 90 #unused cars cars_not_driven = cars - drivers # number of used cars cars_driven = drivers #total number passengers can travel today carpool_capacity = cars_driven * space_in_a_car #average passengers per car average_passengers_per_car = passengers / cars_driven print("There are", cars, "cars available.") print("There are only", drivers, "drivers available.") print("There will be", cars_not_driven, "empty cars today.") print("We can transport", carpool_capacity, "people today.") print("We have", passengers, "to carpool today.") print("We need to put about", average_passengers_per_car, "in each car.")
f23c8c117ce2c583e70d525d2dd7ac95a57f5f04
amandamurray2021/Programming-Semester-One
/labs/Topic07-Files/tryCatch.py
711
3.921875
4
# Q2(e) # This program creates an OS "init" program that initialises count.txt instead. # Use a try catch loop on the read. # Author: Amanda Murray filename = "count.txt" def readNumber (): try: with open (filename) as f: number = int(f.read()) return number except IOError: # this file will be created when we write back # no file assumes first time running # ie. 0 previous runs return 0 def writeNumber(number): with open (filename, "wt") as f: # write takes a string so we need to convert f.write(str(number)) #main num = readNumber () num += 1 print ("We have run this program {} times".format (num)) writeNumber (num)
0ad0860ee6202d744443a864fd86406db37b0262
yanhongliu/secalgo
/sa/Misc/Padding.py
567
3.53125
4
#This files contains implementations of padding algorithms. def pkcs7_pad(bytestring, blocksize=16): bytestring_length = len(bytestring) pad_length = blocksize - (bytestring_length % blocksize) return bytestring + bytearray([pad_length] * pad_length) #end pkcs7_pad() def pkcs7_unpad(bytestring, blocksize=16): pad_length = bytestring[-1] if pad_length > blocksize: raise ValueError('Input is not padded or the padding is corrupted.') real_length = len(bytestring) - pad_length return bytestring[:real_length] #end pkcs7_unpad()
e1da806a0aba0df5f8e20560e5875787c9ad27cb
donir125/lab2
/binary.py
509
3.828125
4
from random import randint def binarySearch(arr, key): left = 0 right = len(arr) - 1 while left <= right: mid = (right + left) // 2 if key > arr[mid]: left = mid + 1 elif key < arr[mid]: right = mid - 1 else: return mid return "No results" n = 1000 key = int(input("Введите число для поиска: ")) arr = [randint(-500, 500) for i in range(n)] arr = sorted(arr) print(binarySearch(arr, key)) print(arr)
eadc89d417fcc3af9ae4033d9242495a73b6cb26
eghobrial/python-resources
/python-tutorial/Tutorial2-LoopsFunctions/whileLoop.py
110
3.5
4
sum = 0 j = 0 while j < 10: sum = sum + j print " For interation num (%d) sum = (%d)" % (j,sum) j = j +1
d35d457ed6d688e38d0fe38cd794b609aa30d8ee
vymaxim/algoritms
/lesson1/task6.py
143
3.796875
4
x = int(input('введите номер буквы в алфавите (от 1 до 26) ')) y = ord('a') x = x + y - 1 x = chr(x) print(x)
f2f672b115be383e4b1d5395b9dd5bdc3f5ee8c5
cocoisland/Graphs
/projects/graph_problem/island.py
5,203
4.21875
4
''' Write a function that takes a 2D binary array and returns the number of 1 islands. An island consists of 1s that are connected to the north, south, east or west. For example: islands = [[0, 1, 0, 1, 0], [1, 1, 0, 1, 1], [0, 0, 1, 0, 0], [1, 0, 1, 0, 0], [1, 1, 0, 0, 0]] island_counter(islands) # returns 4 ''' islands = [[0, 1, 0, 1, 0], [1, 1, 0, 1, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 0], [1, 1, 0, 1, 1]] # islands = [[1, 0, 0, 1, 1, 0, 1, 1, 0, 1], # [0, 0, 1, 1, 0, 1, 0, 0, 0, 0], # [0, 1, 1, 1, 0, 0, 0, 1, 0, 1], # [0, 0, 1, 0, 0, 1, 0, 0, 1, 1], # [0, 0, 1, 1, 0, 1, 0, 1, 1, 0], # [0, 1, 0, 1, 1, 1, 0, 1, 0, 0], # [0, 0, 1, 0, 0, 1, 1, 0, 0, 0], # [1, 0, 1, 1, 0, 0, 0, 1, 1, 0], # [0, 1, 1, 0, 0, 0, 1, 1, 0, 0], # [0, 0, 1, 1, 0, 1, 0, 0, 1, 0]] # 1. Translate problem into graph terminology: ''' Understand the problem: 1. An island is made up of at least 3 ones' located in 3 of the 4 direction(n,s,w,e). Island boundary is marked by 0 or matrix edge. Is a graph problem because of keyword "connected" to north, south, west or east. 2. Build a graph based on "connected" to north, south, west, or east. 3. Traverse graph checking for connection to north, south, west or east. ''' # 2. Build your graph def get_neighbors(v, matrix): col = v[0] row = v[1] neighbors = [] # Check North if row > 0 and matrix[row - 1][col] == 1: neighbors.append((col, row-1)) # Check South if row < len(matrix) - 1 and matrix[row + 1][col] == 1: neighbors.append((col, row+1)) # Check East if col < len(matrix[0]) - 1 and matrix[row][col + 1]: neighbors.append((col + 1, row)) # Check West if col > 0 and matrix[row][col - 1]: neighbors.append((col - 1, row)) return neighbors # 3. Traverse your graph class Stack(): def __init__(self): self.stack = [] def push(self, value): self.stack.append(value) def pop(self): if self.size() > 0: return self.stack.pop() else: return None def size(self): return len(self.stack) class Queue(): def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if self.size() > 0: return self.queue.pop(0) else: return None def size(self): return len(self.queue) def island_counter(matrix): # DFS - traverse vertically by each row first, then horizontally by column # Create a visited matrix visited = [] for i in range(len(matrix)): # number of rows in 2x2 matrix visited.append([False] * len(matrix[0])) # number of columns in 2x2 matrix island_count = 0 # Walk through each cel in the matrix for col in range(len(matrix[0])): for row in range(len(matrix)): # If that cel has not been visited if not visited[row][col]: # When I reach a 1, if matrix[row][col] == 1: # Do a DFT and mark each as visited visited = dft(col, row, matrix, visited) # Then increment the counter by 1 island_count += 1 # Return island count return island_count def island_counter_BFS(matrix): # BFS - traverse horizontal by each column first, then vertically by row # Create a visited matrix visited = [] for i in range(len(matrix)): # number of rows in 2x2 matrix visited.append([False] * len(matrix[0])) # number of columns in 2x2 matrix island_count=0 # Walk through each cel in the matrix for row in range(len(matrix)): for col in range(len(matrix[0])): # If that cel has not been visited if not visited[row][col]: # When I reach a 1, if matrix[row][col] == 1: # Do a BFT and mark each as visited visited = bft(col, row, matrix, visited) # Then increment the counter by 1 island_count += 1 # Return island count return island_count def dft(col, row, matrix, visited): s = Stack() s.push((col, row)) while s.size() > 0: v = s.pop() col = v[0] row = v[1] if not visited[row][col]: visited[row][col] = True for neighbor in get_neighbors(v, matrix): # STUB s.push(neighbor) return visited def bft(col, row, matrix, visited): s = Queue() s.enqueue((col, row)) while s.size() > 0: v = s.dequeue() col = v[0] row = v[1] if not visited[row][col]: visited[row][col] = True for neighbor in get_neighbors(v, matrix): # STUB s.enqueue(neighbor) return visited print(f' DFS-traverse vertically row, then horizontally column = {island_counter(islands)}') print(f' BFS-traverse horizontally column, then vertically row = {island_counter_BFS(islands)}')
4803afc191e57e4cd35e70cdc95ef3bc91d5b8b1
zeeshan-emumba/GoogleCodingInterviewQuestions
/matrixMaxProd.py
596
3.578125
4
""" Maximun product of 4 adjacent elements in a matrix. input = [[6, 2, 3, 4], [5, 4, 3, 1], [7, 4, 5, 6], [8, 3, 1, 0]] output = 1860 """ input = [[6, 2, 3, 4],[5, 4, 3, 1],[7, 4, 5, 6],[8, 3, 1, 0]] def proDuct(input): if len(input) == 0: return 0 ans = 1 for x in input: ans = ans * x return ans def matrixMaxProd(input): final =[] for i in range(len(input)): final.append(proDuct(input[i])) final.append(proDuct([row[i] for row in input])) return max(final) print(matrixMaxProd(input)) """ 1680 """
ddf269a655675d49e63f2693bae91c538c23f94e
mitch-hannigan/atividades-do-Edutech
/02 08/16.py
214
3.765625
4
# valores não verificados. dias = int(input("quantos dias você ficou com o carro?")) km_rodado = int(input("quantos km você andou com o carro?")) print(f"você terá de pagar r${dias*60.0+km_rodado*0.15:.{2}f}")
3ecacdedd43d4c1985f901f8805d906b974e38a4
tangwz/leetcode
/leetcode/python3/symmetric-tree.py
1,435
4.03125
4
# # @lc app=leetcode id=101 lang=python # # [101] Symmetric Tree # # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ # def is_symmetric(left, right): # if left and right: # if left.val != right.val: # return False # elif not left and not right: # return True # else: # return False # return is_symmetric(left.right, right.left) and is_symmetric(left.left, right.right) # if not root: # return True # return is_symmetric(root.left, root.right) if not root: return True q = [] q.append(root.left) q.append(root.right) while q: t1 = q.pop(0) t2 = q.pop(0) if not t1 and not t2: continue if not t1 or not t2: return False if t1.val != t2.val: return False q.append(t1.left) q.append(t2.right) q.append(t1.right) q.append(t2.left) return True
f255e6a40ed184c57441f72f9493d9d1a22d13ab
201410090/p1_201410090
/w12Main2.py
197
3.6875
4
myfile=open('output.txt','w') line1='first line \n' myfile.write(line1.upper()) line2='second line \n' myfile.write(line2.upper()) line3='third' myfile.write(line3.upper()) myfile.close()
252b6591668ba1917a360001aeea6288c8d0755f
vvselischev/Software-Design
/Bash-CLI/src/bash/environment.py
790
3.984375
4
import os class Environment: """Represents an environment with a dict interface.""" def __init__(self): self._variables = {} def put(self, variable, value): """Puts the pair to the environment or updates the existing variable.""" self._variables[variable] = value def get(self, name): """ Returns a value of a given variable or throws an exception if it does not exist. """ if name not in self._variables: raise Exception("Variable " + name + " is not in the environment.") return self._variables[name] def update_system_environment(self): """Copies all variables to the system environment.""" for key, value in self._variables: os.environ[key] = value
c436f69553293816d520a4272c5aaf806be156f2
evtoz/learning_python
/Exercise1_solved.py
288
3.5625
4
intro = "Hello, My Name Is" print (intro) intro = "Pratik Rai" print (intro) print ('I told my friend "Python" is my favorite Language.') print ("The language 'Python' is named after Monty Python, not the snake.") print ("One of python's strengths is its diverse and supportive community.")
b61ce8a0316c5a1eb3369182826cc0f6a409a705
Meaguileraa/algorithms
/move-zeroes.py
762
4.3125
4
# Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. # Example: # Input: [0,1,0,3,12] # Output: [1,3,12,0,0] # Note: # You must do this in-place without making a copy of the array. # Minimize the total number of operations. #Leetocde Problem: Move Zeroes def move_zeroes(nums): """Given an array of numbers move all the zeroes to the end.""" for idx, num in enumerate(nums): if num == 0: nums.pop(idx) nums.append(num) return nums # nums.insert(-1, num) # nums.pop(num.insert(-1, num)) print(move_zeroes([0,1,0,3,12])) #[1,3,12,0,0] print(move_zeroes([5,4,0])) #[5,4,0] #could use .remove as well
9b9e0293ecba66fa36974a205cc60a4d27c2f126
office-github/python_mysql_demo
/demo_file/scope_namespace.py
881
3.75
4
def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam spam = "nonlocal spam" def do_global(): global spam spam = "global spam" spam = "test spam" do_local() print("After local assignment:", spam) do_nonlocal() print("After nonlocal assignment:", spam) do_global() print("After global assignment:", spam) scope_test() print("In global scope:", spam) # The output of the example code is: # # After local assignment: test spam # After nonlocal assignment: nonlocal spam # After global assignment: nonlocal spam # In global scope: global spam # Note how the local assignment (which is default) didn’t change scope_test’s binding of spam. # The nonlocal assignment changed scope_test’s binding of spam, and the global assignment changed the module-level binding.
c2a5297040f65ff9ac32240c8a09296e9ef86a23
pwchen21/pros
/python/Leetcode/July.30day_challenge/0702_107.py
777
3.578125
4
class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] queue = [root] res = [[root.val]] while queue: child=[] for node in queue: if node.left: child.append(node.left) if node.right: child.append(node.right) if not child: break queue = child #print(queue) res.append([node.val for node in queue]) #print(res) return(res[::-1])
b7aa9e1e7e8584918c941c87a5433cc168d58127
Chayaaaa/n96104488-lab3
/N96104488-Lab3/Hint/move_function_example/move_example_1.py
512
3.65625
4
import pygame pygame.init() win = pygame.display.set_mode((1024, 800)) clock = pygame.time.Clock() # coordinate of the rect surface x = 0 y = 100 run = True while run: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False # update the coordinate each frame x += 2 y += 1 # draw win.fill((0, 0, 0)) pygame.draw.rect(win, (255, 255, 255), [x, y, 50, 50]) pygame.display.update() pygame.quit()