blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d4940aba594178c67a075c8d419c4f9923ee3ac2
siddharth15121998/python-programs
/squareroot.py
173
3.78125
4
n1=int(input("enter a number:")) n2=int(input("enter a number:")) n3=int(input("enter a number:")) list1=[n1,n2,n3] def sqr(a): return a**2 print(list(map(sqr,list1)))
aeb13848fcff9e22d1b541d559c3dd76198b8aeb
ResearchInMotion/CloudForce-Python-
/UnboxQuestions/sample.py
615
3.875
4
emp = [] # emp = [[],[][,[]] emp = [['id', 'name', 'Gender', "Sal"]] f = True while f: ch = input('do you want to add datat then press y and exist press n:') if ch == 'n': f = False elif ch == 'y': row = [] i = input('enter id :') name = input('enter name :') g = input('enter gender :') sal = input('enter sal :') row.append(i) row.append(name) row.append(g) row.append(sal) emp.append(row) else: print('invalid input, please choice from given option.') # print(emp) for r in emp: print(r)
fb303846e73f0a2ab5be9110c2c45c4b23681aa5
ParkerCS/ch15-searches-bernhardtjj
/ch15Lab.py
1,452
4.15625
4
""" Complete the chapter lab at http://programarcadegames.com/index.php?chapter=lab_spell_check """ import re # This function takes in a file of text and returns # a list of words in the file. def split_file(file): return [x for line in file for x in re.findall('[A-Za-z]+(?:\'[A-Za-z]+)?', line.strip())] dict_words = split_file(open("dictionary.txt")) def split_file(file): # this returns it in lines return [re.findall('[A-Za-z]+(?:\'[A-Za-z]+)?', line.strip()) for line in file] alice = split_file(open("AliceInWonderLand200.txt")) print("--- Linear Search ---") for n in range(len(alice)): for word in alice[n]: i = 0 while i < len(dict_words) and dict_words[i] != word.upper(): i += 1 if i >= len(dict_words): print("Line", n + 1, "possible misspelled word:", word) print("--- Binary Search ---") for i in range(len(alice)): for word in alice[i]: lower_bound = 0 upper_bound = len(dict_words) - 1 found = False while lower_bound <= upper_bound and not found: target = (lower_bound + upper_bound) // 2 if dict_words[target] < word.upper(): lower_bound = target + 1 elif dict_words[target] > word.upper(): upper_bound = target - 1 else: found = True if not found: print("Line", i + 1, "possible misspelled word:", word)
a2cf7d8969902bbbd93799a64ad7cbd863c1f4e5
ThomasCarstens/SelfStudyIRM
/Data_structures/graph.py
4,049
3.546875
4
import numpy as np import math import test import matplotlib.pyplot as plt from collections import deque graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']} ##file:///home/txa/SelfStudyIRM/Data%20Structure%20and%20Algorithms%20--%20Ouch.pdf ##COMPLEXITY: https://www.datacamp.com/community/tutorials/analyzing-complexity-code-python ##COMPLEXITY: https://towardsdatascience.com/understanding-time-complexity-with-python-examples-2bda6e8158a7 ##COMP: BASICS https://stackabuse.com/big-o-notation-and-algorithm-analysis-with-python-examples/ ##DIFF. FIB SEQ https://www.educative.io/edpresso/how-to-implement-the-fibonacci-sequence-in-python ##Adapted from: https://www.python.org/doc/essays/graphs/ #function to find a path between two nodes: return a list of nodes comprising the path. def find_path(graph, start, end, path=[]): #path default not traversed path = path + [start] #creates a new list. if start == end: return path #avoiding cycles. if not start in graph: #if no path is found. return None for node in graph[start]: if node not in path: newpath = find_path(graph, node, end, path) if newpath: return newpath return None def find_all_paths(graph, start, end, path=[]): #path default not traversed path = path + [start] #creates a new list. if start == end: return [path] #avoiding cycles. if not start in graph: #if no path is found. return [] paths = [] for node in graph[start]: if node not in path: newpaths = find_all_paths(graph, node, end, path) for newpath in newpaths: paths.append(newpath) return paths def find_shortest_path(graph, start, end, path=[]): #path default not traversed path = path + [start] #creates a new list. if start == end: return path #MUST FIND SHORTEST if not start in graph: #if no path is found. return None shortest = None for node in graph[start]: if node not in path: newpath = find_shortest_path(graph, node, end, path) if newpath: if not shortest or len(newpath)<len(shortest): shortest = newpath return shortest def bfs_shortest_path(graph, start, end): dist = {start: [start]} q = deque(start) while len(q): at = q.popleft() for next in graph[at]: if next not in dist: dist[next] = [dist[at], next] q.append(next) return dist.get(end) ##LIST THE EDGES def generate_edges(graph): edges = [] for node in graph: for neighbour in graph[node]: edges.append((node, neighbour)) #print(edges) return edges print(generate_edges(graph)) #sample run: print(find_path(graph, 'A', 'D')) print(find_all_paths(graph, 'A', 'D')) print(find_shortest_path(graph, 'A', 'D')) print(bfs_shortest_path(graph, 'A', 'D')) class Node: def __init__(self, id): self.id = id #id per node. self.connections = [] def print_connections(self): for conn in self.connections: print(f'{self.id}->{conn.id}') class Graph: def __init__(self): self.nodes = [] self.connections = [] def is_connected(self, n1: Node, n2: Node): for conn in self.connections: if n1 in conn and n2 in conn: return True return False def connect(self, n1: Node, n2: Node): self.connections.append([n1, n2]) #def disconnect()... #more adapted from https://www.python-course.eu/graphs_python.php import networkx as nx G = nx.Graph() G.add_edge('A', 'B', weight=4) G.add_edge('B', 'D', weight=2) G.add_edge('A', 'C', weight=3) G.add_edge('C', 'D', weight=4) nx.shortest_path(G, 'A', 'D', weight='weight') nx.draw(G, with_labels=True, font_weight='bold') #nx.draw_shell(G, nlist=[range(5, 10), range(5)], with_labels=True, font_weight='bold') plt.show()
2333cb5815961ac0f5416da4a6ee0de8d5311d5c
roshan2M/edX--mitX--introduction-to-computer-science-and-programming-with-python
/Week 2/Lecture 4 - Functions/In-Video Problems/Lec4.3Slide1.py
504
4.6875
5
# Lecture 4.3, slide 1 # Here, we are taking a number x and raising it to the power p via successive multiplication. # Takes the values of the base and exponent from the user. x = float(raw_input('Enter a number: ')) p = int(raw_input('Enter an integer power: ')) # Sets an intermediate result variable to find the result. result = 1 # Gives the result every time an iteration is completed. for i in range(p): result *= x print ('Iteration: ' + str(i + 1) + '; Current Result: ' + str(result))
e79184bcd4f378d666baa19eecd1ccd0379772e6
Artarin/Python-Trashbox
/test_new_commands.py
496
3.671875
4
UserInfo = input('введите известные данные пользователя без пробелов: ') UserInversed = UserInfo.swapcase() UserInfo+=UserInversed UserInfo= ''.join(sorted(''.join(set(UserInfo)))) print (UserInfo) FullAlphabet = '0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()' print (set(FullAlphabet)) Difference = ''.join(set (FullAlphabet) - set(UserInfo)) print (Difference) Alphabet = UserInfo + ''.join(sorted(Difference)) print (Alphabet)
8af22689444e7c09a17923e60c314da2129fe7c6
aparecida-gui/learning-python
/exercicios/bolaMagica.py
845
3.984375
4
import random print('Seja bem vindo a bola magica') print() bolaMagica = ['sim', 'provavelmente sim', 'não', 'sem duvida que sim', 'talvez', 'concentre-se e pergunte novamente', 'estou sentindo que sim', 'não crie espectativas'] continuaJogando = True while continuaJogando == True: print('Digite sua pergunta para a bola magica') pergunta = input() respostaDaBolaMagica = random.choice(bolaMagica) print('>>>>>> resposta da bola magica: ', respostaDaBolaMagica) print() print('Voce deseja fazer outra pergunta para a bola magica?') print("Digite Sim ou Não") suaResposta = input() print() suaResposta = suaResposta.upper() if suaResposta == 'SIM' or suaResposta == 'S': continuaJogando = True else: print('Fim da consulta') continuaJogando = False
d7c06414f2470076512542745430578f703d26a4
ssolanki/algorithms
/c files/paran.py
945
3.84375
4
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def isPairMatched( ch1, ch2): if (ch1 == '(' and ch2 == ')'): return 1 else: return 0 def balanceParenthesis(exp): i = 0 stack = Stack() str = "" while (i< len(exp)): if (exp[i] == '('): stack.push(exp[i]) str += exp[i] if (exp[i] == ')'): if (stack.isEmpty()): # print "stack empty" str = '(' + str + exp[i] else: elem = stack.pop() print "3" str = str + exp[i] i+=1 while (not stack.isEmpty()): str = str + ')' stack.pop() return str exp = "((())((" print balanceParenthesis(exp)
1d7fc15007ef57b03a3f836d42f31d0e33a75018
wjpe/EjemplosPython-Cisco
/ej20.py
1,068
3.875
4
# bloques = int(input("Ingrese el número de bloques:")) # # # # Escribe tu código aquí. # # # altura = 0 # base = 0 # while bloques > 0: # if base == 0: # base = base +1 # altura = altura +1 # else: # if bloques > base: # base = base + 1 # bloques = bloques - base # altura = altura+1 # print ("base",base) # print("La altura de la pirámide:", altura) bloques = int(input("Ingrese el número de bloques:")) capa_superior = 0 altura = 0 while bloques > 0: if capa_superior == 0: capa_superior += 1 altura += 1 bloques -= 1 else: if bloques <= capa_superior: #altura = altura #print (altura) break #return else: capa_superior += 1 bloques = bloques - (altura + 1) print(f"capa superior{capa_superior}, bloque {bloques}") altura += 1 # # Escribe tu código aquí. # print("La altura de la pirámide:", altura)
2476406f27835f3c56e17116093bdbfc8409e488
rafalcode/pwtables
/simpmpl0.py
434
3.78125
4
#!/usr/bin/env python import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 2*np.pi, 400) y = np.sin(x**2) # Creates just a figure and only one subplot fig, ax = plt.subplots() ax.plot(x, y) ax.set_title('Simple plot') # Creates two subplots and unpacks the output array immediately # f, (ax1, ax2) = plt.subplots(1, 2, sharey=True) # ax1.plot(x, y) # ax1.set_title('Sharing Y axis') # ax2.scatter(x, y) plt.show()
0c40990cb123b2649165d295b5788f648c0a79b4
fatihaydnn/Python
/Barbut.py
2,123
3.953125
4
# Oyuncu classı oluşturun # Her oyuncunun bakiyesi olacak. # Para yatırma fonksiyonu olacak # Zar at fonksiyonu olacak # Bilgisayar da yatırılan parayı karşılayacak # Yüksek zar atan tüm parayı alacak from random import randint as r import time class Oyuncu: bakiye = 500 def __init__(self, isim): self.name = isim def zar_at(self): return r(1, 6) def para_yatir(self, miktar): if miktar > self.bakiye: print("Yeterli bakiyeniz yoktur") return False elif miktar < 50: print("En az 50 kredi girmelisiniz") return False self.bakiye -= miktar return miktar insan = Oyuncu("Fatih") bilgisayar = Oyuncu("Robot") havuz = 0 def Cikis(): print("Oyundan Çıkılıyor...") time.sleep(3) while True: oyuncu_miktari = int(input("Lütfen bir miktar giriniz")) if insan.para_yatir(oyuncu_miktari) == False: continue havuz += oyuncu_miktari bilgisayar_miktari = bilgisayar.para_yatir(r(50, bilgisayar.bakiye)) print(bilgisayar.name, bilgisayar_miktari,"kadar para yatırdı") havuz += bilgisayar_miktari while True: x = insan.zar_at() y = bilgisayar.zar_at() if x > y: insan.bakiye += havuz print("Oyuncu zarı : {}, robot zarı {}, Toplam Bakiyeniz: {}, Kazanılan Miktar {}, oyuncu kazandı!".format(x, y, insan.bakiye, havuz)) havuz = 0 break elif x < y: bilgisayar.bakiye += havuz print( "Oyuncu zarı : {}, bilgisayar zarı {}, Robot Bakiye: {}, Kazanılan Miktar {}, robot kazandı!".format(x, y, bilgisayar.bakiye, havuz)) havuz = 0 break elif x == y: print("Berabere... Tekrar Zar Atılıyor...") continue if insan.bakiye < 50: print("Kaybettiniz") Cikis() elif bilgisayar.bakiye < 50: print("Kazandınız. Toplam Bakiyeniz {}".format(insan.bakiye)) Cikis()
74dbb6db8dc5fcd6727bf1179ffd673db76a6ad0
sstadick/pygrep
/pygrep/pygrep.py
3,464
3.953125
4
#!/usr/bin/env python # Skip Loop # Match Loop # Shift # class BoyerMooreSearch: """Boyer Moore search implememtation""" from string class BoyerMoyer: """ Good general pupose searching algorithm for natural language. made to behave like fgrep -i """ def __init__(self, pattern: str) -> str: self.pattern = pattern.lower() self.patternLen = len(pattern) self.badCharacterTable = self.preProcessBadCharacters() self.goodSuffixTable = self.preProcessGoodSuffix() def preProcessBadCharacters(self) -> dict: """Create the lookup for bad character matches Value = len(pattern) - index(character) - 1 Returns: table- {character: value} """ pattern = list(self.pattern) patternLen = len(pattern) table = {} for index, character in enumerate(pattern): if index < patternLen - 1: # assign value based on rightmost character table[character] = patternLen - index - 1 elif (index == patternLen - 1) and (character not in table.keys()): # Unless it's the last character, then it prefers its leftmost value table[character] = patternLen table['*'] = patternLen # any letter not in the pattern return table def preProcessGoodSuffix(self): """ """ pass def badCharacterRule(self, index: int, mismatch: str) -> int: """Bad character rule: Upon mismatch, skip alignments util (a) mismatch becomes a match, or (b) P moves past mismatched character Args: index- The index at which the mismatch occured mismatch- the character from the text that is the mismatch Returns: skip- The distance to skip down the text """ pass def goodSuffixRule(self): """Good Suffix rule: let t = substring matched by inner loop; skip until (a) there are no mismatches between P an t or (b) P moves past t Args: index- The index at which the mimatch occured Returns: skip- The distance to skip down the text """ pass def gaililRule(self): """ If a match was found, try to move on assumtion of perodicity """ pass # When there is a mismatch, try both rules, use the one that gives the biggest shift def search(self, text: str) -> str: if len(self.pattern) == 0 or len(text) == 0 or len(text) < len(self.pattern): return [] matches = [] i = 0 # place tracking variable while i < len(text) - len(self.pattern) + 1: shift = 1 misMatched = False for j in range(self.patternLen-1, -1, -1): if not self.pattern[j] == text[i + j]: skipBC = self.badCharacterRule(j, t[i + j]) skipGS = self.goodSuffixRule(j) shift = max(shift, skipBC, skipGS) misMatched = True break if not misMatched: matches.append(i) skipMatched = self.gaililRule() shift = max(shift, skipMatched) i += shift return matches if __name__ == '__main__': pattern = 'tooth' b = BoyerMoyer(pattern) print(b.badCharacterTable) print(b.bad_character_table()) # print(b.goodSuffixTable)
2fefb0b82b86c6486b1f78c24ace02104c325602
aumc-bscs5th/Lab-Submissions
/Lab Test -17 Nov 2017/153193/Q4.py
499
3.578125
4
inputString = str(input("Please type a sentence: ")) a = "a" A = "A" e = "e" E = "E" i = "i" I = "I" o = "o" O = "O" u = "u" U = "U" acount = 0 ecount = 0 icount = 0 ocount = 0 ucount = 0 if A or a in stri : acount = acount + 1 if E or e in stri : ecount = ecount + 1 if I or i in stri : icount = icount + 1 if o or O in stri : ocount = ocount + 1 if u or U in stri : ucount = ucount + 1 print(acount + ecount + icount + ocount + ucount)
410a8c324506d0fc441a3ebcac20753c9dd9277a
lamhuynhb779/xla_ud
/object_detection/myobject.py
493
3.53125
4
class MyObject: def __init__(self): self.id = 0 self.name = "" self.prob = 0 print('Khoi tao doi tuong object') def getId(self): return self.id def setId(self, myid): self.id = myid def getTenDoiTuong(self): return self.name def setTenDoiTuong(self, name): self.name = name def getXacSuat(self): return self.prob def setXacSuat(self, prob): self.prob = prob def toString(self): print("id: %s, tendoituong: %s, xacsuat: %s" %(self.id, self.name, self.prob))
dbdcbed435a71d33a8d13f0810ea908110731e47
thormeier-fhnw-repos/ip619bb-i4ds02-audio-text-alignment
/lib/test/test_utils/TempFile.py
976
3.734375
4
from tempfile import NamedTemporaryFile import os class TempFile: """ Temporary file for convenience in tests that include opening and reading files. """ def __init__(self, content: str) -> None: """ Initializes a temporary file :param content: File content """ with NamedTemporaryFile(delete=False, mode="w", encoding="utf-8") as f: f.write(content) f.flush() f.close() self.f = f.name def __del__(self) -> None: """ Deconstructor to make sure the file is deleted :return: None """ self.delete() def get_name(self) -> str: """ Returns the temp files name :return: File name """ return self.f def delete(self) -> None: """ Delete the file from disk if it exists. :return: """ if os.path.exists(self.f): os.unlink(self.f)
74f34766170c574b594a245cbc51d67677bf830c
estebango/coding-skills-sample-code
/coding205-writing-file-ga/write-file.py
1,924
3.59375
4
# Most basic example of writing to a file # amwhaley@cisco.com # twitter: @mandywhaley # http://developer.cisco.com # http://developer.cisco.com/learning # Jan 15, 2015 # * THIS SAMPLE APPLICATION AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY # * OF ANY KIND BY CISCO, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED # * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR # * PURPOSE, NONINFRINGEMENT, SATISFACTORY QUALITY OR ARISING FROM A COURSE OF # * DEALING, LAW, USAGE, OR TRADE PRACTICE. CISCO TAKES NO RESPONSIBILITY # * REGARDING ITS USAGE IN AN APPLICATION, AND IT IS PRESENTED ONLY AS AN # * EXAMPLE. THE SAMPLE CODE HAS NOT BEEN THOROUGHLY TESTED AND IS PROVIDED AS AN # * EXAMPLE ONLY, THEREFORE CISCO DOES NOT GUARANTEE OR MAKE ANY REPRESENTATIONS # * REGARDING ITS RELIABILITY, SERVICEABILITY, OR FUNCTION. IN NO EVENT DOES # * CISCO WARRANT THAT THE SOFTWARE IS ERROR FREE OR THAT CUSTOMER WILL BE ABLE # * TO OPERATE THE SOFTWARE WITHOUT PROBLEMS OR INTERRUPTIONS. NOR DOES CISCO # * WARRANT THAT THE SOFTWARE OR ANY EQUIPMENT ON WHICH THE SOFTWARE IS USED WILL # * BE FREE OF VULNERABILITY TO INTRUSION OR ATTACK. THIS SAMPLE APPLICATION IS # * NOT SUPPORTED BY CISCO IN ANY MANNER. CISCO DOES NOT ASSUME ANY LIABILITY # * ARISING FROM THE USE OF THE APPLICATION. FURTHERMORE, IN NO EVENT SHALL CISCO # * OR ITS SUPPLIERS BE LIABLE FOR ANY INCIDENTAL OR CONSEQUENTIAL DAMAGES, LOST # * PROFITS, OR LOST DATA, OR ANY OTHER INDIRECT DAMAGES EVEN IF CISCO OR ITS # * SUPPLIERS HAVE BEEN INFORMED OF THE POSSIBILITY THEREOF.--> # Use the open method to open a file # Pass in the name of the file to open and mode. 'r' for read only 'w' if you want to write to the file # To write to this file we will use "w" # If the file does not exist, it will be created. my_file_object = open("my-new-file.txt", "w") my_file_object.write("The grey penguin flies at noon.") my_file_object.close()
09ae5f6922ea3b9a61adeaf7226fcd1c7e61f134
neethu567/examplePyth
/dict.py
122
3.53125
4
d={"name":"neethu","age":33,"subjet":['python','maths','physics']} print(d.keys()) print(d.values()) print(d["subjet"][1])
9cafb5b8bf7c088631179ba1f80522d25d2a1205
khangvtran/SeatingChart_OOP
/chart.py
4,214
3.625
4
from seat import * class Chart(): def __init__(self): self._chart = [ ] # initate the List (of lists) keepReading = True while(keepReading): try: fileName = input("Enter a file name or hit Enter to use lab7input2.txt: ") if fileName == "" : fileName = "lab7input2.txt" with open(fileName, "r") as inFile: firstLine = inFile.readline().split() #Process the 3 prices here premiumPrice = int(firstLine[0]) choicePrice = int(firstLine[1]) regularPrice = int(firstLine[2]) for line in inFile: # Process each line after the first one rowList = [] for price in line.split(): # Process each price in the line price = int(price) # create seat object appropriately to each price if price == premiumPrice : rowList.append(Premium(price)) elif price == choicePrice : rowList.append(Choice(price)) else : rowList.append(Choice(price)) self._chart.append(rowList) # apend the list of object into seatingChart #print(rowList, end = " ") #print() # PRINT METHOD GOES HERE self.print() keepReading = False except FileNotFoundError as e: print("Can't open" + str(e)) print() keepReading = True def print(self): numRow = len(self._chart) numCol = len(self._chart[0]) print("Price Chart".center((numCol+1)*5)) print("Column".center((numCol+1)*5)) # print 'Column' print(" ", end="") for i in range(1,numCol+1) : print(" ",i, end="") print( ) print("Row ", end="") # Print the Row headers for i in range(1,numCol+1) : print("=====", end="") print() for row in range(numRow): print(str(row+1) + " | ", end = "") for col in range(numCol): print("%5s" %(self._chart[row][col]), end = "") print() def buySeat(self): takenSeat = [ ] seatCount = 0 totalPrice = 0 print("Available seats are shown with price") keepPrompting = True while keepPrompting: seat = input("Enter row,col for seat %d or enter 0 to end: " %(seatCount+1)) if(seat == "0"): keepPrompting = False else: try: #print("abc") seat = seat.split(",") row = int(seat[0]) - 1 col = int(seat[1]) - 1 if row < 0 or col < 0 : raise IndexError if self._chart[row][col].isTaken(): print("Sorry, that seat is not available.") else: takenSeat.append((row+1, col+1)) seatCount += 1; totalPrice += self._chart[row][col].getPrice() self._chart[row][col].setTaken() #print(totalPrice) except ValueError: print("Row and column must be numbers") except IndexError: print("Invalid row or column") # print price print("Your total: $%d" %totalPrice) # print location print("Your %d seat(s) at " %(seatCount), end = "") for seat in takenSeat: print(seat, end = " ") print("are marked with 'X'") #print updated chart self.print() """ #### Testing Area #### chartTest = Chart() chartTest.buySeat() """
c9d46802f7b8b8538cbedfa9bb8ea54030c84992
getChan/algorithm
/greedy/1339_단어수학.py
210
3.625
4
from collections import defaultdict n = int(input()) # 자릿수의 빈도를 구하자 alphabet = defaultdict([0 for _ in range(10)]) for _ in range(n): word = input() for ch in word[::-1]:
76b7d8c8f0e2c14045b70bb0c843c748398080f2
MintuKrishnan/subrahmanyam-batch
/python_lectures/1. introduction/2.typecast.py
459
4.6875
5
""" This code will show you how to do typecasting Whenever you want a specific type to be converted to another type we say it as typecasting it is simple ;) just wrap data in int() or str() or float() >>> a = "5" a = int("5") """ print("Typecasting from str to int") a = "5" print("before: ", type(a)) a = int("5") print("after:", type(a)) print("Typecasting from int to str") a = 5 print("before: ", type(a)) a = str(a) print("after:", type(a))
ce85f79aecc95c09bc0f410cc498af41af6c32cc
JamCh01/porter-stemmer
/porter-stemmer/api.py
6,424
3.828125
4
from static import static class Stemmer(object): def __init__(self): self.vowels = 'aeiou' self.cvc_ignore = 'wxy' def is_consonant(self, letter: str) -> bool: # 判断字母是否为辅音 if letter not in self.vowels: return True return False def is_vowel(self, letter: str) -> bool: # 判断字母是否为元音 return not self.is_consonant(letter=letter) def consonant_in_word_by_index(self, word: str, index: int) -> bool: # 判断单词第index位是否为辅音 letter = word[index] if self.is_consonant(letter=letter): if letter == 'y' and self.is_consonant(word[index - 1]): return False return True return False def vowel_in_word_by_index(self, word: str, index: int) -> bool: # 判断单词第index位是否为元音 return not self.consonant_in_word_by_index(word=word, index=index) def is_end_with(self, stem: str, letter='s') -> bool: # *s stem词干是否以s结尾 if stem.endswith(letter): return True return False def is_end_with_double_same_consonants(self, stem: str) -> bool: # *d 判断词干以两个相同辅音结尾 if len(stem) < 2: return False if stem[-1] != stem[-2]: return False if not (self.consonant_in_word_by_index(word=stem, index=-1) and self.consonant_in_word_by_index(word=stem, index=-2)): return False return True def vowel_in_word(self, stem: str) -> bool: # *v* 判断词干包含一个元音 for letter in stem: if self.is_vowel(letter=letter): return True return False def get_form(self, word: str) -> str: # 根据word的元音和辅音组成返回VC序列 form = str() for index in range(len(word)): if self.consonant_in_word_by_index(word=word, index=index): if index: if not self.is_end_with(stem=form, letter='C'): form += 'C' else: form += 'C' else: if index: if not self.is_end_with(stem=form, letter='V'): form += 'V' else: form += 'V' return form def get_m_count(self, word: str) -> int: # 获得单词中VC出现的次数 return self.get_form(word=word).count('VC') def cvc(self, word: str) -> bool: # *o - 判断词干是否以以cvc的形式结束, 但是第二个C(辅音)不是 W, X 或者Y if len(word) < 3: return False if self.consonant_in_word_by_index(word=word, index=-1) and \ self.vowel_in_word_by_index(word=word, index=-2) and \ self.consonant_in_word_by_index(word, index=-3): if word[-1] not in self.cvc_ignore: return True return False return False def replace(self, origin: str, rem: str, rep: str, m=None) -> str: # 将输入的origin单词后缀替换 if m is None: return origin[:origin.rfind(rem)] + rep else: base = origin[:origin.rfind(rem)] if self.get_m_count(word=base) > m: return base + rep else: return origin def stem(self, word: str) -> str: if word.endswith('sses'): word = self.replace(origin=word, rem='sess', rep='ss') elif word.endswith('ies'): word = self.replace(origin=word, rem='ies', rep='i') elif word.endswith('ss'): word = self.replace(origin=word, rem='ss', rep='ss') elif word.endswith('s'): word = self.replace(origin=word, rem='s', rep='') flag = False if word.endswith('eed'): base = word[:word.rfind('edd')] if self.get_m_count(word=base): word = base + 'ee' elif word.endswith('ed'): base = word[:word.rfind('ed')] if self.vowel_in_word(stem=base): word = base flag = True elif word.endswith('ing'): base = word[:word.refind('ing')] if self.vowel_in_word(stem=word): word = base flag = True if flag: if word.endswith( ('at', 'bl', 'iz') ) or self.get_m_count(word=word) == 1 and self.cvc(word=word): word += 'e' elif self.is_end_with_double_same_consonants( stem=word) and not self.is_end_with( stem=word, letter='l') and not self.is_end_with( stem=word, letter='s') and not self.is_end_with( stem=word, letter='z'): word = word[:-1] if word.endswith('y'): base = word[:word.rfind('y')] if self.vowel_in_word(stem=base): word = base + 'i' for x, y in static.step_a.items(): if word.endswith(x): word = self.replace(origin=word, rem=x, rep=y) for x, y in static.step_b.items(): if word.endswith(x): word = self.replace(origin=word, rem=x, rep=y) for x, y in static.step_c.items(): if word.endswith(x): word = self.replace(origin=word, rem=x, rep=y, m=1) if word.endswith('ion'): base = word[:word.rfind('ion')] if self.get_m_count(word=base) > 1 and ( self.is_end_with(stem=base, letter='s') or self.is_end_with(stem=base, letter='t')): word = base else: word = self.replace(origin=word, rem='', rep='', m=1) if word.endswith('e'): base = word[:-1] m_count = self.get_m_count(word=base) if m_count > 1 or (m_count == 1 and not self.cvc(word=base)): word = base if self.get_m_count( word=word) > 1 and self.is_end_with_double_same_consonants( stem=word) and self.is_end_with( stem=word, letter='l'): word = word[:-1] return word
8ea1e4a728d57dad91858a0119a850a832406a0f
carlosbarcelos/CS4341
/astar.py
24,694
3.625
4
# -*- coding: utf-8 -*- ''' A* Link: https://codeshare.io/alobxj a* ref: http://web.mit.edu/eranki/www/tutorials/search/ a* tutorial: http://www.policyalmanac.org/games/aStarTutorial.htm steps: 1) Begin at the starting point A and add it to an “open list” of squares to be considered. The open list is kind of like a shopping list. Right now there is just one item on the list, but we will have more later. It contains squares that might fall along the path you want to take, but maybe not. Basically, this is a list of squares that need to be checked out. 2) Look at all the reachable or walkable squares adjacent to the starting point, ignoring squares with walls, water, or other illegal terrain. Add them to the open list, too. For each of these squares, save point A as its “parent square”. This parent square stuff is important when we want to trace our path. It will be explained more later. 3) Drop the starting square A from your open list, and add it to a “closed list” of squares that you don’t need to look at again for now 4) Drop it from the open list and add it to the closed list. 5) Check all of the adjacent squares. Ignoring those that are on the closed list or unwalkable (terrain with walls, water, or other illegal terrain), add squares to the open list if they are not on the open list already. Make the selected square the “parent” of the new squares. 6) If an adjacent square is already on the open list, check to see if this path to that square is a better one. In other words, check to see if the G score for that square is lower if we use the current square to get there. If not, don’t do anything. On the other hand, if the G cost of the new path is lower, change the parent of the adjacent square to the selected square (in the diagram above, change the direction of the pointer to point at the selected square). Finally, recalculate both the F and G scores of that square. Summary: 1) Add the starting square (or node) to the open list. 2) Repeat the following: a) Look for the lowest F cost square on the open list. We refer to this as the current square. b) Switch it to the closed list. c) For each of the 8 squares adjacent to this current square … If it is not walkable or if it is on the closed list, ignore it. Otherwise do the following. If it isn’t on the open list, add it to the open list. Make the current square the parent of this square. Record the F, G, and H costs of the square. If it is on the open list already, check to see if this path to that square is better, using G cost as the measure. A lower G cost means that this is a better path. If so, change the parent of the square to the current square, and recalculate the G and F scores of the square. If you are keeping your open list sorted by F score, you may need to resort the list to account for the change. d) Stop when you: Add the target square to the closed list, in which case the path has been found (see note below), or Fail to find the target square, and the open list is empty. In this case, there is no path. 3) Save the path. Working backwards from the target square, go from each square to its parent square until you reach the starting square. That is your path. CS 4341: Assignment 1 Carlos Barcelos Justin Myerson Connor Smith Ryan Walsh January 28, 2017 ''' import math #import queue import sys NORTH = 'N' EAST = 'E' SOUTH = 'S' WEST = 'W' RIGHT = "right" LEFT = "left" TRUE = 1 FALSE = 0 UNNAV = 1 START = 2 GOAL = 3 # reference: # [y][x] points = 0 # Returns whether or not the next move is a valid move or not def isValid(field, x, y): # Will forward progress lead off of the field #print("isvalid check:" + str(x) + " " + str(y)) if(x < 0 or x > X_SIZE-1): return FALSE elif(y < 0 or y > Y_SIZE-1): return FALSE else: # There are no out of bounds errors return TRUE ''' try: node = field[x][y] # Will forward progress lead to unnavigable terrain? if(node.flag == UNNAV): return FALSE else: return TRUE except (IndexError): print(" isValid(): Safely caught IndexError") return FALSE ''' class agent: # Agent class represents a robot navigating a field def __init__(self, x, y, dir=NORTH, cost=0, a_leap=0,a_forward=0,a_turn=0): self.x = x self.y = y self.dir = dir self.cost = cost self.a_leap = a_turn self.a_forward = a_forward self.a_turn = a_turn def forward(self, field): #Make the move (or try to) if self.dir == NORTH : if(isValid(field, self.x, self.y - 1)): self.cost = self.cost + field.field[self.y - 1][self.x] self.y = self.y - 1 else: return elif self.dir == EAST : if(isValid(field, self.x + 1, self.y)): self.cost = self.cost + field.field[self.y][self.x + 1] self.x = self.x + 1 else: return elif self.dir == SOUTH : if(isValid(field, self.x, self.y + 1)): self.cost = self.cost + field.field[self.y + 1][self.x] self.y = self.y + 1 else: return elif self.dir == WEST : if(isValid(field, self.x - 1, self.y)): self.cost = self.cost + field.field[self.y][self.x - 1] self.x = self.x - 1 else: return else: print ("ERROR: agent.forward()") return #Report move and increment move counter print ("Forward") self.a_forward += 1 return def leap(self, field): #Make the move (or try to) if self.dir == NORTH : if(isValid(field, self.x, self.y - 3)): self.cost = 20 self.y = self.y - 3 else: return elif self.dir == EAST : if(isValid(field, self.x + 3, self.y)): self.cost = 20 self.x = self.x + 3 else: return elif self.dir == SOUTH : if(isValid(field, self.x, self.y + 3)): self.cost = 20 self.y = self.y + 3 else: return elif self.dir == WEST : if(isValid(field, self.x - 3, self.y)): self.cost = 20 self.x = self.x - 3 else: return else: print (" ERROR: agent.leap()") return #Report move and increment move counter print ("Leap") self.a_leap += 1 return def turn(self, direction, field): if(direction == RIGHT): if(self.dir == NORTH): self.dir = EAST elif(self.dir == EAST): self.dir = SOUTH elif(self.dir == SOUTH): self.dir = WEST else: self.dir = NORTH print ("Turn right") if(direction == LEFT): if(self.dir == NORTH): self.dir = WEST elif(self.dir == EAST): self.dir = NORTH elif(self.dir == SOUTH): self.dir = EAST else: self.dir = SOUTH print ("Turn left") #self.cost += field.field[self.x][self.y] self.a_turn += 1 return class node: # Node class represents one tile on the board def __init__( self, x, y, cost, flag, dir=NORTH, parent=None, f=0): self.x = x self.y = y self.cost = cost self.dir = dir self.flag = flag self.parent = parent self.f = f def __str__(self): return "[" + str(self.x) + ", " + str(self.y) + "]" ''' def __cmp__(self, other): if self.f < other.f: return -1 elif self.f > other.f: return 1 else: return 0 ''' def __eq__(self, other): return self.f == other.f def __lt__(self, other): return self.f < other.f def __hash__(self): return (self.x * 3) + (self.y * 5) def neighbors(this_node, field): neighbors = [] #print ("valid neighbors:") if(isValid(field, this_node.x, this_node.y - 1)): #print(str(this_node.x) + " " + str(this_node.y-1)) neighbors.append(field[this_node.y - 1][this_node.x]) if(isValid(field, this_node.x + 1, this_node.y)): #print(str(this_node.x+1) + " " + str(this_node.y)) neighbors.append(field[this_node.y][this_node.x + 1]) if(isValid(field, this_node.x, this_node.y + 1)): #print(str(this_node.x) + " " + str(this_node.y + 1)) neighbors.append(field[this_node.y + 1][this_node.x]) if(isValid(field, this_node.x - 1, this_node.y)): #print(str(this_node.x - 1) + " " + str(this_node.y)) neighbors.append(field[this_node.y][this_node.x - 1]) #print("xxxxxxxxxxxxx") return neighbors def neighbors_leap(this_node, field): neighbors_leap = [] #print ("valid leap neighbors:") if(isValid(field, this_node.x, this_node.y - 3)): #print(str(this_node.x) + " " + str(this_node.y-3)) neighbors_leap.append(field[this_node.y - 3][this_node.x]) if(isValid(field, this_node.x + 3, this_node.y)): #print(str(this_node.x+3) + " " + str(this_node.y)) neighbors_leap.append(field[this_node.y][this_node.x + 3]) if(isValid(field, this_node.x, this_node.y + 3)): #print(str(this_node.x) + " " + str(this_node.y + 3)) neighbors_leap.append(field[this_node.y + 3][this_node.x]) if(isValid(field, this_node.x - 3, this_node.y)): #print(str(this_node.x - 3) + " " + str(this_node.y)) neighbors_leap.append(field[this_node.y][this_node.x - 3]) #print("xxxxxxxxxxxxx") return neighbors_leap # Read a file using tab-delimited file def read_file(inputfile): f = open (inputfile , 'r') #read the string input l = [] l = [line.split('\t') for line in f] f.close() global Y_SIZE Y_SIZE = len(l) global X_SIZE X_SIZE = len(l[0]) #this_node.row #this_node.col #this_node.cost matrix = [] #convert to integers and return for col in range(0, len(l)): mtrix = [] for row in range(0, len(l[col])): my_node = node(0,0,0,0) if l[col][row].strip() is "#": my_node.x = row my_node.y = col my_node.cost = -1 my_node.flag = UNNAV elif l[col][row].strip() is "S": my_node.x = row my_node.y = col my_node.cost = 1 my_node.flag = START global START_NODE START_NODE = my_node elif l[col][row].strip() is "G": my_node.x = row my_node.y = col my_node.cost = 1 my_node.flag = GOAL global GOAL_NODE GOAL_NODE = my_node else: my_node.x = row my_node.y = col my_node.cost = int(l[col][row]) my_node.flag = 0 mtrix.append(my_node) matrix.append(mtrix) return matrix # Calculate the movement cost of moving from current_node to next_node def movement(current_node, next_node): cost = 0 # Turn cost if(current_node.dir == NORTH): if(next_node.y == current_node.y - 1): # North to North | No turn action required next_node.dir = NORTH elif(next_node.y == current_node.y + 1): # North to South | Turn twice cost += 2 * math.ceil(current_node.cost / 3) next_node.dir = SOUTH elif(next_node.x == current_node.x - 1): # North to West | Turn left once cost += math.ceil(current_node.cost / 3) next_node.dir = WEST elif(next_node.x == current_node.x + 1): # North to East | Turn right once cost += math.ceil(current_node.cost / 3) next_node.dir = EAST elif(current_node.dir == SOUTH): if(next_node.y == current_node.y - 1): # South to North | Turn twice cost += 2 * math.ceil(current_node.cost / 3) next_node.dir = NORTH elif(next_node.y == current_node.y + 1): # South to South | No turn action required next_node.dir = SOUTH elif(next_node.x == current_node.x - 1): # South to West | Turn right once cost += math.ceil(current_node.cost / 3) next_node.dir = WEST elif(next_node.x == current_node.x + 1): # South to East | Turn left once cost += math.ceil(current_node.cost / 3) next_node.dir = EAST elif(current_node.dir == WEST): if(next_node.y == current_node.y - 1): # West to North | Turn right once cost += math.ceil(current_node.cost / 3) next_node.dir = NORTH elif(next_node.y == current_node.y + 1): # West to South | Turn left once cost += math.ceil(current_node.cost / 3) next_node.dir = SOUTH elif(next_node.x == current_node.x - 1): # West to West | No turn action required next_node.dir = WEST elif(next_node.x == current_node.x + 1): # West to East | Turn twice cost += 2 * math.ceil(current_node.cost / 3) next_node.dir = EAST elif(current_node.dir == EAST): if(next_node.y == current_node.y - 1): # East to North | Turn left once cost += math.ceil(current_node.cost / 3) next_node.dir = NORTH elif(next_node.y == current_node.y + 1): # East to South | Turn right once cost += math.ceil(current_node.cost / 3) next_node.dir = SOUTH elif(next_node.x == current_node.x - 1): # East to West | Turn twice cost += 2 * math.ceil(current_node.cost / 3) next_node.dir = WEST elif(next_node.x == current_node.x + 1): # East to East | No turn action required next_node.dir = EAST # Calculate distance x = abs(current_node.x - next_node.x) y = abs(current_node.y - next_node.y) d = max(x,y) # isForward if(d == 1): cost += next_node.cost # isLeap elif(d == 3): cost += 20 else: print(" ERROR: agent.movement() d = " + str(d)) return #print("cost:") #print(cost) return cost # node_cost is the cost to reach the next node from this node def node_cost(field, x_next, y_next): return field[y_next][x_next] ''' Heuristic Functions: the cost to get from the next node to the goal ''' # Heuristic of 0: Baseline of how uninformed search would perform def heuristic1(): return 0 # Min(vertical,horizontal) def heuristic2(x_goal, y_goal, x_next, y_next): x = abs(x_goal - x_next) y = abs(y_goal - y_next) return min(x,y) # Max(vertical,horizontal) def heuristic3(x_goal, y_goal, x_next, y_next): x = abs(x_goal - x_next) y = abs(y_goal - y_next) return max(x,y) # Manhattan Distance: vertical + horizontal distance def heuristic4(x_goal, y_goal, x_next, y_next): x = abs(x_goal - x_next) y = abs(y_goal - y_next) return x + y # Admissable heuristic def heuristic5(x_goal, y_goal, x_next, y_next): x = abs(x_goal - x_next) y = abs(y_goal - y_next) return math.ceil(math.sqrt(x**2 + y**2)) # Non-admissable heuristic def heuristic6(x_goal, y_goal, x_next, y_next): return 3 * heuristic5(x_goal, y_goal, x_next, y_next) #returns appropriate h(n) heuristic value. def heuristic_selection(version, this_node): #print("heuristic debug:") #print(version) #print(this_node) #print("----------") goal_node = GOAL_NODE if version == 1: return heuristic1() elif version == 2: return heuristic2(goal_node.x, goal_node.y, this_node.x, this_node.y) elif version == 3: return heuristic3(goal_node.x, goal_node.y, this_node.x, this_node.y) elif version == 4: return heuristic4(goal_node.x, goal_node.y, this_node.x, this_node.y) elif version == 5: return heuristic5(goal_node.x, goal_node.y, this_node.x, this_node.y) elif version == 6: return heuristic6(goal_node.x, goal_node.y, this_node.x, this_node.y) else: print(" ERROR: heuristic_selection()") return -1 #A* Search, modified to take agent as input ''' def a_star(agent, field, start_node, goal_node, heuristic): open_nodes = queue.PriorityQueue() closed_nodes = [] prev_node = {} total_cost = 0 open_nodes.put(start_node, 0) print("start_node: " + str(start_node.x) + ", " + str(start_node.y)) while not open_nodes.empty(): print("++++++++++++++++++++++++++++++++++++++++++++") print("iteration...") current_node = open_nodes.get() if (current_node.x == GOAL_NODE.x and current_node.y == GOAL_NODE.y): print("GOAL found") break neighbor_leap_nodes = neighbors_leap(current_node, field) direct_neighbors = neighbors(current_node, field) possible_nodes = neighbors(current_node, field) + neighbors_leap(current_node, field) for next_node in possible_nodes: print("next possible node...") print("current_node info: " + str(current_node.x) + ", " + str(current_node.y)) print("next_node info: " + str(next_node.x) + ", " + str(next_node.y)) next_node.parent = current_node movement_val = movement(current_node, next_node) print("movement_val: " + str(movement_val)) current_node.cost += movement_val g = current_node.cost # Current node cost to get where you are h = heuristic_selection(int(heuristic), next_node) # Heuristic cost to get to node print("h = " + str(h)) print("g = "+ str(g)) f = g + h if next_node in possible_nodes: print("first if") if f <= next_node.cost: continue elif next_node in closed_nodes: print("second if") if f <= next_node.cost: continue else: print("else yo") open_nodes.put(next_node) print("___________________________") closed_nodes.append(current_node) return ''' ''' def a_star(agent, field, start_node, goal_node, heuristic): open_nodes = [] closed_nodes = [] prev_node = {} total_cost = 0 open_nodes.append(start_node) print("start_node: " + str(start_node.x) + ", " + str(start_node.y)) while open_nodes: #print("++++++++++++++++++++++++++++++++++++++++++++") #print("iteration...") current_node = open_nodes[0] open_nodes.remove(open_nodes[0]) if (current_node.x == GOAL_NODE.x and current_node.y == GOAL_NODE.y): print("GOAL found") print("" + str(current_node.cost)) createPath(current_node) break neighbor_leap_nodes = neighbors_leap(current_node, field) direct_neighbors = neighbors(current_node, field) possible_nodes = neighbors(current_node, field) + neighbors_leap(current_node, field) for next_node in possible_nodes: #print("next possible node...") #print("current_node info: " + str(current_node.x) + ", " + str(current_node.y)) #print("next_node info: " + str(next_node.x) + ", " + str(next_node.y)) next_node.parent = current_node movement_val = movement(current_node, next_node) #print("movement_val: " + str(movement_val)) if(current_node.parent is None): current_node.cost = movement_val else: current_node.cost = movement_val + current_node.parent.cost g = current_node.cost # Current node cost to get where you are h = heuristic_selection(int(heuristic), next_node) # Heuristic cost to get to node #print("h = " + str(h)) print("g = "+ str(g)) f = g + h if next_node in open_nodes: print("first if") if f <= next_node.cost: continue elif next_node in closed_nodes: print("second if") if f <= next_node.cost: continue else: print("else yo") open_nodes.append(next_node) print("node info: " + str(next_node.x) + ", " + str(next_node.y)) print("___________________________") closed_nodes.append(current_node) return ''' def createPath(goal_node): node = goal_node while node.parent is not None: print("" + str(node.x) + "," + str(node.y)) node = node.parent return ''' def a_star(agent, field, start_node, goal_node, heuristic): open_nodes = queue.PriorityQueue() closed_nodes = [] prev_node = {} total_cost = 0 open_nodes.put(start_node, 0) print("start_node: " + str(start_node.x) + ", " + str(start_node.y)) while not open_nodes.empty(): #print("++++++++++++++++++++++++++++++++++++++++++++") #print("iteration...") #current_node_tup = open_nodes.get() #current_node = current_node_tup[1] current_node = open_nodes.get() if (current_node.x == GOAL_NODE.x and current_node.y == GOAL_NODE.y): print("GOAL found") print("" + str(current_node.cost)) #createPath(current_node) break neighbor_leap_nodes = neighbors_leap(current_node, field) direct_neighbors = neighbors(current_node, field) possible_nodes = neighbors(current_node, field) + neighbors_leap(current_node, field) for next_node in possible_nodes: #print("next possible node...") #print("current_node info: " + str(current_node.x) + ", " + str(current_node.y)) #print("next_node info: " + str(next_node.x) + ", " + str(next_node.y)) next_node.parent = current_node movement_val = movement(current_node, next_node) #print("movement_val: " + str(movement_val)) if(current_node.parent is None): current_node.cost = movement_val else: current_node.cost = movement_val + current_node.parent.cost g = current_node.cost # Current node cost to get where you are h = heuristic_selection(int(heuristic), next_node) # Heuristic cost to get to node #print("h = " + str(h)) print("g = "+ str(g)) f = g + h if next_node in open_nodes: print("first if") if f <= next_node.cost: continue elif next_node in closed_nodes: print("second if") if f <= next_node.cost: continue else: print("else yo") open_nodes.append(next_node) print("node info: " + str(next_node.x) + ", " + str(next_node.y)) print("___________________________") closed_nodes.append(current_node) return ''' def a_star(agent, field, start_node, goal_node, heuristic): open_nodes = queue.PriorityQueue() start_node.f = 0 open_nodes.put(start_node) closed_nodes = {} cost_so_far = {} closed_nodes[start_node] = None cost_so_far[start_node] = 0 while not open_nodes.empty(): current_node = open_nodes.get() if current_node.flag == GOAL: print("GOAL FOUND") createPath(current_node) break possible_nodes = neighbors(current_node, field) + neighbors_leap(current_node, field) for next in possible_nodes: print("ITERATION") new_cost = cost_so_far[current_node] + field[next.y][next.x].cost if next not in cost_so_far or new_cost < cost_so_far[next]: cost_so_far[next] = new_cost f = new_cost + heuristic_selection(int(heuristic), next) next.f = f open_nodes.put(next) closed_nodes[next] = current_node return closed_nodes, cost_so_far, open_nodes def createPath(goal_node): node = goal_node while node.parent is not None: print("" + str(node.x) + "," + str(node.y)) node = node.parent return ''' Main function. Execution from command line. ''' def main(argv): if(len(argv) != 3): # {1:} print("Please reconsider your command line input for running this program:") print(" $> astar.py <input_field.txt> <heuristic_number(1-6)>") return 0 #Code goes here to run the program my_field = read_file(argv[1]) agent_1 = agent(START_NODE.x, START_NODE.y) a_star_return = a_star(agent_1, my_field, START_NODE, GOAL_NODE, argv[2]) # Have astar return an array of (score, number_actions, number_nodes, branching_factor, series_of_actions) print("Closed Nodes:\n" + str(a_star_return[0])) print("Final Cost:\n" + str(a_star_return[1])) print(str(len(a_star_return[1]))) if __name__ == "__main__": main(sys.argv)
dd4b7dee3cd96a5d7f993199953fca6dcca2ff9d
9929eric/9-24hwd5
/hw5problem1.py
707
3.734375
4
romantic_movie1 = ("The Princess Bride", 1987, 98, "The story of a man and a woman who lived happily ever after.", ["Buttercup", "Westley", "Fezzik", "Inigo Montoya", "Vizzini"]) romantic_movie2 = ("Groundhog Day", 1993, 101, "He's having the day of his life… over and over again.", ["Phil Connors"]) romantic_movie3 = ("Amélie", 2001, 122, "One person can change your life forever.", ["Amélie Poulain", "Nino Quincampoix", "The Garden Gnome"]) header = "Here are my favorite romance movies:" print(header) print(" ") romantic_movie_list = [romantic_movie1,romantic_movie2, romantic_movie3] for movie in romantic_movie_list: print(movie[0],sep = " ", end = '') print(' (' ,movie[1],")",sep = '', end = ': ') print(movie[3]) print(" ")
69874fb51329984840a0db97c158ed735916c90e
vlkonageski/Logica
/Python/Exercicio02.py
377
4
4
""" Faça um programa que calcule o estoque medio de uma peça, sendo que: estoque medio = quantidade minima + quantidade maxima / 2 """ qtd_minima = int(input("Informe a quantidade minima da peça: ")) qtd_maxima = int(input("Informe a quantidade maxima da peça: ")) media_estoque = (qtd_minima + qtd_maxima) / 2 print("A media da peça é {}".format(media_estoque))
460a24b694e41ad51e8f006eedabda2b7fa2dcd3
zhansoft/pythoncourseh200
/Assignment4/moreloops.py
3,403
3.765625
4
# Input Parameter: a list of, possibly empty, numbers x # Returns: the max number in list x (does not have to be unique) def maxFor(xlst): if xlst: maxNumber = xlst[0] for i in xlst: if i > maxNumber: maxNumber = i return maxNumber else: return xlst #TODO: implement this function with a for loop # Input Parameter: a list of, possibly empty, numbers x # Returns: the max number in list x (does not have to be unique) def maxWhile(xlst): if xlst: maxNumber = 0 while xlst: if xlst[0] > maxNumber: maxNumber = xlst[0] xlst = xlst[1:] return maxNumber else: return xlst #TODO: implement this function with a while loop # Input Parameter: a non-empty list of numbers x # Returns: the minimal number value in list x (does not have to be unique) def minFor(xlst): if xlst: minNumber = xlst[0] while xlst: if xlst[0] < minNumber: minNumber = xlst[0] xlst = xlst[1:] return minNumber else: return xlst #TODO: implement this function #Input Parameters:a list of numbers lst #Returns: the list lst with all occurrences of evens removed def RemoveEvens(xlst): newlst = [] for i in xlst: if i % 2 == 1: a = [i] newlst += a return newlst #TODO: implement this function using for # Input Parameters: list that contains either integers or strings # Return Value: oldX replaced with num copies newX def myReplace(oldX, num, newX, xlst): newlst = [] for i in xlst: a = [] if i == oldX: for n in range (0, num): a += [newX] else: a += [i] newlst += a return newlst #TODO: implement this function # Input Parameters: list of numbers # Returns: sum of the odd numbers # if there are no odd numbers, then print zero # if the list is empty, print the empty list def sumOdd(xlst): sumOdd = 0 if xlst: while xlst: if xlst[0] % 2 == 1: sumOdd += xlst[0] xlst = xlst[1:] return sumOdd else: return xlst #TODO: implement this function using while # Input Parameter: a list x of objects [x1, x2, x3,..., xn] # Returns: a string that is the concatenation of all the strings # in the list in order encountered def StringConcat(xlst): stringC = "" if xlst: while xlst: if (type(xlst[0]) == str): stringC += str(xlst[0]) xlst = xlst[1:] return stringC else: return xlst #TODO: implement this function # Data w = [] x = [1,42,24,22,61,100,0,42] y = [2] z = [555,333,222] nlst = [w,x,y,z] c = [0,1,1,0,2,1,4] a = ["a","b","b", "a", "c","b","e"] b = [1,1,2,1,1,2,1,1,2,1,3,1] d = ["a",1,"row",0,3,"d","ef",453] print("maxFor_____") for i in nlst: print(maxFor(i)) print("\nmaxWhile_____") for i in nlst: print(maxWhile(i)) print("\nminFor_____") for i in nlst: print(minFor(i)) print("\nRemoveEvens_____") print(RemoveEvens(b)) print(RemoveEvens(c)) print("\nmyReplace_____") print(myReplace(1,2,"dog",c)) print(myReplace(1,2,1,b)) print("\nsumOdd_____") for i in nlst: print(sumOdd(i)) print("\nStringConcat_____") print(StringConcat(a)) print(StringConcat(d)) if __name__ == "__main__": pass
97c3ca5990be167c9dea8f73cf61d31804f18bfc
AbnerZhangZN/PythonLearning
/003_advanced characteristics/day004_02.py
683
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #setup 14 高级特性-列表生成式 #单层循环 print([x * x for x in range(1, 11)]) #单层循环后加判断 print([x * x for x in range(1, 11) if x % 2 == 0]) #两层循环 全排列 print([m + n for m in 'ABC' for n in 'XYZ']) import os print([d for d in os.listdir('.')])# os.listdir可以列出文件和目录 d = {'a':'1','b':'2','c':'3'} print([k + '=' + v for k,v in d.items()]) L = ['Hello','World','Java','IBM','Apple','Python'] print([s.lower() for s in L]) print([s.upper() for s in L]) L0 = ['Hello','World',22,None,'Java','IBM','Apple','Python','231asfADS'] print([s.lower() for s in L0 if isinstance(s, str)])
9d394339d929d92b50bfb26552f0a1d27b02544e
ritikagupta25051998/FSDP2019
/day10/random.py
494
3.8125
4
# -*- coding: utf-8 -*- """ Created on Tue May 14 07:48:06 2019 @author: HP WORLD """ result=eval(input("enter the chara")) print(result) if True: print("qwe") else: print("zxc") import random names=['Mary','Isla','Sem'] code_names=['Mr.Pink','Mr.Orange','Mr.Blonde'] list3=list(map(lambda x: random.choice(['Mr.Pink','Mr.Orange','Mr.Blonde']),names)) x=3 if x==1: print("one") elif x==2: print("two") elif x==3: print("three") else: print("wrong")
83340646c493ff0d927822fb330bb58fc9e42704
ppen/basicPython
/test.py
215
3.6875
4
# test number = 5 p1 = 5 p2 = 10 if number == 10: print(p1 + p2) else: print(p1*p2) # test print(sum(range(1, 10))) print("Hello World!") # test data = ['physics', 'chemistry', 1997, 2000]; # print(data)
5880d51df4e753d7fa58c5ac246c515439fe4a7d
thedabs91/Scrabble
/WordListUpdater.py
1,097
3.5625
4
# A file to update a word list with additions and deletions # Importing the original word List words_orig = file.open('Words/words_orig', 'r') list_orig = [] for line in words_orig: word = line.strip('\n\r') word = word.upper() list_orig.append(word) words_orig.close() # Additions words_add = file.open('Words/words_add', 'r') list_add = [] for line in words_add: word = line.strip('\n\r') word = word.upper() list_add.append(word) words_add.close() # Deletions words_del = file.open('Words/words_del', 'r') list_del = [] for line in words_del: word = line.strip('\n\r') word = word.upper() list_del.append(word) words_del.close() # Creating place for new list list_new = [] list_new.extend(list_orig) # Deleting deletions for word in list_del: while list_new.count(word) > 0: list_new.remove(word) # Adding additions list_new.extend(list_add) # Sorting the list list_new.sort() # Writing to a file words_new = file.open('Words/UpdatedWordList', 'w') for word in list_new: if word.strip(' ') != '': words_new.write(word + '\n\r') # I think this is it.
83a82ba825cbba8c7780cabaa48e478b5c3ef144
sashakrasnov/datacamp
/13-introduction-to-data-visualization-with-python/4-analyzing-time-series-and-images/05-plotting-moving-averages.py
1,970
3.84375
4
''' Plotting moving averages In this exercise, you will plot pre-computed moving averages of AAPL stock prices in distinct subplots. * The time series aapl is overlayed in black in each subplot for comparison. * The time series mean_30, mean_75, mean_125, and mean_250 have been computed for you (containing the windowed averages of the series aapl computed over windows of width 30 days, 75 days, 125 days, and 250 days respectively). ''' import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('../datasets/stocks.csv', index_col='Date', parse_dates=True) aapl = df['AAPL'] mean_30 = aapl.rolling(window=30).mean() mean_75 = aapl.rolling(window=75).mean() mean_125 = aapl.rolling(window=125).mean() mean_250 = aapl.rolling(window=250).mean() ''' INSTRUCTIONS * In the top left subplot, plot the 30-day moving averages series mean_30 in 'green'. * In the top right subplot, plot the 75-day moving averages series mean_75 in 'red'. * In the bottom left subplot, plot the 125-day moving averages series mean_125 in 'magenta'. * In the bottom right subplot, plot the 250-day moving averages series mean_250 in 'cyan'. ''' # Plot the 30-day moving average in the top left subplot in green plt.subplot(2, 2, 1) plt.plot(mean_30, color='green') plt.plot(aapl, 'k-.') plt.xticks(rotation=60) plt.title('30d averages') # Plot the 75-day moving average in the top right subplot in red plt.subplot(2, 2, 2) plt.plot(mean_75, color='red') plt.plot(aapl, 'k-.') plt.xticks(rotation=60) plt.title('75d averages') # Plot the 125-day moving average in the bottom left subplot in magenta plt.subplot(2, 2, 3) plt.plot(mean_125, color='magenta') plt.plot(aapl, 'k-.') plt.xticks(rotation=60) plt.title('125d averages') # Plot the 250-day moving average in the bottom right subplot in cyan plt.subplot(2, 2, 4) plt.plot(mean_250, color='cyan') plt.plot(aapl, 'k-.') plt.xticks(rotation=60) plt.title('250d averages') # Display the plot plt.show()
3d87c95db1d5cbfe0e31c166a56f29fcfa52941a
diegoaleman/ciu-old
/leet-problems/053-maximum-subarray.py
578
3.5
4
# Kadane's algorithm class Solution: def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ max_value = None prev_max = None for index, val in enumerate(nums): if index == 0: max_value = nums[0] prev_max = nums[0] else: if val > prev_max + val: prev_max = val else: prev_max = prev_max + val max_value = max(max_value,prev_max) return max_value
e5584e56f70a12d004a9100d653cbc267152622e
dsergiyenko/pyneng-examples-exercises
/exercises/18_db/task_18_4/get_data.py
1,223
3.578125
4
# -*- coding: utf-8 -*- import sqlite3 import sys from tabulate import tabulate db_filename = 'dhcp_snooping.db' if len(sys.argv) == 3: key, value = sys.argv[1:] keys = ['vlan', 'mac', 'ip', 'interface', 'switch'] if not key in keys: print('Enter key from {}'.format(', '.join(keys))) else: conn = sqlite3.connect(db_filename) print('\nDetailed information for host(s) with', key, value) query = "select * from dhcp where active = 1 and "+key+" = '"+value+"' " result = conn.execute(query) print('Active records: ') print(tabulate(result)) query = "select * from dhcp where active = 0 and "+key+" = '"+value+"' " result = conn.execute(query) print('Inactive records: ') print(tabulate(result)) elif len(sys.argv) == 1: conn = sqlite3.connect(db_filename) query = 'select * from dhcp' + ' where active = 1' result = conn.execute(query) print('Active records: ') print(tabulate(result)) query = 'select * from dhcp' + ' where active = 0' result = conn.execute(query) print('Inactive records: ') print(tabulate(result)) else: print("Please enter 2 or 0 arguments") exit()
cf382d4decb18759516e2d8df6bb588890ea8f50
soledadvega/Ingenieria
/testing_varios/test_sut.py
1,736
3.796875
4
import unittest import sut class TestSut(unittest.TestCase): def test_area(self): area = sut.area(3, 2) self.assertTrue(area==6) def test_sumar(self): resultado = sut.sumar(2, 3) self.assertTrue(resultado==5) def test_saludar(self): resultado = sut.saludar("Luz") self.assertTrue("Hola" + "Luz") def test_multiplicar(self): resultado = sut.multiplicar(2, 4) self.assertTrue(resultado==8) def test_valorabsoluto(self): resultado = sut.valorabsoluto(-5) self.assertTrue(resultado==5) def test_productoria(self): resultado = sut.productoria([1, 2, 3, 4, 5],3) self.assertTrue(resultado==6) def test_sumatoria(self): resultado = sut.sumatoria([1, 2, 3, 4, 5],3) self.assertTrue(resultado==6) def test_comparar(self): if a < b: return "A menor que B" if a > b: return "A mayor que B" if a == b: return "A y B son iguales" def test_costototal(self): resultado = sut.costototal() self.asserTrue(resultado== "El costo total es $2") total = sumar(producto1, producto2) return "El costo total es $" + str(total) def test_supercalc(self): exp = math.exp(num) sum = exp + 2 sqrt = math.sqrt(sum) resultado = sut.supercalc() self.assertTrue(resultado == ) return sqrt if __name__ =="__main__": unittest.main() ''' def test_sumatoria(self): resultado = sut.sumatoria() self.assertTrue(resultado== ) def test_productoria(self): resultado = sut.productoria() self.assertTrue(resultado== ) '''
3e4f04d3844a08f3c0f0ed1e9235f807af7c49a6
Samsogo/MachineLearning
/Alex_lei/ML/Numpy/get_elements_from_array.py
507
3.703125
4
import numpy as np arr = np.array(np.arange(12).reshape(3,4)) print(arr) print(arr[0]) #获取二维数组的第一行 print(arr[1]) #获取二维数组的第二行 print(arr[:3]) #获取二维数组的前三行 print(arr[[0,2]]) #获取二维数组的第1行和第三行 print(arr[:,1]) #获取二维数组的第二列 print(arr[:,-2:]) #获取二维数组的后两列 print(arr[:,[0,2]]) #获取二维数组的第一列和第三列 print(arr[1,3]) #获取二维数组的第二行第四列的元素
f0e29227ecd2f68921bc81ceb16f5a1bdd767a75
phlalx/algorithms
/leetcode/542.01-matrix.py
2,440
3.546875
4
# # @lc app=leetcode id=542 lang=python3 # # [542] 01 Matrix # # https://leetcode.com/problems/01-matrix/description/ # # algorithms # Medium (36.68%) # Likes: 804 # Dislikes: 82 # Total Accepted: 52.3K # Total Submissions: 142.7K # Testcase Example: '[[0,0,0],[0,1,0],[0,0,0]]' # # Given a matrix consists of 0 and 1, find the distance of the nearest 0 for # each cell. # # The distance between two adjacent cells is 1. # # # # Example 1: # # # Input: # [[0,0,0], # ⁠[0,1,0], # ⁠[0,0,0]] # # Output: # [[0,0,0], # [0,1,0], # [0,0,0]] # # # Example 2: # # # Input: # [[0,0,0], # ⁠[0,1,0], # ⁠[1,1,1]] # # Output: # [[0,0,0], # ⁠[0,1,0], # ⁠[1,2,1]] # # # # # Note: # # # The number of elements of the given matrix will not exceed 10,000. # There are at least one 0 in the given matrix. # The cells are adjacent in only four directions: up, down, left and right. # # # #TAGS multisource BFS, see 286 # @lc code=start # This is too slow, quite similar to Bellman-Ford # class Solution: # def updateMatrix(self, matrix): # if not matrix or not matrix[0]: # return matrix # n = len(matrix) # p = len(matrix[0]) # def neighbors(i, j): # u = [0, 1, 0, -1] # v = [1, 0, -1, 0] # for a, b in zip(u, v): # ii = i + a # jj = j + b # if 0 <= ii < n and 0 <= jj < p: # yield ii, jj # k = n + p # for _ in range(k): # for i in range(n): # for j in range(p): # if matrix[i][j] != 0: # matrix[i][j] = min(1 + matrix[ii][jj] for ii, jj in neighbors(i, j)) # return matrix from collections import deque class Solution: def updateMatrix(self, matrix): if not matrix or not matrix[0]: return matrix n = len(matrix) p = len(matrix[0]) def neighbors(i, j): u = [0, 1, 0, -1] v = [1, 0, -1, 0] for a, b in zip(u, v): ii = i + a jj = j + b if 0 <= ii < n and 0 <= jj < p: yield ii, jj q = deque() for i in range(n): for j in range(p): m = matrix[i][j] if m == 0: q.appendleft((i,j)) else: matrix[i][j] = None while(q): i, j = q.pop() for ii, jj in neighbors(i, j): if matrix[ii][jj] is None: matrix[ii][jj] = matrix[i][j] + 1 q.appendleft((ii, jj)) return matrix # @lc code=end
a4ec936c880998078120ad6e0106d5bb07e32159
wangerde/codewars
/python2/kyu_6/mkdir_p.py
762
3.9375
4
# coding=utf-8 """mkdir -p http://www.codewars.com/kata/mkdir-p Write a synchronous function that makes a directory and recursively makes all of its parent directories as necessary. A directory is specified via a sequence of arguments which specify the path. For example: mkdirp('/','tmp','made','some','dir') ...will make the directory /tmp/made/some/dir. Like the shell command mkdir -p, the function you program should be idempotent if the directory already exists. """ import os def mkdirp(*directories): """Recursively create all directories as necessary Args: directories (tuple): List of directories Returns: None """ try: os.makedirs(os.path.join(*directories)) except OSError: pass
612c768046467780b665ed234a89c23d4c1532a0
andrew-yt-wong/ITP115
/ITP 115 .py/Labs/ITP115_L10_1_Wong_Andrew.py
1,578
3.90625
4
# Andrew Wong, awong827@usc.edu # ITP 115, Spring 2020 # Lab 10-1 # ---- readDictionaryFile ------------------------------- # # Input: string # Output: list of strings # # Side Effect: None # Description: Read in each word and store it in a list # ------------------------------------------------------- def readDictionaryFile(fileName): fileIn = open(fileName, "r") dictionaryList = list() for line in fileIn: word = line.strip() dictionaryList.append(word) fileIn.close() return dictionaryList # ---- checkWord ---------------------------------------- # # Input: list of strings, string # Output: boolean # # Side Effect: None # Description: Return True if in dictionary # ------------------------------------------------------- def checkWord(dictionaryList, word): for words in dictionaryList: if words == word: return True return False # ---- main -------------------------------------------- # # Input: None # Output: None # # Side Effect: Prints the instructions # Description: Calls the dictionary and checks words # ------------------------------------------------------- def main(): print("Welcome to the Spell Checker!") fileName = input("Please enter the dictionary file you wish to read in: ") word = input("Please enter the word you wish to spell check: ") dictionaryList = readDictionaryFile(fileName) if checkWord(dictionaryList, word): print("That word is in the dictionary.") else: print("That word is NOT in the dictionary, so it must be spelled wrong.") main()
d3e4990432892386ff8463adbb24977fcc5a0c5f
kvetab/BioinfoToolbox
/Hamming.py
851
3.8125
4
import FASTAparser class HammingDist: # calculates the Hamming distance of two sequences of equal length def Hamming(self, seq1, seq2): dist = 0 str1 = str(seq1) str2 = str(seq2) for i in range(len(str1)): if str1[i] != str2[i]: dist += 1 return dist # returns distance of two sequences or an error message, if their lengths differ. def GetDist(self, seq1, seq2): if len(seq1) == len(seq2): return self.Hamming(seq1, seq2) else: print("The lengths of the sequences don't match.") if __name__ == "__main__": #seq1 = "AACTGTCA" #seq2 = "ATCTTTC" parser = FASTAparser.FASTAparser("fasta_simple.txt") seq1 = parser.getSeq(1) seq2 = parser.getSeq(2) dist = HammingDist() print(dist.GetDist(seq1, seq2))
3607652c43f915852f3c8449740514bd1b145f6a
zanderobert/GROUP-ASSIGNENT
/banking.py
5,051
3.53125
4
import random class Bank: def __init__(self, BankId, Name, Location): self.bank_id = BankId self.name = Name self.location = Location self.customers = {} self.tellers = {} self.loan = {} self.accounts = {} def add_accounts_info(self, customer_id, account): self.accounts[customer_id] = account def add_loan_info(self, customer_id, loan): self.loan[customer_id] = loan def add_customers(self, customer_id, customer): self.customers[customer_id] = customer def customers(self): return self.customers def add_tellers(self, teller_name, teller): self.tellers[teller_name] = teller def tellers(self): return self.tellers def toList(self): return [self.bank_id, self.name, self.location] class Customer: def __init__(self, Id, cust_Name, Address, PhoneNo, AccNo, bank): self.Customer_id = Id self.customer_name = cust_Name self.Address = Address self.phoneNo = PhoneNo self.account_no = AccNo self.bank = bank #self.bank.add_customers(self.Customer_id) def add_customer(self, customer): self.bank.add_customers(self.Customer_id, customer) def General_Inquiry(self): pass def depositMoney(self, amount): if self.bank.tellers: teller = random.choice(self.bank.tellers.keys()) self.bank.tellers[teller].collectMoney() my_account = self.bank.accounts[self.Customer_id] my_account.add_balance(amount) def WithdrawMoney(self, amount): my_account = self.bank.accounts[self.Customer_id] my_account.subtract_balance(amount) def OpenAccount(self, type): if self.bank.tellers: teller = random.choice(self.bank.tellers.keys()) self.bank.tellers[teller].openAccount(type, self.Customer_id, self.account_no) def CloseAccount(self): pass def ApplyForLoan(self, amount): if self.bank.tellers: teller = random.choice(self.bank.tellers) teller.loanRequest(amount, self.account_no, self.Customer_id, Type=None) else: print ('No teller at the moment') def RequestCard(self): pass class Teller: def __init__(self, Id, teller_name, bank): self.teller_id = Id self.name = teller_name self.bank = bank #self.bank.add_tellers(self.name) def add_teller(self,teller): self.bank.add_tellers(self.name, teller) def collectMoney(self): print ('%s collecting Money' %(self.name)) def openAccount(self, type, Customer_id, account_no): if type.upper() == 'SAVINGS': account = Savings(Customer_id, account_no) elif type.upper() == 'CHECKING': account = Checking(Customer_id, account_no) else: print ("Account-types(Checking or Savings)") self.bank.add_accounts_info(Customer_id, account) def closeAccount(self): pass def loanRequest(self, amount, account_id, customer_id, Type=None): loan = Loan(account_id, customer_id, Type=None) self.bank.add_loan_info(customer_id, loan) def provideInfo(self): pass def issueCard(self): pass class Account: def __init__(self, customer_id, account_no): self.cust_id = customer_id self.account_no = account_no self.balance = 0 def add_balance(self, amount): self.balance += amount print ("%s deposited into %s account" % (amount, self.cust_id)) def subtract_balance(self, amount): if self.balance >= amount: self.balance -= amount else: print ('insufficient balance') def check_balance(self): return self.balance class Checking(Account): def accountInfo(self): print ("Account-number: %s ,Account-type: %s, Account_balance: %s" \ %(self.account_no, 'Checking', self.balance)) class Savings(Account): def accountInfo(self): print ("Account-number: %s ,Account-type: %s, Account_balance: %s" \ %(self.account_no, 'Savings', self.balance)) class Loan: def __init__(self, id, account_id, customer_id, Type=None): self.loan_id = id self.loan_type = Type self.account_id = account_id self.customer_id = customer_id def amount(self, amount): self.amount = amount def payment(self, amount): if amount <= self.amount: self.amount -= amount else: print ('The amount exceeds the loan') stanbic = Bank(1, 'Stanbic Bank', 'Kampala') teller1 = Teller(1, 'teller1', stanbic) teller2 = Teller(2, 'teller2', stanbic) teller3 = Teller(3, 'teller3', stanbic) teller1.add_teller(teller1) teller2.add_teller(teller2) teller3.add_teller(teller3) print (stanbic.tellers) customer1 = Customer(1, 'cust1','kampala', '43526', '85874', stanbic) customer1.add_customer(customer1)
39a40cf206f1e258ad5d2ef81b20488cf4d3e4df
luisfe12/desarrollo
/URIPT1/puntos.py
240
3.765625
4
import math x1, y1 = [float(x1,y1) for x1 in raw_input().split()] x2, y2 =[float(x2,y2) for x2 in raw_input().split()] val1 = x2 - x1 val2 = y2 -y1 Distancia = math.sqrt(pow(x2-x1, 2) + pow(y2-y1, 2)) print("{:.4f}".format(Distancia))
ce4221453ce1c9e0d90fee7151486c73ab01daad
scls19fr/openphysic
/python/oreilly/cours_python/solutions/exercice_10_29.py
475
3.90625
4
#! /usr/bin/env python # -*- coding: Latin-1 -*- # Affichage de tables de multiplication nt = [2, 3, 5, 7, 9, 11, 13, 17, 19] def tableMulti(m, n): "renvoie n termes de la table de multiplication par m" ch ="" for i in range(n): v = m * (i+1) # calcul d'un des termes ch = ch + "%4d" % (v) # formatage 4 caractres return ch for a in nt: print tableMulti(a, 15) # 15 premiers termes seulement
82f752147f144d731de92040ea7aa3479f672863
OhsterTohster/Project-Euler
/Python/q7.py
878
3.859375
4
# What is the 10 001st prime number? #idk whats wrong with the code but something is wrong somewhere because 10001st prime number would mean 10001 elements in the list and thus # primeNumbers[10000] right? import math def checkPrime(num): isPrime = True if (num % 2 == 0): isPrime = False return isPrime for i in range(3,math.ceil(math.sqrt(num))+1,2): if (num % i == 0): isPrime = False break return isPrime def solve(): primeNumbers = [2,3,5,7,11,13] currentNumber = 13 while True: if (len(primeNumbers) > 10001): break else: checkValue = checkPrime(currentNumber) if (checkValue == True): primeNumbers.append(currentNumber) currentNumber+=2 print(primeNumbers[10001]) print(len(primeNumbers)) solve()
0b7bb66baa9e52dfa4660725addb699b5549394a
minthf/Parseltang
/lab3/koch_curve.py
1,785
3.515625
4
from PIL import Image, ImageColor from PIL import ImageDraw import math as m image = Image.new("RGB", (400, 300)) draw = ImageDraw.Draw(image) class Point: def __init__(self, x, y): self.x = x self.y = y def find_part_of_line(start: Point, end: Point, part): y = (start.y + (part * end.y)) / (1 + part) x = (start.x + (part * end.x)) / (1 + part) return Point(x, y) class Koh_curve: def __init__(self, start:Point, end:Point): self.start = start self.end = end def draw_koh_curve(self, start: Point, end: Point, deep=3): if deep == 1: return length = m.sqrt(pow((start.x - end.x), 2) + pow((start.y - end.y), 2)) second_point = find_part_of_line(start, end, 1 / 2) fourth_point = find_part_of_line(start, end, 2) angle = m.atan((start.y - end.y) / (end.x - start.x)) if end.x < start.x: angle += m.pi triangle_angle = (m.pi / 3) + angle cx = second_point.x + (m.cos(triangle_angle) * (length / 3)) cy = second_point.y - (m.sin(triangle_angle) * (length / 3)) third_point = Point(cx, cy) draw.line((second_point.x, second_point.y, third_point.x, third_point.y)) draw.line((third_point.x, third_point.y, fourth_point.x, fourth_point.y)) draw.line((second_point.x, second_point.y, fourth_point.x, fourth_point.y), fill=ImageColor.getrgb("black")) self.draw_koh_curve(start, second_point, deep - 1) self.draw_koh_curve(second_point, third_point, deep - 1) self.draw_koh_curve(third_point, fourth_point, deep - 1) self.draw_koh_curve(fourth_point, end, deep - 1) start_point = Point(10, 200) end_point = Point(390, 200) koh = Koh_curve(start_point,end_point) draw.line((start_point.x, start_point.y, end_point.x, end_point.y)) koh.draw_koh_curve(koh.start, koh.end, 5) image.save("picture_koch.png", "PNG") image.show()
55bf46a98532d956f442bab5c7d1715f9bfaa0eb
priestd09/project_euler
/e_47.py
855
3.640625
4
#!/usr/bin/env python ''' Created on 10 feb. 2012 @author: Julien Lengrand-Lambert DESCRIPTION: Solves problem 47 of Project Euler The first two consecutive numbers to have two distinct prime factors are: 14 = 2*7 15 = 3*5 The first three consecutive numbers to have three distinct prime factors are: 644 = 2^2 * 7 * 23 645 = 3 * 5 * 43 646 = 2 * 17 * 19. Find the first four consecutive integers to have four distinct primes factors. What is the first of these numbers? ''' import pickle # list of primes up to one million. plist = pickle.load(open("primes_list.dup", "rb")) def is_prime(val): """ Returns True if the number is prime """ return (val in plist) def consecutive_primes(num): """ Returns the first of the first num consecutive primes. """ if __name__ == '__main__': print 1 #print "Answer : %d " % (last_ten())
d6637a9b9a288a46c82afbe8ce6014b05fd89e82
vbabushkin/NaoRoboticProject
/relatedPythonProjectsFromDellLaptop/visionOptimization/Shape.py
1,320
3.578125
4
__author__ = 'vahan' class Shape: # color="" # shape="" # centers=[] # contours=[] def __init__(self,color=None,shape=None): if color!=None: self.color=color if shape!=None: self.shape=shape self.centers=[] self.contours=[] def setColor(self, color): self.color=color def getColor(self): return self.color def setShape(self, shape): self.shape=shape def getShape(self): return self.shape def addContours(self,contour): self.contours.append(contour) def getContours(self): return self.contours def addCenters(self,center): self.centers.append(center) def getCenters(self): return self.centers def reset(self): self.color="" self.shape="" self.centers=[] self.contours=[] # # if __name__ == '__main__': # shape1=Shape() # shape2=Shape("red","triangle") # print shape2.getColor() # print shape2.getShape() # shape1.setColor("green") # shape1.setShape("triangle") # print shape1.getColor() # print shape1.getShape() # shape1.reset() # print shape1.getColor() # print shape1.getShape() # listOfShapes=[shape1, shape2] # print listOfShapes[0].getColor()
0fa14f42b2170ba6bcbd68a1d600464ae3c0b5f3
fulviocanducci/python
/primitives.py
237
3.953125
4
n1 = input('Digite o número: ') n2 = input('Digite o número: ') re = int(n1) + int(n2) print('O resultado é {}'.format(re)) print('O resultado entre', n1, 'e', n2, 'é', re) print('O resultado entre {} e {} é {}'.format(n1, n2, re))
86647bd5c31f2c4dae20e9c9e9ddac40634be9d5
anj339/dtf
/lists.py
448
3.984375
4
import random list = [] for i in range (10) : list.append(random.randrange(1, 999)) print (list) question= input("pick a number from the list") number= int(question) question2= input("Pick another number from the list") number2= int(question2) x= number y= number2 def Maximum_Number(number, number2): if(x < y): return y else: return x print("The bigger number is....") print(Maximum_Number(number, number2))
d378aa40caf2243958c7b9541ef6dc1c8544b3e3
mitchelloliveira/python-pdti
/Aula01_03082020/aula01_exe08.py
521
4.0625
4
# Curso de Python - PDTI-SENAC/RN # Profº Weskley Bezerra # Mitchell Oliveira # 04/08/2020 # -------------------------------------------------------------- # Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. # Calcule e mostre o total do seu salário no referido mês. val_hora = float(input("Informe o valor da sua hora/mês: ")) qtd_horas = float(input("Informe a quantidade de horas trabalhadas por mês: ")) salario = val_hora * qtd_horas print("O salário corresponde é: ", salario)
320c43fadde8753baf6dda74bb934629154f3777
Archanciel/Pygame_2d_Cartesian_coordinates_system
/twodcartesiancoordsystem.py
8,049
3.5
4
import math from constants import * class TwoDCartesianCoordSystem: """ This class has no dependency on Pygame. So, it can be unit tested more efficiently. It hosts the Cartesian axes computation logic used by its subclass PygameTwoDCartesianCoordSystem. """ def __init__(self, origin, xLength, yLength, xRange, yRange, xLabel='X', yLabel='Y', color=BLACK, thickness=2, titleLst=[]): ''' :param origin: :param xLength: :param yLength: :param xRange: tuple containing the min and max X axis values (values are provided from left to right. Ex: (-25, -3), (-30, 45), (0, 75), (12, 125). :param yRange: tuple containing the max and min Y axis values (values are provided from top to bottom. Ex: (25, 3), (30, -45), (75, 0), (0, -50), (-12, -125). :param xLabel: :param yLabel: :param color: :param thickness: :param titleLst: ''' self.origin = origin self.xLabel = xLabel self.yLabel = yLabel self.titleLst = titleLst self.color = color self.thickness = thickness # computing how many pixels correspond to delta x self.xStep = math.floor(xLength / (xRange[1] - xRange[0])) # computing how many pixels correspond to delta y self.yStep = math.floor(yLength / (yRange[0] - yRange[1])) # computing the X axis coordinates self.xAxisCoordStart, self.xAxisCoordEnd = self.computeXAxisCoordinates(origin, xLength, xRange) # computing the Y axis coordinates self.yAxisCoordStart, self.yAxisCoordEnd = self.computeYAxisCoordinates(origin, yLength, yRange) self.axesColor = color # computing X axis arrow coord self.xArrowCoord = self.computeXAxisArrowCoordinates(self.origin, self.xAxisCoordStart, self.xAxisCoordEnd) # computing Y axis arrow coord self.yArrowCoord = self.computeYAxisArrowCoordinates(self.origin, self.yAxisCoordStart, self.yAxisCoordEnd) # computing X axis label x coord and X axis arrow direction self.xAxisLabelXCoordAndDirection = self.computeXAxisLabelXCoordAndDirection(self.origin, self.xAxisCoordStart, self.xAxisCoordEnd) # computing Y axis label x coord and Y axis arrow direction self.yAxisLabelYCoordAndDirection = self.computeYAxisLabelXCoordAndDirection(self.origin, self.yAxisCoordStart) #print("origin ", self.origin, " xAxisCoordEnd", self.xAxisCoordEnd, " yAxisCoordStart", self.yAxisCoordStart) def computeXAxisCoordinates(self, origin, xAxisLength, xAxisValueRange): """ This method computes the X axis line start and end coordinates expressed in pixels. The returned tuples will be used by the Pygame.draw.line method to draw the X axis. :param origin: Cartesian axes system origin coordinate tuple in pixels. Its position in the Pygame Surface. :param xAxisLength: :param xAxisValueRange: tuple containing the minimal and maximal x value :return: xAxisCoordStart and xAxisCoordEnd tuples """ if xAxisValueRange[0] < 0: if xAxisValueRange[1] <= 0: xAxisCoordStart = (origin[0] - xAxisLength, origin[1]) else: xAxisCoordStart = (origin[0] - abs(xAxisValueRange[0] * self.xStep), origin[1]) else: xAxisCoordStart = (origin[0], origin[1]) xAxisCoordEnd = (xAxisCoordStart[0] + xAxisLength, xAxisCoordStart[1]) return xAxisCoordStart, xAxisCoordEnd def computeYAxisCoordinates(self, origin, yLength, yRange): """ This method computes the Y axis line start and end coordinates expressed in pixels. The returned tuples will be used by the Pygame.draw.line method to draw the X axis. :param origin: Cartesian axes system origin coordinate tuple in pixels. Its position in the Pygame Surface. :param xAxisLength: :param xAxisValueRange: tuple containing the minimal and maximal y value :return: yAxisCoordStart and yAxisCoordEnd tuples """ if yRange[0] > 0: if yRange[1] > 0: yAxisCoordStart = (origin[0], origin[1] - yLength) else: yAxisCoordStart = (origin[0], origin[1] - yRange[0] * self.yStep) else: yAxisCoordStart = (origin[0], origin[1]) yAxisCoordEnd = (yAxisCoordStart[0], yAxisCoordStart[1] + yLength) return yAxisCoordStart, yAxisCoordEnd def computeXAxisArrowCoordinates(self, origin, xAxisCoordStart, xAxisCoordEnd): if xAxisCoordEnd[0] > origin[0]: xArrowPoint1 = (xAxisCoordEnd[0] - ARROW_LENGTH, xAxisCoordEnd[1] - ARROW_BASE / 2) xArrowPoint2 = (xAxisCoordEnd[0], xAxisCoordEnd[1]) xArrowPoint3 = (xAxisCoordEnd[0] - ARROW_LENGTH, xAxisCoordEnd[1] + ARROW_BASE / 2) else: xArrowPoint1 = (xAxisCoordStart[0] + ARROW_LENGTH, xAxisCoordStart[1] - ARROW_BASE / 2) xArrowPoint2 = (xAxisCoordStart[0], xAxisCoordStart[1]) xArrowPoint3 = (xAxisCoordStart[0] + ARROW_LENGTH, xAxisCoordStart[1] + ARROW_BASE / 2) return (xArrowPoint1, xArrowPoint2, xArrowPoint3) def computeYAxisArrowCoordinates(self, origin, yAxisCoordStart, yAxisCoordEnd): if yAxisCoordStart[1] < origin[1]: yArrowPoint1 = (yAxisCoordStart[0] - ARROW_BASE / 2, yAxisCoordStart[1] + ARROW_LENGTH) yArrowPoint2 = (yAxisCoordStart[0], yAxisCoordStart[1]) yArrowPoint3 = (yAxisCoordStart[0] + ARROW_BASE / 2, yAxisCoordStart[1] + ARROW_LENGTH) else: yArrowPoint1 = (yAxisCoordEnd[0] - ARROW_BASE / 2, yAxisCoordEnd[1] - ARROW_LENGTH) yArrowPoint2 = (yAxisCoordEnd[0], yAxisCoordEnd[1]) yArrowPoint3 = (yAxisCoordEnd[0] + ARROW_BASE / 2, yAxisCoordEnd[1] - ARROW_LENGTH) return (yArrowPoint1, yArrowPoint2, yArrowPoint3) def computeXAxisLabelXCoordAndDirection(self, origin, xAxisCoordStart, xAxisCoordEnd): # This method returns a tuple whose first element = x coord of X axis label # and second element = X axis arrow direction (1 == right, -1 == left). if xAxisCoordEnd[0] > origin[0]: return (xAxisCoordEnd[0], 1) else: return (xAxisCoordStart[0], -1) def computeYAxisLabelXCoordAndDirection(self, origin, yAxisCoordStart): # This method returns a tuple whose first element = x coord of Y axis label # and second element = Y axis arrow direction (1 == top, -1 == bottom). if yAxisCoordStart[1] < origin[1]: return (origin[0], 1) else: return (origin[0], -1) def computeOriginLabelPosition(self, origin, xAxisCoordEnd, yAxisCoordStart): if xAxisCoordEnd[0] > origin[0]: if yAxisCoordStart[1] < origin[1]: return QUADRANT_1 else: return QUADRANT_4 else: if yAxisCoordStart[1] < origin[1]: return QUADRANT_2 else: return QUADRANT_3 def computeNegTicks(self, tickSize, minValue): return [x for x in range(-tickSize, minValue - int(tickSize / 2), -tickSize)] def computePosTicks(self, tickSize, maxValue): return [x for x in range(tickSize, maxValue + int(tickSize / 2), tickSize)] def computeXAxisTicks(self, tickValues, xRange): negTicks = self.computeNegTicks(tickValues[0], xRange[0]) negTicks.reverse() lastTickIdx = len(negTicks) - 1 if lastTickIdx >= 0 and negTicks[lastTickIdx] > xRange[1]: # if the last negative tick is greater than the max x range value, it is # removed from the list. This is the case if for example xRange == [-9, -3] # with a x tick value of 2 negTicks = negTicks[:-1] posTicks = self.computePosTicks(tickValues[0], xRange[1]) if len(posTicks) > 0 and posTicks[0] < xRange[0]: # if the first positive tick is smaller than the min x range value, it is # removed from the list. This is the case if for example xRange == [3, 9] # with a x tick value of 2 posTicks = posTicks[1:] return negTicks + posTicks def computeYAxisTicks(self, tickValues, yRange): negTicks = self.computeNegTicks(tickValues[1], yRange[1]) if len(negTicks) > 0 and negTicks[0] > yRange[0]: # if the first negative tick is greater than the min y range value, it is # removed from the list. This is the case if for example yRange == [-4, -10] # with a y tick value of 3 negTicks = negTicks[1:] posTicks = self.computePosTicks(tickValues[1], yRange[0]) posTicks.reverse() lastTickIdx = len(posTicks) - 1 if lastTickIdx >= 0 and posTicks[lastTickIdx] < yRange[1]: posTicks = posTicks[:-1] return posTicks + negTicks
d92e985b1b01a053cfbf7d976b97d5d6f318dc37
beautiousmax/hint_game
/hint_game.py
2,432
4.1875
4
import random #This is HINT. Like "CLUE", but not copyright infringing. #Here we have a list of options for a murder. Char = ["Mrs. Scarlet", "Col. Mustard", "Ms. White", "Mr. Green", "Rebecca Black", "Blue Man Group"] Weapon = ["Gun", "Candle Stick", "Lead Pipe", "Antifreeze", "Wrench", "Rope", "Arson"] Rooms = ["Library", "Kitchen", "Dining Room", "Garage", "Office", "Make-out Shed", "Auxiliary Basement"] #This Dictionary is going randomly select from the options to guess at. Murder = {"person": random.choice(Char), "killingthingy": random.choice(Weapon), "place": random.choice(Rooms)} #Here we populate the dict with the murder facts. print(""" Isn't this a lovely party? Well, somebody is dead now, let's figure out who. Your guests are: {0} The weapons on hand are: {1} Your weird house has: {2} So, there you have it. Start guessing. Be careful! If you take too long to figure it out,\ the murderer will get nervous and kill you too! """.format(", ".join(Char), ", ".join(Weapon), ", ".join(Rooms))) #random number of chances you get to guess: hints_left = random.randint(25, 36) #The idea is that after a set of guessing the number of guesses left decreases. #The guesses get checked against the murder dict. #If any guess is wrong, give a hint for a wrong guess. #i.e. who = Mrs. Scarlet "but Mrs. Scarlet was with me the whole time!" #When all guesses are right, game won. #When no guesses are left, game over. #Kinda like hangman?? but a little more sinister? def ask_me_anything(): who = raw_input("Who did it? ") what = raw_input("With what? ") where = raw_input("Where? ") return who, what, where def run_game(lives): while lives > 0: wrongers = [] who, what, where = ask_me_anything() if who != Murder['person']: wrongers.append(who) if what != Murder['killingthingy']: wrongers.append(what) if where != Murder['place']: wrongers.append(where) if len(wrongers) == 0: print("YOU WIN!") return else: print (str(random.choice(wrongers)) + " isn't right!\n") lives -= 1 "You died. \ {0} killed you with {1} in the {2}.".format(Murder["person"], Murder["killingthingy"], Murder["place"]) run_game(hints_left)
dd85a717ed1243c5cb7ff1b1e10ef9f8ae1fcbdf
s-surineni/atice
/code_chef/covid_run.py
555
3.609375
4
# https://www.codechef.com/OCT20B/problems/CVDRUN tc = int(input().strip()) def solve(): city_count, hop_dist, start, melive = [int(i) for i in input().strip().split()] # <!TODO> see why this is a failure # if city_count % 2: # return 'YES' curr_city = (start + hop_dist) % city_count while curr_city != melive and curr_city != start: curr_city = (curr_city + hop_dist) % city_count return 'YES' if curr_city == melive else 'NO' for _ in range(tc): print(solve())
2daef6ed8e06557301821c03e0a98ab4ba699c2d
arjunkorandla/automationlearning
/arjun2/forloop.py
1,078
3.71875
4
for i in range(1,12): print("the counting value of: {:4}".format(i)) num= "123,156,23,86561,846" for i in range(0,len(num)): print(num[i]) for i in range(0,len(num)): if num[i] in '0123456789': print(num[i]) for i in range(0,len(num)): if num[i] in '0123456789': print(num[i],end='') cleanedNumber='' for i in range(0,len(num)): if num[i] in '0123456789': cleanedNumber=cleanedNumber+num[i] newNumber=int(cleanedNumber) print(newNumber) for chr in ("uhdsu","kduyagd","ajdg"): print("the char are" + chr) for p in range(1,16,3): for q in range (1,16,3): print("the num {1} is multipled by{0} and sol is{2}".format(p,q,p*q)) for f in range(1,100,3): print(f) for p in range(1,16,3): for q in range (1,16,4): print("the num {1} is multipled by{0} and sol is{2}".format(p,q,q*p)) que="""Sanitation, the Medicine, Education, Wine, Public Order, Irrigation, Roads, the Fresh-Water System, and Public Health""" for char in que: if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": print(char,end='')
2bf957987e06a418b5c5988280e8720abe610135
HeithRobbins/python_notes
/replace-function.py
290
3.921875
4
sentence = 'The quick brown fox jumped over the lazy dog' sentence = sentence.replace('quick', 'slow') print(sentence) sentence = 'The quick brown fox jumped over the lazy dog.' sentence = sentence.replace('quick', 'slow') sentence = sentence.replace('slow', 'fast') print(sentence)
6a51badb0ab0b679fa4b1a783768ca8f160a4b40
wangsiyang68/Coding-Pains
/Content Notes/Problem Solving/Algorithms/Sorting/Self Learn Sorting Exercise.py
2,812
4.21875
4
##sorting exercise import random import time ##implement bubble, insertion and quick sort def bubble_sort(my_list): for i in range(0, len(my_list)): for j in range(0, len(my_list)-i-1): if my_list[j] > my_list[j+1]: my_list[j], my_list[j+1] = my_list[j+1],my_list[j] return my_list def insertion_sort(my_list): for i in range(1, len(my_list)): j = i - 1 this_number = my_list[i] while j >= 0 and this_number < my_list[j]: my_list[j+1] = my_list[j] j -= 1 my_list[j+1] = this_number return my_list def quick_sort(my_list): if len(my_list) <= 1: return my_list else: left = [] right = [] pivot = my_list[0] for i in range(1, len(my_list)): if my_list[i] >= pivot: right.append(my_list[i]) else: left.append(my_list[i]) return quick_sort(left) + [pivot] + quick_sort(right) def create_random_list(): random_list = [random.randint(0,100) for i in range(1000)] print("\nYour random list is :",random_list) return random_list ##UI SCRIPT learning = True while learning: print("Lets learn about sorting") print("1. Bubble Sort") print("2. Insertion Sort") print("3. Quick Sort") print("4. Quit") try: option = int(input("Please choose an option: ")) if option == 4: learning = False else: original_random_list = create_random_list() copy_of_random_list = original_random_list[:] input("Press Enter to continue\n") if option == 1: start = time.time() for i in range(100): sorted_list = bubble_sort(copy_of_random_list) end = time.time() text = "Bubble Sort returns:" elif option == 2: start = time.time() for i in range(100): sorted_list = insertion_sort(copy_of_random_list) end = time.time() end = time.time() text = "Insertion Sort returns:" elif option == 3: start = time.time() for i in range(100): sorted_list = quick_sort(copy_of_random_list) end = time.time() text = "Quick Sort returns:" print("Is the list sorted?", sorted_list == sorted(original_random_list)) print("Is this implementation of the sort in place?", copy_of_random_list == sorted_list) print("Time taken for the sort to complete:",float(end - start)/100) input("Press Enter to continue\n") except: print("Please enter a value from 1-4")
a01b5121cc8788d17c3fe07052616480a4d529de
iqram1337/komputasi_geofisika
/exercise 3.2 (pert 2).py
108
3.625
4
ans = 0 for i in range(2, 12, 2): print(i, end =' ') ans = ans + i print('') print(ans)
1c64fb54cd7e8bffa89060790db648e5e309d643
oucler/DLND-Bike-Sharing-Project
/multipleLayers.py
9,246
3.859375
4
import numpy as np np.random.seed(21) class NeuralNetworkMultiLayers(object): def __init__(self, input_nodes, hidden1_nodes, hidden2_nodes,hidden3_nodes, output_nodes, learning_rate): # Set number of nodes in input, hidden and output layers. self.input_nodes = input_nodes self.hidden1_nodes = hidden1_nodes self.hidden2_nodes = hidden2_nodes self.hidden3_nodes = hidden3_nodes self.output_nodes = output_nodes # Initialize weights self.weights_input_to_hidden1 = np.random.normal(0.0, self.input_nodes**-0.5, (self.input_nodes, self.hidden1_nodes)) self.weights_hidden1_to_hidden2 = np.random.normal(0.0, self.hidden1_nodes**-0.5, (self.hidden1_nodes, self.hidden2_nodes)) self.weights_hidden2_to_hidden3 = np.random.normal(0.0, self.hidden2_nodes**-0.5, (self.hidden2_nodes, self.hidden3_nodes)) self.weights_hidden_to_output = np.random.normal(0.0, self.hidden3_nodes**-0.5, (self.hidden3_nodes, self.output_nodes)) self.lr = learning_rate #### TODO: Set self.activation_function to your implemented sigmoid function #### # # Note: in Python, you can define a function with a lambda expression, # as shown below. self.activation_function = lambda x : 1/(1+np.exp(-x)) # Replace 0 with your sigmoid calculation. ### If the lambda code above is not something you're familiar with, # You can uncomment out the following three lines and put your # implementation there instead. # #def sigmoid(x): # return 0 # Replace 0 with your sigmoid calculation here #self.activation_function = sigmoid def train(self, features, targets): ''' Train the network on batch of features and targets. Arguments --------- features: 2D array, each row is one data record, each column is a feature targets: 1D array of target values ''' n_records = features.shape[0] delta_weights_i_h1 = np.zeros(self.weights_input_to_hidden1.shape) delta_weights_h1_h2 = np.zeros(self.weights_hidden1_to_hidden2.shape) delta_weights_h2_h3 = np.zeros(self.weights_hidden2_to_hidden3.shape) delta_weights_h_o = np.zeros(self.weights_hidden_to_output.shape) for X, y in zip(features, targets): final_outputs, hidden1_outputs, hidden2_outputs,hidden3_outputs = self.forward_pass_train(X) # Implement the forward pass function below # Implement the backproagation function below delta_weights_i_h1, delta_weights_h1_h2,delta_weights_h2_h3, delta_weights_h_o = self.backpropagation(final_outputs, hidden1_outputs,hidden2_outputs, hidden3_outputs, X, y, delta_weights_i_h1,delta_weights_h1_h2, delta_weights_h2_h3,delta_weights_h_o) self.update_weights(delta_weights_i_h1, delta_weights_h1_h2,delta_weights_h2_h3, delta_weights_h_o, n_records) def forward_pass_train(self, X): ''' Implement forward pass here Arguments --------- X: features batch ''' #### Implement the forward pass here #### ### Forward pass ### # TODO: Hidden layer - Replace these values with your calculations. hidden1_inputs = np.dot(X,self.weights_input_to_hidden1) # signals into hidden layer hidden1_outputs = self.activation_function(hidden1_inputs) # signals from hidden layer hidden2_inputs = np.dot(hidden1_outputs,self.weights_hidden1_to_hidden2) hidden2_outputs = self.activation_function(hidden2_inputs) hidden3_inputs = np.dot(hidden2_outputs,self.weights_hidden2_to_hidden3) hidden3_outputs = self.activation_function(hidden3_inputs) # TODO: Output layer - Replace these values with your calculations. final_inputs = np.dot(hidden3_outputs,self.weights_hidden_to_output) # signals into final output layer final_outputs = final_inputs#self.activation_function(final_inputs) # signals from final output layer return final_outputs, hidden1_outputs, hidden2_outputs, hidden3_outputs def backpropagation(self, final_outputs, hidden1_outputs, hidden2_outputs,hidden3_outputs,X, y, delta_weights_i_h1, delta_weights_h1_h2,delta_weights_h2_h3,delta_weights_h_o): ''' Implement backpropagation Arguments --------- final_outputs: output from forward pass y: target (i.e. label) batch delta_weights_i_h: change in weights from input to hidden layers delta_weights_h_o: change in weights from hidden to output layers ''' #### Implement the backward pass here #### ### Backward pass ### # TODO: Output error - Replace this value with your calculations. error = y-final_outputs # Output layer error is the difference between desired target and actual output. # TODO: Backpropagated error terms - Replace these values with your calculations. output_error_term = error#*final_outputs*(1-final_outputs) hidden3_error = np.dot(self.weights_hidden_to_output,output_error_term) hidden3_error_term = hidden3_error * hidden3_outputs * (1 - hidden3_outputs) # TODO: Calculate the hidden layer's contribution to the error hidden2_error = np.dot(self.weights_hidden2_to_hidden3,hidden3_error_term) hidden2_error_term = hidden2_error * hidden2_outputs * (1 - hidden2_outputs) hidden1_error = np.dot(self.weights_hidden1_to_hidden2,hidden2_error_term) hidden1_error_term = hidden1_error * hidden1_outputs * (1 - hidden1_outputs) # Weight step (input to hidden) delta_weights_i_h1 += hidden1_error_term*X[:,None] delta_weights_h1_h2 += hidden1_outputs[:,None]*hidden2_error_term delta_weights_h2_h3 += hidden2_outputs[:,None]*hidden3_error_term # Weight step (hidden to output) delta_weights_h_o += hidden3_outputs[:,None]*output_error_term return delta_weights_i_h1,delta_weights_h1_h2,delta_weights_h2_h3, delta_weights_h_o def update_weights(self, delta_weights_i_h1, delta_weights_h1_h2, delta_weights_h2_h3,delta_weights_h_o, n_records): ''' Update weights on gradient descent step Arguments --------- delta_weights_i_h: change in weights from input to hidden layers delta_weights_h_o: change in weights from hidden to output layers n_records: number of records ''' self.weights_hidden_to_output += self.lr*delta_weights_h_o/n_records # update hidden-to-output weights with gradient descent step self.weights_input_to_hidden1 += self.lr*delta_weights_i_h1/n_records # update input-to-hidden weights with gradient descent step self.weights_hidden1_to_hidden2 += self.lr*delta_weights_h1_h2/n_records # update input-to-hidden weights with gradient descent step self.weights_hidden2_to_hidden3 += self.lr*delta_weights_h2_h3/n_records # update input-to-hidden weights with gradient descent step def run(self, features): ''' Run a forward pass through the network with input features Arguments --------- features: 1D array of feature values ''' #### Implement the forward pass here #### # TODO: Hidden layer - replace these values with the appropriate calculations. hidden1_inputs = np.dot(features,self.weights_input_to_hidden1) # signals into hidden layer hidden1_outputs = self.activation_function(hidden1_inputs) # signals from hidden layer hidden2_hidden1 = np.dot(hidden1_outputs,self.weights_hidden1_to_hidden2) hidden2_outputs = self.activation_function(hidden2_hidden1) hidden3_hidden2 = np.dot(hidden2_outputs,self.weights_hidden2_to_hidden3) hidden3_outputs = self.activation_function(hidden3_hidden2) # TODO: Output layer - Replace these values with the appropriate calculations. final_inputs = np.dot(hidden3_outputs, self.weights_hidden_to_output)# signals into final output layer final_outputs = final_inputs#self.activation_function(final_inputs) # signals from final output layer return final_outputs ######################################################### # Set your hyperparameters here ########################################################## iterations = 10000 learning_rate = 0.4 hidden1_nodes = 12 hidden2_nodes = 12 hidden3_nodes = 10 output_nodes = 1
ab1a83ffb91909966c799cde082c52a1dfc4d5dc
bFraley/python-examples
/TRAVIS_BAUMANN.py
752
4.40625
4
""" # Number one will be a random number generator using the "random" function. In the print section I get to choose my chosen integer range, dissected by commas. This program basically simulates a 6-sided dice """ from random import randint print (randint(1,6)) """ # HEX function this will convert any number into a hexidecimal number. In my example I had 154 carrots and wanted to see that value in hexidecimal. """ print ("\n\n") Carrots = 154 print hex(Carrots) """ # The int() function generates a static identity of an object that will be constant throughout the program. could be used to make sure two id's are the same thing. ex. a=b. id(a) and id(b) will show up with the same number. """ randomobj = int(1) print(id(randomobj))
193784c22f38b819e3ec57e91ceceb309a16d9c4
pontushojer/rosalind
/tree.py
1,463
3.71875
4
#!/usr/bin/env python3 """ Problem: Completing a Tree url: http://rosalind.info/problems/tree/ Given: A positive integer nn (n≤1000n≤1000) and an adjacency list corresponding to a graph on nn nodes that contains no cycles. Return: The minimum number of edges that can be added to the graph to produce a tree. """ def inputAdjacencies(file_name): with open(file_name,"r") as file: firstLine = True adjList = [] for line in file.readlines(): line = line.replace('\n','') if firstLine: nodesTotal = int(line) firstLine = False else: adjList.append(line.split(' ')) return adjList, nodesTotal def main(): [adjList, nodesTotal] = inputAdjacencies("./data/rosalind_tree.txt") clusters = {node:[] for node in range(1,nodesTotal+1)} for nodes in adjList: n0 = int(nodes[0]) n1 = int(nodes[1]) clusters[n0].append(n1) clusters[n1].append(n0) trees=[] for c in clusters: newTree=True for tree in trees: if c in tree: tree.update(clusters[c]) newTree=False if newTree: currentSet=set() currentSet.add(c) currentSet.update(clusters[c]) trees.append(currentSet) print(len(trees)-1) if __name__ == '__main__': main()
6ce72bf638e319d62acd972ed3ddfda559246f4d
salamba-eric/BMI-calculator
/BMI_calculator.py
3,118
3.59375
4
import sign_up import pymongo from tkinter import * from pymongo import * window = Tk() client = MongoClient() Data_Base = client.BMI users_data = Data_Base.users_data #def calculate_bmi(): # Calculating function # def metric_calculator(): # Clear what's on the space # BMI_display_entry.delete(0, 'end') #Getting the values # try: height = (int(height_str.get())/100) weight = int(weight_str.get()) BMI = weight/(height*height) except ValueError: value_error() BMI = 0 # What to display # if BMI != 0: BMI_listbox.delete(0, 'end') BMI_display_entry.insert(END ,str(BMI)) Error_msg1.destroy() if BMI <16: comment = "You are Severely Underweight" elif BMI < 18: comment = "You are Underweight" elif BMI < 23: comment = "You are Healthy" elif BMI <29: comment = "You are Overweight" elif BMI <39: comment = "You are Obese" else: comment = "You are Extremely Obese" BMI_listbox.insert(1, " " + str(BMI)) BMI_listbox.insert(2 ,comment) current_doc = list(users_data.find({},sort = [( '_id', pymongo.DESCENDING )]).limit(1)) data = dict(current_doc[0]) user_name = data["Username"] users_data.update_one({"Username": user_name },{"$set":{"BMI": BMI }}) # Window widgets # # The labels # label_1 = Label(window, text = "This will calculate your BMI", fg = "black", font = ("Arial" , 12)) label_2 = Label(window, text = "Input your weight and height below", fg = "black", font = ("Arial" , 12)) height_label = Label(window, text = "Enter your height (cm)", fg = "black", font = ("Arial" , 14)) weight_label = Label(window, text = "Enter your weight (kg)", fg = "black", font = ("Arial" , 14)) BMI_display_label = Label(window, text = "Your BMI is ", fg = "black", font = ("Arial", 14)) list_label = Label(window, text = "Your previous BMI's", font = ("Arial" , 12)) Error_msg1 = Label(window, text = "Input numerals as your height and weight", fg = "red", font = ("Arial", 12)) #The entrys # height_str = Entry(window, bg = "white", fg = "black", bd = 3) weight_str = Entry(window, bg = "white", fg = "black", bd = 3) BMI_display_entry = Entry(window, font = ("Arial", 12)) #The buttons# calculate_button = Button(window,text = "Calculate", bd = 1, font = ("Arial" , 12), command = metric_calculator) #The listbox # BMI_listbox = Listbox(window,width = 30, height = 11, font = ("Raleway" )) #Widget placements # # labels # label_1.place(x = 75, y = 25) label_2.place(x = 50, y = 50) height_label.place(x = 10, y = 85) weight_label.place(x = 10, y = 113) BMI_display_label.place(x = 125, y = 185) list_label.place(x = 100, y = 265) # entrys # height_str.place(x = 200, y = 90 ,width = 90 , height = 20) weight_str.place(x = 200, y = 118 ,width = 90 , height = 20) BMI_display_entry.place(x = 90, y = 210) # buttons # calculate_button.place(x = 125, y = 150) # listbox # BMI_listbox.place(x = 25, y = 285,width = 300, height = 120) # Error handling # def value_error(): Error_msg1.place(x = 33, y = 240) #Generating the window # window.title("BMI Calculator") window.geometry("350x500+550+100") window.mainloop()
cc12b2e4ba04e4a82b02a3b0c76f26331e7f9009
NikhilaBanukumar/GeeksForGeeks-and-Leetcode
/strings16.py
1,030
3.546875
4
def pallindrome(strings,k,l): m=k for n in range(l,k,-1): if strings[m]!=strings[n]: return False m+=1 return True def find_pallindrome_substrings(strings,i,j): count=0 for k in range(i,j+1,1): count+=1 for l in range(j,k,-1): pallin=pallindrome(strings,k,l) if pallin: count+=1 return count def simpler(str): n=len(str) dp=[[0 for i in range(n)]for j in range(n)] ispalin=[[0 for i in range(n)] for j in range(n)] for i in range(n-1,-1,-1): dp[i][i]=1 ispalin[i][i]=1 for j in range(i+1,n,1): print(str[i]+" "+str[j]) ispalin[i][j]= (str[i]==str[j]) and ((i+1>j-1) or (1 if ispalin[i+1][j-1]!=0 else 0)) dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1]+ispalin[i][j] for i in ispalin: print(i) print("") for i in dp: print(i) print(dp[3][5]) # print(find_pallindrome_substrings("xyaabax",2,3)) simpler("xyaabaa")
58a62b3469fcebcfa331df5bb01dc6201f04c889
Srishti20022/Python-basics
/numpy/array3.py
700
3.671875
4
# to compare time and space took by array and list import numpy as np import time import sys list_1 = list(range(1000)) # get size functions used to get size of any function print("size of lst : ", end = ' ') print(sys.getsizeof(list_1)) array_1 = np.array(list(range(1000))) array_2 = np.array(list(range(1000))) print("size of array : ", end = ' ') print(sys.getsizeof(array_1)) list_2 = list(range(1000)) start = time.time() for i in range(len(list_1)): list_1[i]+list_2[i] end = time.time() total = end - start print("total time for lists: "+str(total)) start = time.time() array_1+array_2 end = time.time() total = end - start print("total time for array:"+str(total))
38ab336fff18c2525a48eccfcff3d45eb01b6977
aliceturino/learning-python-projects
/bmi-calculator.py
621
4.375
4
# 🚨 Don't change the code below 👇 height = input("enter your height in m: ") weight = input("enter your weight in kg: ") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 height = float(height) weight = float(weight) BMI = weight / height ** 2 print("Your BMI is " + str(int(BMI))) #extra que eu fiz if BMI < 18.5: print("You're underweight") elif BMI > 18.5 and BMI < 24.9: print("You're in normal weight") elif BMI > 25 and BMI < 29.9: print("You're overweight") elif BMI > 30 and BMI < 30.4: print("You're obese") elif BMI > 35: print("You're extremely obese")
6a87a72becf7ed4a55b25dacdf48e6d88157ed93
Yuto-kimura/data-management
/datamanagement.py
576
3.796875
4
import random class MenuItem: def road(self): print("Rolling the dice...") def dais(self,daisA,daisB): print("Die:"+str(daisA)) print("Die:"+str(daisB)) def hello(self): print("Hello,"+self.name+"!") menu_item1 = MenuItem() print("What is your name?") menu_item1.name = input(">") menu_item1.hello() menu_item1.road() daisA = random.randint(1,6) daisB = random.randint(1,6) result = daisA + daisB menu_item1.dais(daisA,daisB) print("Total value:"+str(result)) if result > 7: print("You won!") else: print("You lost.")
e4fa6bc6a1eea3c84519e91fc284667ac83919d6
BobIT37/Python3Programming
/venv/03-Methods and Functions/04-Function Level 1 Solutions.py
319
4.0625
4
# Level 1 Problems' solution def old_macdonald(name): if len(name) > 3: return name[:3].capitalize() + name[3:].capitalize() else: return "name is too short!" print(old_macdonald('macdonald')) def master_yoda(text): return ' '.join(text.split()[::-1]) print(master_yoda('We are ready'))
4e2732888bd2d6440a808f505a4c5782747d120f
mdk44/OtherProjects
/Avalon/Avalon.py
836
3.65625
4
# Avalon Test import random character_list = { 0: 'Merlin', # Knows all evil except Mordred 1: 'Percival', # Knows who Merlin is 2: 'Loyal Servant of Arthur', 3: 'Loyal Servant of Arthur', 4: 'Loyal Servant of Arthur', 5: 'Loyal Servant of Arthur', 6: 'Loyal Servant of Arthur', 7: 'Mordred', # Unknown to Merlin 8: 'Assassin', # Gets to attempt assassination of Merlin if good guys 'win' 9: 'Oberon', # Unknown to evil 10: 'Morgana', # Appears as Merlin to Percival 11: 'Minion of Mordred', 12: 'Minion of Mordred', 13: 'Minion of Mordred' } curr_characters = [0, 1, 2, 7, 8] random.shuffle(curr_characters) for c in curr_characters: if c == 0: print("My character: " + character_list[curr_characters[c]]) else: print("--")
e80bf29a01d65ee42a2b383809eebed9a2d57ce6
Infra1515/Automate-the-boring-stuff
/CH5_Fantasy_game_inventory.py
735
3.84375
4
#! python 3 # Fantasy game inventory + list_to_dict function stuff = {'Arrows': 2, 'Belt': 1, 'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'Arrows': 12} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] def displayInventory(inventory): print ('Inventory: ') item_total = 0 for k, v in inventory.items(): print (k,v) item_total += v print ('Total: ' + str(item_total)) def addToInventory(inventory, addedItems): print ('Items to be added: ' + str(addedItems)) for item in addedItems: inventory.setdefault(item, 0) inventory[item] += 1 print ('New Inventory: ') displayInventory(stuff) addToInventory(stuff, dragonLoot) displayInventory(stuff)
b6dd84d51b0bacac1a604cdf72156aa0343365f5
Wu22e/JUNGLE_DS_ALGO
/WEEK01/B4[2588] 곱셈.py
208
3.578125
4
a=input() b=input() a=int(a) b=int(b) location100=b//100 location10=(b-location100*100)//10 location1=b-location100*100-location10*10 print(a*location1) print(a*location10) print(a*location100) print(a*b)
aec7a69ede6151eaa36af402b1f563d972ccdeaf
Muhammad-Hozefa-Haider/Probability-Statistics-Project
/task5.py
1,632
3.578125
4
import turtle import random import matplotlib.pyplot as plt # t = turtle.Turtle() t.speed(0) t.penup() t.setposition(0,-100) t.pendown() t.pensize(3) t.fillcolor("green") t.begin_fill() t.circle(100) t.end_fill() t.penup() t.setposition(0,0) t.pendown() t.hideturtle() t.color("yellow") # t.penup() # t.forward(50) # t.pendown() # t.circle(100) # t.penup() # t.backward(50) def randommovement(startx=0,starty=0): t.pensize(1) t.setposition(startx,starty) maxdist=0 for i in range(10000): x=(t.pos())[0] y=(t.pos())[1] if maxdist<((x-startx)**2+(starty-y)**2): maxdist = (x-startx)**2+(starty-y)**2 while (x**2 + y**2 > 100**2): t.penup() if (x<0): x+=1 else: x-=1 if (y<0): y+=1 else: y-=1 t.setposition(x,y) t.pendown() continue t.forward(random.uniform(0,1)) t.right(random.uniform(0,360)) return (maxdist**0.5) def randommovementgraph(): turtle.tracer(0, 0) res={} for i in range(101): res[i]=0 for i in range(100): a = int (randommovement()) if a in list(res.keys()): res[a]+=1 else: res[a]=1 plt.bar(list(res.keys()), list(res.values())) plt.suptitle('times how many times walk ended at a certain distance\nwith starting position 0,0 (1000 steps)', fontsize=10) plt.xlabel('distances') plt.ylabel('no of times a walk ended') plt.show() randommovement() turtle.Screen().exitonclick()
811634a9a923ad4f329619a62cd880ccd6d5f5ef
prashant-subedi/Ellastic-Collision-Game
/graphics_final.py
8,240
3.8125
4
import numpy as np import pygame class Ball: """Define physics of elastic collision.""" def __init__(self, mass, radius, position, velocity): """Initialize a Ball object mass the mass of ball radius the radius of ball position the position vector of ball velocity the velocity vector of ball """ self.mass = mass self.radius = radius self.position = position self.velocity = velocity print(self.velocity) self.vafter = np.copy(velocity) # temp storage for velocity of next step self.delete = False def compute_step(self, step): """Compute position of next step.""" #print(self.velocity) self.position += step * self.velocity #print(self.position) def new_velocity(self): """Store velocity of next step.""" self.velocity = self.vafter def compute_coll(self, ball, step): """Compute velocity after elastic collision with another ball.""" m1 = self.mass m2 = ball.mass r1 = self.radius r2 = ball.radius v1 = self.velocity v2 = ball.velocity x1 = self.position x2 = ball.position di = x2-x1 norm = np.linalg.norm(di) if norm-r1-r2 < step*abs(np.dot(v1-v2,di))/norm: self.vafter = v1 - 2.*m2/(m1+m2) * np.dot(v1-v2,di)/(np.linalg.norm(di)**2.) * di def compute_refl(self, step, borders,obstacle): """Compute velocity after hitting an edge. step the step of computation size the size of a square edge """ r = self.radius v = self.velocity x = self.position projx = step*abs(np.dot(v,np.array([1.,0.]))) projy = step*abs(np.dot(v,np.array([0.,1.]))) a = pygame.Rect(0,0,borders[3][0],borders[3][0]) b = pygame.Rect(0,borders[0][1]+borders[0][3],borders[3][0],borders[3][1]+borders[3][3]) c = pygame.Rect(borders[2][0]+borders[2][2],0,borders[3][0],borders[3][0]) d = pygame.Rect(borders[3][0]+borders[3][2],borders[1][1]+borders[1][3],borders[3][0],borders[3][0]) if(a.collidepoint(*self.position) or b.collidepoint(*self.position) or c.collidepoint(*self.position) or d.collidepoint(*self.position)): self.vafter *= 0 self.delete = True else: if (abs(x[0])-r -borders[0][0]-borders[0][2] < projx ) or (abs(borders[1][0]- x[0])-r < projx): self.vafter[0] *= -1 if abs(x[1])-r -(borders[2][1]+borders[2][3]) < projy or abs(borders[3][1]-x[1])-r < projy: self.vafter[1] *= -1. if obstacle != None: obs = pygame.Rect(*obstacle) if obs.collidepoint(x[0] + r,x[1]): self.vafter[0] = -20 if obs.collidepoint(x[0] - r,x[1]): self.vafter[0] = 20 if obs.collidepoint(x[0],x[1]- r): self.vafter[1] = 20 if obs.collidepoint(x[0], x[1]+ r): self.vafter[1] = -20 def step1(ball_list, step,borders,obstacle=None): """Detect reflection and collision of every ball.""" index_list = range(len(ball_list)) for i in index_list: ball_list[i].compute_refl(step,borders,obstacle) for j in index_list: if i!=j: ball_list[i].compute_coll(ball_list[j],step) return ball_list def step2(ball_list, step): """Compute position of every ball.""" index_list = range(len(ball_list)) for i in index_list: ball_list[i].new_velocity() ball_list[i].compute_step(step) return ball_list def solve_step(ball_list, step,borders,obstacle=None): """Solve a step for every ball.""" ball_list = step1(ball_list, step,borders,obstacle) ball_list = step2(ball_list, step) def init_list(N): """Generate N Ball objects in a list.""" ball_list = [] r = 10. for i in range(N): v = 10.*np.array([(-1.)**i,1.]) pos = 800./float(N+1)*np.array([float(i+1),float(i+1)])+[50,50] ball_list.append(Ball(r, r, pos, v)) return ball_list def gameLoop(time_before): ball_list = init_list(20) size = 800. step = 0.1 pygame.init() border = 50 white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) yellow = (255,125,0) grey = (0,255,0) gameDisplay = pygame.display.set_mode((int(size)+2*border,int(size)+2*border)) pygame.display.set_caption("Elastic Collision") clock = pygame.time.Clock() left_border = [0,3*border//2,border,size-border] right_border = [size+border,3*border//2,size+2*border,size-border] top_border = [3*border//2,0,size-border,border] bottom_border = [3*border//2,size+border,size-border,border] pressed = False time = 0 pygame.font.init() myfont = pygame.font.SysFont('Comic Sans MS', 30) space = False exit = False game_over = False prev_obs = [] while(True): space = False for event in pygame.event.get(): if event.type == pygame.QUIT: exit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: space = True if event.type == pygame.MOUSEBUTTONDOWN: mp = pygame.mouse.get_pos() #print(a) pressed = True if event.type == pygame.MOUSEBUTTONUP: pressed = False if exit == True: pygame.quit() quit() gameDisplay.fill((255, 255, 255)) #LEFT gameDisplay.fill(yellow, rect=left_border) #RIGHT gameDisplay.fill(yellow, rect=right_border) #UP gameDisplay.fill(yellow, rect=top_border) #DOWN gameDisplay.fill(yellow, rect=bottom_border) borders = [left_border,right_border,top_border,bottom_border] gameDisplay.fill(black,rect=[0,0,borders[3][0],borders[3][0]]) gameDisplay.fill(black,rect=[0,borders[0][1]+borders[0][3],borders[3][0],borders[3][1]+borders[3][3] ]) gameDisplay.fill(black,rect=[borders[2][0]+borders[2][2],0,borders[3][0],borders[3][0]]) gameDisplay.fill(black,rect=[borders[3][0]+borders[3][2],borders[1][1]+borders[1][3],borders[3][0],borders[3][0]]) #gameDisplay.fill(black,rect=[borders[2][0]+borders[2]]) if len(ball_list) == 0: textsurface = myfont.render("Game Over. Your time is "+str((time-time_before)//1000), False, (0, 0, 0)) gameDisplay.blit(textsurface, (size // 2, size // 2 - size // 4)) game_over = True if game_over == False: time = pygame.time.get_ticks() textsurface = myfont.render('Time: ' + str((time-time_before) // 1000), False, (0, 0, 0)) gameDisplay.blit(textsurface, (size // 2, 0)) if pressed == True: a = pygame.mouse.get_pressed() print(a) if a[0]==1: obstacle = list(pygame.mouse.get_pos()) + [20, 400] #obstacle = list(mp) + [20, 400] elif a[2]==1: obstacle = list(pygame.mouse.get_pos()) + [400, 20] #obstacle = list(mp) + [400, 20] if obstacle == prev_obs: pygame.draw.rect(gameDisplay,black,obstacle) solve_step(ball_list, step, borders,obstacle) else: pygame.draw.rect(gameDisplay,grey,obstacle) solve_step(ball_list, step, borders) prev_obs = obstacle else: solve_step(ball_list, step, borders) for i in ball_list: if i.delete == True: ball_list.remove(i) pygame.draw.circle(gameDisplay,(255, 0, 0) , i.position.astype('int'),int(i.radius)) else: if game_over == True and space == True: break pygame.display.update() clock.tick(1000) pygame.quit() gameLoop(time) if __name__ == "__main__": gameLoop(0)
e396ca4d51c42c278ef6a6c517d380bc8dd4bcb1
faradayyg/data-structures-python
/linked_list.py
436
3.8125
4
#!/usr/bin/python3 from LinkedList.LinkedList import LinkedList linked_list = LinkedList() linked_list.insert_start(23) linked_list.insert_start(33) linked_list.insert_start(36) linked_list.traverse() print('\n\n ==== ') linked_list.remove(23) print(linked_list.size()) linked_list.traverse() print('\n\n ==== ') linked_list.insert_start('mbido') linked_list.insert_end('nkwusi') linked_list.traverse() print(linked_list.size())
78cf6d6ad0d0e5fd8a0f1dbae14ce870bae37ac2
DhilipBinny/Python_for_everybody
/Python Data Structures/week 4/Assignment 8.4.py
251
4.0625
4
fname = input("Enter file name: ") fh = open(fname) list = [] for line in fh: line = line.rstrip() words = line.split(' ') for word in words: if word not in list: list.append(word) list.sort() print (list)
5040332e6103d3d69fcbc276a335c66e85fe53a5
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/leetcode/LeetCode/670 Maximum Swap.py
1,173
3.828125
4
#!/usr/bin/python3 """ Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get. Example 1: Input: 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. Example 2: Input: 9973 Output: 9973 Explanation: No swap. Note: The given number is in the range [0, 108] """ class Solution: def maximumSwap(self, num: int) -> int: """ stk maintain a increasing stack from right to left """ stk = [] nums = list(str(num)) n = len(nums) for i in range(n-1, -1, -1): if stk and stk[-1][1] >= nums[i]: # only keep the rightmost duplicate continue stk.append((i, nums[i])) for i in range(n): while stk and stk[-1][0] <= i: stk.pop() if stk and stk[-1][1] > nums[i]: j = stk[-1][0] nums[i], nums[j] = nums[j], nums[i] break return int("".join(nums)) if __name__ == "__main__": assert Solution().maximumSwap(2736) == 7236 assert Solution().maximumSwap(9973) == 9973
0c9caf4322140428c3437cd3663c4943f01bea5c
martinearlz/PSB-Quiz-Application
/logic.py
5,325
3.640625
4
"""This script stores the train logic class that contains all the program-related functions.""" from variables import Variables variables = Variables() class Logic: def __init__(self): self.username = "" def login(self, username, password): # Load the users dictionary, users = variables.get_users() # If the username is not in the dictionary, then return false (prevents exceptions). if username not in users: return False # Else, if the username is in the dictionary, just # check whether the value is the same as the password enter. if users[username] == password: self.username = username return True return False def get_current_user_name(self): return self.username def get_user_scores(self): scores = variables.get_scores() # Create a new list to assign value from LINES list, based on the current username. user_scores = list(filter(lambda score: self.username in score, scores)) # return last 3 in the list return user_scores[-3:] def get_high_scores(self): # Get the last 10 scores scores = variables.get_scores()[-10:] # Sort from highest to lowest. scores.sort(reverse=True, key=lambda x: int(''.join(filter(str.isdigit, x)))) return scores def save_user_score(self, score): with open(variables.resource_path("databases/high_scores.txt"), "a+") as score_file: score_file.write(f"{self.username} {score}\n") class Quiz: def __init__(self): self.correct_answers = 0 self.user_answers = [] self.answers = variables.get_answers() self.questions = variables.get_questions() self.options = variables.get_options() self.has_initialized = False self.answer_map = {1 : "A", 2 : "B", 3 : "C", 4 : "D"} def mark_answer(self, answer, q_no): ''' Marks the given answer for the given question number. Args: - answer (int) : The answer that the user gave. - q_no (int) : The question number. Returns: - none ''' if answer == self.answers[q_no]: self.correct_answers += 1 self.user_answers.append(answer) def get_results(self): ''' Returns the results of an attempt. Args: - none Returns: - correct_answers (int) : number of correct answers. - wrong_answers (int) : number of wrong answers. - score (int) : score. ''' # calculates the wrong count wrong_answers = len(self.questions) - self.correct_answers # calculates the percentage of correct answers score = int(self.correct_answers / len(self.questions) * 100) return self.correct_answers, wrong_answers, score def is_end_of_quiz(self, q_no): ''' Checks whether the quiz is already at the end. Args: - q_no (int) : Current question number. Returns: - is_end_of_quiz (bool) : True if the quiz is already at the end. False otherwise. ''' return q_no == len(self.questions) def load_options(self, opts, q_no): ''' Loads options to the radio button. Args: - opts (radio button) : Options. - q_no (int) : Current question number. Returns: - none ''' for val, option in enumerate(self.options[q_no]): opts[val]['text'] = f"{self.answer_map[val+1]}. {option}" def get_current_question(self, q_no): ''' Returns the current question text for the given question number. Args: - q_no (int) : Question number. Returns: - question (str) : The question. ''' return self.questions[q_no] def get_correct_answers(self): return self.correct_answers def reset_answers(self): self.correct_answers = 0 self.user_answers.clear() def get_questions(self): return self.questions def get_answers(self): answers = list(map(lambda x: self.answer_map[x], self.answers)) return answers def get_corrections(self): corrected_list = [] if not self.user_answers: return corrected_list # For every answer for each question, for index, correct_answer in enumerate(self.answers): answer = self.user_answers[index] # Skip records where the user's answer is correct. if answer == correct_answer: continue # Check whether the answer is above 0, and gets the answer from the options list. Otherwise, the user did not answer. if answer > 0: users_answer = self.options[index][answer - 1] else: users_answer = "empty" corrected_list.append(f"For question {index + 1}, your answer is: {users_answer}. The correct answer is: {self.options[index][correct_answer - 1]}") if not corrected_list: corrected_list.append("You got it all correct!") return corrected_list
544f1775e6fb234fd26f439da84c37961f76522b
wjjameslee/ATMController
/account.py
691
3.703125
4
class Account: def __init__(self, balance=0, limit=0): self.balance = balance self.limit = limit def deposit(self, amount): self.balance += amount print("Successfully deposited $" + str(amount) + ".") def withdraw(self, amount): if amount > self.limit: print("Amount to withdraw exceeds account limit.") return if self.balance - amount < 0: print("Cannot withdraw amount exceeding balance.") else: self.balance -= amount print("Successfully withdrew $" + str(amount) + ".") def read_balance(self): print("Your Balance: $" + str(self.balance))
35a7ffdf07c41e67d128e6205b1b3772ee0db3d1
bedros-bzdigian/intro-to-python
/week 4/homework/problem7.py
159
3.6875
4
list4 = [[10,20,40], [40,50,60] , [70,80,90] ] list5 = list4.copy() for x in range (0,3): list5[x][2] = 100 print ("list4 ", list4) print ("list5 ", list5)
e458218b8170dd2174a8961b4b37462a6d2dc72b
Lancelot1106/HU_AI_Blok_C
/Structured Programming/Simple Algorithm.py
1,909
3.734375
4
from random import randint from itertools import * code = "ABCD" def Allcombos(): """creates a list with all options for the AI to choose from the first time around""" global allcombos allcombos = [] results = product("ABCDEF", repeat=4) allcombos = resulttolist(results) return AIpicks(allcombos) def resulttolist(result): """turns a result from a calculation with itertools into a list and returns it""" newlist = [] for i in result: j = "".join(i) newlist.append(j) return newlist def AIpicks(codes): AIguess = codes[0] print(f"Your code was {code}") print(f"My guess was {AIguess}") correct = input(str("how many did I get completely correct? ")) semicorrect = input(str("and how many colors are right? ")) feedback = (correct, semicorrect) print(feedback) return NewlistAI(codes, AIguess, feedback) def auto_feedback(guess, code): wit = 0 zwart = 0 used = [] #needed a way to split the strings from the list into lists Codesplit = [] Codesplit[:0] = code Extracode = Codesplit.copy() for i in range(len(guess)): Guesssplit = [] Guesssplit[:0] = guess[i] if guess[i] == code[i]: wit += 1 used.append(i) for i in used: Extracode.remove(code[i]) for i in range(len(guess)): Guesssplit = [] Guesssplit[:0] = guess[i] if guess[i] in Extracode and guess[i] not in used: if guess[i] in Extracode: zwart += 1 Extracode.remove(guess[i]) print (wit, zwart) return (wit, zwart) def NewlistAI(previouslist, guess, feedback): newlist = [] for i in previouslist: if feedback == auto_feedback(guess, i): newlist.append() print(newlist) return AIpicks(newlist) print(Allcombos())
d0f73b1a92c80e39f2e5c7d09d5163c9d18e2316
charlesfranciscodev/codingame
/clash-of-code/fastest/calc-weight/calc_weight.py
713
4
4
def calculate_actual_weight(body_weight, repetitions, exercise_type, added_weight): if exercise_type == 'bp': actual_weight = (added_weight + 20) * repetitions elif exercise_type == 'lp': actual_weight = (added_weight + 47) * repetitions elif exercise_type == 'p': actual_weight = (added_weight + body_weight) else: actual_weight = 0 return actual_weight # Get input from the user body_weight = int(input()) repetitions = int(input()) exercise_type = input() added_weight = int(input()) # Calculate the actual weight actual_weight = calculate_actual_weight(body_weight, repetitions, exercise_type, added_weight) # Output the result print(actual_weight)
006074011ebe991f9728982aa7aa47cb76474aaa
Edgar-La/Machine_Learning
/Bounds_classifier_comparison/FFNN_module.py
5,147
3.9375
4
#Feed Forward Neural Network import numpy as np import pandas as pd #This is for avoid future warning: RuntimeWarning: overflow encountered in exp from scipy.special import expit def sigmoid(s): # Activation function return 1 / (1 + np.exp(-s)) def sigmoid_prime(s): # Derivative of the sigmoid return sigmoid(s) * (1 - sigmoid(s)) class FFNN(object): def __init__(self, input_size=2, hidden_size=2, output_size=1): # Adding 1 as it will be our bias self.input_size = input_size + 1 self.hidden_size = hidden_size + 1 self.output_size = output_size self.o_error = 0 self.o_delta = 0 self.z1 = 0 self.z2 = 0 self.z3 = 0 self.z2_error = 0 # The whole weight matrix, from the inputs till the hidden layer self.w1 = np.random.randn(self.input_size, self.hidden_size) # The final set of weights from the hidden layer till the output layer self.w2 = np.random.randn(self.hidden_size, self.output_size) def forward(self, X): # Forward propagation through our network X['bias'] = 1 # Adding 1 to the inputs to include the bias in the weight self.z1 = np.dot(X, self.w1) # dot product of X (input) and first set of 3x2 weights self.z2 = sigmoid(self.z1) # activation function self.z3 = np.dot(self.z2, self.w2) # dot product of hidden layer (z2) and second set of 3x1 weights o = sigmoid(self.z3) # final activation function return o def backward(self, X, y, output, step): # Backward propagation of the errors X['bias'] = 1 # Adding 1 to the inputs to include the bias in the weight self.o_error = y - output # error in output self.o_delta = self.o_error * sigmoid_prime(output) * step # applying derivative of sigmoid to error self.z2_error = self.o_delta.dot( self.w2.T) # z2 error: how much our hidden layer weights contributed to output error self.z2_delta = self.z2_error * sigmoid_prime(self.z2) * step # applying derivative of sigmoid to z2 error self.w1 += X.T.dot(self.z2_delta) # adjusting first of weights self.w2 += self.z2.T.dot(self.o_delta) # adjusting second set of weights def predict(self, X): return forward(self, X) def fit(self, X, y, epochs=10, step=0.05): for epoch in range(epochs): X['bias'] = 1 # Adding 1 to the inputs to include the bias in the weight output = self.forward(X) self.backward(X, y, output, step) ###################################################################### def convert_values(X, y_label): train_x = pd.DataFrame(data=X, columns=["x1", "x2"]) train_y = [] for n in range(len(y_label)): train_y.append([int(y_label[n])]) train_y = np.array(train_y) return train_x, train_y #train_x, train_y = convert_values(X, y_label) ###################################################################### def get_binary_labels(pred_y): pred_y_ = [i[0] for i in pred_y] #print(pred_y_) threshold = 0.5 pred_y_binary = [0 if i < threshold else 1 for i in pred_y_] return np.array(pred_y_binary) ###################################################################### def run_FFNN(X, y_label, xx, yy, Epochs=1, L_step = .005): train_x, train_y = convert_values(X, y_label) #print(train_x) #print(train_y) my_network = FFNN() my_network.fit(train_x, train_y, epochs=Epochs, step=L_step) test_x_ = np.c_[xx.ravel(), yy.ravel()] test_x = pd.DataFrame(data=test_x_, columns=["x1", "x2"]) pred_y = test_x.apply(my_network.forward, axis=1) pred_y_binary = get_binary_labels(pred_y) Z = pred_y_binary.reshape(xx.shape) return Z ''' ################ RUNNER def generate_datasets(datasets_names): return np.array(pd.read_csv(datasets_names, index_col = 0)) def clean_datasets(datasets): X = [] for n in range(len(datasets)): X.append([datasets[n][0],datasets[n][1]]) X = np.array(X) y_label = datasets[:,2] return X, y_label def read_datasets(datasets_names): datasets = generate_datasets(datasets_names) X, y_label = clean_datasets(datasets) return X, y_label ###################################################################### import os; os.system('clear') X, y_label = read_datasets('Data/dataset_classifiers1.csv') #print(X); print(len(X)) #print(y_label); print(len(y_label)) #for k in range(len(y_label)): #print(y_label[k]) x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, .09), np.arange(y_min, y_max, .09)) Z = run_FFNN(X, y_label, xx, yy, Epochs=10000, L_step = .005) #print(xx); print(len(xx)) #print(yy); print(len(yy)) #print(Z); print(len(Z)) for k in range(len(Z)): print(Z[k]) #print(Z) import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap cm_bright = ListedColormap(['#FF0000', '#0000FF']) colormap = plt.cm.RdYlBu plt.pcolormesh(xx, yy, Z, cmap=colormap, shading='auto') plt.scatter(X[:, 0], X[:, 1], c=y_label, s=7, cmap=cm_bright, edgecolor='k') plt.show() '''
812f9e8540e14921b96fc088c09b399458ef7158
dwangproof/1337c0d3
/33_Search_in_Rotated_Sorted_Array/solution.py
1,707
3.984375
4
""" Problem: 33. Search in Rotated Sorted Array Url: https://leetcode.com/problems/search-in-rotated-sorted-array/ Author: David Wang Date: 09/05/2019 """ class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if not nums or len(nums) == 0: return -1 return self.rotated_binary_search(0, len(nums)-1, nums, target) def rotated_binary_search(self, start, end, array, target): if start > end: return -1 mid = int((start + end) / 2) if target == array[mid]: return mid # rotation happens in the left half if array[start] > array[mid]: # target is in the non-rotated part of the array. if target > array[mid] and target <= array[end]: return self.rotated_binary_search(mid+1, end, array, target) else: return self.rotated_binary_search(start, mid-1, array, target) # rotation happens on the right half else: # target is in the non-rotated part of the array. if target < array[mid] and target >= array[start]: return self.rotated_binary_search(start, mid-1, array, target) else: return self.rotated_binary_search(mid+1, end, array, target) if __name__ == '__main__': # Test Case 1 nums = [4,5,6,7,0,1,2] target = 4 output = 0 res = Solution().search(nums, target) assert res == output # Test Case 2 nums = [4,5,6,7,0,1,2] target = 3 output = -1 res = Solution().search(nums, target) assert res == output
7f603f7f5a4adc4adf29202997b9aac554583b38
irobbwu/Python-3.7-Study-Note
/basic Grammar/09. 序列.py
1,600
3.859375
4
# 10.1 作业 # 序列 1)list():把一个可迭代的对象转换为列表 2)tuple([iterable]):把一个可迭代的对象转化为元组 3)str(obj):把obj对象转化为字符串 4)max(),min():返回序列或者参数集合中的最大或最小值 5)sum(iterable[,start=0]):返回序列iterable和可选参数start的总和 6)sorted():返回排序的列表,默认从小到大 7)reversed():翻转 8)enumerate():枚举,生成由每个元素索引值和元素组成的元组 9)zip():返回各个参数的序列组成的元组 # 1.猜想一下 min() 这个BIF的实现过程: # 答: 不会 # 参考答案 def min(x): least = x[0] for each in x: if each < least: least = each return least print(min('123456789')) # 2.视频中我们说 sum() 这个BIF有个缺陷,就是如果参数里有字符串类型的话就会报错,请写出一个新的实现过程,自动“无视”参数里的字符串并返回正确的计算结果。 # 答: number = [1,23,23,23,2,312,3,213,13,'sd'] number2 = str(number) while number2.isdigit() != True: # number2.isdigit()函数只能在字符串中使用 for each in number2: if each.isdigit() != True: number number = number2.remove(each) sum(number) # 参考答案: def sum(x): result = 0 for each in x: if (type(each) == int) or (type(each) == float): result += each else: continue return result print(sum([1, 2.1, 2.3, 'a', '1', True]))
48adb6d155e12f1c328975f5e49b52ead71a8993
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/13_Functions/13.4(return)/9.py
574
4.15625
4
""" Напишите функцию number_of_factors(num), принимающую в качестве аргумента число и возвращающую количество делителей данного числа. """ # 1 вариант def get_factors(num): score = 0 for i in range(1, num + 1): if num % i == 0: score += 1 return score n = int(input()) print(get_factors(n)) # 2 вариант def get_factors(num): return len([i for i in range(1, num + 1) if num % i == 0]) n = int(input()) print(get_factors(n))
a1e6f671c20c752acc89d6150e89d414b3dbbc76
nesen2019/everyday
/ctasks/year_2021/month_07/day_20210702/L00100304.py
1,052
3.59375
4
''' 剑指 Offer 42.连续子数组的最大和 LCOF 剑指 Offer 42.连续子数组的最大和 https://leetcode-cn.com/problems/ lian-xu-zi-shu-zu-de-zui-da-he-lcof 输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。 要求时间复杂度为O(n)。   示例1: 输入: nums = [-2,1,-3,4,-1,2,1,-5,4] 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。   提示: 1 <= arr.length <= 10^5 -100 <= arr[i] <= 100 注意:本题与主站 53 题相同:https://leetcode-cn.com/problems/maximum-subarray/   class Solution: def maxSubArray(self, nums: List[int]) -> int: ''' from typing import List from clecode import decorator_default @decorator_default("") def ctest(method_name, class_name): return f""" >>> >>> res = {class_name}().{method_name}() """ class Solution: def maxSubArray(self, nums: List[int]) -> int: pass if __name__ == "__main__": import doctest doctest.testmod()
b4e01a92c1c5a7256c607f50be52fac6b193222b
architarora/TowerDefenseGame
/Enemy.py
5,161
3.71875
4
""" Enemy.py Creates and moves the enemy (balloons) throughout the screen """ import pygame import sys import random import math from random import uniform from os import path from settings import * class Enemy(pygame.sprite.Sprite): def __init__(self,game): self.groups = game.all_sprites, game.enemy pygame.sprite.Sprite.__init__(self) #based on balloonStren in Game Class, health and image of balloon get selected if (bloonTypes[game.balloonStren]["color"]=="red"): self.image = game.balloon_red self.health = 20 elif (bloonTypes[game.balloonStren]["color"]=="purple"): self.image = game.balloon_purple self.health = 40 elif (bloonTypes[game.balloonStren]["color"]=="blue"): self.image = game.balloon_blue self.health = 60 elif (bloonTypes[game.balloonStren]["color"]=="yellow"): self.image = game.balloon_yellow self.health = 80 elif (bloonTypes[game.balloonStren]["color"]=="moab"): self.image = game.balloon_moab self.health = 170 game.balloonStren-=1 self.game = game self.rect = self.image.get_rect() self.rect.x = 20 self.rect.y = 20 self.speedy = 5 self.speedx = 5 self.damageMultiplier = 1 self.distance = 0 self.speedBalloon = 5 def update(self): #coordinates of the balloon x = self.rect.x y = self.rect.y #get the row and column of the balloon (row,col) = self.game.getCell(x,y) #check what the image and balloon speed should be based on #the health of the balloon if(self.health>80): self.image = self.game.balloon_moab self.damageMultiplier = 5 self.speedBalloon = self.game.speedMOAB elif(self.health<=80 and self.health>60): self.image = self.game.balloon_yellow self.damageMultiplier = 4 self.speedBalloon = self.game.speedYELLOW elif(self.health<=60 and self.health>40): self.image = self.game.balloon_blue self.damageMultiplier = 3 self.speedBalloon = self.game.speedBLUE elif(self.health<=40 and self.health>20): self.image = self.game.balloon_purple self.damageMultiplier = 2 self.speedBalloon = self.game.speedPURPLE elif(self.health<=20 and self.health>0): self.image = self.game.balloon_red self.damageMultiplier = 1 self.speedBalloon = self.game.speedRED #moves the balloon self.rect.y+=self.speedy self.rect.x+=self.speedx #Based on map, find the coordinates where the direction of the balloon #should be changed if(self.game.strMap=="map.txt"): if((row,col)==(0,0)): self.speedx = 0 if((row,col)==(4,0)): self.speedy=0 self.speedx = self.speedBalloon if((row,col)==(4,6)): self.speedy = self.speedBalloon self.speedx = 0 if((row,col)==(10,6)): self.speedy = 0 self.speedx = self.speedBalloon if((row,col)==(10,11)): self.speedy = self.speedBalloon self.speedx = 0 if((row,col)==(11,11)): self.game.lives-=(1/10)*self.damageMultiplier #Based on map, find the coordinates where the direction of the balloon #should be changed if(self.game.strMap == "map2.txt"): if((row,col)==(0,0)): self.speedx = 0 if((row,col)==(3,0)): self.speedy=0 self.speedx = self.speedBalloon if((row,col)==(3,1)): self.speedy = self.speedBalloon self.speedx = 0 if((row,col)==(8,1)): self.speedy = 0 self.speedx = self.speedBalloon if((row,col)==(8,7)): self.speedy = self.speedBalloon self.speedx = 0 if((row,col)==(10,7)): self.speedy = 0 self.speedx = self.speedBalloon if((row,col)==(10,10)): self.speedy = self.speedBalloon self.speedx = 0 if((row,col)==(11,10)): self.game.lives-=(1/10)*self.damageMultiplier #Based on map, find the coordinates where the direction of the balloon #should be changed if(self.game.strMap == "map3.txt"): if((row,col)==(0,0)): self.speedx = 0 if((row,col)==(9,0)): self.speedy=0 self.speedx = self.speedBalloon if((row,col)==(9,11)): self.speedy = self.speedBalloon self.speedx = 0 if((row,col)==(11,11)): self.game.lives-=(1/10)*self.damageMultiplier #remove the balloon off the screen if the health is 0 if(self.health<=0): self.kill()
25827995c5edd8dced9f808e610e3176015d7971
zero1hac/cp-practice
/spoj/CANDY3.py
176
3.5
4
T = int(raw_input()) while T>0: N = int(raw_input()) K = N sumi=0 while N>0: x = int(raw_input()) sumi+=x N-=1 if sumi%K==0: print "YES" else: print "NO" T-=1
54fe11fafa60259a5699c31ad9de2c0c6317aa95
Mr-alan9693/cursoemvideopython
/Tinta para pintar parede.py
255
3.875
4
altura = float(input('Digite a altura da parede: ')) largura = float(input('Digite a largura da parede: ')) area = altura * largura litros = area / 2 print('Para pintar uma parede de {:.2f}m2, você vai precisar de {:.1f} l de tinta'.format(area, litros))
873593a04b62a80e765eabed5f65dda791c40d99
wenlins/Python-Self-study
/2.第二节课.py
552
3.59375
4
good = str(input('您感觉怎么样:')) print('I\'m a student') print(good) print("您好最近怎么样,我想你有一个",good,'的一天') print("您好\n最近怎么样,我想你有一个",good,'的一天') print("\v祝你好运\t\v每天开心") print('%s\n'*2 %('祝你好运','每天开心')) print('%d\n'*2 %(3.14,1.414)) print('%.3f\n'*2 %(3.14,1.414)) print('%s%.3f\n'*2 %('祝你好运',3.14,'每天开心',1.414)) A=1 A+=5#=1+5 print(A) ''' 2f保留多少位 %s字符串 %d取整 %.xf 小数点(保留x位) '''
0b2b674abbba7374ff239b8dc73ecb2e8e5b0abb
HorseSF/pp_Python
/sample/05_set_dictionary.py
1,088
4.03125
4
s1={3,4,5} # 判断对象是否在集合里 print("判断3是否在集合中") print(3 in s1) print("判断10是否不在集合中") print(10 not in s1) print("------------") s2={4,5,6,7} # 交集 print("交集") s3=s1&s2 print(s3) print("------------") # 连集 print("连集") s3=s1|s2 print(s3) print("------------") # 差集 print("差集") s3=s1-s2 print(s3) print("------------") # 反交集 print("反交集") s3=s1^s2 print(s3) print("------------") # 拆解字符串成集合 print("拆解字符串成集合") s=set("hello") print(s) print("h" in s) print("------------") #字典 Key-value print("字典") dic={"apple":"苹果","orange":"橘子"} print(dic["apple"]) dic["apple"]="青苹果" print(dic["apple"]) print("------------") # 判断对象是否在字典里 print("判断对象是否在字典里") print("apple" in dic) print("------------") # 删除字典中的键值 print("删除键") print(dic) del dic["apple"] print(dic) print("------------") # 列表转换字典 print("列表转换字典") dic={i:i*2 for i in [3,4,5]} print(dic) print("------------")
1f77092d2fd20920b5a31e800edc950e1f1caad2
gptech/python
/investment.py
471
3.8125
4
from __future__ import division from decimal import Decimal def invest(amount, rate, time): print "Principle amount: $%d " %amount print "annual rate of return: %r " %rate #Take the amount of years and use it in a range and print out that corresponding year #The year is based off of this total formula $1,000 × (1 + 0.06) for y in range(1, time): total = (amount * (y + rate)) print "Year %d: $%r" % (y, total) y = y+1 invest(2000, 0.025, 10)
f09304f93d018cda2d9234d5b5d3abbaf432719a
NiamV/SortingAlgorithms
/quick.py
604
3.875
4
def quickIter(xs, steps): if xs == []: return [], steps pivot = xs[0] less, same, more = [], [], [] for x in xs: nextstep = [] for y in xs: nextstep.append(y) steps.append(nextstep) print(less, same, more, xs) if x < pivot: less.append(x) elif x == pivot: same.append(x) else: more.append(x) return (quickIter(less, steps)[0] + same + quickIter(more, steps)[0]), steps def quick(xs): steps = [] return quickIter(xs, steps)[1] print(quick([4,3,2,5,1]))
625a34ab6d4eed80b35f40a787b54e99b24eb78a
Shyzay/Solutions-to-Problem-3-and-4-Algorithm-and-data-structure-
/problem4/SearchingAndSortingD.py
4,931
3.875
4
#------------------------------------------------------------------------------- # Name: Implementing the in method (__contains__) for the hash table Map ADT # Two contain methods one to check for keys and the other for the value # Purpose:Education # # Author: mmk and emeka # # Created: 07/09/2018 # Copyright: (c) mmk 2018 # Licence: <gloriaconcepto> #------------------------------------------------------------------------------- class HashTable: ''' The map abstract data type implements the simple Remainder method and the collision resolution technique use is Linear Probing method''' def __init__(self,size): ''' The hash map size must be a odd number to help avoid collision''' #class attributes self.size = size self.slots = [None] *self.size self.data = [None] *self.size def put(self, key, data): hash_value = self.hash_function(key,len(self.slots)) if self.slots[hash_value] == None: self.slots[hash_value] = key self.data[hash_value] = data else: if self.slots[hash_value] == key: self.data[hash_value] = data #replace else: next_slot = self.rehash(hash_value, len(self.slots)) while self.slots[next_slot] != None and self.slots[next_slot] != key: next_slot = self.rehash(next_slot, len(self.slots)) if self.slots[next_slot] == None: self.slots[next_slot] = key self.data[next_slot] = data else: self.data[next_slot] = data #replace def hash_function(self, key, size): return key % size def rehash(self, old_hash, size): return (old_hash + 1) % size def get(self, key): start_slot = self.hash_function(key, len(self.slots)) data = None stop = False found = False position = start_slot while self.slots[position] != None and not found and not stop: if self.slots[position] == key: found = True data = self.data[position] else: position=self.rehash(position, len(self.slots)) if position == start_slot: stop = True return data def __getitem__(self, key): return self.get(key) def __setitem__(self, key, data): self.put(key, data) def delete(self,key): '''' the delete method implemented using linear probing using replacing with an identifier method''' #get the hash value .... hash_value = self.get(key) #get the hash key....... hash_key = self.hash_function(key,len(self.slots)) #check if the slot is empty if self.data[hash_key]==hash_value and self.data[hash_key]!=None: #replace it with a None value self.data[hash_key]=None else: pass # over-ride with the default delete method def __delitem__(self, key): self.delete(key) def len(self) : '''' Implementing a method that determined the length of hash map ''' #get the length and return the value. length =len(self.data) return length def __len__(self): ''' Implementing the len method (__len__) for the hash table Map ADT ''' self.len(self) def contain_keys(self,key): '''This method return True if key is found ,e.g k.contain_keys(20)''' #check if the key have a slot value in the slot... hash_value = self.get(key) #if the value is None if hash_value==None: return False else: return True def contain_value(self,data): '''This method return True if the data is found ,e.g k.contain_keys("cow")''' #iterate through the database... for index,value in enumerate(self.data): #check if the value in the database... if value==data: return True break else: #check if it has reach the end of the list if index==len(self.data)-1: return False else: pass def main(): #pass h=HashTable(11) h[54]="cat" h[26]="dog" h[93]="lion" h[17]="tiger" h[77]="bird" h[31]="cow" h[44]="goat" h[55]="pig" h[20]="chicken" print("is this key 20 present", h.contain_keys(20)) print() print("is this key 80 present", h.contain_keys(80)) print() print("is pig in the data ",h.contain_value("pig")) print() print("Nonso is not in the data ",h.contain_value("Nonso")) if __name__ == '__main__': main()
8f45971d766dd5dea450c9b9802e49551121fe84
erikkaplun/tmp-proxy
/rain-proxy.py
3,940
3.625
4
#!/usr/bin/python # coding: utf-8 import socket import select import sys import os if sys.version_info > (3, 0, 0): #print "This version of python is not supported!\nPlease download python 2.x" sys.exit(1) def console_write(text): if os.name == 'nt': with open("dump.txt", "a+") as f: f.write(text + '\n') else: print(text) def handle_client(listener, remote_addr, local_to_server, server_to_local, sockets): print ("Something trying to connect...") client_sock, address = listener.accept() server_sock = socket.create_connection(remote_addr) print ("Client accepted.") sockets.append(client_sock) sockets.append(server_sock) local_to_server[client_sock] = server_sock server_to_local[server_sock] = client_sock def send(connection, data, local_to_server, server_to_local, local_to_server_func, server_to_local_func): print("send:") def _do_send(socket, fn, data): socket.send(fn(data) if fn else data) if connection in local_to_server: console_write("Local:%s\n" % data) _do_send(local_to_server[connection], local_to_server_func) else: console_write("Remote:%s\n" % data) _do_send(server_to_local[connection], server_to_local_func) def close_socket(connection, sockets): connection.close() sockets.remove(connection) def proxy(remote_addr, local_addr, chunk_size=1024, local_to_server_func=None, server_to_local_func=None): local_to_server = {} server_to_local = {} sockets = [] data_to_write = {} listener = socket.socket() listener.setblocking(0) listener.bind(local_addr) listener.listen(5) sockets.append(listener) while True: print ("Waiting...") ready_to_read, ready_to_write, in_error = select.select(sockets, [], [], 1) for connection in ready_to_read: if connection == listener: # Add new socket handle_client(listener, remote_addr, local_to_server, server_to_local, sockets) else: # handle existing socket try: # If socket died print("recv") data = connection.recv(chunk_size) except socket.error: print ("Connection reset") sockets.remove(connection) else: if data: # Forward data data_to_write[connection] = data print("appending data [" + str(connection) + "] = " + str(data_to_write[connection])) else: # If socket closed close_socket(connection, sockets) #ready_to_read, ready_to_write, in_error = select.select(sockets, [], [], 1) for connection in ready_to_write: send(connection, ''.join(data_to_write.pop(connection)), local_to_server, server_to_local, local_to_server_func, server_to_local_func) #print ("Done.") def to_server(data): if len(data) < 2000: if data[0:3] == "GET": #~ print ("Header detected:") #~ print(data) #~ firefox = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0" #~ data = re.sub("(User-Agent\:.*?\r\n)","User-Agent: "+firefox+"\r\n",data) #~ data = data.replace("Accept-Encoding: gzip, deflate\r\n","") data = "GET / HTTP/1.1\r\n" data += "User-Agent: AutoIt\r\n" data += "Host: 127.0.0.1:8000\r\n" data += "Cache-Control: no-cache\r\n\r\n" print(data) return data def to_client(data): return data if __name__ == '__main__': try: #~ proxy.proxy('212.95.32.219', 8005, '0.0.0.0', 8005, 8192,to_server, to_client) proxy(('195.50.209.244', 80), ('0.0.0.0', 80), 1024, to_server, to_client) except KeyboardInterrupt: sys.exit(1) else: sys.exit(0)
b8acdc3ca577e1c469c1aab67135059bc025b2e7
VirtualMe64/jeopardy-sim
/player.py
1,380
3.75
4
import random class Player: def __init__(self, p_know, p_correct, buzzer_skill, daily_double_strat, final_jeopardy_strat, pick_question_strat): ''' param p_know: Probability of 'knowing' question - deciding to buzz in\n param p_correct: Probability of getting question correct after buzzing in\n param buzzer_skill: Skill at buzzer (weighting for buzz in random selection), positive float\n param daily_double_strat: Function to decide daily double wager based on game info\n param final_jeopardy_strat: Function to decide final jeopardy wager based on game info\n param pick_question_strat: Function to pick question from board based on game info\n ''' self.p_know = p_know self.p_correct = p_correct self.buzzer_skill = buzzer_skill self.daily_double_strat = daily_double_strat self.final_jeopardy_strat = final_jeopardy_strat self.pick_question_strat = pick_question_strat self.money = 0 def know_question(self): return random.random() <= self.p_know def is_correct(self): return random.random() <= self.p_correct if __name__ == '__main__': player = Player(0.7, 0.95, 1, lambda x : x, lambda x : x, lambda x : x) n = 0 for i in range(0, 10): if player.know_question(): n += 1 print(n)
44418d41b360bb17d4540d96c648c7078734f633
kenberman/NextGen
/Problems_Conditionals_Set1.py
1,574
4.0625
4
import random # won = False # # Win = random.randint(1, 5) # while won == False: # guess = int(input('Guess the Number: ')) # message = 'You Win.' # if guess > Win: # print('Number is too high.') # elif guess < Win: # print('Number is too low.') # elif guess == Win: # print(message) # won = True Job = input('Would you like to apply for a Job? ') while Job != 'no' or Job != 'No' or Job.lower() != 'yes' or Job != 'i guess' or Job != 'probably' or Job != 'prob': if Job == 'no' or Job == 'No': print('Goodbye!') elif Job.lower() == 'yes' or Job == 'i guess' or Job == 'probably' or Job == 'prob': Exp = input('Do you have job experience? ') if Exp.lower() == 'no': print('You may apply for an entry level position.') elif Exp == 'yes' or Exp == 'Yes': Years = input('How many years of experience do you have? ') if int(Years) >= 3: print('You may apply for a advanced position.') elif int(Years) < 3: print('You may apply for a mid-level position.') else: print('Please enter number amount of years. (ex. 1, 2, 3, 4...)') else: print("Please type 'yes' or 'no'") else: print("Please type 'yes' or 'no'") Job = input() # dice_one = random.randint(1, 6) # dice_two = random.randint(1, 6) # # if dice_one == dice_two or dice_one + dice_two == 6 or dice_one + dice_two ==3: # print('You Win!') # else: # print("You Lost.")
105640121098a722ca18f509a828a5e7dfdb1d6f
rodrigotoro/Rosalind
/exercises/lia.py
1,000
3.640625
4
import argparse from math import factorial sample_dataset = "2 1" sample_output = "0.684" def heterozygous_organisms_prob(k, n): prob_double_het = 0.25 prob_other = 1 - prob_double_het num_organisms = 2 ** k prob = 0 for i in range(n, num_organisms + 1): k_combinations = factorial(num_organisms) / ( factorial(num_organisms - i) * factorial(i) ) prob += ( k_combinations * (prob_double_het ** i) * (prob_other ** (num_organisms - i)) ) return f"{prob:.3}" if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-i", "--input") args = parser.parse_args() if args.input: with open(args.input, "r") as f: input_dataset = f.read() else: input_dataset = sample_dataset k, n = [int(item) for item in input_dataset.split() if len(item) > 0] solution = heterozygous_organisms_prob(k, n) print(solution)
82ad3c3928b623fdb4931bada45bd299e2c1b887
ong-ekken/nlp100knocks-rev2
/03_pi.py
443
4.15625
4
#!/usr/bin/env python3 """ 03. pi Split the sentence “Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics”. into words, and create a list whose element presents the number of alphabetical letters in the corresponding word. """ S = ("Now I need a drink, alcoholic of course, after the heavy " "lectures involving quantum mechanics") s = S.split() result = map(len, s) print(*result)
36971fa2e3b2e68bc1fc99c49066c0d0a66ea29f
kookminYeji/SW-Proj2-class1-3
/Byeongjo/Byeongjo_week4/assignment4_factorial_combination_recursive_20171593.py
352
4
4
def factorial(n) : if n == 1 or n == 0 or n == -1: return 1 else : return n * factorial(n-1) n = int(input("Enter n : ")) m = int(input("Enter m : ")) c = factorial(n-1) d = factorial(m) e = factorial((n-1)-m) f = int(c/(d*e)) d = factorial(m-1) e = factorial((n-1)-(m-1)) g = int(c/(d*e)) print("C(",n,",",m,")" + "=", f+g)
9774fcc0ae93a565ff16c3426e8f8a70bad5251f
phantomrush/untitled
/client2.py
1,170
4.0625
4
# Import socket module import socket # Create a socket object class client: def __init__(self,username,port): # Create a socket object self.s = socket.socket() # Define the port on which you want to connect self.port = port self.username = username self.connecting_message = username self.ending_message = 'Bye' def connect_client(self): # connect to the server on local computer ipconfig = socket.gethostbyname(socket.gethostname()) self.s.connect((ipconfig, self.port)) self.s.send(self.connecting_message.encode()) toclose = False while True: send_msg = input('Me : ') # type in messages to send to server self.s.send(send_msg.encode()) # close the connection if 'bye' in send_msg: toclose = True self.s.send(self.ending_message.encode()) self.s.close() break if toclose: break self.s.close() #self,username,port USER = input("Enter username: ") meClient = client(USER,12345) meClient.connect_client()
fce109e13934270ee5392f3b3644caff8e4e6142
lbordino/unipy
/es1.py
285
3.640625
4
V_UNO = input("inserisci il valore 1 :") V_DUE = input("inserisci il valore 2: ") def somma(a,b): return a + b def prodotto(a,b): return a * b def v_medio(a,b): return (a + b)/2 def dist(a,b): return abs(somma(a,b)) print(max(V_UNO,V_DUE)) print(min(V_UNO,V_DUE))
2695ccf531a9c4403c540a5f98e4911841344ee5
Musa6630/my_program
/hackerrank.py
96
3.765625
4
Input = input() Answer = '' for i in range(1,Input+1): Answer += str(i) print(Answer)
ea102dda35073b7b4f900164fe604f45994d6f49
lichen911/adventofcode
/2018/day2.py
2,656
3.5625
4
<<<<<<< HEAD from collections import Counter input_file = 'day2_input.txt' box_counts = { 'twice': 0, 'thrice': 0 } def char_appears_twice(box_code): char_counts = Counter(box_code) for value in char_counts.values(): if value == 2: return True return False def char_appears_thrice(box_code): char_counts = Counter(box_code) for value in char_counts.values(): if value == 3: return True return False with open(input_file, 'r') as fd: box_list = fd.read().splitlines() for box in box_list: if char_appears_twice(box): box_counts['twice'] += 1 if char_appears_thrice(box): box_counts['thrice'] += 1 print(box_counts) print('checksum:', box_counts['twice'] * box_counts['thrice']) print(box_list) box_list.sort() print(box_list) for i in range(1, len(box_list)): box1 = box_list[i-1] box2 = box_list[i] mismatch_count = 0 for x, y in zip(box1, box2): if x != y: mismatch_count += 1 if mismatch_count > 1: break if mismatch_count == 1: print(box1) print(box2) ======= def get_intcode(input_file): intcode = [] with open(input_file, 'r') as file: intcode = file.readline().split(',') intcode = [int(x) for x in intcode] return intcode def run_intcode(intcode): for index in range(0, len(intcode), 4): # print('intcode line: {}'.format(intcode[index:index+4])) param1 = intcode[index + 1] param2 = intcode[index + 2] result_address = intcode[index + 3] opcode = intcode[index] if opcode == 99: break elif opcode == 1: opcode_result = intcode[param1] + intcode[param2] elif opcode == 2: opcode_result = intcode[param1] * intcode[param2] else: print('Unknown opcode.') break intcode[result_address] = opcode_result def main(): input_file = 'day2_input.txt' # input_file = 'day2_input_test.txt' intcode = get_intcode(input_file) noun = 0 verb = 0 for noun in range(0,100): for verb in range(0,100): intcode_copy = intcode[::] intcode_copy[1] = noun intcode_copy[2] = verb run_intcode(intcode_copy) if intcode_copy[0] == 19690720: break else: continue break print(intcode_copy) print(100 * noun + verb) if __name__ == '__main__': main() >>>>>>> ad2019