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
8165feb1cf2ff8de8f80ca6d2aa289c848364481
buildtesters/buildtest
/buildtest/utils/timer.py
818
4.09375
4
import time class TimerError(Exception): """A custom exception used to report errors in use of Timer class""" class Timer: def __init__(self): self._start_time = None self._duration = 0 def start(self): """Start a new timer""" if self._start_time is not None: raise TimerError("Timer is running. Use .stop() to stop it") self._start_time = time.perf_counter() def stop(self): """Stop the timer, and report the elapsed time""" if self._start_time is None: raise TimerError("Timer is not running. Use .start() to start it") self._duration += time.perf_counter() - self._start_time self._start_time = None # return elapsed_time def duration(self): return round(self._duration, 3)
d8508b1c364c2e9a2da7a50ac32a85bcb4bbc0a1
searfmat/CLRS-Algos
/heapsort.py
930
3.828125
4
import math def left(i): return (i << 1) + 1 def right(i): return (i << 1) + 2 def maxHeapify(arr, i, heapsize): l = left(i) r = right(i) if l <= heapsize and arr[l] > arr[i]: largest = l else: largest = i if r <= heapsize and arr[r] > arr[largest]: largest = r if largest != i: arr[i], arr[largest] = arr[largest], arr[i] maxHeapify(arr, largest, heapsize) def buildMaxHeap(arr, heapsize): for i in range(math.floor(len(arr) / 2) - 1, -1, -1): maxHeapify(arr, i, heapsize) def heapsort(arr, heapsize): buildMaxHeap(arr, heapsize) print("Array after build max heap: ", arr) for i in range(len(arr)): arr[heapsize], arr[0] = arr[0], arr[heapsize] heapsize = heapsize - 1 maxHeapify(arr, 0, heapsize) arr = [22,95,35,11,17,27,18,4,5] heapsize = len(arr) - 1 heapsort(arr, heapsize) print(arr)
60e768f72e64ce0952b5baa1199848861301e999
mahalakshmiraja/learn-python
/anti_vowel.py
318
4.03125
4
def anti_vowel(text): lst = [] text = text.lower() length = len(text) for i in range(length): if text[i]!="a" and text[i]!="e" and text[i]!="i" and text[i]!="o" and text[i]!="u": lst.append(text[i]) print ("".join(map(str,lst))) anti_vowel("welcome DAY")
d57c2dfcc21a8a6a2c7aecc1ab70b75b1ce3c9b5
alvinwang922/Data-Structures-and-Algorithms
/Trees/House-Robber-Three.py
1,274
3.921875
4
""" The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night. Determine the maximum amount of money the thief can rob tonight without alerting the police. """ # 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 rob(self, root: TreeNode): res = self.helper(root) return max(res[0], res[1]) def helper(self, root): res = [0, 0] if root == None: return res left = self.helper(root.left) right = self.helper(root.right) res[0] = max(left[0], left[1]) + max(right[0], right[1]) res[1] = root.val + left[0] + right[0] return res print(rob([3, 2, 3, None, 3, None, 1])) print(rob([1, 2, 3, None, 4, None, 5])) print(rob([3, 4, 5, 1, 3, None, 1])) print("The values above should be 7, 10, and 9.")
b236a94f8b28348347ead209b98a7e0b996f9671
FrosT2k5/LucifeR
/lucifer.py
4,060
3.53125
4
import sys import os def clr(): if os.name == 'nt': os.system('cls') else: os.system('clear') def banner (): ban = """ _ _ __ _____ | | (_)/ _| | __ \ | | _ _ ___ _| |_ ___| |__) | | | | | | |/ __| | _/ _ \ _ / | |___| |_| | (__| | || __/ | \ \ |______\__,_|\___|_|_| \___|_| \_\\ """ print(ban) print('Welcome to Terminal LucifeR by FrosT,LemoN,Yuvi and DarK.Enter help or h for list of options') def nth(): z = open('files/holp.txt') ct = z.read() print(z) z.close() def help(): file = open('files/help.txt') cont = file.read() print(cont) file.close() def calc(): print('Enter 1 for addition/subtraction/multiplication/division') print('Enter 2 for square,cube,square root and raise power') ip = int(input('Choose option 1 or 2: ')) if ip == 1: num1 = float(input('Enter first number: ')) op = input('Enter operation: ') num2 = float(input('Enter second number: ')) if op == '+': print('Addition: ',num1+num2) elif op == '-': print('Subtraction: ',num1-num2) elif op == '*': print('Multiplication: ',num1*num2) elif op == '/': print('Division: ',num1/num2) else: print('Please enter one of these: +,-,* or /') elif ip == 'options': nth() elif ip == 2: while True: print('Enter square, cube, squareroot or sqrt, raise or raiseto') lo = input('Calc: ') if lo == 'square': sq = int(input('Enter number for it\'s square: ')) print('Square: ',sq**2 ) elif lo == 'cube': cb = int(input('Enter number for it\'s cube: ')) print('Cube: ',cb**3) elif lo == 'squareroot' or lo == 'square root' or lo == 'sqrt': sr = float(input('Enter number for its square root: ')) elif lo == 'quit' or 'exit': sys.exit() print('The square root of the number is: ',sr**(1/2)) elif lo == 'raiseto' or lo == 'raise' or lo == 'power': nm = int(input('Enter a number to raise it\'s power: ')) pr = int(input('Enter the index number: ')) print('The result is: ',nm**pr) else: print('Incorrect option,enter options for getting list of options') else: print('Please enter option 1 or 2') def lp(): st = input('Enter the sentence to be looped: ') no = input('Enter the number of times to be printed: ') i = 1 while(i<=int(no)): print(st) i += 1 def tables(): ta = int(input('Enter the number for its table: ')) bl = int(input("Enter the number of times till you want it's table: ")) j = 1 while(j<=bl): print(ta,'x',j,'=',ta*j) j += 1 def numgame(): fun = float(input('Enter any number for its weight on other planets: ')) print("If your weight was",fun,"kgs on earth ,then your weight on :-\nMercury =",fun*0.38,'\nVenus =',fun*0.9,'\nMars =',fun*0.38,'\nJupiter =',fun*2.34,'\nSaturn =',fun*1.06,'\nUranus =',fun*0.91,'\nNeptune =',fun*1.19,'\nPluto',fun*0.06) banner() while True: inp = str(input('LucifeR: ')) if inp == 'calc' or inp == 'calculator': calc() elif inp == 'help' or inp == 'h': help() elif inp == 'lp' or inp == 'loopprint': lp() elif inp == 'numbergame' or inp == 'weight': numgame() elif inp == 'tables': tables() elif inp == 'quit' or inp == 'exit': sys.exit() elif inp == 'clear': clr() else: print('Please enter one of the following options:') help()
ca9f3c0c2336fe605b241d25e6b380496f733eaa
Jelowpat/Patryk-Jelowicki
/projects_from_infoshare_course/funtests/funtests.py
5,677
3.625
4
#a function for creating a new funtest def nowy_test(nazwa=""): licznik = 0 if nazwa == "": nazwa = input("podaj nazwe testu(pliku)")+".txt" plik = open(nazwa, "a", encoding="utf-8") while True: a = 0 pytanie_nowe = input("wpisz tekst swojego pytania, 'k' by zakonczyc") if pytanie_nowe == "k": if licznik > 0: break else: print("nie ma jeszcze żadnych pytań") continue elif len(pytanie_nowe) < 3: print("zadaj prawdziwe pytanie!") continue else: plik.write(f"{pytanie_nowe}\n") while a < 15: answer = input(f"podaj wariant {warianty[a]}) lub wcisnij 'k' jesli to wszystkie warianty") if answer == "k": if a > 1: while True: poprawna = input("podaj poprawna odpowiedz") if poprawna in warianty[:a] and len(poprawna) == 1: plik.write(f"{poprawna}\n") break else: print("podaj literkę poprawnej odpowiedzi") break else: print("podaj przynajmniej 2 odpowiedzi") continue elif len(answer) == 0: print("podaj prawdziwy wariant!") continue else: plik.write(f"{warianty[a]}) {answer}\n") a += 1 licznik += 1 plik.close() warianty = "abcdefghijklmno" # a string for options chwilowa = [] # initiating a variable for appending a list # main program loop while True: pytania = [] # a list for questions, options and answers print("witaj w FUNteście") o_kim = input("wpisz nazwę testu(pliku) lub naciśnij 'n' by stworzyć nowy test\n")+".txt" if o_kim == "n.txt": nowy_test() continue try: f = open(o_kim, "r", encoding="utf-8") pass except IOError: nowy = input("nie ma takiego pliku, czy chciałbyś/chciałabyś stworzyć funtest o takiej nazwie? ('t')") if nowy == "t": nowy_test(nazwa=o_kim) continue f1 = f.readlines() for x in f1: if x != "": chwilowa.append(x.strip()) if len(x) == 2: chwilowa[-1] = x[0] pytania.append(chwilowa) chwilowa = [] f.close() # a loop for answering the test while True: imie = input("podaj swoje imie by zacząć\n") numer = 0 # a variable holding the number of the question wynik = 0 # a variable holding the score of the user zle_odpowiedzi = [] # a list of wrong answers highscores = [] # a list for highscores for pytanie in pytania: numer += 1 for x in pytanie[:-1]: print(x) odpowiedz = input().lower() while odpowiedz not in warianty[:len(pytanie)-2] or len(odpowiedz) != 1: print("nie ma takiej odpowiedzi") for x in pytanie[:-1]: print(x) odpowiedz = input().lower() if odpowiedz == pytanie[-1]: wynik += 1 else: zle_odpowiedzi.append([numer, odpowiedz]) print(f"Twój wynik to {wynik}pkt", "BRAWO!!!" if wynik/len(pytania) > 0.75 else "cienko :/") high = imie + "-" + str(wynik) + "\n" with open(f"highscores.{o_kim}", "a", encoding="utf-8") as f: f.write(high) with open(f"highscores.{o_kim}", "r+", encoding="utf-8") as f: f1 = f.readlines() for x in f1: name, score = x.split(sep="-") score = int(score) highscores.append([name, score]) highscores.sort(key=lambda s: s[1], reverse=True) f = open(f"highscores.{o_kim}", "w") f.close() with open(f"highscores.{o_kim}", "r+", encoding="utf-8") as f: for x in highscores: f.write(f"{x[0]}-{x[1]}\n") while True: co_dalej = input("nacisnij 'z' by poznac swoje bledne odpowiedzi, 'q' zeby wyjsc z programu," " 'd' by wyswietlic dobre odpowiedzi,\n'h' by wyswietlic najwyzsze wyniki," " 'n' by sprobowac jeszcze raz, cokolwiek innego by wrócić\n") if co_dalej == "q": exit() elif co_dalej == 'z': for x in zle_odpowiedzi: print(x[0], "-", x[1]) elif co_dalej == 'd': for x in range(numer-1): print(x+1, "-", pytania[x][-1]) elif co_dalej == 'h': najdluzszy = len(highscores[0][0]) for x in highscores: dlugosc = len(x[0]) if dlugosc > najdluzszy: najdluzszy = dlugosc for x in highscores: dlugosc = len(x[0]) if dlugosc > 20: x[0] = x[0][:18]+"(...)" dlugosc = 23 print(f"{x[0]}{'-' * (23 - dlugosc)}-{x[1]}") else: break if co_dalej == "n": continue break
2b74bc9a8dd5a098fa983cf352cb4222103c1068
ywkpl/DataStructuresAndAlgorithms
/tree/test.py
294
3.515625
4
from datetime import datetime, timedelta if __name__=="__main__": begin = datetime(2018, 11, 1) end = datetime(2019, 6, 18) times=end-begin print('天数:') print(times.days) print('月数余天数:') print(str(times.days//30)+'月'+str(times.days%30)+'天')
d62313fc1a9dd396bfbb3e09defa940bdc2ef88c
jgarza9788/HackerRankCode
/Python/MergeTheTools!.py
709
3.765625
4
#Merge the Tools! #https://www.hackerrank.com/challenges/merge-the-tools/forum def merge_the_tools0(string, k): i = 0 while i < len(string): s = string[i:][:k] fs = '' for l in s: if l in fs: pass else: fs = fs+l print(fs) i+=k def merge_the_tools(string, k): for part in zip(*[iter(string)] * k): # print(part) d = dict() # print(d) print(''.join([ d.setdefault(c, c) for c in part if c not in d ])) if __name__ == '__main__': # string, k = input(), int(input()) string, k = 'AAAAAAADA', 1 # merge_the_tools0(string, k) merge_the_tools(string, k)
a40b78c6a113961e0a4eced2938e3da6c59c7af4
developeryuldashev/python-core
/python core/Lesson_9/list_53.py
158
3.796875
4
a=[3,5,9,6,1] b=[2,5,7,4,9] c=[] for i in range(len(a)): if a[i]>=b[i]: c.append(a[i]) else: c.append(b[i]) print(a) print(b) print(c)
9b42a10f3f7729255de50021347b3b93eb7db675
Zasaz/Python-Practise
/Conditional.py
165
3.875
4
age = 18 if age >= 18: print("You can vote") print("Mature") elif age < 18: print("Not mature") else: print("Ok bye") print("Ok i am done")
934c54e6dfab43180cb50c67dca9296ee1638e2f
danlaratta/rock-paper-scissors
/Rock_Paper_Scissors.py
3,745
3.96875
4
import tkinter as tk import random # sets up window, window's size, window's title, and window's background color window = tk.Tk() window.geometry("350x300") window.title("Rock, Paper, Scissors") window.configure(background='#66e0ff') # game title game_title = tk.Label(text="Rock, Paper, Scissors", bg="#66e0ff") game_title.grid(row=0, column=0) # simple directions for game enter_pick = tk.Label(text="Enter Your Pick", bg="#66e0ff") enter_pick.grid(row=1, column=0) # validates the entry making sure its only letters def validate(data): if data.isalpha(): return True elif user_entry.get() == "": return False else: return False # creates entry widget and creates a string variable to allow edits to the entry data (capitalize it) var = tk.StringVar() user_entry = tk.Entry(textvariable=var, highlightthickness=0, width=12) user_entry.grid(row=2, column=0, padx=10, pady=5) reg = window.register(validate) user_entry.config(validate="key", validatecommand=(reg, "%P")) # function capitalizes the first letter of the entry def caps(*arg): var.set(var.get().capitalize()) # function checks to see who won # noinspection PyRedundantParentheses def check(): # prints the PC pick pc_label = tk.Label(text="The PC guessed " + pc_pick, bg="#66e0ff") pc_label.grid(row=7, column=0) pc_label.after(5000, lambda: pc_label.destroy()) # prints the user's pick user_label = tk.Label(text="Your pick was " + user_entry.get(), bg="#66e0ff") user_label.grid(row=8, column=0) user_label.after(5000, lambda: user_label.destroy()) # checks who won as well as makes sure entry is text if (pc_pick == user_entry.get()): same_label = tk.Label(text="You both chose " + pc_pick, bg="#66e0ff") same_label.grid(row=9, column=0) same_label.after(5000, lambda: same_label.destroy()) elif (pc_pick == "Rock" and user_entry.get() == "Scissors"): pc_won = tk.Label(text="Sorry, you lose :(", bg="#66e0ff") pc_won.grid(row=9, column=0) pc_won.after(5000, lambda: pc_won.destroy()) elif (pc_pick == "Paper" and user_entry.get() == "Rock"): pc_won = tk.Label(text="Sorry, you lose :(", bg="#66e0ff") pc_won.grid(row=9, column=0) pc_won.after(5000, lambda: pc_won.destroy()) elif (pc_pick == "Scissors" and user_entry.get() == "Paper"): pc_won = tk.Label(text="Sorry, you lose :(", bg="#66e0ff") pc_won.grid(row=9, column=0) pc_won.after(5000, lambda: pc_won.destroy()) elif (user_entry.get() == "Rock" and pc_pick == "Scissors"): user_won = tk.Label(text="Congratulations, you won :)", bg="#66e0ff") user_won.grid(row=9, column=0) user_won.after(5000, lambda: user_won.destroy()) elif (user_entry.get() == "Paper" and pc_pick == "Rock"): user_won = tk.Label(text="Congratulations, you won :)", bg="#66e0ff") user_won.grid(row=9, column=0) user_won.after(5000, lambda: user_won.destroy()) elif (user_entry.get() == "Scissors" and pc_pick == "Paper"): user_won = tk.Label(text="Congratulations, you won :)", bg="#66e0ff") user_won.grid(row=9, column=0) user_won.after(5000, lambda: user_won.destroy()) # performs the actions of the other functions when the button is clicked def click(): caps() check() user_entry.delete(0, "end") # creates the submit button submit_btn = tk.Button(text="Enter", command=click) submit_btn.grid(row=3, column=0) # makes the stringvar read only var.trace("r", caps) # list of possible picks pick_list = ["Rock", "Paper", "Scissors"] # randomly chooses a list item as the pick for the PC pc_pick = random.choice(pick_list) window.mainloop()
155be1715b0e48b444fb66f8ac858ee3432bfd73
shohoku3/Python30
/demo9.py
844
4.25
4
# 结构化数据 字典 # 比较字典与列表 spam =['cats','dogs','mosses'] bacon=['dogs','cats','mosses'] if spam == bacon: print('两个 list相同') else: print('两个list 不同') eggs={'name':'zomap','age':'8'} ham={'age':'8','name':'zomap'} if eggs==ham: print('两个字典相同') else: print('两个字典不同') # values() keys() items() for v in eggs.values(): print(v) for i in eggs.items(): print(i) for k in eggs.keys(): print(k) #保存朋友的生日 birthday={'Alice':'Apir 1','Syf':'Oct 02'} while True: print('Enter a name: (blank to quit)') name=input() if name == '': break if name in birthday: print(birthday[name]+'is the birthday of '+name) else: print('I do not have birthday info for' + name) print('Please input') bday=input() birthday[name]=bday print('birthday info is update')
574d23e153afbdaf9b044b5296a12a9ef7c868e3
gyang274/leetcode
/src/0500-0599/0542.matrix.distance.py
1,046
3.609375
4
from typing import List class Solution: def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]: """bfs """ n = len(matrix) if n == 0: return [] m = len(matrix[0]) if m == 0: return [[]] queue = [] for i in range(n): for j in range(m): if matrix[i][j] == 0: queue.append((i, j)) dist, visited = 1, set(queue) while queue: bound = [] while queue: x, y = queue.pop() for dx, dy in [(-1, 0), (0, 1), (1, 0), (0, -1)]: i, j = x + dx, y + dy if 0 <= i < n and 0 <= j < m and (i, j) not in visited: visited.add((i, j)) matrix[i][j] = dist bound.append((i, j)) queue = bound dist += 1 return matrix if __name__ == '__main__': solver = Solution() cases = [ [[0,0,0],[0,1,0],[0,0,0]], [[0,0,0],[0,1,0],[1,1,1]], ] rslts = [solver.updateMatrix(matrix) for matrix in cases] for cs, rs in zip(cases, rslts): print(f"case: {cs} | solution: {rs}")
fe13512203237ee2d6dd3ba89e56840a611e315f
nsyzrantsev/algorithms_2
/BinarySearchTree/BinarySearchTree.py
5,239
3.609375
4
# https://skillsmart.ru/algo/15-121-cm/bcd63523a1.html class BSTNode: def __init__(self, key, val, parent): self.NodeKey = key self.NodeValue = val self.Parent = parent self.LeftChild = None self.RightChild = None class BSTFind: def __init__(self): self.Node = None self.NodeHasKey = False self.ToLeft = False class BST: def __init__(self, node): self.Root = node self.count = 1 def FindNodeByKey(self, key): result = BSTFind() node = self.Root while node is not None: if node.NodeKey == key: result.Node = node result.NodeHasKey = True return result elif key < node.NodeKey: if node.LeftChild is None: result.Node = node result.ToLeft = True return result else: node = node.LeftChild elif key > node.NodeKey: if node.RightChild is None: result.Node = node return result else: node = node.RightChild return result def AddKeyValue(self, key, val): node = self.FindNodeByKey(key) if node.NodeHasKey: return False if self.Root is None: self.Root = BSTNode(key, val, None) elif node.ToLeft: node.Node.LeftChild = BSTNode(key, val, node.Node) else: node.Node.RightChild = BSTNode(key, val, node.Node) self.count += 1 return True def FinMinMax(self, FromNode, FindMax): if self.Root is not None: if FindMax: while FromNode.RightChild is not None: FromNode = FromNode.RightChild else: while FromNode.LeftChild is not None: FromNode = FromNode.LeftChild return FromNode def FindPrePostNode(self, node): if node.RightChild is not None: return self.FinMinMax(node.RightChild, False) parent = node.Parent while parent is not None and node == parent.RightChild: node = parent parent = parent.Parent return parent def FindNewNode(self, node): new_node = None if node.LeftChild == None or node.RightChild == None: new_node = node else: new_node = self.FindPrePostNode(node) return new_node def FindNewChild(self, node): new_child = None if node.LeftChild != None: new_child = node.LeftChild else: new_child = node.RightChild return new_child def ConnectParentAndChild(self, new_node, new_child): if new_child != None: new_child.Parent = new_node.Parent if new_node.Parent == None: self.Root = new_child elif new_node == new_node.Parent.LeftChild: new_node.Parent.LeftChild = new_child else: new_node.Parent.RightChild = new_child def DeleteNodeByKey(self, key): # Find the removed node node = self.FindNodeByKey(key).Node if node.NodeKey != key: return False # Find new_node instead of the removed node new_node = self.FindNewNode(node) # Find a child of the new_node new_child = self.FindNewChild(new_node) # Connect a new_node.Children # with new_node.Parent self.ConnectParentAndChild(new_node, new_child) # Change key and value of the removed # node with new_node if new_node != node: node.NodeKey = new_node.NodeKey node.NodeValue = new_node.NodeValue self.count -= 1 return True def Count(self): if self.count and self.Root is None: self.count -= 1 return self.count def In_Order(self, nodes, root): if root is not None: self.In_Order(nodes, root.LeftChild) nodes.append(root) self.In_Order(nodes, root.RightChild) return nodes def Pre_Order(self, nodes, root): if root is not None: nodes.append(root) self.Pre_Order(nodes, root.LeftChild) self.Pre_Order(nodes, root.RightChild) return nodes def Post_Order(self, nodes, root): if root is not None: self.Post_Order(nodes, root.LeftChild) self.Post_Order(nodes, root.RightChild) nodes.append(root) return nodes def DeepAllNodes(self, p): if p == 0: return self.In_Order([], self.Root) elif p == 1: return self.Post_Order([], self.Root) elif p == 2: return self.Pre_Order([], self.Root) def WideAllNodes(self): nodes = [self.Root] if self.Root is not None: for i in nodes: if i.LeftChild is not None: nodes.append(i.LeftChild) if i.RightChild is not None: nodes.append(i.RightChild) return nodes
4c177efc84ae9b4b127ba9560fef79962a48f7fe
sandeephalder/AlgoPractice
/Python/DP_Tushar/MinimumCostpath.py
917
3.78125
4
class MinimumCostPath(): weights = [[1,3,5,8],[4,2,1,7],[4,3,2,3]] knapsack = [[0 for i in range(4)] for j in range(3)] def print(self): for i in range(3): print() for j in range(4): print('-->',self.knapsack[i][j],end='-->') def compute(self): self.knapsack[0][0] = self.weights[0][0] for i in range(1,4): self.knapsack[0][i] = self.weights[0][i] +self.knapsack[0][i-1] for i in range(0,3): self.knapsack[i][0] = self.weights[i][0] +self.knapsack[i-1][0] for i in range(3): for j in range(4): if i ==0 or j ==0: continue else: self.knapsack[i][j] = min(self.knapsack[i][j-1],self.knapsack[i-1][j]) + self.weights[i][j] k = MinimumCostPath() k.compute() k.print()
887eb20cba1cf61d838a65665d8b354cd0db50d0
desmondlee/python
/while.py
122
3.75
4
# -*- coding: utf-8 -*- L = ['Bart', 'Lisa', 'Adam'] n = len(L) while n > 0 : print("Hello, %s" % L[n-1]) n = n-1
dc48c9fc6d4326b999b17b65620514e0cfb3b58b
dombroks/Daily-Coding-Problems
/Microsoft_Problems/Microsoft_Problem_02.py
1,370
3.734375
4
""" This problem was asked by Microsoft. You have an N by N board. Write a function that, given N, returns the number of possible arrangements of the board where N queens can be placed on the board without threatening each other, i.e. no two queens share the same row, column, or diagonal. """ N = 4 #NxN matrix with all elements 0 board = [[0]*N for _ in range(N)] def is_under_attack(i, j): #checking if there is a queen in row or column for k in range(0,N): if board[i][k]==1 or board[k][j]==1: return True #checking diagonals for k in range(0,N): for l in range(0,N): if (k+l==i+j) or (k-l==i-j): if board[k][l]==1: return True return False def setting_up_queens_on_board(n): #if n is 0, solution found if n==0: return True for i in range(0,N): for j in range(0,N): if (not(is_under_attack(i,j))) and (board[i][j]!=1): board[i][j] = 1 #wether we can put the next queen with this arrangment or not if setting_up_queens_on_board(n-1)==True: return True board[i][j] = 0 return False #-------- setting_up_queens_on_board(N) print("Queens coordinates are: ") for i in range(N): for j in range(N): if board[i][j] == 1 : print(i,j)
a515377a5c40ad22a74ea8a739af760ab9228d57
testtatto/project_euler
/problem5.py
583
4.0625
4
""" 2520 は 1 から 10 の数字の全ての整数で割り切れる数字であり, そのような数字の中では最小の値である. では, 1 から 20 までの整数全てで割り切れる数字の中で最小の正の数はいくらになるか. """ import math # 最小公倍数を求める関数 def lcm(a, b): return a * b // math.gcd(a, b) if __name__ == '__main__': current_lcm = 1 # 最小公倍数を再帰的に更新していく for i in range(1, 21): current_lcm = lcm(current_lcm, i) answer = current_lcm print(answer)
2ab678ffac70087c9374212c2451f1be19f27526
neelabhpant/Intermediate_Python_For_Data_Science
/Using_Pandas.py
948
4.03125
4
import pandas as pd names = ['United States', 'Australia', 'Japan', 'India', 'Russia', 'Morocco', 'Egypt'] # The country names for which data is available. dr = [True, False, False, False, True, True, True] # A list with booleans that tells whether people drive left or right in the corresponding country. cpc = [809, 731, 588, 18, 200, 70, 45] # The number of motor vehicles per 1000 people in the corresponding country. # Create dictionary my_dict with three key:value pairs: my_dict my_dict = {"country":names, "drives_right":dr, "cars_per_cap":cpc} # Build a DataFrame cars from my_dict: cars cars = pd.DataFrame(my_dict) print(cars) row_labels = ['US', 'AUS', 'JAP', 'IN', 'RU', 'MOR', 'EG'] # Specify the row labels cars.index = row_labels print(cars) # The data is available in a CSV file, named cars.csv # Import CSV files and make the column 0 as the index or row label cars = pd.read_csv("cars.csv", index_col=0) print(cars)
0d9a60aa6fb66af8c29c1c2fe0e0368f62410772
ehhglen/Temperature-Conversion-Table
/TempConvertor.py
960
4.03125
4
# Variables Celsius = 0 list_of_celsius = [ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 ] # Function to convert Celsius to Fahrenheit def convToFahrenheit(Celsius): listOfFahrenheits = [] while (Celsius != 110): fahrenheit = (Celsius * 9/5) + 32 Celsius += 10 listOfFahrenheits.append(fahrenheit) return (listOfFahrenheits) list_of_fahrenheits = convToFahrenheit(Celsius) list_of_celsius_fahrenheit = [list_of_celsius, list_of_fahrenheits] print("Celsius to Fahrenheit") print("Conversion Table") print("-----------------") print("Celsius\t\tFahrenheit") print(*list_of_celsius_fahrenheit, sep="\n") # for i in range(len(list_of_celsius)): # print(list_of_celsius[i] + '\t ' + list_of_fahrenheits[i]) # Sorta close # for temps in zip(*list_of_celsius_fahrenheit): # print(*temps) # print(*list_of_celsius, sep = "\n") # print(*list_of_fahrenheits, sep = "\n")
44e1a16a97bfc253815c17d6abe79e441d035da3
18801308557/versusGame20210401
/positionFunc.py
305
3.84375
4
import math #计算两点之间距离是否小于r def distanceInR(cx,cy,r,x,y): dist=math.sqrt((math.pow(x-cx,2)+math.pow(y-cy,2))) if dist<r: return True else: return False def distanceCal(cx,cy,x,y): dist=math.sqrt((math.pow(x-cx,2)+math.pow(y-cy,2))) return dist
16a873eb730d19c2d438a3369d599df0fdef55bf
szabgab/slides
/python/examples/dictionary/count_words_speed.py
1,841
3.84375
4
from collections import defaultdict from collections import Counter import timeit def generate_list_of_words(number, repeat): #words = ['Wombat', 'Rhino', 'Sloth', 'Tarantula', 'Sloth', 'Rhino', 'Sloth'] words = [] for ix in range(number): for _ in range(repeat): words.append(str(ix)) return words def plain_counter(words): counter = {} for word in words: if word not in counter: counter[word] = 0 counter[word] += 1 return counter def counter_with_exceptions(words): counter = {} for word in words: try: counter[word] += 1 except KeyError: counter[word] = 1 return counter def counter_with_counter(words): counter = Counter() for word in words: counter[word] += 1 return counter def counter_with_default_dict(words): counter = defaultdict(int) for word in words: counter[word] += 1 return counter def main(): #words = generate_list_of_words(1000, 1) #counter = plain_counter(words) #counter = counter_with_counter(words) #counter = counter_with_default_dict(words) #counter = counter_with_exceptions(words) #for word in sorted(counter.keys()): # print("{}:{}".format(word, counter[word])) for repeat in [1, 10, 20, 50]: different = int(1000 / repeat) print(f'repeat {repeat} different {different}') for name in ['plain_counter', 'counter_with_counter', 'counter_with_default_dict', 'counter_with_exceptions']: print("{:26} {}".format(name, timeit.timeit(f'{name}(words)', number=10000, setup=f'from __main__ import {name}, generate_list_of_words; words = generate_list_of_words({different}, {repeat})'))) print() if __name__ == "__main__": main()
34fcab54149e7ba78af0cdc80470629c5ec53d43
BettiouiFarid/SHA-1
/sha256.py
1,078
3.640625
4
# import the library module import hashlib def sha256 (text): # encode the string encoded_str = text.encode() # create a sha1 hash object initialized with the encoded string hash_obj = hashlib.sha256(encoded_str) # convert the hash object to a hexadecimal value hexa_value = hash_obj.hexdigest() return hexa_value def H(text1,text2): id = text1 y = text2 x = 0 #10000000015880 20505 while True : print('\n\n==> X = ',x ,'\n===> X apres le hashage est : ',sha256( str(x) )) h = sha256( id + str(x) ) if h <= y : print('====> la valeur de H apres le hashage : ',sha256(id + str(x)) ) return x x += 1 id = input("veuillez-vous saiser votre ID : ") y = "00005d10cc11e27bd8d4d1ce91bc725665ddbaa6ca2498ef38a88a58ad48cdb4" x = H(id , y) #X apres le hashage est : bdc954f3c2058d4a7a5c349cccc8295eac3d244ac2c2b7383b447d76fb0a2830 #la valeur de H apres le hashage : 00000a04e461b771d88284ed986dd69b49f3ab3ef19898cd7ee821b93a4da3c9
81b2618645cdbe98598fd21e66f78c38bb005b7c
sanjoycode97/python-programming-beginners
/python tutorial/arithmatic progression/print the sum of n/python programming practice/count number of odd and even number in the list.py
150
3.984375
4
My_list=[1,2,3,4,5,6,7,8] even=0 odd=0 for x in My_list: if x%2==0: even=even+1 else: odd=odd+1 print(" ",even) print(" ",odd)
bac9041c8fd2278a20219b5af95cf6533f005971
corineru/show_sword_to_offer
/print_binaryTree_after_lines.py
799
3.578125
4
# 2018-04-29 # xinru # file: 把二叉树打印成多行 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回二维列表[[1,2],[4,5]] def Print(self, pRoot): # write code here if not pRoot: return [] node_list = [pRoot] all_list = [] while node_list: new_node_list = [] val_list = [] for node in node_list: val_list.append(node.val) if node.left: new_node_list.append(node.left) if node.right: new_node_list.append(node.right) all_list.append(val_list) node_list = new_node_list return all_list
6c6279f8b6d10384c37708f51cc435d2ce0bce75
GayatriMhetre21/python10aug21
/Assignment2.que1/Area/oval/aoval.py
144
3.890625
4
# area of oval i.e area of an ellipse PI = 3.14 def areaofoval(a, b): result = PI * a * b print("Area of oval : ", result, "units")
7e9e962f2885f0129f27ab3d47ff8a70ab5b4850
madduxc/Think_Python
/Chapter_5.py
4,866
4.28125
4
#Author: Charles D. Maddux #Date: 12/28/2020 #Description: Think Python Chapter 5 exercises import time import turtle def exercise_1(current_time): """ times the current time and converts to days, hours, minutes, seconds since the epoch """ #declare variables unit_min = 60 #[seconds/minute] unit_hour = 60 #[minutes/hour] unit_day = 24 #[hours/day] hours = unit_min * unit_hour #[seconds/hour] days = hours * unit_day #[seconds/day] current_days = int(current_time // days) current_day = current_time % days current_hours = int(current_day // hours) current_hour = current_day % hours current_minutes = int(current_hour // unit_min) current_seconds = round(current_hour % unit_min, 1) print(current_time, "seconds have passed since January 1, 1970 GMT") print("That equates to", current_days, "days,", current_hours, "hours,", current_minutes, "minutes, and ", current_seconds, "seconds.") def check_fermat(num_a, num_b, num_c, num_n=2): """ verifies Fermat's Theorem - "there are no positive integers (n > 2) such that a^n + b^n = c^n :param num_a: int :param num_b: int :param num_c: int :param num_n: int :return: 0 """ left_side = num_a**num_n + num_b**num_n right_side = num_c**num_n if left_side == right_side: print("Holy smokes! Fermat was wrong!") else: print("No, that doesn't work.") return left_side == right_side def exercise_2(): """ retrieves inputs for "check_fermat" function and prints results :return: 0 """ check_a = False check_b = False check_c = False check_n = False while check_a == False: num_a = int(input("Enter 1st positive integer:")) if num_a > 0: check_a = True else: print("Input MUST be an integer greater than zero.") while check_b == False: num_b = int(input("Enter 2nd positive integer:")) if num_b > 0: check_b = True else: print("Input MUST be an integer greater than zero.") while check_c == False: num_c = int(input("Enter 3rd positive integer:")) if num_c > 0: check_c = True else: print("Input MUST be an integer greater than zero.") while check_n == False: num_n = int(input("Enter Exponent (must be a positive integer greater than 2):")) if num_n > 2: check_n = True else: print("Input MUST be an integer greater than two.") verify = check_fermat(num_a, num_b, num_c, num_n) #print(verify) def is_triangle(leg_a, leg_b, leg_c): """ checks if 3 given sides can form a triangle :param leg_a: int :param leg_b: int :param leg_c: int :return: str """ if leg_a > (leg_b + leg_c): return "No" elif leg_b > (leg_a + leg_c): return "No" elif leg_c > (leg_a + leg_b): return "No" else: return "Yes" def exercise_3(): """ retrieves user input for triangle sides :return: 0 """ leg_1 = input("Enter the length of the first leg: ") leg_1 = int(leg_1) leg_2 = input("Enter the length of the second leg: ") leg_2 = int(leg_2) leg_3 = input("Enter the length of the third leg: ") leg_3 = int(leg_3) possible = is_triangle(leg_1, leg_2, leg_3) print(possible) def recurse(n, s): """ copy from text """ if n == 0: print(s) else: recurse(n - 1, n + s) def draw(pencil, length, num): """ aefe """ if num == 0: return angle = 50 pencil.fd(length* num) pencil.lt(angle) draw(pencil, length, num - 1) pencil.rt(2* angle) draw(pencil, length, num - 1) pencil.lt(angle) pencil.bk(length* num) def kock(pencil, length, a=1): """ draws a Kock curve """ angle = 60 * a pencil.fd(length) pencil.lt(angle) pencil.fd(length) pencil.rt(2*angle) pencil.fd(length) pencil.lt(angle) pencil.fd(length) pencil.lt(angle) def snowflake(pencil, length, num, a=1): """ adf """ if num == 0: return for j in range(2): for i in range(3): kock(pencil, length, a) a = (-1)* a pencil.lt(60) snowflake(pencil, length, num - 1, a) def main(): current_time = round(time.time(), 1) exercise_1((current_time)) # print("\n") # exercise_2() # print("\n") # exercise_3() recurse(5, 0) bobo = turtle.Turtle() snowflake(bobo, 10, 3) turtle.mainloop() main()
bc3029b6ae717e192d185775694849c348cc48d7
DanWro/Python
/Pythons/TicetForSpeed.py
247
3.5
4
a=float(input("podaj limit: ")) b=float(input("podaj predkosc: ")) x=list(range(1,10)) m=(b-a<=10) M=(b-a>10) m1=(b-a)*5 M1=((10*5)+(b-(a+10))*15) if m: print(m1, "zl") if M: print(M1, "zl")
6e05b539a961ba4a5eae8b6ab07ac1b94e221246
WuIFan/LeetCode
/Solutions/Roman_to_Integer.py
527
3.578125
4
class Solution: table = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, } def romanToInt(self, s: str) -> int: ans = 0 last = 0 for c in reversed(s): num = self.table.get(c) if last > num: ans -= num else: ans += num last = num return ans sol = Solution() s = "MCMXCIV" print(sol.romanToInt(s))
57367bee7da71ff6af5f18f68296240fda53b7d1
gkimetto/PyProjects
/GeneralPractice/ListComprehension.py
415
4.21875
4
x = [i for i in range(10)] print(x) squares = [] squares = [i**2 for i in range(10)] print(squares) inlist = [lambda i:i%3==0 for i in range(5)] print(inlist) # a list comprehension cubes = [i**3 for i in range(5)] print(cubes) # A list comprehension can also contain an if statement to enforce # a condition on values in the list. # Example: evens=[i**2 for i in range(10) if i**2 % 2 == 0] print(evens)
93df2fe9045a1d3c8f928ab64313371f3c0ce803
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4159/codes/1637_869.py
270
3.640625
4
# Teste seu código aos poucos. # Não teste tudo no final, pois fica mais difícil de identificar erros. # Use as mensagens de erro para corrigir seu código. total = float(input("valor: ")) if(total>=200): print(round(total-total/20, 2)) else: print(round(total, 2))
0500420871411c5dd37882d145898a3cdb80abac
ericksalas11/python-exercise
/par-impar.py
225
3.875
4
print("Los numeros son: 4, 12, 15, 51, 563, 10 ") numbers = [4, 12, 15, 51, 563, 10] for numero in numbers: if numero % 2 == 0: print("Es par") else: print("Es impar") print("Respectivamente")
b4cbe92376ecb0f65fb64f6a08ea3e4f7699ddd9
3deep0019/python
/Input And Output Statements/evil.py
336
4.375
4
# eval(): # ---> eval Function take a String and evaluate the Result. x = eval('10+20+30') print(x) # eval() can evaluate the Input to list, tuple, set, etc based the provided Input. # Eg: Write a Program to accept list from the keynboard on the display l = eval(input('Enter List')) print (type(l)) print(l)
1166b2e3a1366c98da23bad5485e3d7887bdb61a
17313/GeorgeGriffindor
/SQL.py
293
3.796875
4
import sqlite3 with sqlite3.connect("BubbleLin.db") as connection: c = connection.cursor() sql = "SELECT * FROM Bubble_tea" c.execute(sql) results = c.fetchall() for result in results: print("BubbleLin: {0:15} Price: ${1:0}" .format(result[1], result[2]))
2b6df80e733ccd30a087ca80deb45f48e5463ae4
EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions
/Chapter4/4.2.py
787
4.09375
4
#Minimal Tree: Given a sorted (increasing order) array with unique integer elements, #write an algorithm to create a binary search tree with minimal height. class Node(): def __init__(self,item): self.right = None self.left = None self.value = item def __str__(self): return '('+str(self.left)+':L ' + "V:" + str(self.value) + " R:" + str(self.right)+')' def create_minimal_BST(arr,start,end): if (end<start): return None mid = (start + end) // 2 new_node = Node(arr[mid]) new_node.left = create_minimal_BST(arr,start,mid-1) new_node.right = create_minimal_BST(arr,mid+1,end) return new_node def main(): arr = [1,2,3,4,5] print(create_minimal_BST(arr,0,len(arr)-1)) if __name__ =='__main__': main()
7b615b039df019a0a278a298f56cacc5cf492c02
Ana-Vi/Homework
/Pythons/futebol.py
609
3.71875
4
'''vitoria= 3 empate= 1 derrota= 0 pontos= 0 total=int(input("digite o numero total de jogos: ")) for aux in range(total): gol_a_favor= int(input("a favor: ")) gol_contra= int(input("contra: ")) if gol_a_favor>gol_contra: pontos= pontos+3 elif gol_a_favor== gol_contra: pontos= pontos+1 else: pontos= pontos print("Seu tive fez", pontos,"no campeonato")''' ####################### soma=0 n= int(input()) for x in range(n): gols= (input()) if int(gols[0])>int(gols[2]): soma= soma+3 elif int(gols[0]== gols[2]): soma= soma+1 print(soma)
88429dbeb7a1b60116168f2701f01060c8f48791
tsakallioglu/Google-Foobar
/KillKthBit.py
757
3.8125
4
#In order to stop the Mad Coder evil genius you need to decipher the encrypted message he sent to his minions. #The message contains several numbers that, when typed into a supercomputer, will launch a missile into the sky blocking out the sun, #and making all the people on Earth grumpy and sad. #You figured out that some numbers have a modified single digit in their binary representation. #More specifically, in the given number n the kth bit from the right was initially set to 0, but its current value might be different. #It's now up to you to write a function that will change the kth bit of n back to 0. def killKthBit(n, k): return [n if len(bin(n))-2<k else (int(bin(n)[:-k]+'0'+bin(n)[-k+1:],2) if k>1 else int(bin(n)[:-k]+'0',2))][0]
6758b82cdbf70f4169672e441197ed86a51476b6
thewinterKnight/Python
/dsa/Trees/6.py
9,452
4
4
# Implement a threaded binary tree. import random import copy class LinkedListNode: def __init__(self, tree_node=None, next=None): self.tree_node = tree_node self.next = next def get_tree_node(self): return self.tree_node def get_next(self): return self.next def set_next(self, new_tree_node): self.next = new_tree_node class Queue(LinkedListNode): def __init__(self, head=None, tail=None): self.head = head self.tail = tail def Enqueue(self, tree_node): queue_node = LinkedListNode(tree_node) if self.head is None and self.tail is None: self.head = queue_node self.tail = queue_node else: self.tail.set_next(queue_node) self.tail = self.tail.get_next() def Dequeue(self): if self.head is None: print('Queue non-existent.\n') return None pop_node = self.head self.head = self.head.get_next() if self.head is None: self.tail = None return pop_node.get_tree_node() def get_front(self): return self.head.get_tree_node() def is_empty(self): if self.head is None and self.tail is None: return True return False class Stack(LinkedListNode): def __init__(self, top=None): self.top = top def Push(self, tree_node): stack_node = LinkedListNode(tree_node) if self.top is None: self.top = stack_node else: stack_node.set_next(self.top) self.top = stack_node def Pop(self): if self.top is None: print('Stack non-existent.\n') return None pop_node = self.top self.top = self.top.get_next() return pop_node.get_tree_node() def get_top(self): return self.top.get_tree_node() def is_empty(self): if self.top is None: return True return False class TreeNode: def __init__(self, data=None, left=None, right=None, is_right_threaded=False): self.data = data self.left = left self.right = right self.is_right_threaded = is_right_threaded def get_data(self): return self.data def get_left(self): return self.left def get_right(self): return self.right def set_left(self, new_tree_node): self.left = new_tree_node def set_right(self, new_tree_node): self.right = new_tree_node def get_right_thread_status(self): return is_right_threaded def set_right_thread_status(self, status): self.is_right_threaded = status class BinaryTree(TreeNode): insertion_queue = Queue() def __init__(self, root=None): self.root = root def insert_node(self, data): tree_node = TreeNode(data) if self.root is None: self.root = tree_node self.insertion_queue.Enqueue(self.root) else: front_tree_node = self.insertion_queue.get_front() if front_tree_node.get_left() is None: front_tree_node.set_left(tree_node) elif front_tree_node.get_right() is None: front_tree_node.set_right(tree_node) if front_tree_node.get_left() is not None and front_tree_node.get_right() is not None: self.insertion_queue.Dequeue() self.insertion_queue.Enqueue(tree_node) def fetch_tree_node(self, node_data): if self.root is None: print('Tree non-existent.\n') return None traversal_stack = Stack() traversal_node = self.root while traversal_node is not None or traversal_stack.is_empty() is False: while traversal_node is not None: traversal_stack.Push(traversal_node) traversal_node = traversal_node.get_left() traversal_node = traversal_stack.Pop() if traversal_node.get_data() == node_data: return traversal_node traversal_node = traversal_node.get_right() def level_order_traversal(self): if self.root is None: print('Tree non-existent.\n') return None traversal_queue = Queue() traversal_queue.Enqueue(self.root) while traversal_queue.is_empty() is False: tree_node = traversal_queue.Dequeue() print(tree_node.get_data()) if tree_node.get_left() is not None: traversal_queue.Enqueue(tree_node.get_left()) if tree_node.get_right() is not None: traversal_queue.Enqueue(tree_node.get_right()) def inorder_traversal_recursive(self): if self.root is None: print('Tree non-existent.\n') return None self.inorder_traversal_recursive_util(self.root) def inorder_traversal_recursive_util(self, node): if node is None: return self.inorder_traversal_recursive_util(node.get_left()) print(node.get_data()) self.inorder_traversal_recursive_util(node.get_right()) def inorder_predecessor(self, node_data): if self.root is None: print('Tree non-existent.\n') return None traversal_stack = Stack() traversal_node = self.root predecessor_node = None while traversal_node is not None or traversal_stack.is_empty() is False: while traversal_node is not None: traversal_stack.Push(traversal_node) traversal_node = traversal_node.get_left() traversal_node = traversal_stack.Pop() if traversal_node.get_data() == node_data: if predecessor_node is not None: print('Inorder predecessor is : {}'.format(predecessor_node.get_data())) else: print('Inorder predecessor does not exist.') return predecessor_node else: predecessor_node = traversal_node traversal_node = traversal_node.get_right() def inorder_successor(self, node_data): if self.root is None: print('Tree non-existent.\n') return None traversal_stack = Stack() traversal_node = self.root while traversal_node is not None or traversal_stack.is_empty() is False: while traversal_node is not None: traversal_stack.Push(traversal_node) traversal_node = traversal_node.get_left() traversal_node = traversal_stack.Pop() if traversal_node.get_data() == node_data: if traversal_stack.is_empty() is False: successor_node = traversal_stack.get_top() print('Successor is : {}'.format(successor_node.get_data())) return successor_node else: print('Inorder successor does not exist.\n') traversal_node = traversal_node.get_right() def construct_incomplete_tree(): binary_tree = BinaryTree(TreeNode(1)) traversal_node = binary_tree.root traversal_node.set_left(TreeNode(2)) traversal_node = traversal_node.get_left() traversal_node.set_left(TreeNode(3)) traversal_node = traversal_node.get_left() traversal_node.set_left(TreeNode(4)) traversal_node = traversal_node.get_left() traversal_node.set_right(TreeNode(5)) traversal_node = binary_tree.fetch_tree_node(2) traversal_node.set_right(TreeNode(6)) traversal_node = traversal_node.get_right() traversal_node.set_left(TreeNode(7)) traversal_node.set_right(TreeNode(8)) traversal_node = traversal_node.get_right() traversal_node.set_left(TreeNode(9)) return binary_tree def populate_inorder_traversal_queue(binary_tree): root = binary_tree.root if root is None: print('Tree non-existent.\n') return inorder_queue = Queue() populate_inorder_traversal_queue_util(root, inorder_queue) return inorder_queue def populate_inorder_traversal_queue_util(node, inorder_queue): if node is None: return populate_inorder_traversal_queue_util(node.get_left(), inorder_queue) inorder_queue.Enqueue(node) populate_inorder_traversal_queue_util(node.get_right(), inorder_queue) def construct_threaded_binary_tree_util(node, inorder_queue): if node is None: return if node.get_left() is not None: construct_threaded_binary_tree_util(node.get_left(), inorder_queue) inorder_queue.Dequeue() if node.get_right() is not None: construct_threaded_binary_tree_util(node.get_right(), inorder_queue) else: if inorder_queue.is_empty() is False: print('Threaded...\n') node.set_right(inorder_queue.get_front()) node.set_right_thread_status(True) def construct_threaded_binary_tree(binary_tree): root = binary_tree.root if root is None: print('Tree non-existent.\n') return inorder_queue = populate_inorder_traversal_queue(binary_tree) construct_threaded_binary_tree_util(root, inorder_queue) if __name__ == "__main__": arr = list(range(1, 12)) # random.shuffle(arr) # print(arr) # print("Converting to a complete binary tree...\n\n") # binary_tree = BinaryTree() # for i in arr: # binary_tree.insert_node(i) binary_tree = construct_incomplete_tree() print("Level Order Traversal :") binary_tree.level_order_traversal() print("\n\nInOrder Traversal(Recursive) :") binary_tree.inorder_traversal_recursive() # node_data = 0 # while node_data != -1: # node_data = int(input("\n\nFind Inorder Predecessor & Successor for : ")) # binary_tree.inorder_predecessor(node_data) # binary_tree.inorder_successor(node_data) threaded_binary_tree = copy.deepcopy(binary_tree) print('Converting binary tree to right threaded binary tree...\n') construct_threaded_binary_tree(threaded_binary_tree) print('Checking threaded binary tree..\n') print('UN-THREADED :\n') traversal_node = binary_tree.fetch_tree_node(2) binary_tree.inorder_successor(traversal_node.get_data()) print('THREADED :\n') traversal_node = threaded_binary_tree.fetch_tree_node(2) threaded_binary_tree.inorder_successor(traversal_node.get_data())
5dbdbfa40c733af412d18ae87904f8acd2d13031
tmtiuca/ECE406
/assignment2.py
2,693
4.4375
4
#!/usr/bin/env python3 """ Username : tmtiuca Student # : 20521385 """ """ Assignment 2 Python file Copy-and-paste your extended_euclid and modexp functions from assignment 1 """ import random import math import sys # part (i) for modular exponentiation -- fill in the code below def modexp(x, y, N): """ Input: Three positive integers x and y, and N. Output: The number x^y mod N """ if (y == 0): return 1 z = modexp(x, math.floor(y/2), N) if (y % 2 == 0): return (z*z) % N else: return (x * z*z) % N # part (ii) for extended Euclid -- fill in the code below def extended_euclid(a, b): """ Input: Two positive integers a >= b >= 0 Output: Three integers x, y, and d returned as a tuple (x, y, d) such that d = gcd(a, b) and ax + by = d """ if (b == 0): return 1, 0, a x, y, d = extended_euclid(b, a%b) return y, x - math.floor(a/b) * y, d ################################## def primality(N): """ Test if a number N is prime using Fermat's little Theorem with ten random values of a. If a^(N-1) mod N = 1 for all values, then return true. Otherwise return false. Hint: you can generate a random integer between a and b using random.randint(a,b). """ for i in range(10): a = random.randint(2, N-1) remainder = modexp(a, N-1, N) if (remainder != 1): return False return True def prime_generator(N): """ This function generates a prime number <= N """ p = random.randint(N/10, N) for i in range(int(math.pow(math.log(N), 4))): p = random.randint(N/10, N) if primality(p): return p return -1 def main(): """ Test file for the two parts of the question """ ## Excercise 1: generating primes and RSA ################## e = 5 p = q = 0 are_relatively_prime = False while not are_relatively_prime: p = prime_generator(10000000) q = prime_generator(10000000) if p == -1 or q == -1: sys.exit() _, _, gcd = extended_euclid(e, (p-1) * (q-1)) are_relatively_prime = gcd == 1 private_key, _, _ = extended_euclid(e, (p-1) * (q-1)) if private_key < 0: private_key = private_key + (p-1) * (q-1) x = 329415 N = p * q encoded = modexp(x, e, N) decoded = modexp(encoded, private_key, N) print('p: ', p) print('q: ', q) print('private_key: ', private_key) print('message : ', x) print('encoded : ', encoded) print('decoded : ', decoded) if __name__ == '__main__': main()
9cd9f47d758a85f49a57141979e5fee50f6e1e38
kielejocain/AM_2015_06_15
/StudentWork/orionbuyukas/madlib.py
914
3.625
4
# -*- coding: utf -8 -*- article = "Here, roughly, is what we know so far about today's middle-class " print article response = raw_input("Enter plural noun.") article += response + ": They seldom walk or " print article response = raw_input("Enter a verb.") article += response + " to school, as generations did before them. They rarely " print article response = raw_input("Enter verb") article += response + " after school " print article response += raw_input("Enter adjective") article += response + " jobs, their time is rigidly " print article response = raw_input("Enter adjective") article += response + " their mothers spend more" print article response = raw_input("Enter noun") article += response + "with them than mothers did with their children in the 1960s, even though most women in the 1960s didn’t" response = raw_input("Enter Verb") article += response + "." print article
4283466430a9a7dffbb88aa4af824f4bce959fae
DavidBitner/Aprendizado-Python
/Curso/Challenges/URI/1038Snack.py
256
3.53125
4
A, B = input().split(" ") x, y = int(A), int(B) total = float(0) if x == 1: total = y * 4 elif x == 2: total = y * 4.50 elif x == 3: total = y * 5 elif x == 4: total = y * 2 elif x == 5: total = y * 1.50 print(f"Total: R$ {total:.2f}")
3017307ef8e6405fe8490003d68647543cdd4ef2
bphillab/Five_Thirty_Eight_Riddler
/Riddler_18_08_03/Riddler_Express.py
355
3.59375
4
def calculate_non_water_weight(total_weight, percent): return (1-percent)*total_weight def calculate_new_weight(non_water_weight, percent): return non_water_weight/(1-percent) if __name__ == "__main__": non_water_weight = calculate_non_water_weight(1000,.99) new_weight = calculate_new_weight(non_water_weight,.98) print(new_weight)
1b240091623b7f7cb1544456dbf1c98927f5ca0e
Kashif1Naqvi/Python-Algorithums-the-Basics
/quick_sort.py
1,387
3.984375
4
# implement a quicksort items = [20,6,8,53,56,23,87,41,49,19] def quickSort(dataset,first,last): if first < last: # calculate the split point pivotIdx = partition(dataset,first,last) # now sort the two partitions quickSort(dataset,first,pivotIdx-1) quickSort(dataset,pivotIdx+1,last) def partition(datavalues,first,last): # choice the first value of pivote value pivotvalue = datavalues[first] lower = first + 1 upper = last # start searching for the crossing point done = False while not done: while lower <= upper and datavalues[lower] <= pivotvalue: lower +=1 while datavalues[upper] >= pivotvalue and upper >= lower: upper -=1 if upper < lower: done = True else: temp = datavalues[lower] datavalues[lower] = datavalues[upper] datavalues[upper] = temp # when the split point is found,exchange the pivot value' temp = datavalues[first] datavalues[first] = datavalues[upper] datavalues[upper] = temp # return the split point index return upper #test the merge sort with data print(items) quickSort(items,0,len(items)-1) print(items) # output #------------------------------------------ # [20, 6, 8, 53, 56, 23, 87, 41, 49, 19] # [6, 8, 19, 20, 23, 41, 49, 53, 56, 87] # -----------------------------------------
3cec8eaf6f68590519155613b2667106672eb034
soraef/nlp100
/1/8.py
330
3.75
4
import re def convert(match): return chr(219 - ord(match.group())) def cipher(text): return re.sub(r"[a-z]", convert, text) # p21 名前に情報を追加する plain_text = "ABCdefg1234あいうえおに" encrypted_text = cipher(plain_text) print(encrypted_text) plain_text = cipher(encrypted_text) print(plain_text)
61e436b47dd905c70193100bcadbe146e17ccff4
BeatrizOliveiraFerreira/DesafiosPython
/exercicio50.py
250
3.90625
4
soma = 0 count = 0 for i in range(1, 7): valor = int(input('Digite um valor: ')) if i % 2 == 0: soma = soma + valor count = count + 1 print('A soma de todos os {} números PARES é igual a {}'.format(count, soma))
b9e9c1adc40e953a9d4a7bd757dfb9da9302f7a4
Jason8Ni/MarkovianMusic
/src/parseMIDI.py
3,442
3.515625
4
#!/usr/bin/python3 # This class will parse the MIDI file and build a basic Markov chain from it import hashlib import mido import argparse from markovChain import MarkovChain class ParseMIDI: def __init__(self, filename): """ This is the constructor for a Serializer. This will serialize a MIDI file given the filename and also generate a markov chain of the notes in the track """ self.filename = filename # Number of MS per beat (given in each line of the MIDI message) self.tempo = None self.ticksPerBeat = None # The difference in time between each MIDI message represents # the number of ticks, which can be converted to beats using # ticks per beat self.markovChain = MarkovChain() self._parse() def _getTempo(self): return self.tempo def _getTicksPerBeat(self): return self.ticksPerBeat def _parse(self): """ This function handles the reading of the MIDI file and breaks the notes into sequenced "chords", which are then inserted into the markov chain. Treats all of the notes that are played simultaneously, """ midi = mido.MidiFile(self.filename) self.ticksPerBeat = midi.ticks_per_beat previousChord = [] currentChord = [] for track in midi.tracks: for message in track: if message.type == "set_tempo": self.tempo = message.tempo elif message.type == "note_on": if message.time == 0: currentChord.append(message.note) else: self._sequence(previousChord, currentChord, message.time) previousChord = currentChord currentChord = [] def _sequence(self, previousChord, currentChord, duration): """ With the previous Chord, the current Chord of notes and an averaged duration of the current notes, sequence cycles through every combination of the previous notes to the current notes and sticks them into the markov chain. """ for note1 in previousChord: for note2 in currentChord: #Some notes are 15,000 ticks long... makes generated tracks too long # and you barely hear them if duration > 3000: duration = 200 self.markovChain.add( note1, note2, self.tickToSeconds(duration)) def tickToSeconds(self, ticks): """ This method takes a tick count and converts it to a time in milliseconds, grouping it to the nearest 250 milliseconds, so that similar enough notes are considered "identical" """ ms = ((ticks / self.ticksPerBeat) * self.tempo) / 1000 return int(ms - (ms % 250) + 250) def getChain(self): return self.markovChain if __name__ == "__main__": #print(ParseMIDI('./MIDIFiles/Unravel.mid').getChain().printAsMatrix()) #print('Finished parsing {}'.format('./MIDIFiles/Unravel.mid')) print(ParseMIDI('./moonlight_sonataTREBLEGen.mid').getChain().printAsMatrix()) print('Finished parsing {}'.format('./moonlight_sonataTREBLEGen.mid'))
962d6503975d869f920e8d21700eb767555b4c52
lpvera22/Study
/Lista_Ejercicios_3/Ejercicio_9.py
678
3.765625
4
# *-* encoding:UTF-8 *-* '''Dado um conjunto S com n elementos, elabore um algoritmo que imprima todos os subconjuntos de S.''' def Subconjuntos(conjunto): subconjuntos = [] set_size = len(conjunto) if set_size > 1: subconjuntos += Subconjuntos(conjunto[1:]) elemento = [conjunto[0]] for sub in subconjuntos[:]: subconjuntos.append(sub + elemento) subconjuntos.append(elemento) else: subconjuntos += [conjunto] return subconjuntos return subc if __name__ == '__main__': sec = raw_input('A').split() S = [int(i) for i in sec] #n = int(input('n')) print(Subconjuntos(S))
a4d113eb0c28e0fce8bf4f2ed33391dac90e5353
RooL1024/-offer
/Python/平衡二叉树.py
668
3.65625
4
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def IsBalanced_Solution(self, pRoot): # write code here if self.getDepth(pRoot) == -1: return False return True def getDepth(self,root): if not root: return 0 left = self.getDepth(root.left) if left == -1: return -1 right = self.getDepth(root.right) if right == -1: return -1 if abs(left - right) > 1: return -1 else: return max(left,right) + 1
b1ccb52ff1fe2024ca8a19a8756d57ccd0d83910
simonpatrick/interview-collections
/python/basic/file_io/randome_access_line.py
382
3.71875
4
# -*- coding: utf-8 -*- # will not read file into memory print(__file__) sum=0 # generator with open('sample_text.txt','r') as f: for line in f: sum+=1 print(line) print(sum) sum=0 # read line big_file = open('sample_text.txt','rt') line = big_file.readline() while line: line=big_file.readline() sum+=1 print(line) big_file.close() print(sum)
46afc3dcc0468761c9c6403d18abd2aeba46196d
royliu317/Code-of-Learn-Python-THW
/ex33_4.py
802
4.09375
4
# The rule of variable scopes: L(Local) –> E(Enclosing) –> G(Global) –>B(Built-in) x1 = int(1) # Bulit-in x2 = 2 # global def outer(): x3 = 3 # Enclosing def inner(): x4 = 4 # Local print(x1, x2, x3, x4) inner() outer() # Keywords: global, nonlocal numbers = [] i = 0 def mywhile(j): global i while i < j: print(f"At the top i is {i}") numbers.append(i) i += 1 # If not use global in the function,it will raise UnboundLocalError: local variable 'a' referenced before assignment print("Numbers now: ", numbers) print(f"At the bottom i is {i}") mywhile(3) print("The numbers: ") for num in numbers: print(num) print(f"Now i is: {i}\nNow numbers is: {numbers}")
a82ddbc979e8a6f1338d77ccc78f123609dd7e91
OokGIT/pythonproj
/stochastic/random_walk.py
4,849
4.03125
4
import random random.seed(0) class Location(object): def __init__(self, x, y): ''' x and y are floats ''' self.x = x self.y = y def move(self, deltaX, deltaY): ''' deltaX and deltaY are floats ''' return Location(self.x + deltaX, self.y + deltaY) def getX(self): return self.x def getY(self): return self.y def distFrom(self, other): ox = other.x oy = other.y xDist = self.x - ox yDist = self.y - oy return (xDist**2 + yDist**2)**0.5 def __str__(self): return '<' + str(self.x) + '. ' + str(self.y) + '>' class Field(object): def __init__(self): """ The key design decision embodied in this implementation is to make the location of a drunk in a field an attribute of the field, rather than an attribute of the drunk """ self.drunks = {} def addDrunk (self, drunk, loc): if drunk in self.drunks: raise ValueError('Duplicate drunk') else: self.drunks[drunk] = loc def getLoc(self, drunk): if drunk not in self.drunks: raise ValueError('Drunk not in field') return self.drunks[drunk] def moveDrunk(self, drunk): if drunk not in self.drunks: raise ValueError('Drunk not in field') xDist, yDist = drunk.takeStep() currentLocation = self.drunks[drunk] # use method of Location to get new location self.drunks[drunk] = currentLocation.move(xDist, yDist) class Drunk(object): def __init__(self, name): self.name = name def __str__(self): return 'This drunk is named' + self.name class UsualDrunk(Drunk): def takeStep(self): stepChoices =\ [(0.0, 1.0), (0.0, -1.0), (1.0, 0.0), (-1.0, 0.0)] return random.choice(stepChoices) class ColdDrunk(Drunk): def takeStep(self): stepChoices =\ [(0.0, 0.9), (0.0, -1.1), (1.0, 0.0), (-1.0, 0.0)] return random.choice(stepChoices) def walk(f, d, numSteps): """ Assumes f a Field, d a Drunk in F, numSteps is an int >= 0 Moves d numSteps times, returns the distance between the final location and the location at the start of the walk. """ start = f.getLoc(d) for s in range(numSteps): f.moveDrunk(d) return start.distFrom(f.getLoc(d)) def simWalks(numSteps, numTrials, dClass): """ Assumes numSteps an int >= 0, numTrials an int > 0, dClass a subclass of Drunk. Simulates NumTrials walks of NumSteps steps each. Returns a list of the final distances for each trial """ Homer = dClass('Homer') origin = Location(0, 0) distances = [] for t in range(numTrials): f = Field() f.addDrunk(Homer, origin) distances.append(round(walk(f, Homer, numSteps), 1)) return distances def drunkTest(walkLengths, numTrials, dClass): """ Assumes walkLengths a sequence of ints >= 0, numTrials an int > 0, dClass a subclass of Drunk. For each number of steps in walkLengths, runs simWalks with numTrial walks and prints results """ for numSteps in walkLengths: distances = simWalks(numSteps, numTrials, dClass) print(dClass.__name__, 'random walk of', numSteps, 'steps') print(' Mean =', round(sum(distances)/len(distances), 4)) print(' Max =', max(distances), 'Min =', min(distances)) def simAll(drunkKinds, walkLengths, numTrials): for dClass in drunkKinds: drunkTest(walkLengths, numTrials, dClass) def getFinalLocs(numSteps, numTrials, dClass): locs = [] d = dClass("Petro") for t in range(numTrials): f = Field() f.addDrunk(d, Location(0, 0)) for s in range(numSteps): f.moveDrunk(d) locs.append(f.getLoc(d)) return locs class OddField(Field): def __init__(self, numHoles = 1000, xRange = 100, yRange = 100): Field.__init__(self) self.wormholes = {} for w in range(numHoles): x = random.randint(-xRange, xRange) y = random.randint(-yRange, yRange) newX = random.randint(-xRange, xRange) newY = random.randint(-yRange, yRange) newLoc = Location(newX, newY) self.wormholes[(x, y)] = newLoc def moveDrunk(self, drunk): Field.moveDrunk(self, drunk) x = self.drunks[drunk].getX() y = self.drunks[drunk].getY() if (x, y) in self.wormholes: self.drunks[drunk] = self.wormholes[(x, y)] #drunkTest([10, 100, 1000, 10000], 100, UsualDrunk) if __name__ == "__main__": simAll((UsualDrunk, ColdDrunk), (1, 10, 100, 1000, 10000), 100)
dc1f13f80a6eaa3463531ccd1a6a1b83135d7696
sharifahmeeed/AlgorithmandDataStructurePython
/array_python_list.py
577
4.0625
4
numbers = [10, 20, 30, 40, 50] numbers[1] = "Adam" print('Standard') for num in numbers: print(num) print('\n \nNot standard') for i in range(len(numbers)): print(numbers[i]) print('first 2 items item: ', numbers[0:2]) print('without last one item: ', numbers[:-1]) print('without last two item: ', numbers[:-2]) print('for all item: ', numbers[:]) #for next part numbers = [10, 20, 30, 40, 50] #linear search #O(N) search running time #linear time complexity maximum = numbers[0] for num in numbers: if num > maximum: maximum = num print(maximum)
adad9d91bd8ffd3498bed2dd18e23177aa1382a2
nekozing/playground
/raw_algorithms/diff/edit_distance_dag.py
497
3.53125
4
def diff(a, b, i, j): return 1 if a[i] != b[j] else 0 def edit_distance(a, b): m = len(a) n = len(b) mn = [[0 for x in xrange(n+1)] for x in xrange(m+1)] for i in range(m + 1): mn[i][0] = i for j in range(n + 1): mn[0][j] = j for j in range(1, n + 1): for i in range(1, m + 1): mn[i][j] = min(mn[i-1][j] + 1, mn[i][j-1] + 1, mn[i-1][j-1] + diff(a, b, i-1, j-1)) return mn[i][j] def test(): a = "b" b = "aaaba" print edit_distance(a, b) if __name__ == '__main__': test()
873db0cb7c9efe8914c7eaf6a9b0026fab2c3464
wansook0316/problem_solving
/210701_백준_최단경로.py
945
3.625
4
import sys import heapq input = sys.stdin.readline def dijkstra(start): q = [] heapq.heappush(q, [0, start]) distance[start] = 0 while q: now_cost, now_node = heapq.heappop(q) if now_cost > distance[now_node]: continue for next_node, weight in graph[now_node]: next_cost = now_cost + weight if next_cost < distance[next_node]: distance[next_node] = next_cost heapq.heappush(q, [next_cost, next_node]) if __name__ == "__main__": INF = int(1e7) V, E = map(int, input().split()) s = int(input()) graph = [[] for _ in range(V + 1)] distance = [INF] * (V + 1) for _ in range(E): u, v, w = map(int, input().split()) graph[u].append([v, w]) dijkstra(s) for i in range(1, len(distance)): if distance[i] == INF: print("INF") else: print(distance[i])
eeda1ad3fb7941a5f496f70312e0d3a4c9b9b282
hiSh1n/learning_Python3
/py_project04.py
245
4.25
4
#To find out the greatest number from any two numbers. first_no = int(input("enter first no. ")) second_no = int(input("enter second no. ")) if first_no >= second_no: print(first_no, "is greater.") else: print(second_no, "is greater.")
6f9704f5bec83a4bde79caab50e62cbe14de6330
darsovit/AdventOfCode2017
/Day16/Day16.75.py
5,419
3.5625
4
#!python def shift_programs( programs, shift_value ): assert( shift_value > 0 ) return programs[-shift_value:] + programs[:-shift_value] def exchange_slots( programs, slots ): assert( len( slots ) == 2 ) tmp = programs[slots[1]] programs[slots[1]] = programs[slots[0]] programs[slots[0]] = tmp return programs def exchange_programs( programs, two_progs ): assert( len(two_progs) == 2) swapped0 = -1 swapped1 = -1 for i in range(len(programs)): if ( programs[i] == two_progs[0] ): programs[i] = two_progs[1] swapped0 = i if swapped1 > -1: break elif ( programs[i] == two_progs[1] ): programs[i] = two_progs[0] swapped1 = i if swapped0 > -1: break assert( swapped0 != swapped1 ) assert( swapped0 > -1 ) assert( swapped1 > -1 ) return programs def build_moves( move ): if move[0] == 's': return ( shift_programs, int(move[1:]) ) elif move[0] == 'x': return ( exchange_slots, list(map(lambda x: int(x), move[1:].split('/') ) ) ) elif move[0] == 'p': return ( exchange_programs, list(move[1:].split('/') ) ) else: assert( False & move[0] ) def handle_input( programs, move ): # if move[0] == 's': # return shift_programs( programs, int(move[1:]) ) # elif move[0] == 'x': # return exchange_slots( programs, list(map(lambda x: int(x), move[1:].split('/')) ) ) # elif move[0] == 'p': # return exchange_programs( programs, list(move[1:].split('/') ) ) # else: # assert( False & move[0] ) my_moves = build_moves( move ) return my_moves[0]( programs, my_moves[1] ) def test1(): test=[ 'a', 'b', 'c', 'd', 'e' ] assert( 'abcde' == ''.join( test ) ) test=handle_input( test, 's1' ) #print( test ) assert( 'eabcd' == ''.join( test ) ) test=handle_input( test, 'x3/4' ) #print( test ) assert( 'eabdc' == ''.join( test ) ) test=handle_input( test, 'pe/b' ) print( test ) assert( 'baedc' == ''.join( test ) ) test=list('abcde') print(test) test=handle_input( test, 'pe/b' ) test=handle_input( test, 's1' ) test=handle_input( test, 'x3/4' ) print( test ) def test2(): test=[ 'a', 'b', 'c', 'd', 'e' ] test = handle_input( test, 's3' ) assert( 'cdeab' == ''.join(test) ) def build_moves_map( shift_moves ): start_positions = list( range(16) ) positions=start_positions for move in shift_moves: positions = move[0]( positions, move[1]) assert( 16 == len( positions ) ) moves_map={} for i in range( 16 ): moves_map[ i ] = positions[ i ] return moves_map def apply_moves_map( start_positions, shift_mapping ): new_positions=list() for i in range( 16 ): new_positions.append( start_positions[ shift_mapping[i] ] ) return new_positions def build_swap_map( swap_moves ): new_positions = list( map( lambda x: chr(ord('a')+x), range(16) ) ) for move in swap_moves: new_positions = move[0]( new_positions, move[1] ) start_positions = list( map( lambda x: chr(ord('a')+x), range(16) ) ) #print ( 'build_swap_map (start pos):', ''.join( start_positions ) ) #print ( 'build_swap_map (final pos):', ''.join( new_positions ) ) swap_map={} for i in range(16): swap_map[start_positions[i]] = new_positions[i] #print( 'build_swap_map: ', swap_map ) return swap_map def apply_swap_map( start_positions, swap_mapping ): #print( 'apply_swap_map: ', ''.join( start_positions ) ) new_positions=list() for i in range( 16 ): new_positions.append( swap_mapping[start_positions[i]] ) #print( 'apply_swap_map: ', ''.join( new_positions ) ) return new_positions def prog(): iterations=1000000000 programs=list( map(lambda x: chr(ord('a')+x), range(16) ) ) #print( programs ) new_positions=programs moves=[] with open('input.txt') as f: for line in f: moves = list( map( lambda x: build_moves(x), line.strip().split(',') ) ) shift_moves=[ move for move in moves if move[0] != exchange_programs ] shift_mapping = build_moves_map( shift_moves ) thousand_shift_mapping = build_moves_map( [(apply_moves_map, shift_mapping)]*1000 ) swap_moves=[ move for move in moves if move[0] == exchange_programs ] swap_mapping = build_swap_map( swap_moves ) thousand_swap_mapping = build_swap_map( [(apply_swap_map, swap_mapping)]*1000 ) for i in range( int( iterations / 1000 ) ): new_positions = apply_moves_map( new_positions, thousand_shift_mapping ) if iterations > 10 and i % int(iterations/10) == 0: print( i ) #for move in shift_moves: # new_positions = move[0]( new_positions, move[1] ) #print( new_positions ) #swap_moves = reduce_swaps( swap_moves ) for i in range( int( iterations / 1000 ) ): new_positions = apply_swap_map( new_positions, thousand_swap_mapping ) if iterations > 10 and i % int(iterations/10) == 0: print( i ) #for move in swap_moves: # new_positions = move[0]( new_positions, move[1] ) #print( shift_moves ) return new_positions # imkn hbla dcpf jego is incorrect #test1() #test2() print( ''.join( prog() ) )
28d1a70bc75fb4d2a6ec551ab1380b3c95f85824
experimentAccount0/lancet
/tests/test_shell_command.py
2,441
3.515625
4
from collections import OrderedDict from unittest import TestCase, main from lancet import ShellCommand class TestShellCommand(TestCase): def test_kwargs_are_passed_correctly_ordered(self): """ Test ShellCommand works correctly with an OrderedDict """ # Given sc = ShellCommand('test.py') # When spec = OrderedDict([('arg1',0), ('arg2',1)]) # Then cmd_line = sc(spec) expected = ['test.py', '--arg1', '0', '--arg2', '1'] self.assertEqual(cmd_line, expected) def test_kwargs_are_passed_correctly_unordered(self): """ Test ShellCommand works correctly with a regular dictionary """ # Given sc = ShellCommand('test.py') # When spec = dict(arg1=0, arg2=1) # Then cmd_line = sc(spec) expected = ['test.py', '--arg1', '0', '--arg2', '1'] # Always the first element self.assertEqual(cmd_line[0], 'test.py') # We cannot know if --arg1 or --arg2 will be presented first self.assertEqual(cmd_line.index('--arg1') < cmd_line.index('0'), True) self.assertEqual(cmd_line.index('--arg2') < cmd_line.index('1'), True) def test_kwargs_with_true_value_is_passed_correctly(self): # Given sc = ShellCommand('test.py') # When spec = OrderedDict(arg=True) # Then cmd_line = sc(spec) expected = ['test.py', '--arg'] self.assertEqual(cmd_line, expected) def test_kwargs_with_false_value_is_not_passed(self): # Given sc = ShellCommand('test.py') # When spec = OrderedDict(arg=False) # Then cmd_line = sc(spec) expected = ['test.py'] self.assertEqual(cmd_line, expected) def test_expansions_are_correctly_called_for_long_filenames(self): # Given lf = ShellCommand.LongFilename('') sc = ShellCommand('test.py', expansions={'output': lf}) # When spec = OrderedDict([('arg', 0)]) info = { 'root_directory': '/tmp', 'batch_name': 'test', 'varying_keys': ['arg'] } # Then. result = sc(spec, info=info) fname = lf(spec, info, None) expected = ['test.py', '--output', fname, '--arg', '0'] self.assertEqual(result, expected) if __name__ == '__main__': main()
4815d4e85ce17aee78cdbc4a065b3b20e06da5de
yevaaaa/homeworkk
/hw8_Yeva.py
2,396
4.0625
4
""" Problem 1 Create 3 dictionaries for your favourite top 3 cars. Dict should contain information like brand, model, year, and color. Add all those dicts in one dict and print items. """ d1 = { "brand": "Mercedes", "model": "amg gt", "year": "2021", "color": "black" } d2 = { "brand": "porsche", "model": "macan", "year": "2020", "color": "red" } d3 = { "brand": "volkswagen", "model": "beatle", "year": "any", "color": "white" } # dict_keys = ['dict1', 'dict2', 'dict3'] # all_dicts = [d1, d2, d3] # res = dict(zip(dict_keys, all_dicts)) # print(res) # print(res.items()) #2 # cars = {} # cars.update({"d1": d1, "d2": d2, "d3":d3}) """ Problem 2 You have a list of lists. Each list in the list contains a key and a value. Transform it into a list of dictionaries. Use loops. """ ls = [['Bob', 45], ['Anna', 4], ['Luiza', 24], ['Martin', 14]] # dt = {} # for i in ls: # dt.update({i[0]: i[1]}) # print(dt) """ Problem 3 Check if value 1000 exists in the dict values. If yes delete all other items except that one. """ dt = {'hundred': 100, 'million': 1000000, 'thousand': 1000, 'ten': 10} print(dt.get("thousand")) # for i in list(dt.keys()): # if i != "thousand": # dt.pop(i) # print(dt) """ Problem 4 Change Narine's salary to 10000 """ sampleDict = { 'employee1': {'name': 'Marine', 'salary': 7500}, 'employee2': {'name': 'Karine', 'salary': 8000}, 'employee3': {'name': 'Narine', 'salary': 6500} } # sampleDict.update({'name': 'Narine', 'salary': 10000}) # print(sampleDict) """ Problem 5 Write a function that will get a dict of employees and their salaries. It will return a new dict with the same keys (employees) and all values will be the average of their salaries. example: dict1 = {'ann': 3000, 'bob': 4000, 'lily': 5000} dict2 = {'ann': 4000, 'bob': 4000, 'lily': 4000} """ d = {'ann': 3000, 'bob': 4000, 'lily': 5000, 'molly': 5500, 'some_intern': 500} # answer = 0 # for i in d: # answer = answer + d[i] # ans = answer / len(d) # print(answer) # print(int(ans)) # d.update((i, int(ans)) for i in d) # print(d) """ Homework 7 Problem 4 Write a program that will add the string 'AAA' as an item before every item of the list. """ the_list = ['chrome', 'opera', 'mozilla', 'explorer'] ls1 = [] for i in the_list: for j in ["AAA", i]: ls1.append(j) print(ls)
51566b71081c89cb4bf35dfba2e3c7da2da803a9
deepcpatel/data_structures_and_algorithms
/Trees/children_sum_parent.py
2,173
4.25
4
# Link: https://www.geeksforgeeks.org/check-for-children-sum-property-in-a-binary-tree/ ''' Given a Binary Tree. Check whether all of its nodes have the value equal to the sum of their child nodes. Example 1: Input: 10 / 10 Output: 1 Explanation: Here, every node is sum of its left and right child. Example 2: Input: 1 / \ 4 3 / \ 5 N Output: 0 Explanation: Here, 1 is the root node and 4, 3 are its child nodes. 4 + 3 = 7 which is not equal to the value of root node. Hence, this tree does not satisfy the given conditions. Your Task: You don't need to read input or print anything. Your task is to complete the function isSumProperty() that takes the root Node of the Binary Tree as input and returns 1 if all the nodes in the tree satisfy the following properties. Else, it returns 0. For every node, data value must be equal to the sum of data values in left and right children. Consider data value as 0 for NULL child. Also, leaves are considered to follow the property. Expected Time Complexiy: O(N). Expected Auxiliary Space: O(Height of the Tree). Constraints: 1 <= N <= 100 1 <= Data on nodes <= 1000 ''' ''' # Node Class: class Node: def init(self,val): self.data = val self.left = None self.right = None ''' # Approach: Traverse Tree using BFS. At Each Node, calculate sum of left and right child (if node has no child, then move to next node). Compare it with current node value. If it is not same, then # return 0, else continue nad finally return 1. from collections import deque # Return 1 if all the nodes in the tree satisfy the given property. Else return 0 def isSumProperty(root): queue = deque([root]) while queue: node, child_sum, no_child = queue.popleft(), 0, True if node.left: child_sum += node.left.data no_child = False queue.append(node.left) if node.right: child_sum += node.right.data no_child = False queue.append(node.right) if not no_child and node.data != child_sum: return 0 return 1
48f54e2587d11c80f5c79df3e79abbb92d8bd9d0
SebastianOsinski/AdventOfCode2017
/Day 2/day2.py
882
3.640625
4
import functools file = open("day2_input", "r") lines = file.readlines() def numbers_from_line( line ): return [int(str) for str in line.split("\t")] matrix = [numbers_from_line(line) for line in lines] def sum(list): sum = 0 for number in list: sum += number return sum # Part 1 max_min_per_row = [(max(row), min(row)) for row in matrix] checksum1 = sum([s[0] - s[1] for s in max_min_per_row]) print(checksum1) # Part 2 def divide_divisibles(numbers): rng = range(0, len(numbers)) for i in rng: for j in rng: if i != j: n_i = numbers[i] n_j = numbers[j] if n_i % n_j == 0: return int(n_i / n_j) if n_j % n_i == 0: return int(n_j / n_i) checksum2 = sum([divide_divisibles(row) for row in matrix]) print(checksum2)
1c523aa8ce307224cf4001a49fdcaf3e1ae3928b
Rujabhatta22/program1
/program2.py
134
4.03125
4
base=int(input('enter any number')) height=int(input('enter any number')) area= (base*height)/2 print(f'area of triangle is{area}')3
b1413be8aff2d5885b7372d05fd4a2b4d91f9d7c
meliezer124/SheCodes
/Lecture8/ex1_Q7.py
973
4.15625
4
# solving common recursion mistakes def sum_every_other_number(n): """Return the sum of every other natural number up to n, inclusive. >>> sum_every_other_number(8) 20 >>> sum_every_other_number(9) 25 """ if n <= 0: return 0 else: return n + sum_every_other_number(n - 2) # was originally n == 0, made it so if it was odd numbers n-2 went into # negatives, making the program go on forever. n <= 0 correction fixed it. #print(sum_every_other_number(9)) def fibonacci(n): """Return the nth fibonacci number. >>> fibonacci(11) 89 """ if n < 0: print("Non-computable") elif n == 1: return 0 elif n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) # had to change 0 to non computable (goes into negatives.. which don't compute) # also made hard rule for 1 and 2, as 1 = f(0) - f(-1) == 0, and 2 = f(1) - f(0) (should be 1) print(fibonacci(11))
0788bd8ccc154ee86fd9bf4e4b6bb4db3cafbf9e
ednacao/conway_game
/game_of_life.py
1,848
3.734375
4
"""Conway's Game of Life Rules: 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by overcrowding. 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. Logic: For any cell in the middle of a 3x3 grid, number of live cells accompanying it has to be >= 2 and <= 3. If each cell is represented by 0 or 1, then the sum of surrounding cells is 8. Use numpy to create a grid of N x N.""" import numpy as np import matplotlib.pyplot as plot import matplotlib.animation as animation N = 100 ON = 255 OFF = 0 a = [ON, OFF] grid = np.random.choice(a, N*N, p=[0.1, 0.9]).reshape(N, N) def permutation(data): global grid new_grid = grid.copy() for i in range(N): for j in range(N): # Add sum of surrounding cells grid_sum = (grid[i, (j-1) % N] + grid[i, (j+1) % N] + grid[(i-1) % N, j] + grid[(i+1) % N, j] + grid[(i-1) % N, (j-1) % N] + grid[(i-1) % N, (j+1) % N] + grid[(i+1) % N, (j-1) % N] + grid[(i+1) % N, (j+1) % N]) / 255 # Implement rules if grid[i, j] == ON: if (grid_sum < 2) or (grid_sum > 3): new_grid[i, j] = OFF else: if grid_sum == 3: new_grid[i, j] = ON # Update grid with new permutation mat.set_data(new_grid) grid = new_grid return [mat] # Animate fig, ax = plot.subplots() mat = ax.matshow(grid) animate = animation.FuncAnimation(fig, permutation, interval=50, save_count=50) plot.show()
0150569cfa4c141cdcac58fad58f5611aca2ef6f
lilbex/algorithm
/anagram.py
1,007
3.96875
4
def anagram(s1,s2): #remove spaces and lowecase letters s1 = s1.replace(' ','').lower() s2 = s2.replace(' ','').lower() #return boolean for sorted match. if sorted(s1) == sorted(s2): return True print(anagram('dog', 'god')) def anagrams(s1,s2): #remove spaces and lowecase letters s1 = s1.replace(' ','').lower() s2 = s2.replace(' ','').lower() #check if same number of letters if len(s1) != len(s2): return False #count frequncy of each letter count = [] for letter in s1: # for every letter in first string if letter in count: # if letter is already in my dictionary, then count[letter] += 1 # add 1 to that letter key else: count[letter] = 1 # do reverse for second string for letter in s2: if letter in count: count[letter] -= 1 else: count[letter] = 1 for k in count: if count[k] != 0: return False return True print(anagrams('sus', 'god'))
ca720249983d762ef10677c3af659a9324ca9a43
wuranxu/leetcode
/101to150/105. 从前序与中序遍历序列构造二叉树.py
1,397
3.890625
4
# Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: mp = {x: i for i, x in enumerate(inorder)} def build(preorder_left, preorder_right, inorder_left, inorder_right): print(preorder_left, preorder_right, inorder_left, inorder_right) if preorder_left > preorder_right: return root = TreeNode(preorder[preorder_left]) i = mp[root.val] size = i - inorder_left root.left = build(preorder_left + 1, preorder_left + size, inorder_left, i) root.right = build(size + preorder_left + 1, preorder_right, i + 1, inorder_right) return root return build(0, len(preorder) - 1, 0, len(inorder) - 1) # if len(preorder) == 0: # return # root = TreeNode(preorder[0]) # i = 0 # while inorder[i] != preorder[0]: # i += 1 # root.left = self.buildTree(preorder[1:i+1], inorder[:i]) # root.right = self.buildTree(preorder[i+1:], inorder[i+1:]) # return root if __name__ == "__main__": s = Solution() a = [3, 9, 20, 15, 7] b = [9, 3, 15, 20, 7] s.buildTree(a, b)
307300e73a370760d1a677b0b4c6c55e790a16fe
RafinaAfreen/Python
/PartTwo/RegularExpression.py
940
3.6875
4
import re #patterns = ['term1','term2'] text = 'this is a strimg with term1, not the other!' #for pattern in patterns: # print("I'm Searching for: "+pattern) # if re.search(pattern,text): # print("MATCH!") # else: # print("no Match!") match = re.search('term1',text) print(match.start()) split_term = '@' email = '[email protected]' print(re.split(split_term,email)) #match print(re.findall('match','test phrase match in match middle')) def multi_re_find(patterns,phrase): for pat in patterns: print("Searching for pattern {}".format(pat)) print(re.findall(pat,phrase)) print('\n') #test_phrase = 'sdsd..sssddd..sdddsddd...dsds...dssssss...sdddddd' test_phrase = 'This is a string! but is has puntuation. How can we remove it 123 #hashtag?' #[[A-Z]+] #[r'\d+'] #[r'\D+'] #[r'\s+'] #[r'\S+'] #[r'\w+'] #[r'\W+'] test_patterns = ['[^!.?]+'] multi_re_find(test_patterns,test_phrase)
4d3cf89a4445429382a44a1adc3fc9014d8528cc
DaftGeologist/Simple-Python-Projects
/Assg_7_Bubble_Sort.py
1,307
3.828125
4
from random import randint def displayList(PList): for i in range(0,10): print(PList[i]) print(" ") def loadList(PList): for i in range(1,11): PList.append(randint(1,10)) def sortList(PList,PDirection): sorted=False cmp=0 swap=0 i=9 while not sorted and i > 0: sorted=True for j in range(0,i): #Passes cmp+=1 need2Swap=False if (PList[j] > PList[j+1]) and (PDirection=="A"): #Need to Swap need2Swap=True if (PList[j] < PList[j+1] and (PDirection=="D")): need2Swap=True if need2Swap: sorted=False swap+=1 (PList[j],PList[j+1]) = (PList[j+1],PList[j]) i-=1 print("%10d Comparison %10d Swaps"%(cmp,swap)) # main code section def main(): myList=[] #OR ["Ben","Jerry","Bill","Jim","Bob","Jeff","Susan","Britt","Marge","Tom"]Looks at first string character during each pass. Compares the string value and orders them. Result is alphabetical order. loadList(myList) displayList(myList) sortList(myList,"A") displayList(myList) sortList(myList,"D") displayList(myList) main()
b9fdb4b34f6a8daafed9e9be5516099ea68ae9cf
ceccs18c36/Course-Codes
/django4e/SimpleWebBrowserPy/swb.py
1,592
4.125
4
import socket # sockets are built into python. # this lib is used to connect to the server,send data and to recieve data from the server mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket.socket is used to make something to make the connections # just like a phone in a telephone communication mysocket.connect(("data.pr4e.org", 80)) # the above line indicate that we are making the call to the server # i.e, connecting to the server # to the specific domain and port given as argument req_cmd = "GET http://data.pr4e.org/page1.htm HTTP/1.0\r\n\r\n".encode() # req_cmd is the place we are sending the request to recieve our file # \r\n\r\n is used to indicate a (return & newline)x2 # we encode the req to UTF-8 since Unicode is not used by the internet # (the req_cmd is in Unicode which is used in everything nowadays) mysocket.send(req_cmd) # since we are the client we need to send the req first # so we send our req to the server using mysocket.send() while True: # after sending the packets we begin to recieve data(piece by piece) data = mysocket.recv(512) # we recieve 512 charcters each time if len(data) < 1: # this continues till we stop recieving data break print(data.decode(), end="") # we use decode() here to decode the data into Unicode # since the data recieved from the server is in UTF-8 # we need to decode it since print() uses Unicode mysocket.close() # closing the connection after data is recieved # -----------------👇🏻---------------- # data recieved from the server is in data.txt
d82b67d3e41716669b7c874689e1c3355bc8846f
kylemarienthal/python_april_2018
/loops.py
4,471
3.75
4
arr = [1,2,3,4,4,5,6,6] # JAVASCRIPT # for (start, stop, step) { # ... # } # for (var i = 0; i < ...; i++) { # # } for i in range(len(arr)): print 'i: {}'.format(i) print 'arr[' + str(i) + ']', arr[i] print 'arr[{}] - {}'.format(i, arr[i]) print '*'*20 for i in arr: print i # if (arr.length > 5 && arr.length < 20) { ... } if len(arr) <> 5 and len(arr) < 20: print 'compound and' # if (arr.length > 5 || arr.length < 20) { ... } if len(arr) > 5 or len(arr) < 20: print 'compound and' # >>> arr # [1, 2, 3] # >>> len(arr) # 3 # >>> arr.sort() # >>> arr # [1, 2, 3] # >>> arr = [3,2,1] # >>> arr.sort() # >>> arr # [1, 2, 3] # >>> arr = [3,2,1] # >>> sorted(arr) # [1, 2, 3] # >>> arr # [3, 2, 1] # >>> arr.reverse() # >>> arr # [1, 2, 3] # >>> reverse(arr) # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # NameError: name 'reverse' is not defined # >>> arr.find(1) # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # AttributeError: 'list' object has no attribute 'find' # >>> arr[1] # 2 # >>> s = 'hello there everyone!' # >>> s.find('there') # 6 # >>> s[6:] # 'there everyone!' # >>> s.replace('there', 'red') # 'hello red everyone!' # >>> s # 'hello there everyone!' # >>> s = 'hello there everyone! there' # >>> s.replace('there', 'red') # 'hello red everyone! red' # >>> # >>> s.replace('there', 'red', 1) # 'hello red everyone! there' # >>> s # 'hello there everyone! there' # >>> s = s.replace('there', 'red', 1) # >>> s # 'hello red everyone! there' # >>> help(min) # # >>> help(max) # # >>> help(sort) # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # NameError: name 'sort' is not defined # >>> help(sorted) # # >>> sorted(s) # [' ', ' ', ' ', '!', 'd', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'h', 'h', 'l', 'l', 'n', 'o', 'o', 'r', 'r', 'r', 't', 'v', 'y'] # >>> sorted(s, reverse=True) # ['y', 'v', 't', 'r', 'r', 'r', 'o', 'o', 'n', 'l', 'l', 'h', 'h', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'd', '!', ' ', ' ', ' '] # >>> # >>> help(range) # # >>> range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # >>> range(-10) # [] # >>> range(0,-10) # [] # >>> range(0,-10,-1) # [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] # >>> range(-10,-1) # [-10, -9, -8, -7, -6, -5, -4, -3, -2] # >>> # >>> s # 'hello red everyone! there' # >>> help(count) # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # NameError: name 'count' is not defined # >>> import string # >>> help(string.count) # # >>> help(string.count) # # >>> 'elephant'.count('e') # 2 # >>> s # 'hello red everyone! there' # >>> s.split() # ['hello', 'red', 'everyone!', 'there'] # >>> s.split('!') # ['hello red everyone', ' there'] # >>> my_list # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # NameError: name 'my_list' is not defined # >>> my_list = ['hello red everyone', ' there'] # >>> my_list # ['hello red everyone', ' there'] # >>> my_list.join() # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # AttributeError: 'list' object has no attribute 'join' # >>> ''.join(my_list) # 'hello red everyone there' # >>> '!!!!!!'.join(my_list) # 'hello red everyone!!!!!! there' # >>> ','.join(my_list) # 'hello red everyone, there' # >>> '\t'.join(my_list) # 'hello red everyone\t there' # >>> s # 'hello red everyone! there' # >>> s.endswith('e') # True # >>> s.endswith('r') # False # >>> i = 0 # >>> i++ # File "<stdin>", line 1 # i++ # ^ # SyntaxError: invalid syntax # >>> push # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # NameError: name 'push' is not defined # >>> arr # [1, 2, 3] # >>> arr.push(4) # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # AttributeError: 'list' object has no attribute 'push' # >>> arr.append(4) # >>> arr # [1, 2, 3, 4] # >>> arr += 5 # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # TypeError: 'int' object is not iterable # >>> arr += [5] # >>> arr # [1, 2, 3, 4, 5] # >>> arr.append('stick to the end!!') # >>> arr # [1, 2, 3, 4, 5, 'stick to the end!!'] # >>> arr2 = ['another', 'list'] # >>> arr # [1, 2, 3, 4, 5, 'stick to the end!!'] # >>> arr2 # ['another', 'list'] # >>> arr.append(arr2) # >>> arr # [1, 2, 3, 4, 5, 'stick to the end!!', ['another', 'list']] # >>> arr.extend(arr2) # >>> arr # [1, 2, 3, 4, 5, 'stick to the end!!', ['another', 'list'], 'another', 'list']
4231ba30d8cfa77e97b9f7a73caac8030b6e8811
GaoZWei/Python_Study
/code/high_level/fun5.py
144
3.65625
4
# map 映射 list_x = [1, 2, 3, 4, 5, 6, 7, 8] def squre(x): return x*x for x in list_x: squre(x) r=map(squre,list_x) print(list(r))
8417ecba88fcdf11b361d551739317be308d6ba5
Pyloons/MyPractices
/算法与数据结构/排序/经典算法/选择排序/select_sort.py
647
4.125
4
def find_smallest(arr): smallest = arr[0] smallest_index = 0 for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def select_sort(arr): new_arr = [] for _ in range(len(arr)): smallest = find_smallest(arr) new_arr.append(arr.pop(smallest)) return new_arr if __name__ == "__main__": try_arrays = [ [5, 3, 6, 2, 10], [3, 4, 2, 8, 9, 5, 1], [38, 65, 97, 76, 13, 27, 49] ] for arr in try_arrays: tmp_arr = arr[:] print("{} -> {}".format(tmp_arr, select_sort(arr)))
5c8a49fb2ed72ec4a6dcc1fae1a96e6c009e9f08
maykim51/ctci-alg-ds
/PastProblems/word_ladder.py
4,028
3.875
4
''' [MS SDE] Word-ladder https://leetcode.com/problems/word-ladder but with a complex description. Same idea, and process. SOLUTION 1) Use bfs in graph, but key is intermediate_word!!!!!! like d*g, *og! traverse 할때는 내가 만들 수 있는 intermediate_word를 기반으로 딕셔너리를 탐색! 2) Bidirecition BFS ''' import unittest ####Option 1 - mine # def ladderLength(beginWord, endWord, wordList): # if endWord not in wordList: # return 0 # wordList.append(beginWord) # #Create graph # ladders = {} # for word in wordList: # if word not in ladders: # ladders[word] = set([]) # visited = set([word]) # for dest in wordList: # if dest in visited or word in ladders[dest]: # break # else: # if is_one_edit(word, dest): # ladders[word].add(dest) # ladders[dest].add(word) # visited.add(dest) # '''remove later''' # print(ladders) # #BFS # queue = [beginWord] # visited = set([beginWord]) # level = 1 # while queue: # curr = queue.pop(0) # if curr == 's': # level += 1 # elif curr == endWord: # return level # else: # visited.add(curr) # for word in ladders[curr] - visited: # queue.append(word) # queue.append('s') # return 0 # def is_one_edit(word1, word2): # count = 0 # #assume len(word1) == len(word2) # for i in range(len(word1)): # if word1[i] != word2[i]: # count += 1 # if count > 1: # return False # return True ###Option 2: Leetcode from collections import defaultdict import collections def ladderLength(beginWord, endWord, wordList): if endWord not in wordList or not endWord or not beginWord or not wordList: return 0 L = len(beginWord) # Dictionary to hold combination of words that can be formed, # from any given word. By changing one letter at a time. ''' key is d*g, *og!! ''' all_combo_dict = defaultdict(list) for word in wordList: for i in range(L): # Key is the generic word # Value is a list of words which have the same intermediate generic word. all_combo_dict[word[:i] + "*" + word[i+1:]].append(word) # Queue for BFS queue = collections.deque([(beginWord, 1)]) # Visited to make sure we don't repeat processing same word. visited = {beginWord: True} while queue: current_word, level = queue.popleft() for i in range(L): # Intermediate words for current word intermediate_word = current_word[:i] + "*" + current_word[i+1:] # Next states are all the words which share the same intermediate state. for word in all_combo_dict[intermediate_word]: # If at any point if we find what we are looking for # i.e. the end word - we can return with the answer. if word == endWord: return level + 1 # Otherwise, add it to the BFS Queue. Also mark it visited if word not in visited: visited[word] = True queue.append((word, level + 1)) all_combo_dict[intermediate_word] = [] return 0 #Driver class Test(unittest.TestCase): def test_ladderLength(self): self.assertEqual(ladderLength('hit', 'cog', ["hot","dot","dog","lot","log","cog"]), 5) self.assertEqual(ladderLength('hit', 'cog', ["hot","dot","dog","lot","log"]), 0) if __name__ == "__main__": unittest.main()
447be83d74195e09cabfe328ba5841cc01e683ae
Symbii/python_Oj
/yield.py
661
3.8125
4
def fab(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 #Fab是一个迭代类 class Fab(object): def __init__(self, max): self.max = max self.n = 0 self.a = 0 self.b = 1 def __iter__(self): return self def __next__(self): if self.n < self.max: ret = self.b self.n += 1 self.a, self.b = self.b, self.a + self.b return ret raise StopIteration if __name__ == "__main__": for x in fab(5): print(x) print(type(fab(5))) s = iter(Fab(5)) for x in s: print(x)
4de49b82e4e01524f927a321bf90f28d0dd3b1f5
MysteriousSonOfGod/LeetCode
/Q003/longest-substring-without-repeating-characters.py
1,019
3.75
4
""" * longest-substring-without-repeating-characters.py * * @param {string} s * * @return {int} """ class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ last_repeating = -1 longest_substring = 0 positions = {} for i in range(len(s)): if s[i] in positions and last_repeating < positions[s[i]]: last_repeating = positions[s[i]] if i-last_repeating > longest_substring: longest_substring = i-last_repeating positions[s[i]] = i return longest_substring ##------------------------------ Simple Testing Code ------------------------------## solution = Solution() longest_substring = solution.lengthOfLongestSubstring("abcabcdb") print(longest_substring) longest_substring = solution.lengthOfLongestSubstring("bbbbb") print(longest_substring) longest_substring = solution.lengthOfLongestSubstring("aab") print(longest_substring)
33cb46b3099c9142b8f380e7c83732df936776ef
ArunkumarRamanan/CLRS-1
/StanfordAlgorithmDesignAnalysis/week5DjikstrShortestPath.py
1,882
3.78125
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 10 13:56:21 2016 @author: Rahul Patni """ # Djistra's shortest path algorithm import sys def loadGraph(): graph = dict() filename = "dijkstraData.txt" #filename = "Graph5Dijkstra.txt" fptr = open(filename) for line in fptr: line = line.rstrip().split("\t") if line[0] not in graph: graph[line[0]] = [] for i in range(1, len(line)): location = line[i].split(",") if location[0] not in graph: graph[location[0]] = [] graph[line[0]].append([location[0], int(location[1])]) return graph def printGraph(graph): for i in graph.keys(): print i def dijkstra(graph, start): # Initializing components X = [start] A = dict() A[start] = 0 B = dict() B[start] = [] while len(X) != len(graph): minimumLength = sys.maxint minimumSource = None minimumRoute = None for i in X: for j in graph[i]: if j[0] not in X: if j[0] not in B: B[j[0]] = [] if A[i] + j[1] < minimumLength: minimumLength = A[i] + j[1] minimumSource = i minimumRoute = j[0] X.append(minimumRoute) A[minimumRoute] = minimumLength new_list = list(B[minimumSource]) B[minimumRoute] = new_list B[minimumRoute].append(minimumRoute) return A def main(): graph = loadGraph() printGraph(graph) A = dijkstra(graph, '1') print A array = ['t','w','7','37','59','82','99','115','133','165','188','197'] for i in array: if i not in A: print "weirds", i else: print A[i], return if __name__ == "__main__": main()
e886c821f918f02af401fc1571ee4bf5e089b5f8
colin-bethea/leetcode
/python/problemset/217.py
523
3.71875
4
# https://leetcode.com/problems/contains-duplicate/ class Solution(object): ''' Solution #1 - Set --- Use a set to retrieve unique elements in input array. Compare the length of the set to the length of input array. If they are the same, there is no duplicate. If they differ, there is a duplicate. --- R: O(n), where n is # of elements in (nums) S: O(n), where n is # of elements in (nums) ''' def containsDuplicateWithSet(self, nums): return len(set(nums)) != len(nums)
805289d59ed33112d18ecdb0e04568d377e3cbdb
Pranav-Khurana/Competitive-Coding
/HackerRank-Algorithms/Bon_appetit.py
661
3.640625
4
#https://hackerrank-challenge-pdfs.s3.amazonaws.com/24060-bon-appetit-English?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1562406181&Signature=wP3fYOaEe4enS72PgBmN5HrbjbY%3D&response-content-disposition=inline%3B%20filename%3Dbon-appetit-English.pdf&response-content-type=application%2Fpdf # Enter your code here. Read input from STDIN. Print output to STDOUT #input process input_line1 = input().split() n = int(input_line1[0]) b = int(input_line1[1]) bill = list(map(int, input().rstrip().split())) r = int(input()) #algo process s=0 for i in range(n): if i==b: continue s+=bill[i] s/=2 s=int(s) if s==r: print('Bon Appetit') else: print(str(r-s))
672a366814df3b813aad582a0ed82926fce694f5
qnguyen3010/Leetcode-Python
/q206.py
863
3.9375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 19 15:28:10 2017 @author: AaronNguyen """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ prevNode , nextNode = None, None currNode = head while currNode != None: nextNode = currNode.next currNode.next = prevNode prevNode = currNode currNode = nextNode head = prevNode return head head = ListNode(1) head.next = ListNode(2) head.next.next = ListNode(3) head.next.next.next = ListNode(4) print(head.val) solution = Solution() solution.reverseList(head) print(head.val)
f7a494c32516f1ba060e7e345d38b5d700a209f4
samidavies/Project-Euler
/euler_1-13-18.py
942
3.578125
4
def isPrime(n): if n == 1: return False for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def euler_sum(n): if n == 1: return 0 if n == 0: return 1 total = 0 for k in range(1,n+1): if isPrime(k): total += k * euler_sum(n-k) for j in range(k+1, n-k+1): if isPrime(j): total -= j*k*euler_sum(n-k-j) for i in range(j+1, n-k-j+1): if isPrime (i): total += j*k*i*euler_sum(n-k-j-i) for l in range(i+1, n-k-j-i+1): print("here") if isPrime (l): total -= j*k*i*l*euler_sum(n-k-j-i-l) return total print(euler_sum(16)) print(euler_sum(17)) print(euler_sum(18))
83dec5b600e336696269ef6bae4ec9b89935efd8
kailash-manasarovar/A-Level-CS-code
/challenges/yes-no-tree.py
990
4.03125
4
class Node: def __init__(self, question, answer): self.left = None self.right = None self.question = question self.answer = answer def insert(self, question, answer): # Compare the new value with the parent node if self.question: if answer == "Y": if self.left is None: self.left = Node(question, answer) else: self.left.insert(question, answer) elif question == "N": if self.right is None: self.right = Node(question, answer) else: self.right.insert(question, answer) else: self.question = question self.answer = answer # Print the tree def printTree(self): if self.left: self.left.printTree() print(self.question, self.answer), if self.right: self.right.printTree()
52eb78599f30346f8bd59c1d0128921fe2be80f4
saipoojavr/saipoojacodekata
/alphanum.py
254
3.6875
4
string=str(input()) count=0 count1=0 for iter in range(0,len(string)): if(string[iter].isalpha()==True): count=count+1 elif(string[iter].isdigit()==True): count1=count1+1 else: continue if(count>0 and count1>0): print("Yes") else: print("No")
d874c9c0074a6e012ed2ba5d7e849f6ff4fd29c7
proformatique/algo
/tp9/Eleve.py
6,510
3.84375
4
class eleve: '''Classe représentant un élève. Example ------- >>> e1 = eleve('1,salmi,said,15.25,14.0,15.5') >>> e1 '1,salmi,said,15.25,14.0,15.5' ''' def __init__(self, texte): '''Constructeur pour créer des élèves. Parameters ---------- texte : str une chaine de la forme id,nom,prenom,n1,n2,n3 Exceptions ---------- AssertionError : si texte ne contient pas 6 champs ValueError : echec de conversion de id ou des notes ''' champs = texte.strip().split(',') assert len(champs) == 6, 'Nombre de champs non compatible' self.id = int(champs[0]) self.nom = champs[1] self.prenom = champs[2] self.note1 = float(champs[3]) self.note2 = float(champs[4]) self.note3 = float(champs[5]) def __str__(self): 'Convertit l\'objet eleve en str.' return "{},{},{},{},{},{}".format(self.id, self.nom, self.prenom, self.note1, self.note2, self.note3) def __repr__(self): 'Représentation de l\'objet eleve.' return self.__str__() #Todo getters def getId(self): return self.id #Todo setters # Méthodes d'instance def format(self): 'Formate l\'élève pour l\'affichage.' return '''\n\nEleve #{}\n=======\n{} {}\nNote1 :{}\nNote2 :{}\nNote3 :{}'''.format(self.id, self.nom, self.prenom, self.note1, self.note2, self.note3) def moyenne(self): 'Calcule la moyenne des notes.' som = self.note1 + self.note2 + self.note3 return som / 3 # Gestion des fichiers class dbeleve: '''Gère le stockage des élèves dans un fichier csv. Les méthodes sont statiques ''' fichier = "eleves.csv" @staticmethod def getEleve(id): '''Retourne l'élève spécifié par l'id. Parameters ---------- id : int identifiant numérique de l'élève. Returns ------- eleveencours : eleve ''' try: trouve = False with open(dbeleve.fichier, encoding='utf-8') as fd: for line in fd: eleveencours = eleve(line) if id == eleveencours.getId(): trouve = True return eleveencours if not trouve: raise ValueError('Id %d non trouvé' % id) except Exception as e: print('Impossible de récupérer l\'élève', e) def getTout(): try: leseleves = [] with open(dbeleve.fichier, encoding='utf-8') as fd: for line in fd: eleveencours = eleve(line) leseleves.append(eleveencours) except: print('Impossible de récupérer les élèves') finally: return leseleves @staticmethod def sauverTout(leseleves): try: assert input('Attention vous allez écraser toutes les données\nContinuer? (o/n) ').upper() == 'O', 'Opération annulée' with open(dbeleve.fichier, "w", encoding='utf-8') as fd: fd.write('\n'.join(map(str, leseleves))) except AssertionError as e: print(e) except Exception as e: print('Impossible d\'effectuer l\'enregistrement', e) else: print('Ok') @staticmethod def sauverun(uneleve): try: with open(dbeleve.fichier, "a", encoding='utf-8') as fd: fd.write('\n'+str(uneleve)) except: print('Impossible d\'effectuer l\'enregistrement') else: print('Opération réussie') class eleveManager(): leseleves = dbeleve.getTout() try: id = leseleves[-1].getId() except: id = 0 @staticmethod def affichertout(): try: assert len(eleveManager.leseleves), 'Aucun élève...' for chaqueeleve in eleveManager.leseleves: print(chaqueeleve.format()) except AssertionError as e: print(e) @staticmethod def sauverTout(): dbeleve.sauverTout(eleveManager.leseleves) @staticmethod def sauverun(): dbeleve.sauverun(eleveManager.leseleves[-1]) @staticmethod def rechercheid(): id = int(input('Entrez l\'id de l\'élève à chercher')) elv = dbeleve.getEleve(id) print(elv.format()) @staticmethod def ajouter(): eleveManager.id += 1 print("\n\n\n*** Ajouter un eleve ***") nom = input("Entrez le nom : ") prenom = input("Entrez le prenom : ") while True: try: note1 = float(input("Entrez la note 1 : ")) note2 = float(input("Entrez la note 2 : ")) note3 = float(input("Entrez la note 3 : ")) if not (0<= note1 <=20): raise ValueError except: print("Notes non valide") else: break elevetxt = "{},{},{},{},{},{}".format(eleveManager.id, nom, prenom, note1, note2, note3) elv = eleve(elevetxt) eleveManager.leseleves.append(elv) # IHM class cli: action = { 'L': eleveManager.affichertout, 'N': eleveManager.ajouter, 'R': eleveManager.rechercheid, 'S': eleveManager.sauverun, 'A': eleveManager.sauverTout } titre = "\n\n\nGestion des élèves" options = ["Nouveau N", "Lister L", "Rechercher R", "Enregistrer S", "Enregistrer tout A", "Quitter Q", ] message = "Entrez votre choix : " @staticmethod def menu(): print(cli.titre) for i, option in enumerate(cli.options): print("{:0>2}- {:20}({})".format(i+1, option[:-2], option[-1])) choix = input(cli.message) return choix @staticmethod def loop(): while True: choix = cli.menu() try: if choix.upper() == 'Q': break else: cli.action[choix.upper()]() except: print("Choix non valide") def main(): cli.loop() if __name__ == "__main__": main()
9e7260f13846f5e35cea372ed909e768270d440d
aashishd/code_jam_2020_python3
/NestingDepth/nesting_depth.py
901
3.9375
4
class NestingDepth: def __init__(self): raw_input = input() self.values = [int(raw_input[i]) for i in range(len(raw_input))] self.result = "" self.nested_string() def nested_string(self): # creates the string with nesting prev_num = 0 for current_value in self.values: diff = current_value - prev_num paren = ")" if diff > 0: paren = "(" parenthesis = "".join([paren for i in range(abs(diff))]) self.result += parenthesis + str(current_value) prev_num = current_value self.result += "".join([")" for i in range(self.values[-1])]) def main(): test_count = int(input()) for t in range(1, test_count + 1): nested = NestingDepth() print("Case #{}: {}".format(t, nested.result)) if __name__ == "__main__": main()
212490fe5275ff731a4d7ba1eabc79f98a841fa4
zita9999/Clean-Code-Z
/How To Send Emails, Using Python (2021).py
1,531
3.984375
4
#---How To Send Emails, Using Python (2021)--- ##################################### -Importing Necessary Libraries- ############################################# import smtplib, ssl from email.mime.text import MIMEText ##################################### -Sender, Reciever, Body of Email- ############################################# #Input the the email address of who you want to send the email sender = '[email protected]' #Input the the email address's of those you want to receive the email receivers = ['[email protected]', '[email protected]'] #input the body of text you want in your email body_of_email = 'Text to be displayed in the email' ##################################### -Creating the Message, Subject line, From and To- ############################################# #Creates the inital messgae msg = MIMEText(body_of_email, 'html') #Input subject line of your email msg['Subject'] = 'Subject line goes here' #From the email addresses you put in the last section those will be the From and To's msg['From'] = sender msg['To'] = ','.join(receivers) ##################################### -Connecting to Gmail SMTP Server- ############################################# #Connects to the Gmail server s = smtplib.SMTP_SSL(host = 'smtp.gmail.com', port = 465) #After it connects you need to put your login details so it can access your Gmail account s.login(user = 'your_username', password = 'your_password') #It will offically send the email s.sendmail(sender, receivers, msg.as_string()) s.quit()
efaef2a6ced638f68eadfe13e2b5c00a40ca666d
Dragon20C/TicTacToe
/main.py
2,070
3.71875
4
import random board = {"top-L": "", "top-M": "", "top-R": "", "mid-L": "", "mid-M": "", "mid-R": "", "low-L": "", "low-M": "", "low-R": ""} def draw(): print(board["top-L"] + " ┃ " + board["top-M"] + " ┃ " + board["top-R"]) print("------") print(board["mid-L"] + " ┃ " + board["mid-M"] + " ┃ " + board["mid-R"]) print("------") print(board["low-L"] + " ┃ " + board["low-M"] + " ┃ " + board["low-R"]) while True: if board["low-L"] and board["low-M"] and board["low-R"] == "X": # horizontal print("You won!") break if board["mid-L"] and board["mid-M"] and board["mid-R"] == "X": print("You won!") break if board["top-L"] and board["top-M"] and board["top-R"] == "X": print("You won!") break if board["low-L"] and board["mid-L"] and board["top-L"] == "X": # Vertical print("You won!") break if board["low-M"] and board["mid-M"] and board["top-M"] == "X": print("You won!") break if board["low-R"] and board["mid-R"] and board["top-R"] == "X": print("You won!") break if board["low-L"] and board["mid-M"] and board["top-R"] == "X": # A cross print("You won!") break if board["low-R"] and board["mid-M"] and board["top-L"] == "X": print("You won!") break player = input("Choose your position top-L,top-M,top-R,mid-L,mid-M,mid-R,low-L,low-M,low-R ") if player == "top-L": # Top row board["top-L"] = "X" elif player == "top-M": board["top-M"] = "X" elif player == "top-R": board["top-R"] = "X" elif player == "mid-L": # Mid row board["mid-L"] = "X" elif player == "mid-M": board["mid-M"] = "X" elif player == "mid-R": board["mid-R"] = "X" elif player == "low-L": # Low row board["low-L"] = "X" elif player == "low-M": board["low-M"] = "X" elif player == "low-R": board["low-R"] = "X" draw()
575838876475c5329ddf730414b6e8d7ea34608d
blue-alexa/ML_models
/dual_perceptron.py
2,858
3.6875
4
""" Dual Perceptron 1. Start with zero counts (alpha) 2. Pick up training instances one by one 3. Try to classify xn, y = argmax(Sigma ai,y K(xi,xn)) bias? 4. If correct, no change! 5. If wrong: lower count of wrong class (for this instance), raise count of right class (for this instance) ay,n = ay,n-1 ay*,n = ay*,n+1 """ def Linear_kernel(X, Xp): """ K(Xi, Xj)=k[i,j]; K(X, Xi)=k[:,i] Input: -X, with shape (N1,d) -Xp, with shape (N2,d) Output: -k, with shape (N1, N2) """ k = np.dot(X, Xp.T) return k def Quadratic_kernel(X, Xp): """ K(Xi, Xj)=k[i,j]; K(X, Xi)=k[:,i] Input: -X, with shape (N1,d) -Xp, with shape (N2,d) Output: -k, with shape (N1, N2) """ k = (np.dot(X, Xp.T)+1)**2 return k def RBF_kernel(X, Xp, tau): """ K(Xi, Xj)=k[i,j]; K(X, Xi)=k[:,i] Input: -X, with shape (N1,d) -Xp, with shape (N2,d) Output: -k, with shape (N1, N2) """ k1 = np.sum(X**2, axis=1, keepdims=True) k2 = np.sum(Xp**2, axis=1, keepdims=True) k12 = np.dot(X, Xp.T) k = np.exp(-(k1+k2.T-2*k12)/(2*tau**2)) return k def Kesler_construction(X, y): # convert y to Kesler constructions class_values = np.unique(y) class_num = len(class_values) yc = np.zeros_like(y) for i, value in enumerate(class_values): yc[y==value]=i KC = np.zeros((len(X), class_num)) KC.fill(-1) KC[range(len(X)), yc]=1 #Keslerlabel = {ind:value for ind, value in enumerate(class_values)} return KC def Xa_construction(X): # add x0=1 Xa = np.hstack((np.ones((len(X),1)), X)) return Xa def fit(X, y): KC = Kesler_construction(X, y) y_KC = np.argmax(KC, axis=1) # N is number of training samples, d is number of features. N, d = X.shape # k is number of classes _, k = KC.shape # initialize alphas, columns are alpha for one class alpha = np.zeros((N, k)) # Use quadratic_kernel Ker = Quadratic_kernel(X, X) iterations = 0 err = N best_err = err best_alpha = alpha while err!=0 and iterations<10000: # update all training sample using matrix formate pred = np.argmax(np.dot(Ker.T, alpha), axis=1) row_change = np.where(pred != y_KC) col_change = y_KC[row_change] alpha[row_change, :] -= 1 alpha[row_change, col_change] += 2 # check error rate: pred = np.argmax(np.dot(Ker.T, alpha), axis=1) err = np.sum(pred!=y_KC) if err < best_err: best_err = err best_alpha = alpha.copy() iterations+=1 """ # update one training sample Xi pred = np.argmax(np.dot(Ker[:, i, np.newaxis].T, alpha)) if pred != y_KC[i]: alpha[i, :] -= 1 alpha[i, y[i]] += 2 """
5f571d6b22cf4e568f526f9b6a87f6f687845d5b
serek2298/Embeded-Sys
/main.py
499
3.875
4
''' Program wyznaczający pierwiastki trójmianu dla przypadków rzeczywistych ''' import math a = float(input('a=')) # Wczytaj a b = float(input('b=')) c = float(input('c=')) delta = b**2 - 4*a*c if delta > 0: x1 = (-1*b + math.sqrt(delta))/(2*a) x2 = (-1*b - math.sqrt(delta))/(2*a) print('Dwa pierwiastki',x1,',',x2) elif delta == 0: x = -1*b/(2*a) print('Jeden pierwiastek',x) else: print('MicroPython nie osbługuje liczb zepolonych')#CPython owszem print('Koniec')
a2aa28e58475505e10bef33ff94d672e1e02e3d2
Delictum/python_algorithms_and_data_structures
/old/db_and_oop/manager.py
1,500
4
4
from person import Person class Manager(Person): ''' Версия класса Person, адаптированная в соответствии со специальными требованиями ''' def __init__(self, name, pay): Person.__init__(self, name, 'manager', pay) def give_raise(self, percent, bonus=.10): Person.give_raise(self, percent + bonus) class Department: def __init__(self, *args): self.members = list(args) def add_member(self, person): self.members.append(person) def give_raise(self, percent): for person in self.members: person.give_raise(percent) def show_all(self): for person in self.members: print(person) if __name__ == '__main__': tom = Manager('Tom Jones', 50000) tom.give_raise(.10) print(tom.get_last_name()) print(tom) bob = Person('Bob Smith') sue = Person('Sue Jones', job='dev', pay=100000) print(bob) print(sue) print(Person.__init__.__annotations__) print(Person.__init__.__doc__) print(bob.get_last_name(), sue.get_last_name()) sue.give_raise(.10) print(sue.pay) print('--All three--') for obj in (bob, sue, tom): obj.give_raise(.10) print(obj) print('--Create department--') development = Department(bob, sue) development.add_member(tom) development.give_raise(.10) development.show_all() print(help(Manager)) print(help(Manager))
93eb293cc634d8b8efc7f305a7ffe16d9da20279
audiodude/advent2019
/3a.py
999
3.609375
4
import fileinput paths = fileinput.input() a_path = paths[0].strip().split(',') b_path = paths[1].strip().split(',') def path_to_coords(path): cur = (0, 0) coords = set() coords.add(cur) for move in path: num = int(move[1:]) if move[0] == 'U': for _ in range(num): cur = (cur[0], cur[1] + 1) coords.add(cur) elif move[0] == 'D': for _ in range(num): cur = (cur[0], cur[1] - 1) coords.add(cur) elif move[0] == 'L': for _ in range(num): cur = (cur[0] - 1, cur[1]) coords.add(cur) elif move[0] == 'R': for _ in range(num): cur = (cur[0] + 1, cur[1]) coords.add(cur) return coords a_coords = path_to_coords(a_path) b_coords = path_to_coords(b_path) intersections = a_coords & b_coords intersections.remove((0,0)) sorted_intersections = sorted( intersections, key=lambda item: abs(item[0]) + abs(item[1])) print(abs(sorted_intersections[0][0]) + abs(sorted_intersections[0][1]))
fc4294f4cb9bf3865f843bb5b36eabc1d4846e44
qiujiandeng/-
/day18-oopday2/a.py
1,021
3.8125
4
class A: def __init__(self,name): self.name = name def __repr__(self): #重写__repr__方法 #返回的是B('jerry','0001') return "B('%s','%s')" % (self.name,self.id) # def __str__(self): #重写__str__函数 # return "name = %s" %self.name class B(A): def __init__(self,name,id): super().__init__(name) #B里没有name属性,需要调用调用父类构造方法 self.id = id #B类只创建了 id属性被创建 def __repr__(self): #重写__repr__方法 #返回的是B('jerry','0001') return "B('%s','%s')" % (self.name,self.id) # def __str__(self): #重写__str__函数 # return "name = %s , id = %s"%(self.name,self.id) b = B("Jerry","00001") print(b) # str_obj = repr(b) # print(str_obj) # new_obj = eval(str_obj) #通过python解释器还原对象 # print(new_obj) # print(b) #在B子类中重写__str__方法,所以可以直接打印 # str_obj = str(b) #将B对象转换成字符串 # print(str_obj)
02853d08436261b19d28d03c4c07d67e140c297f
daxiangpanda/lintCode
/128.py
1,450
4
4
# 描述 # 在数据结构中,哈希函数是用来将一个字符串(或任何其他类型)转化为小于哈希表大小且大于等于零的整数。一个好的哈希函数可以尽可能少地产生冲突。一种广泛使用的哈希函数算法是使用数值33,假设任何字符串都是基于33的一个大整数,比如: # hashcode("abcd") = (ascii(a) * 333 + ascii(b) * 332 + ascii(c) *33 + ascii(d)) % HASH_SIZE # = (97* 333 + 98 * 332 + 99 * 33 +100) % HASH_SIZE # = 3595978 % HASH_SIZE # 其中HASH_SIZE表示哈希表的大小(可以假设一个哈希表就是一个索引0 ~ HASH_SIZE-1的数组)。 # 给出一个字符串作为key和一个哈希表的大小,返回这个字符串的哈希值。 # 您在真实的面试中是否遇到过这个题? 是 # 说明 # For this problem, you are not necessary to design your own hash algorithm or consider any collision issue, you just need to implement the algorithm as described. # 样例 # 对于key="abcd" 并且 size=100, 返回 78 class Solution: """ @param key: A string you should hash @param HASH_SIZE: An integer @return: An integer """ def hashCode(self, key, HASH_SIZE): sum = 0 for char in key: sum = sum * 33 + ord(char) sum = sum % HASH_SIZE return sum A = Solution() print(A.hashCode("abcd",100))
9807d113d594235b6cc5470be0ec757125cd5b61
Jamesgarrett279/TicTacToe
/JamesGarrettProject2.py
5,951
3.921875
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: # Author: James Carter Garrett # Creates a blank game board def create_board(): board = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] return board # Display the game board def display_board(gameboard): counter = 0 for rows in gameboard: pos = 0 for position in rows: # First Row if counter == 0: if position == 0: print("_ | ", end='') pos += 1 elif position == 1: print("X | ", end='') pos += 1 else: print("O | ", end='') pos += 1 if pos == 4: print("\n---------------") # Second Row elif counter == 1: if position == 0: print("_ | ", end='') pos += 1 elif position == 1: print("X | ", end='') pos += 1 else: print("O | ", end='') pos += 1 if pos == 4: print("\n---------------") # Third Row elif counter == 2: if position == 0: print("_ | ", end='') pos += 1 elif position == 1: print("X | ", end='') pos += 1 else: print("O | ", end='') pos += 1 if pos == 4: print("\n---------------") # Fourth Row else: if position == 0: print("_ | ", end='') pos += 1 elif position == 1: print("X | ", end='') pos += 1 else: print("O | ", end='') pos += 1 if pos == 4: print("\n---------------") counter += 1 # Check for winning - def check_winner(gameboard, currentMoves): noWinner = " " xWins = "X" oWins = "O" # If there have been less than 7 moves made, there can't be a winner if currentMoves < 7: return noWinner # If there have been 7 or more, continue checking else: # Checking each row for a winner for rows in gameboard: if rows == [1, 1, 1, 1]: return xWins elif rows == [2, 2, 2, 2]: return oWins else: continue # Checking each column for a winner for columns in range(0, 3): # Checking for 4 X's in each column if gameboard[0][columns] == 1: if gameboard[1][columns] == 1: if gameboard[2][columns] == 1: if gameboard[3][columns] == 1: return xWins # Checking for 4 O's in each column if gameboard[0][columns] == 2: if gameboard[1][columns] == 2: if gameboard[2][columns] == 2: if gameboard[3][columns] == 2: return oWins # Checking diagonal # Top Left -> Bottom Right if gameboard[0][0] == 1: if gameboard[1][1] == 1: if gameboard[2][2] == 1: if gameboard[3][3] == 1: return xWins if gameboard[0][0] == 2: if gameboard[1][1] == 2: if gameboard[2][2] == 2: if gameboard[3][3] == 2: return oWins # Bottom Left -> Top Right if gameboard[3][0] == 1: if gameboard[2][1] == 1: if gameboard[1][2] == 1: if gameboard[0][3] == 1: return xWins if gameboard[3][0] == 2: if gameboard[2][1] == 2: if gameboard[1][2] == 2: if gameboard[0][3] == 2: return oWins # If there's no winning combination else: return noWinner # Runs the game player1 = input("Enter player one's name: ") player2 = input("Enter player two's name: ") print() p1Wins = 0 p2Wins = 0 movesMade = 0 keepRunning = True while (keepRunning == True): newBoard = create_board() while ((check_winner(newBoard, movesMade) == " " and movesMade < 16) or (check_winner(newBoard, movesMade) == None and movesMade < 16)): display_board(newBoard) inputChecker = True while (inputChecker == True): try: userRow = int (input("Enter the row you would like to choose (1-4): ")) if (userRow >= 1 and userRow <= 4): inputChecker = False else: print("Invalid number, must be either 1, 2, 3, or 4. Try again.") except: print("Invalid input. Try again.") inputChecker = True while (inputChecker == True): try: userColumn = int (input("Enter the column you would like to choose (1-4): ")) if (userColumn >= 1 and userColumn <= 4): inputChecker = False else: print("Invalid number, must be either 1, 2, 3, or 4. Try again.") except: print("Invalid input. Try again.") if ((movesMade + 1) % 2) == 0: if (newBoard[(userRow - 1)][(userColumn - 1)] == 0): newBoard[(userRow - 1)][(userColumn - 1)] = 2 movesMade += 1 else: print("That space is not empty. Choose another space.") else: if (newBoard[(userRow - 1)][(userColumn - 1)] == 0): newBoard[(userRow - 1)][(userColumn - 1)] = 1 movesMade += 1 else: print("That space is not empty. Choose another space.") if (check_winner(newBoard, movesMade) == "X"): p1Wins += 1 if (check_winner(newBoard, movesMade) == "O"): p2Wins += 1 display_board(newBoard) inputChecker = True while (inputChecker == True): try: userAns = input("Would you like to play again? (yes/no): ") if (userAns.upper() == "YES"): inputChecker = False elif (userAns.upper() == "NO"): inputChecker = False keepRunning = False else: print("Invalid input, type either \"yes\" or \"no\". Try again.") except: print("Invalid input. Try again.") print() print("Wins for", player1, ":", p1Wins) print("Wins for", player2, ":", p2Wins)
ca7bdb2f3ff170e59265deca1e3d4e094adcfd10
computingForSocialScience/cfss-homework-KTCO
/Assignment5/fetchArtist.py
1,025
3.78125
4
import sys import requests import csv def fetchArtistId(name): """Using the Spotify API search method, take a string that is the artist's name, and return a Spotify artist ID. """ url = "https://api.spotify.com/v1/search?q="+name+"&type=artist" src = requests.get(url) id_data = src.json() ID = id_data['artists']['items'][0]['id'] return ID def fetchArtistInfo(artist_id): """Using the Spotify API, takes a string representing the id and ` returns a dictionary including the keys 'followers', 'genres', 'id', 'name', and 'popularity'. """ artists_dict = {} url = "https://api.spotify.com/v1/artists/"+artist_id src = requests.get(url) artist_data = src.json() artists_dict['followers'] = artist_data['followers']['total'] artists_dict['genres'] = artist_data['genres'] artists_dict['id'] = artist_data['id'] artists_dict['name'] = artist_data['name'] artists_dict['popularity'] = artist_data['popularity'] return artists_dict
2537ab826a6fba1c6a89ecc846ef7047d068236e
Padmabala/Leetcode_MonthlyChallenges
/Leetcode_JuneChallenge/12_InsertDeleteGetRandom.py
156
3.625
4
h={} j=['a','b','c','d','a'] s=[] for i in range(len(j)): if j[i] not in h: h[i]=j[i] s.append(i) print(h) print(s) a=[*h.keys()]x print(a)
ac83bb61b90b1feae8cf9e228e929c2ce1222f65
mertlsarac/Numeric-Analysis
/Graphic.py
1,177
4.21875
4
print("---Graphical Method---") def calculateEq(l, x): res = 0 degree = len(l) - 1 for i in l: res += pow(x, degree) * i degree -= 1 return res #inputs coefficients = [float(input("Enter the coefficient of the %d. degree of the equation(x^%d): " % (i, i))) for i in range(int(input("Enter the max degree: ")), -1, -1)] print() tmp_x = float(input("Enter the starting value(x0): ")) delta_x = float(input("delta_x: ")) tolerance = float(input("Tolerance(Epsilon): ")) l = [0, 0] k = [tmp_x] tmp = l[-2] input("Press any key to find root of the equation via Graphical Method.") print("---\n") while abs(tmp) > tolerance or tmp == 0: while l[-1] * l[-2] >= 0: print("delta_x :", delta_x) l.append(calculateEq(coefficients, k[-1])) print("Results of the equation :", l[2:]) print("x value :", k[-len(l) + 2:]) k.append(k[-1] + delta_x) tmp = abs(l[-1] - l[-2]) print("\n") if abs(tmp) > tolerance or tmp == 0: print("---") delta_x = delta_x / 2 print("New delta_x :", delta_x) l = [0, 0] k = k[:-2] print("\n") print("x_root :", k[-3])
a472eb4b8e5c724db0aff398a1003197200e5605
thejosmeister/Advent-of-code-2019
/Day14pt2.py
6,330
3.625
4
# Day 14 pt2 # Did this after about 3 days of thinking. Eventually went with finding the average amount of ore required for 1000 fuel. # Once you find the average you can find the remaing ore from the trillion and run the make_ingredient alg until it has been used up. # The initial fuel made will require more ore as there are no remainders of products. # A sample of 10 iterations produced an average that gave me an answer too high (3849044). # A smaple of 100 iteratrions was more successful giving me the right answer (3848998). # The code below is left in the state I used to find the fuel made from the remaining ore. import time # Open file and remove \n stuff with open("Inputs/day14Input.txt") as f: list_of_recepies = f.readlines() list_of_recepies = [x.strip() for x in list_of_recepies] dict_of_amounts = {} amount_made = {} total_ore = 0 made_temp = 0 # create a tree of these class Ingredient: def __init__(self, primary: str, no_produced: int, list_of_ingreds, list_of_numbers): self.primary = primary self.no_produced = no_produced self.list_of_ingreds = list_of_ingreds self.list_of_numbers = list_of_numbers def create_ingredient(input_string: str) -> Ingredient: global dict_of_amounts ingred_name = pull_out_word(input_string) dict_of_amounts[ingred_name] = 0 amount_made[ingred_name] = 0 #find num created num = 0 for recepie in list_of_recepies: if recepie[-len(ingred_name):] == ingred_name: num = pull_out_number(recepie.split(">")[1]) return Ingredient(pull_out_word(input_string), num, find_children_create_ingreds(ingred_name), find_children_numbers(ingred_name)) def find_children_numbers(ingredient_name: str) -> list: output = [] if ingredient_name == "ORE": return output for recepie in list_of_recepies: if recepie[-len(ingredient_name):] == ingredient_name: component = recepie.split("=")[0] split_recepie = component.split(",") for part in split_recepie: output.append(pull_out_number(part)) return output def pull_out_number(input_string: str) -> int: output = "" for letter in input_string: if letter.isnumeric(): output = output + letter return int(output) def pull_out_word(input_string: str) -> int: output = "" for letter in input_string: if letter.isalpha(): output = output + letter return output def find_children_create_ingreds(ingredient_name: str) -> list: output = [] if ingredient_name == "ORE": return output for recepie in list_of_recepies: if recepie[-len(ingredient_name):] == ingredient_name: component = recepie.split("=")[0] split_recepie = component.split(",") for part in split_recepie: output.append(create_ingredient(part)) return output # Sets up map of ingredients that will be iterated over fuel_ingred = create_ingredient("1 FUEL") def make_ingredient(ingred: Ingredient) -> int: global dict_of_amounts global total_ore made_temp = 0 #print("making: " + ingred.primary) #print(dict_of_amounts) for i in range(len(ingred.list_of_ingreds)): #print("state: " + str(i)) if ingred.list_of_ingreds[i].primary == "ORE": total_ore = total_ore + ingred.list_of_numbers[i] amount_made[ingred.primary] = amount_made[ingred.primary] + ingred.no_produced return ingred.no_produced else: #print("name " + str(ingred.list_of_ingreds[i].primary) + ", number req: " + str(ingred.list_of_numbers[i])) made_temp = 0 while made_temp + dict_of_amounts[ingred.list_of_ingreds[i].primary] < ingred.list_of_numbers[i]: made_temp = made_temp + make_ingredient(ingred.list_of_ingreds[i]) amount_made[ingred.list_of_ingreds[i].primary] = amount_made[ingred.list_of_ingreds[i].primary] + made_temp dict_of_amounts[ingred.list_of_ingreds[i].primary] = dict_of_amounts[ingred.list_of_ingreds[i].primary] + made_temp - ingred.list_of_numbers[i] return ingred.no_produced thingy = True i = 0 fuel_made = 0 previous_state = 0 set_of_remainders = set() list_of_remainders = [] list_of_total_ores = [] list_of_fuel_made = [] def find_in_list(dict_of_amounts: str) -> int: for idd in range(len(list_of_remainders)): if list_of_remainders[i] == dict_of_amounts: return idd return -1 tic = time.perf_counter() times = 0 # Make first ingred to populate a set of remainders. make_ingredient(fuel_ingred) # Sample of the dictionary containing amounts after producing 1 fuel. # dict_of_amounts = {'FUEL': 0, 'MHJMX': 6, 'LTHFW': 8, 'SWZCB': 2, 'GDNG': 4, 'LBHQ': 2, 'CXNM': 2, 'ZNPRL': 6, 'ORE': 0, 'PDVR': 5, 'TZMWG': 2, 'QZQLZ': 0, 'VFXHC': 0, 'MJQS': 1, 'HMRGM': 0, 'XPTXL': 4, 'HNCDS': 0, 'SMSB': 0, 'MTQCB': 2, 'FWZN': 1, 'PDCV': 4, 'PFQRG': 1, 'XVNL': 8, 'PBMPL': 1, 'PRXT': 1, 'FDVH': 1, 'THRVR': 3, 'XHPHR': 0, 'GSMP': 2, 'NWNSH': 1, 'JRZXM': 0, 'NSVJL': 4, 'RNMKC': 0, 'MHBZ': 2, 'HJVN': 0, 'WPFP': 1, 'XRDN': 0, 'VPSDV': 1, 'MRVFT': 5, 'NTJZH': 3, 'JMWQG': 6, 'XHQDX': 0, 'ZFCD': 0, 'SVSTJ': 1, 'HJTD': 5, 'LDHX': 3, 'ZBNCP': 2, 'VJTFJ': 1, 'LBQB': 6, 'DLWT': 0, 'ZXMGK': 0, 'JTXWX': 0, 'XSFVQ': 5, 'BNMWF': 3, 'PBNSF': 0, 'MJCLX': 0, 'QWRB': 8, 'SVNVJ': 4, 'JCHP': 0, 'GHVN': 0, 'QZNCK': 1} # code to find averages commented out: list_of_total_ores.append(total_ore) # while times < 100: # fuel_made = 0 # total_ore_start = total_ore while total_ore < 259681800: fuel_made = fuel_made + make_ingredient(fuel_ingred) print(fuel_made) # list_of_total_ores.append(total_ore - total_ore_start) # times = times + 1 toc = time.perf_counter() print("time taken " + str(toc - tic)) # summ = 0 # for ore in list_of_total_ores[1:]: # summ = summ + ore # print("ans = " + str(summ/len(list_of_total_ores[1:]))) print(total_ore)
bbf0d8537680ed4cb6701c36f66989a73ea0f085
HenryHo6688/Python
/cu2l.py
134
3.96875
4
#!/usr/bin/python3.6 u = input("Enter an uppercase letter:") du=ord(u) print ("The lower case letter you entered is:",chr(du + 32))
5e0dba0d39f0b30b095817b8ebed695f6152d9ba
ednayssell7/bedu_14_nov_1stsession
/e03_ciclo_for.py
65
3.734375
4
list = [1, 2, 3, 4] for element in list: print(element)
36522d898632827853a798e0bb53584d0981595b
gitter-badger/Printing-Pattern-Programs
/Python Pattern Programs/Symbol Patterns/Pattern 78.py
251
4.15625
4
for row in range(0, 6): for col in range(0, 7): if (row == 0 and col % 3 != 0) or (row == 1 and col % 3 == 0) or (row - col == 2)or(row + col == 8): print("*",end=" ") else: print(" ",end=" ") print(" ")
da40f7972c1b9a4086e6aa405aa61f35b5098558
mumana98/CS-313E-Elements-Of-Software-Design
/Boxes.py
3,567
3.796875
4
# File: Boxes.py # Description: given the dimensions (length width and height) of 20 boxes, # find the largest combination of boxes that can fit inside of each other # Student Name: Matthew Umana # Student UT EID: msu245 # Course Name: CS 313E # Unique Number: 50300 # Date Created: 03/07/20 # Date Last Modified: 03/09/20 # generates all subsets of boxes and stores them in all_box_subsets # box_list is a list of boxes that have already been sorted # sub_set is a list that is the current subset of boxes # idx is an index in the list box_list # all_box_subsets is a 3-D list that has all the subset of boxes def sub_sets_boxes(box_list, sub_set, idx, all_box_subsets): hi = len(box_list) if idx == hi: all_box_subsets.append(sub_set) return all_box_subsets else: c = sub_set[:] sub_set.append(box_list[idx]) sub_sets_boxes(box_list, sub_set, idx + 1, all_box_subsets) sub_sets_boxes(box_list, c, idx + 1, all_box_subsets) # goes through all the subset of boxes and only stores the # largest subsets that nest in the 3-D list all_nesting_boxes # largest_size keeps track what the largest subset is def largest_nesting_subsets (all_box_subsets, largest_size, all_nesting_boxes): largest_size = 0 nesting_list = [] for subset in all_box_subsets: count = 0 is_long = False for box in range(0, len(subset)-1): if does_fit(subset[box], subset[box+1]) == False: is_long = False break else: count += 1 is_long = True if largest_size < count: largest_size = count if is_long: nesting_list.append(subset) for sub in nesting_list: if len(sub) > largest_size: all_nesting_boxes.append(sub) return all_nesting_boxes # returns True if box1 fits inside box2 def does_fit (box1, box2): return (box1[0] < box2[0] and box1[1] < box2[1] and box1[2] < box2[2]) def main(): # open the file for reading in_file = open ("boxes.txt", "r") # read the number of boxes line = in_file.readline() line = line.strip() num_boxes = int (line) # create an empty list for the boxes box_list = [] # read the boxes from the file for i in range (num_boxes): line = in_file.readline() line = line.strip() box = line.split() for j in range (len(box)): box[j] = int (box[j]) box.sort() box_list.append (box) # close the file in_file.close() # sort the box list box_list.sort() # create an empty list to hold all subset of boxes all_box_subsets = [] # create a list to hold a single subset of boxes sub_set = [] # generate all subsets of boxes and store them in all_box_subsets sub_sets_boxes(box_list, sub_set, 0, all_box_subsets) # initialize the size of the largest sub-set of nesting boxes largest_size = 0 # create a list to hold the largest subsets of nesting boxes all_nesting_boxes = [] # go through all the subset of boxes and only store the # largest subsets that nest in all_nesting_boxes largest_nesting_subsets (all_box_subsets, largest_size, all_nesting_boxes) # print all the largest subset of boxes print("Largest Subset of Nesting Boxes") for sub in all_nesting_boxes: for i in range(len(sub)): print(sub[i]) print() if __name__ == "__main__": main()