blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
f984cc81842f604c1c29e1ddecf630c2f49df851
cd-chicago-june-cohort/dojo_assignments_mikeSullivan1
/python_OOP/product.py
1,605
3.875
4
class product(object): def __init__(self,price,name,weight,brand,cost): self.name = name self.price = price self.weight = weight self.brand = brand self.cost = cost self.status = "for sale" def sell(self): self.status = "sold" print self.name,"was sold\n",50 *'=' return self def add_tax(self,rate): return float(self.price) * (1.0+rate) def return_item(self,reason): if reason == "defective": self.status = "defective" self.price = 0 print self.name,"is defective and was returned.\n",50 *'=' return self elif reason =="like new": self.status = "for sale" print self.name,"is back in stock.\n",50 *'=' return self elif reason == "open box": self.status = "for sale" self.price = .8 * self.price print "Open box", self.name,"is discounted and for sale.\n",50 *'=' return self def display(self): print "Price: ", self.price, '\n',"Item Name: ", self.name, "\nWeight: ", self.weight, "\nBrand: ", self.brand, "\nCost: ", self.cost, "\nStatus: ", self.status, "\n",50 *'=' return self example= product(.75,"lacroix","12oz","soda", .50) example.display() print example.add_tax(.1) example.display example.sell() example.return_item("open box") example.display() example.sell() example.return_item("like new") example.display() example.sell() example.return_item("defective") example.display()
6c96a66ca122128582076cba695de6325d6b32e9
cd-chicago-june-cohort/dojo_assignments_mikeSullivan1
/python_fundamentals/strings_and_lists.py
993
3.96875
4
'''def replace_string(long_string, old,new): return long_string.replace(old,new) words = "It's thanksgiving day. It's my birthday,too!" old_string = "day" new_string = "month" print words print replace_string(words,old_string,new_string) def minmax(some_list): some_list.sort() x=len(some_list) -1 print "Min is " +str(some_list[0])+"." print "Max is " +str(some_list[x])+"." minmax([2,54,-2,7,12,98]) def print_first_last(some_list): x=len(some_list) -1 print str(some_list[0]), str(some_list[x]) return (str(some_list[0]), str(some_list[x])) print print_first_last (["hello",2,54,-2,7,12,98,"world"]) ''' def new_list(some_int_list): some_int_list.sort() print some_int_list half=len(some_int_list)/2 new_int_list= [some_int_list[:len(some_int_list)/2]] i=half while i<len(some_int_list): new_int_list.append(some_int_list[i]) i+=1 print new_int_list new_list([19,2,54,-2,7,12,98,32,10,-3,6])
7ca52317a28ac1a45a2a44b3d8d769def95493e5
cd-chicago-june-cohort/dojo_assignments_mikeSullivan1
/python_fundamentals/MakingDicts.py
329
4.34375
4
def print_dict(dict): print "My name is", dict["name"] print "My age is", dict["age"] print "My country of birth is", dict["birthplace"] print "My favorite language is", dict["language"] myDict = {} myDict["name"]="Mike" myDict["age"]=34 myDict["birthplace"]="USA" myDict["language"]="Python" print_dict(myDict)
7732208f5d3e7826e263da85dd8941cadd25fa37
MarkiianAtUCU/TeamTask
/interface.py
2,375
3.796875
4
from main import * import os menu = """ 1) - Add Client 2) - Add Mail 3) - Send All 4) - Mail Number 5) - Clients info 6) - Quit """ clients = [] mails = MailBox() def create_client(lst): name = input("[Client name] > ") age = input("[Client age] >") while not age.isdigit() and not (1 < int(age) < 110): print("[Error] Enter integer") age = input("[Client age] > ") age = int(age) sex = input("[Client sex] (male, female)> ") while sex not in ["male", "female"]: print("Sex must be male or femele") sex = input("[Client sex] (male, female)> ") email = input("[Client email] > ") other = input("[Client short info] >") lst.append(Client(name, age, sex, email, other)) def create_mail(clients, box): text = input("[Email text] > ") for i in range(len(clients)): print(str(i+1)+") "+clients[i].less_info()) n = input("[Client number] >") while n not in map(lambda x: str(x), list(range(1, len(clients)+1))): print("Wrong client number") n = input("[Client number] >") t = input("[Mail type] (1-Birthday 2-Work_mail, 3-Sail)> ") while t not in ["1", "2", "3"]: print("Wrong mail type") t = input("[Mail type] (1,2,3)> ") box.add_mail_info(MailInfo(clients[int(n)-1], t, text)) while True: os.system("cls") print(menu) command = input("[o] > ") if command in ["1", "2", "3", "4", "5", "6"]: if command == "1": create_client(clients) elif command == "2": create_mail(clients, mails) elif command == "3": try: try: login=input("[login] > ") password=input("[password] > ") mails.send_all(login, password) except smtplib.SMTPAuthenticationError: print("Wrong emeil or password") except smtplib.SMTPRecipientsRefused: print("Wrong email") else: print("Sending done!") elif command == "4": print("Number of mails", len(mails.inf)) elif command == "5": for i in clients: print(i) print("=================") elif command == "6": break else: print("Wrong Input") input() print("Good-bye!")
09d3cf114f83a5d284c0f810b02ca87dee711b30
ical9016/bootcamp13_fundamental
/fundamental_01.py
892
4
4
""" syntax programming language consist of: - Sequential - Branching - Loop - Modularization using : a. Function b. Class c. Package example program to be made : Blog with Django """ judul = 'Menguasai python dalam 3 jam' author = 'Nafis Faisal' tanggal = '2019-11-02' #jumlah_artikel = 100 # #if jumlah_artikel > 100: # print ('Jumlah artikel besar, akan dipecah ke dalam beberapa halaman') #for i in range(1,11): # print (i) #list angka = [1, 'loro', 3, 4.0] #for item in angka: # print (item) #dictionary #kamus_cinta = {} #kamus_cinta['love']='tresna' #kamus_cinta['sayang']='kangen' #print (kamus_cinta) manusia = [{ 'nama' : 'Nafis Faisal', 'alamat' : { 'line 1' : 'Perumahan Greenland', 'Kecamatan' : 'Bojongsari', 'Kota' : 'Depok', 'Provinsi' : 'Jawa Barat' } }] print (manusia[0]['nama']) print (manusia[0]['alamat']['Kota'])
188abf2fd259085a3bcf6d538ce8dfb67d6357f5
ashley015/python20210203
/3-2.py
370
3.625
4
m=[] total=0 high=0 low=100 n=int(input('How many people in this class?')) for i in range(n): score=int(input('Plase input the score:')) total=total+score if high< score: high=score if low>score: low=score m.append(score) average=total/n print(m) print('average',average) print('high',high) print('low',low)
63cd3250a2453bc5dcf1083a3f9010fd6496fe1f
BrandonCzaja/Sololearn
/Python/Control_Structures/Boolean_Logic.py
650
4.25
4
# Boolean logic operators are (and, or, not) # And Operator # print(1 == 1 and 2 == 2) # print(1 == 1 and 2 == 3) # print(1 != 1 and 2 == 2) # print(2 < 1 and 3 > 6) # Example of boolean logic with an if statement # I can either leave the expressions unwrapped, wrap each individual statement or wrap the whole if condition in () if (1 == 1 and 2 + 2 > 3): print('true') else: print('false') # Or Operator age = 15 money = 500 if age > 18 or money > 100: print('Welcome') # Not Operator # print(not 1 == 1) # False # print(not 1 > 7) # True if not True: print('1') elif not (1 + 1 == 3): print("2") else: print("3")
5cf03dca2de00592db494a9bb2c00b80147f387a
frba/biomek
/biomek/function/spotting.py
6,045
3.59375
4
""" Functions to create CSV files to be used in biomek Source Plate Name,Source Well,Destination Plate Name,Destination Well,Volume PlateS1,A1,PlateD1,A1,4 PlateS1,A1,PlateD1,B1,4 PlateS1,A2,PlateD1,C1,4 PlateS1,A2,PlateD1,D1,4 """ from ..misc import calc, file from ..container import plate import sys MAX_PLATES = 12 VOLUME = 4 BY_ROW = 0 BY_COL = 1 BIOMEK = 2 def verify_entry(type, num): try: '''Verify if the numbers type is correct''' num = type(num) except ValueError: message = str(num) + ' is not a number' print(message) sys.exit() if num <= 0: message = 'the value needs to be greater than ' + str(num) print(message) sys.exit() else: return num def verify_biomek_constraints(num_source_plates, num_pattern, pattern): """ Calls a function to create a output file The output file has the source plate and the distribution of the samples according to the num_pattern and pattern :param num_source_plates: int number :param num_pattern: int number :param pattern: 0, 1 or 2 """ ver_num_source = verify_entry(int, num_source_plates) ver_pattern = verify_entry(int, num_pattern) total_destination = ver_num_source * ver_pattern total_plates = ver_num_source + total_destination if total_plates > MAX_PLATES: print('The total plates (%d) exceeds the biomek limit of %d' % (total_plates, MAX_PLATES)) else: print('The total plates in biomek is %d' % total_plates) print('The total destination plate(s) is %d and total source plate(s) is %d' % (total_destination, ver_num_source)) create_output_file(ver_num_source, total_destination, pattern) def generate_random_names(name, init, end): """ Returns a vector with a main name + number :param name: string :param init: int number :param end: int number :return: a vector """ names = [] for i in range(init, end): names.append(str(name) + str(i)) return names def create_plate(num_wells, name): """ Returns a named plate type 96 or 384 according to num_wells :param num_wells: int [96, 384] :param name: string :return: object from class Plate """ rows, cols = calc.rows_columns(int(num_wells)) new_plate = plate.Plate(rows, cols, name) return new_plate def create_output_file(total_source, total_destination, pattern): """ Create a random output file name, and plates names :param total_source: integer number :param total_destination: integer number :param pattern: integer number 0 -> BY_ROW or 1 -> BY_COL """ num_pattern = int(total_destination/total_source) '''Add the header''' if pattern == BY_ROW: outfile = file.create('biomek/output/source_' + str(total_source) + '_' + str(num_pattern) + 'spot_byrow.csv', 'w') outcsv = file.create_writer_csv(outfile) file.set_header(outcsv) ''' Create the source plates''' for i in range(0, total_source): plateS_num = i + 1 source_name = 'Source_' + str(plateS_num) source_plate = create_plate(96, source_name) destination_names = generate_random_names('Destination_', num_pattern*i+1, num_pattern*i+num_pattern+1) destination_plates = [] for j in range(0, len(destination_names)): destination_plates.append(create_plate(96, destination_names[j])) '''Call Function to write the CSV by rows''' file.write_by_row(source_plate, destination_plates, num_pattern, outcsv, VOLUME) print(file.colours.BOLD + 'Output File: ' + outfile.name + file.colours.BOLD) elif pattern == BY_COL: outfile = file.create('biomek/output/source_' + str(total_source) + '_' + str(num_pattern) + 'spot_bycol.csv', 'w') outcsv = file.create_writer_csv(outfile) file.set_header(outcsv) ''' Create the source plates''' for i in range(0, total_source): plateS_num = i + 1 source_name = 'Source_' + str(plateS_num) source_plate = create_plate(96, source_name) destination_names = generate_random_names('Destination_', num_pattern * i + 1, num_pattern * i + num_pattern + 1) destination_plates = [] for j in range(0, len(destination_names)): destination_plates.append(create_plate(96, destination_names[j])) '''Call Function to write the CSV by rows''' file.write_by_col(source_plate, destination_plates, num_pattern, outcsv, VOLUME) print(file.colours.BOLD + 'Output File: ' + outfile.name + file.colours.BOLD) elif pattern == BIOMEK: outfile = file.create('biomek/output/source_' + str(total_source) + '_' + str(num_pattern) + 'spot_biomek.csv', 'w') outfile_worklist = file.create('biomek/output/source_' + str(total_source) + '_' + str(num_pattern) + 'worklist.csv', 'w') outcsv = file.create_writer_csv(outfile) outcsv_worklist = file.create_writer_csv(outfile_worklist) file.set_biomek_header(outcsv) file.set_worklist_header(outcsv_worklist) ''' Create the source plates''' for i in range(0, total_source): plateS_num = i + 1 source_name = 'Source_' + str(plateS_num) source_plate = create_plate(96, source_name) destination_names = generate_random_names('Destination_', num_pattern * i + 1, num_pattern * i + num_pattern + 1) destination_plates = [] for j in range(0, len(destination_names)): destination_plates.append(create_plate(96, destination_names[j])) '''Call Function to write the CSV by rows''' file.write_scol_dcol_by_spot(source_plate, destination_plates, num_pattern, outcsv, VOLUME, outcsv_worklist) print(file.colours.BOLD + 'Output File: ' + outfile.name + file.colours.BOLD) else: print('Invalid option') sys.exit()
3605da3592356af8f961812c48b5d8b0ea3a7a16
CharnyshMM/python_tracker
/console_interface/parser.py
344
3.578125
4
"""This module describes Parser class""" import argparse import sys class Parser(argparse.ArgumentParser): """Just a wrapper for default ArgumentParser to add ability to print help in case of error arguments""" def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2)
ddda02473ba71bf752d22572e92a52bd9dff6f35
BlandineLemaire/StegaPy
/tools/charSearch.py
1,223
3.75
4
''' Fonction : charSearcher(byteList) byteList : liste de byte dans lesquels on va chercher tout les caracteres qui sont imprimable Explication : charSearcher est une fonction qui permet de trouver tout les caracteres imprimable qui sont dans une liste de bytes et de les retourner dans une variable qui les contient. On va regarde les valeurs decimale de chaque byte et si elle est entre 32(spc) et 126(~) alors on l'ajoutera à la variable de sortie Exemple : liste = ['01110100','01100101','01110011','01110100'] lesChar = charSearcher(liste) print(lesChar) >test ''' def charSearcher(byteList): # Initialisation de la variable qui va contenir tout les char trouver dans la liste listOfChar = "" # Boucle sur tout les char de la liste passee en arguments for i in range(0, len(byteList)): # On regarde les valeurs decimale de chaque byte et si elle est entre 32 et 126 alors on l'ajout # a notre liste de char if int(byteList[i], 2) > 31 and int(byteList[i], 2) < 127: # Ajout du char dans la liste listOfChar = listOfChar + chr(int(byteList[i], 2)) return listOfChar
38ea269387d3a34e05fa0831239d249f487347f9
LeeJiangWei/algorithms
/8-puzzle.py
3,999
3.796875
4
import random class puzzle: def __init__(self, state=None, pre_move=None, parent=None): self.state = state self.directions = ["up", "down", "left", "right"] if pre_move: self.directions.remove(pre_move) self.pre_move = pre_move self.parent = parent self.cost = 0 def random_init(self): for i in range(9): self.state.append(i) random.shuffle(self.state) def get_space(self): for i in range(9): if self.state[i] == 0: return i def print(self): c = 0 for i in range(3): for j in range(3): print(self.state[c], end=" ") c += 1 print("\n") print(" ↓\n") def cal_cost(self, step): eva = 0 for i in range(9): eva += not (self.state[i] == goal[i]) self.cost = eva + step def generate_substates(self, step, Astar): if not self.directions: return [] substates = [] space = self.get_space() # check the state if it can move. If so, move it if "up" in self.directions and space < 6: temp = self.state.copy() temp[space], temp[space + 3] = temp[space + 3], temp[space] new_puz = puzzle(temp, pre_move="up", parent=self) if Astar: new_puz.cal_cost(step) substates.append(new_puz) if "down" in self.directions and space > 2: temp = self.state.copy() temp[space], temp[space - 3] = temp[space - 3], temp[space] new_puz = puzzle(temp, pre_move="down", parent=self) if Astar: new_puz.cal_cost(step) substates.append(new_puz) if "left" in self.directions and space % 3 < 2: temp = self.state.copy() temp[space], temp[space + 1] = temp[space + 1], temp[space] new_puz = puzzle(temp, pre_move="left", parent=self) if Astar: new_puz.cal_cost(step) substates.append(new_puz) if "right" in self.directions and space % 3 > 0: temp = self.state.copy() temp[space], temp[space - 1] = temp[space - 1], temp[space] new_puz = puzzle(temp, pre_move="right", parent=self) if Astar: new_puz.cal_cost(step) substates.append(new_puz) return substates def solve(self, Astar): open_table = [] close_table = [] open_table.append(self) steps = 0 while len(open_table) > 0: curr = open_table.pop(0) close_table.append(curr) substates = curr.generate_substates(steps,Astar) path = [] for i in substates: if i.state == goal: while i.parent and i.parent != origin_state: path.append(i.parent) i = i.parent path.reverse() return path, steps + 1 open_table.extend(substates) if Astar: # if Astar algorithm is used, sort the open table with cost open_table = sorted(open_table, key=lambda x:x.cost) steps += 1 else: return None, None origin_state = [2,8,3,1,4,5,7,6,0] goal = [1, 2, 3, 8, 0, 4, 7, 6, 5] puz = puzzle(state=origin_state) puz2 = puzzle(state=origin_state) path, step = puz.solve(True) if path: for n in path: n.print() c = 0 for i in range(3): for j in range(3): print(goal[c], end=" ") c += 1 print("\n") print("Astar total steps: %d" % step) path, step = puz2.solve(False) if path: for n in path: n.print() c = 0 for i in range(3): for j in range(3): print(goal[c], end=" ") c += 1 print("\n") print("BFS total steps: %d" % step)
4dacc73ac8d08acb3a6ac4d6fda0c62c4b89305f
kyle-yan/python
/sets.py
134
3.828125
4
#集合-用大括号表示,去重 sets = {1, 2, 3, 4, 5, 6, 1} print(sets) if 3 in sets: print('haha') else: print('hoho')
8545c73344abaabdafdd6686bafe4a6382e48b2f
bhattacharyya/biopythongui
/objects.py
6,264
3.65625
4
class Item: def save(self, filename=0): import cPickle if filename==0: filename = self.name ext = filename.split('.')[-1] if ext == filename: filename += self.extension file = open(filename, 'wb') cPickle.dump(file, self, -1) file.close() def changeName(self, newName): self.project.delItem(self.name) self.name = newName self.project.addItem(self) def register(self): try: self.project.getIten(self.name) except KeyError: self.project.addItem(self) seqnoname = 0 class SequenceItem(Item): def __init__(self, project, seq=None, name=0, typ=None): """name is the name of the seq object, if none then an automatic name is assigned seq is a Bio.Seq.Seq object or a string and type is the type of the seq either DNA RNA or protein """ global seqnoname self.extension = '.seq' self.project = project if type(seq)==str: from Bio.Seq import Seq self.seq = Seq(seq.upper()) else: self.seq = seq if name == 0: self.name = 'seq'+str(seqnoname) seqnoname += 1 else: self.name = name if typ: self.chgAlpha(typ) else: typ = self.seq.alphabet self.checkAlpha() self.project.addItem(self) def checkAlpha(self): #here's a check to make sure the user is sane s = self.seq.tostring() for letter in self.seq.alphabet.letters: s = s.replace(letter, '') if s: raise NameError, 'Your input included letters not in the alphabet' def transcribe(self, name=0): from Bio import Transcribe out = None transcribers = ['ambiguous_transcriber', 'generic_transcriber', 'unambiguous_transcriber'] for transcriber in transcribers: try: exec('out = Transcribe.'+transcriber+'.transcribe(self.seq)') except AssertionError: pass else: seqItem = SeqenceItem(self.project, seq=out, name=name) return seqItem return out def transpose(self, name=0): from Bio import Translate out = None translators = ['ambiguous_dna_by_id', 'ambiguous_dna_by_name', 'ambiguous_rna_by_id', 'ambiguous_rna_by_name', 'unambiguous_dna_by_id', 'unambiguous_dna_by_name', 'unambiguous_rna_by_id', 'unambiguous_rna_by_name'] for translator in translators: try: exec('out = Translate.'+translator+'.translate(self.seq)') except AssertionError: pass else: seqItem = SeqenceItem(self.project, seq=out, name=name) return seqItem return out def chgAlpha(self, newAlpha): """Accepts 'DNA' 'RNA' or 'protein' or an alphabet object""" from Bio.Seq import Seq from Bio.Alphabet import IUPAC alpha = None if newAlpha=="DNA": alpha = IUPAC.IUPACUnambiguousDNA() self.typ = alpha elif newAlpha=="RNA": alpha = IUPAC.IUPACUnambiguousDNA() self.typ = alpha elif newAlpha=="protein": alpha = IUPAC.IUPACProtein() self.typ = alpha else: raise NameError, "type not 'DNA', 'RNA', or 'protein'" if not alpha: alpha = newAlpha self.seq = Seq(self.seq.tostring(), alpha) self.checkAlpha() def copy(self, name=0): from Bio.Seq import Seq return SequenceItem(seq=Seq(self.seq.tostring, self.seq.alphabet), name=name, type=self.type, project=self.project) dbitemnoname = 0 class DBItem(Item): def __init__(self, project, title='', seq=None, id='', descript='', abstract='', record=None, name=0): global dbitemnoname self.extension = '.dbi' self.project = project if name==0: self.name = 'dbitem'+str(dbitemnoname) dbitemnoname += 1 else: self.name = name if record: if not title: title = record.title if not id: id = record.id if not abstract: abstract = record.abstract self.abstract = abstract.replace('\n', '') self.seq = seq self.title = title self.id = id self.descript = descript self.record = record self.project.addItem(self) self.seqItem = SequenceItem(self.project, seq, name=id) def getAbstract(self): return self.abstract def getSequence(self): return self.seq def getTitle(self): return self.title def getID(self): return self.id def getDescription(self): return descript def copy(self, name=0): return DBItem(self.project, title=self.title, seq=self.seq, id=self.id, descript=self.descript, abstract=self.abstract, record=self.record, name=name) dbquerynoname = 0 class DBQuery(Item): def __init__(self, project, searchTerm='', database='PubMed', type='nucleotide', maxResults=5, name=0): global dbquerynoname self.extension = '.dbq' self.project = project if name==0: self.name = 'dbquery'+str(dbquerynoname) dbquerynoname += 1 else: self.name = name self.items = {} self.searchTerm = searchTerm database = database.upper() if database == 'PUBMED' or database=='GENBANK': self.database = 'PubMed' else: raise NameError, 'No such database as '+database self.type = type self.maxResults = maxResults self.project.addItem(self) def search(self): if self.database=='PubMed': from Bio import PubMed from Bio import GenBank searchIds = PubMed.search_for(self.searchTerm, max_ids=self.maxResults) GBrecParser = GenBank.FeatureParser() ncbiDict = GenBank.NCBIDictionary(self.type, 'genbank', parser=GBrecParser) from Bio import Medline MLrecParser = Medline.RecordParser() medlineDict = PubMed.Dictionary(delay=1.0, parser=MLrecParser) for id in searchIds: MLrecord = medlineDict[id] GBrecord = ncbiDict[id] newDBItem = DBItem(self.project, seq=GBrecord.seq, descript=GBrecord.description, id=id, record=MLrecord) self.items[id] = newDBItem def getItems(self): return self.items def copy(self, name=0): return DBQuery(self.project, searchTerm=self.searchTerm, database=self.database, maxResults=self.maxResults, type=self.type, name=name)
e6042faa1b4190457bf74b49b0d8728a36e14bbe
Ang3l1t0/holbertonschool-higher_level_programming
/0x0A-python-inheritance/4-inherits_from.py
305
3.859375
4
#!/usr/bin/python3 """Inherits """ def inherits_from(obj, a_class): """inherits_from Arguments: obj a_class Returns: bol -- true or false """ if issubclass(type(obj), a_class) and type(obj) is not a_class: return True else: return False
aacccdbd244dd21b31268344bc4a6cbcd31fa597
Ang3l1t0/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-number_of_lines.py
311
3.703125
4
#!/usr/bin/python3 """Number of Lines """ def number_of_lines(filename=""): """number_of_lines Keyword Arguments: filename {str} -- file name or path (default: {""}) """ count = 0 with open(filename) as f: for _ in f: count += 1 f.closed return(count)
6ae9ddc15cbedfe51a661dbcd58911f22b616280
Ang3l1t0/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/6-print_comb3.py
239
3.921875
4
#!/usr/bin/python3 for n1 in range(0, 9): for n2 in range(0, 10): if n1 < n2: if n1 < 8: print("{:d}{:d}".format(n1, n2), end=', ') else: print("{:d}{:d}".format(n1, n2))
674d9922f89514e4266c48ec91b98f223fdcf313
Ang3l1t0/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
410
4.1875
4
#!/usr/bin/python3 """Append """ def append_write(filename="", text=""): """append_write method Keyword Arguments: filename {str} -- file name or path (default: {""}) text {str} -- text to append (default: {""}) Returns: [str] -- text that will append """ with open(filename, 'a', encoding="UTF8") as f: out = f.write(text) f.closed return (out)
982c7852214a41e505052c5674006286fc26b4b9
Ang3l1t0/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
444
4.34375
4
#!/usr/bin/python3 """print_square""" def print_square(size): """print_square Arguments: size {int} -- square size Raises: TypeError: If size is not an integer ValueError: If size is lower than 0 """ if type(size) is not int: raise TypeError("size must be an integer") elif size < 0: raise ValueError("size must be >= 0") for _i in range(size): print('#' * size)
af528387ea37e35a6f12b53b392f920087e5284b
Ang3l1t0/holbertonschool-higher_level_programming
/0x02-python-import_modules/2-args.py
596
4.375
4
#!/usr/bin/python3 import sys from sys import argv if __name__ == "__main__": # leng argv starts in 1 with the name of the function # 1 = function name if len(argv) == 1: print("{:d} arguments.".format(len(sys.argv) - 1)) # 2 = first argument if is equal to 2 it means just one arg elif len(argv) == 2: print("{:d} argument:".format(len(sys.argv) - 1)) else: print("{:d} arguments:".format(len(sys.argv) - 1)) # range start in 1 because range start counting at 0 for i in range(1, len(argv)): print("{:d}: {:s}".format(i, argv[i]))
5253817eac722b8e72fa1eadb560f8b7c7d73250
weeksghost/snippets
/fizzbuzz/fizzbuzz.py
562
4.21875
4
"""Write a program that prints the numbers from 1 to 100. But for multiples of three print 'Fizz' instead of the number. For the multiples of five print 'Buzz'. For numbers which are multiples of both three and five print 'FizzBuzz'.""" from random import randint def fizzbuzz(num): for x in range(1, 101): if x % 3 == 0: print '%d --> Fizz' % x if x % 5 == 0: print '%d --> Buzz' % x if x % 3 == 0 and x % 5 == 0: print '%d --> FizzBuzz' % x def main(): fizzbuzz(randint(1, 100)) if __name__ == '__main__': main()
4d221fa61d3ec90b303ef161455e3cf4f328c40e
Pavanyeluri11/LeetCode-Problems-Python
/numTeams.py
833
3.5625
4
def numTeams(rating): ans = 0 n = len(rating) #increasing[i][j] denotes the num of teams ending at soldier i with length of j in the order of increasing rating. increasing = [[0] * 4 for _ in range(n)] #decreasing[i][j] denotes the num of teams ending at soldier i with length of j in the order of decreasing rating. decreasing = [[0] * 4 for _ in range(n)] #Final answer = (increasing[i][3] + decreasing[i][3]) for i in [0, n - 1]. for i in range(n): for j in range(i): if rating[j] < rating[i]: increasing[i][2] += 1 increasing[i][3] += increasing[j][2] else: decreasing[i][2] += 1 decreasing[i][3] += decreasing[j][2] ans += increasing[i][3] + decreasing[i][3] return ans
1efbc8cb0c81c8e34da0c5ec8370f2b7eee61095
NeutronCat/EarlyLearningPython
/String_Challenge.py
3,057
4.0625
4
#counts letters letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" def unique_english_letters(word): uniques = 0 for letter in letters: if letter in word: uniques += 1 return uniques print(unique_english_letters("mississippi")) # should print 4 print(unique_english_letters("Apple")) # should print 4 def count_char_x(word, x): occurrences = 0 for letter in word: if letter == x: occurrences += 1 return occurrences print(count_char_x("mississippi", "s")) # should print 4 print(count_char_x("mississippi", "m")) # should print 1 def count_multi_char_x(word, x): splits = word.split(x) return(len(splits)-1) print(count_multi_char_x("mississippi", "iss")) # should print 2 print(count_multi_char_x("apple", "pp")) # should print 1 #slicing string using find def substring_between_letters(word, start, end): start_ind = word.find(start) end_ind = word.find(end) if start_ind > -1 and end_ind > -1: return(word[start_ind+1:end_ind]) return word print(substring_between_letters("apple", "p", "e")) # should print "pl" print(substring_between_letters("apple", "p", "c")) # should print "apple" #word length def x_length_words(sentence, x): words = sentence.split(" ") for word in words: if len(word) < x: return False return True print(x_length_words("i like apples", 2)) # should print False print(x_length_words("he likes apples", 2)) # should print True #check for name def check_for_name(sentence,name): if name.lower() in sentence.lower(): return True else: return False print(check_for_name("My name is Jamie", "Jamie")) # should print True print(check_for_name("My name is jamie", "Jamie")) # should print True print(check_for_name("My name is Samantha", "Jamie")) # should print False #every other letter in word def every_other_letter(word): every_other = "" for i in range(0, len(word), 2): every_other += word[i] return every_other print(every_other_letter("Codecademy")) # should print Cdcdm print(every_other_letter("Hello world!")) # should print Hlowrd print(every_other_letter("")) # should print #reverse_string, works because range takes start, end, step parameters and the -1 will count it down def reverse_string(word): reverse = "" for i in range(len(word)-1, -1, -1): reverse += word[i] return reverse print(reverse_string("Codecademy")) # should print ymedacedoC print(reverse_string("Hello world!")) # should print !dlrow olleH print(reverse_string("")) # should print #make spoonerism def make_spoonerism(word1, word2): return word2[0]+word1[1:]+" "+word1[0]+word2[1:] print(make_spoonerism("Codecademy", "Learn")) # should print Lodecademy Cearn print(make_spoonerism("Hello", "world!")) # should print wello Horld! print(make_spoonerism("a", "b")) # should print b a #adding exclamations to 20 def add_exclamation(word): while(len(word) < 20): word += "!" return word print(add_exclamation("Codecademy")) # should print Codecademy!!!!!!!!!! print(add_exclamation("Codecademy is the best place to learn"))
d6f097dd5b99e039ac4d33ba958ca79834075248
NeutronCat/EarlyLearningPython
/BasicMathFunctions.py
2,936
4.0625
4
# average # Write your average function here: def average(num1, num2): return (num1+num2)/2 # Uncomment these function calls to test your average function: print(average(1, 100)) # The average of 1 and 100 is 50.5 print(average(1, -1)) # The average of 1 and -1 is 0 # tenth power # Write your tenth_power function here: def tenth_power(num): return (num**10) # Uncomment these function calls to test your tenth_power function: print(tenth_power(1)) # 1 to the 10th power is 1 print(tenth_power(0)) # 0 to the 10th power is 0 print(tenth_power(2)) # 2 to the 10th power is 1024 # square root # Write your square_root function here: def square_root(num): return (num**0.5) # Uncomment these function calls to test your square_root function: print(square_root(16)) # should print 4 print(square_root(100)) # should print 10 # tipping calc # Write your tip function here: def tip(total,percentage): return ((total*percentage)/100) # Uncomment these function calls to test your tip function: print(tip(10, 25)) # should print 2.5 print(tip(0, 100)) # should print 0.0 # win/loss percentage # Write your win_percentage function here: def win_percentage(wins, losses): total_games = wins+losses ratio_won = wins/total_games return ratio_won*100 # Uncomment these function calls to test your win_percentage function: print(win_percentage(5, 5)) # should print 50 print(win_percentage(10, 0)) # should print 100 # first three multiples # Write your first_three_multiples function here: def first_three_multiples(num): first = num second = (num * 2) third = (num * 3) print (first) print (second) print (third) return third # Uncomment these function calls to test your first_three_multiples function: first_three_multiples(10) # should print 10, 20, 30, and return 30 first_three_multiples(0) # should print 0, 0, 0, and return 0 # dog years # Write your dog_years function here: def dog_years(name,age): dogage = (age * 7) return str(name)+", you are "+str(dogage)+" years old in dog years" # Uncomment these function calls to test your dog_years function: print(dog_years("Lola", 16)) # should print "Lola, you are 112 years old in dog years" print(dog_years("Baby", 0)) # should print "Baby, you are 0 years old in dog years" # remainders # Write your remainder function here: def remainder(num1, num2): return (2*num1)%(num2/2) # Uncomment these function calls to test your remainder function: print(remainder(15, 14)) # should print 2 print(remainder(9, 6)) # should print 0 # "lots of math" # Write your lots_of_math function here: def lots_of_math(a, b, c, d): first = a+b second = c-d third = first*second fourth = third%a print(first) print(second) print(third) return fourth # Uncomment these function calls to test your lots_of_math function: print(lots_of_math(1, 2, 3, 4)) # should print 3, -1, -3, 0 print(lots_of_math(1, 1, 1, 1)) # should print 2, 0, 0, 0
7b55bb9eddd6cf5f9a4be3738a2fab13dfcfca00
abdullahelshoura/MOBILE-COMPUTING
/NerualN.py
987
3.515625
4
#1 Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier from sklearn import datasets from sklearn import metrics iris = datasets.load_iris() X = iris.data[:, :4] y = iris.target #preparing ( splitting .... ) training,testing data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.30) #training the model classifier = MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(4), random_state=1)#one hidden layer with 4 neurons classifier.fit(X_train, y_train) #mpredictions to test the model y_pred = classifier.predict(X_test) #printing the weights print("the coefs are : ",classifier.coefs_) #printing the bias print("\n the biases are : ",classifier.intercepts_) # Model Accuracy, how often is the classifier correct? print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
e2ad5022f9820b69b1f85f863bf6326155d7f876
Jonly-123/homework1_3
/获取文件大小.py
795
3.828125
4
import os # def getFileSize(filePath,size = 0): 定义获取文件大小的函数,初始文件大小是0 # for root, dirs, files in os.walk(filePath): # for f in files: # size += os.path.getsize(os.path.join(root, f)) # print(f) # return size # print(getFileSize('./yuanleetest')) all_size = 0 def dir_size(dir_name): global all_size file_list = os.listdir(dir_name) # print(file_list) for file in file_list: file_path = os.path.join(dir_name,file) print(dir_name) if os.path.isfile(file_path): size = os.path.getsize(file_path) print(size) all_size += size print(file_path) else: dir_size(dir_name) print(dir_size('./yuanleetest'))
d49ada9b93882faf7afc97e34094015263f8dfc4
Yuxiao98/PE
/PE34.py
595
3.953125
4
# Project Euler: Q34 # Find the sum of all numbers which are equal to the sum of the factorial of their digits. import math def individualDigits(num): digitsList = [] while num: digitsList.append(num%10) num //= 10 digitsList = digitsList[::-1] return digitsList magicSet = set() for i in range(math.factorial(9)): digitsSum = 0 digits = individualDigits(i) for digit in digits: digitsSum += math.factorial(digit) if digitsSum == i: magicSet.add(i) print(f"The sum of curious numbers is: {sum(magicSet) - 3}")
0e8b73b3dd48465db2b9f1c6673d8437b9876908
Yuxiao98/PE
/PE25.py
510
3.875
4
# Project Euler: Q25 # Find the index of the first term in the Fibonacci sequence to contain 1000 digits def countDigits(num): c = 0 while num: num //= 10 c += 1 return c fibonacci_numbers = [0, 1] i = 2 while True: fibonacci_numbers.append(fibonacci_numbers[i-1]+fibonacci_numbers[i-2]) i += 1 if(countDigits(fibonacci_numbers[len(fibonacci_numbers)-1]) == 1000): break print(f"The index of the first number containing 1000 digits is: {i-1}")
a3cb355f81a27113efd62c52523b958855e673fa
Kirstihly/Edge-Directed_Interpolation
/edi.py
5,388
3.625
4
import cv2 import numpy as np from matplotlib import pyplot as plt import math import sys """ Author: hu.leying@columbia.edu Usage: EDI_predict(img, m, s) # img is the input image # m is the sampling window size, not scaling factor! The larger the m, more blurry the image. Ideal m >= 4. # s is the scaling factor, support any s > 0 (e.g. use s=2 to upscale by 2, use s=0.5 to downscale by 2) If you want to directly call EDI_upscale to upscale image by the scale of 2: EDI_upscale(img, m) # m should be the power of 2. Will increment by 1 if input m is odd If you want to directly call EDI_downscale to downscale image by the scale of 2: EDI_downscale(img) """ def EDI_downscale(img): # initializing downgraded image w, h = img.shape imgo2 = np.zeros((w//2, h//2)) # downgrading image for i in range(w//2): for j in range(h//2): imgo2[i][j] = int(img[2*i][2*j]) return imgo2.astype(img.dtype) def EDI_upscale(img, m): # m should be equal to a power of 2 if m%2 != 0: m += 1 # initializing image to be predicted w, h = img.shape imgo = np.zeros((w*2,h*2)) # Place low-resolution pixels for i in range(w): for j in range(h): imgo[2*i][2*j] = img[i][j] y = np.zeros((m**2,1)) # pixels in the window C = np.zeros((m**2,4)) # interpolation neighbours of each pixel in the window # Reconstruct the points with the form of (2*i+1,2*j+1) for i in range(math.floor(m/2), w-math.floor(m/2)): for j in range(math.floor(m/2), h-math.floor(m/2)): tmp = 0 for ii in range(i-math.floor(m/2), i+math.floor(m/2)): for jj in range(j-math.floor(m/2), j+math.floor(m/2)): y[tmp][0] = imgo[2*ii][2*jj] C[tmp][0] = imgo[2*ii-2][2*jj-2] C[tmp][1] = imgo[2*ii+2][2*jj-2] C[tmp][2] = imgo[2*ii+2][2*jj+2] C[tmp][3] = imgo[2*ii-2][2*jj+2] tmp += 1 # calculating weights # a = (C^T * C)^(-1) * (C^T * y) = (C^T * C) \ (C^T * y) a = np.matmul(np.matmul(np.linalg.pinv(np.matmul(np.transpose(C),C)), np.transpose(C)), y) imgo[2*i+1][2*j+1] = np.matmul([imgo[2*i][2*j], imgo[2*i+2][2*j], imgo[2*i+2][2*j+2], imgo[2*i][2*j+2]], a) # Reconstructed the points with the forms of (2*i+1,2*j) and (2*i,2*j+1) for i in range(math.floor(m/2), w-math.floor(m/2)): for j in range(math.floor(m/2), h-math.floor(m/2)): tmp = 0 for ii in range(i-math.floor(m/2), i+math.floor(m/2)): for jj in range(j-math.floor(m/2), j+math.floor(m/2)): y[tmp][0] = imgo[2*ii+1][2*jj-1] C[tmp][0] = imgo[2*ii-1][2*jj-1] C[tmp][1] = imgo[2*ii+1][2*jj-3] C[tmp][2] = imgo[2*ii+3][2*jj-1] C[tmp][3] = imgo[2*ii+1][2*jj+1] tmp += 1 # calculating weights # a = (C^T * C)^(-1) * (C^T * y) = (C^T * C) \ (C^T * y) a = np.matmul(np.matmul(np.linalg.pinv(np.matmul(np.transpose(C),C)), np.transpose(C)), y) imgo[2*i+1][2*j] = np.matmul([imgo[2*i][2*j], imgo[2*i+1][2*j-1], imgo[2*i+2][2*j], imgo[2*i+1][2*j+1]], a) imgo[2*i][2*j+1] = np.matmul([imgo[2*i-1][2*j+1], imgo[2*i][2*j], imgo[2*i+1][2*j+1], imgo[2*i][2*j+2]], a) # Fill the rest with bilinear interpolation np.clip(imgo, 0, 255.0, out=imgo) imgo_bilinear = cv2.resize(img, dsize=(h*2,w*2), interpolation=cv2.INTER_LINEAR) imgo[imgo==0] = imgo_bilinear[imgo==0] return imgo.astype(img.dtype) def EDI_predict(img, m, s): try: w, h = img.shape except: sys.exit("Error input: Please input a valid grayscale image!") output_type = img.dtype if s <= 0: sys.exit("Error input: Please input s > 0!") elif s == 1: print("No need to rescale since s = 1") return img elif s < 1: # Calculate how many times to do the EDI downscaling n = math.floor(math.log(1/s, 2)) # Downscale to the expected size with linear interpolation linear_factor = 1/s / math.pow(2, n) if linear_factor != 1: img = cv2.resize(img, dsize=(int(h/linear_factor),int(w/linear_factor)), interpolation=cv2.INTER_LINEAR).astype(output_type) for i in range(n): img = EDI_downscale(img) return img elif s < 2: # Linear Interpolation is enough for upscaling not over 2 return cv2.resize(img, dsize=(int(h*s),int(w*s)), interpolation=cv2.INTER_LINEAR).astype(output_type) else: # Calculate how many times to do the EDI upscaling n = math.floor(math.log(s, 2)) for i in range(n): img = EDI_upscale(img, m) # Upscale to the expected size with linear interpolation linear_factor = s / math.pow(2, n) if linear_factor == 1: return img.astype(output_type) # Update new shape w, h = img.shape return cv2.resize(img, dsize=(int(h*linear_factor),int(w*linear_factor)), interpolation=cv2.INTER_LINEAR).astype(output_type)
87a46c9d2df91ef1d4fdddd74e1c7c0771b72fd9
linnil1/2020pdsa
/teams.sol.py
1,140
3.765625
4
from collections import defaultdict from typing import List from queue import Queue class Teams: def teams(self, idols: int, teetee: List[List[int]]) -> bool: # build the graph self.nodes = defaultdict(list) for i,j in teetee: self.nodes[i].append(j) self.nodes[j].append(i) # bfs start self.color = {} for i in self.nodes: if i not in self.color: if not self.bfs(i): return False return True def bfs(self, i): now = True self.color[i] = now q = Queue() q.put(i) while not q.empty(): node = q.get() node_color = self.color[node] for i in self.nodes[node]: if i not in self.color: self.color[i] = not node_color q.put(i) elif self.color[i] == node_color: return False return True if __name__ == "__main__": print(Teams().teams(4, [[0,1],[0,3],[2,1],[3,2]])) print(Teams().teams(4, [[0,1],[0,3],[0,2],[2,1],[3,2]]))
f10d6210fc4e22a2d9adaf14ec5b40f756804f09
atjason/Python
/learn/map_reduce.py
765
3.890625
4
def str2int(str): def merge_int(x, y): return x * 10 + y def char2int(c): char_dict = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9 } return char_dict[c] # map means apply function to each member in list, # and reture a new list. int_list = map(char2int, str) # reduce means apply function to each memeber with previous result, # and return a single result. return reduce(merge_int, int_list) print str2int("423") ### def format_word(word): return word.capitalize() print map(format_word, ["jason", "APPLE"]) print map(str.capitalize, ["jason", "APPLE"]) ### def plus(x, y): return x * y print reduce(plus, [2, 3, 4])
9a6e7b9ac1d4dceb8acf9e618cbe5dc63a92566e
roger1688/AdvancedPython_2019
/03_oop_init/hw1.py
1,039
4.125
4
class Node: def __init__(self, val): self.val = val self.next = None def print_linked_list(head): now = head while now: print('{} > '.format(now.val),end='') now = now.next print() # print newline # # Linked-list and print test # n1 = Node(1) # n2 = Node(3) # n3 = Node(5) # n1.next = n2 # n2.next = n3 # # print_linked_list(n1) # # expect 1 > 3 > 5 > # Let's do a linked-list version stack # Functions: push, pop, is_empty class Stack: def __init__(self): self.head = None def push(self, n): # push n behind last one in self.head pass def pop(self): # pop last one in self.head return 0 # and return def is_empty(self): # check is linked-list empty return True # return bool True or False # # Stack test script # l = [1, 3, 5] # s = Stack() # for n in l: # s.push(n) # # s.pop() # s.push('a') # s.push('b') # s.pop() # # while not s.is_empty(): # print(s.pop(), end='>') # print() # # ans is a > 3 > 1
fe1e263511e1f24f17a10b4dc54e0b1c3cd40bc9
David-Loibl/gistemp4.0
/steps/eqarea.py
9,455
3.703125
4
#!/usr/local/bin/python3.4 # # eqarea.py # # David Jones, Ravenbrook Limited. # Avi Persin, Revision 2016-01-06 """Routines for computing an equal area grid. Specifically, Sergej's equal area 8000 element grid of the Earth (or any sphere like object). See GISTEMP code, subroutine GRIDEA Where "tuple" is used below, some "tuples" may in fact be other sequence types, such as lists. Duck typing rules. """ # http://www.python.org/doc/2.3.5/lib/module-itertools.html import itertools import math import sys #: Array of band altitudes. #: #: Altitude refers to the distance from the equatorial plane. The #: "North" pole being at altitude 1, the "South" pole being at altitude #: -1. #: #: band_altitude[n] #: gives the northern altitude of band n, n from 0 to 3. #: #: band_altitude[n+1] #: gives the southern altitude of band n. #: #: Note: These are the sines of the latitude. band_altitude = [1, 0.9, 0.7, 0.4, 0] #: Number of horizontal boxes in each band. #: #: To ensure equal area these should be proportional to the thickness of each #: band (Archimedes' Hat Box Theorem). band_boxes = [4, 8, 12, 16] def lerp(x, y, p): """Interpolate between x and y by the fraction p. When p == 0 x will be returned, when p == 1 y will be returned. Note that p is not restricted to being between 0 and 1. :Return: The interpolated value. :Param x, y: The interpolation end-points. :Param p: The interpolation fraction. """ p = float(p) return y * p + (1 - p) * x def northern40(): """Generator: Yields the 40 northern hemisphere boxes. The yielded value is a tuple of:: (southern, northern, western, eastern). See `grid` for more details about the coordinates. """ for band in range(len(band_boxes)): # number of horizontal boxes in band n = band_boxes[band] for i in range(n): lats = 180 / math.pi * math.asin(band_altitude[band + 1]) latn = 180 / math.pi * math.asin(band_altitude[band]) lonw = -180 + 360 * float(i) / n lone = -180 + 360 * float(i + 1) / n yield (lats, latn, lonw, lone) def southern40(): """Generator: Yields the 40 southern hemisphere boxes.i The yielded value is a tuple of:: (southern, northern, western, eastern). See `grid` for more details about the coordinates. """ # Note: Avoid "reversed" because it is not in Python 2.3 n = list(northern40()) # We want to take the northern list and reverse the bands, within each # band the boxes will still be in the same order. So first # gather into bands. i = 0 band = [] for w in band_boxes: band.append(n[i:i + w]) i += w # Then reverse the band list band.reverse() # And stitch back into a single, southern, list s = [] # Note: used for side-effect! for x in band: s.extend(x) assert len(s) == len(n) # Flip each box north/south for x in s: yield (-x[1], -x[0], x[2], x[3]) def grid(): """Generator: Yields a list of 80 boxes equally dividing a sphere. Each box comprises an equal area division of a sphere; each box is described by a 4-tuple of its boundaries:: (southern, northern, western, eastern). Co-ordinates are given as (fractional) degrees of latitude (for northern and southern borders) and longitude (for western and eastern borders). """ return itertools.chain(northern40(), southern40()) def gridsub(): """Generator: Yields 80 boxes each containing a subbox generator. Each yielded box contains, in a general sense, 100 subboxes. The 80 boxes are those corresponding to grid(). A box is returned as a pair (bound, subgen), where bound is the 4-tuple as returned by `grid` (boundaries in degrees for S N W E edges), and subgen is a generator for the 100 subboxes. The order of the boxes is the same as `grid`. The subboxes are returned as 4-tuples using the same latitude/longitude box representation as `grid`. Note that Sheffield, +53.40-001.50, is in subbox 759: />>> subbox=list(list(gridsub())[7][1])[59] />>> subbox[0] < 53.4 < subbox[1] True />>> subbox[2] < -1.5 < subbox[3] True and Vostok, -78.40+106.90, is in subbox 7921: />>> subbox=list(list(gridsub())[79][1])[21] />>> subbox[0] < -78.4 < subbox[1] True />>> subbox[2] < 106.9 < subbox[3] True """ def subgen(box): """A generator for the subboxes of box.""" # Altitude for southern and northern border. alts = math.sin(box[0] * math.pi / 180) altn = math.sin(box[1] * math.pi / 180) for y in range(10): s = 180 * math.asin(lerp(alts, altn, y * 0.1)) / math.pi n = 180 * math.asin(lerp(alts, altn, (y + 1) * 0.1)) / math.pi for x in range(10): w = lerp(box[2], box[3], x * 0.1) e = lerp(box[2], box[3], (x + 1) * 0.1) yield (s, n, w, e) for box in grid(): yield (box, subgen(box)) def grid8k(): """Generator: As `gridsub`, but flattened. Yields the same set of boxes as `gridsub`, but returns a single generator for all 8000 subboxes. Not used by core code, but used by tools and useful for debugging. """ for box in gridsub(): for subbox in box[1]: yield subbox def gridR3(): """Generator: Yields a list of 80 R3-coordinate boxes equally dividing a sphere. Like `grid` but each box is described in a right-hand 3-dimensional euclidean co-ordinate system. The sphere is centred at the origin ``(0,0,0)``. The equator lies on the plane containing the x- and y-axes ``(z=0)``. The north pole has co-ordinate ``(0,0,1)``; the intersection of the eqautor and the prime meridian (0 longitude at equator) is ``(1,0,0)``. That should be enough for you to deduce that longitude 90 on the equator is at ``(0,1,0)``. Each box is a quadrilateral described by its corners; from the viewpoint of a distant observer viewing the side of the sphere with the box on, the corners are in a counter-clockwise order (so this consistent ordering can be used for face culling if desired). Each box is described by a 4-tuple of 3-tuples. Note polar boxes have co-incident corners. """ def llto3d(i): """Convert (latitutude, longitude) into 3D triple (x,y,z). Latitude and longitude are given in degrees.""" lat = i[0] * math.pi / 180 z = math.sin(lat) c = math.cos(lat) long = i[1] * math.pi / 180 x = math.cos(long) * c y = math.sin(long) * c return x, y, z def bto3d(i): """Convert 4-tuple of borders into counter-clockwise 4-tuple of 3d co-ordinates.""" # For counter-clockwise corners, start at NE and work round. # Recall border 4-tuple convention described in grid. return map(llto3d, ((i[1], i[3]), (i[1], i[2]), (i[0], i[2]), (i[0], i[3]))) return map(bto3d, grid()) def gridJSON(): """Create array of 80 R3-coordinate boxes in JSON format. As `gridR3` but in JSON (http://www.json.org/) format. Returned string matches a JSON array production. """ return str(list(map(lambda x: map(list, x), gridR3()))) def centre(box): """Calculate the (latitude,longitude) pair for the centre of box/subbox. This is the "equal area" centre in the sense that the area to the north will equal the area to the south, and the same for east/west. :Return: The ``(latitude,longitude)`` for the box or subbox. :Param box: The box (or subbox) to find the centre of. Specified as a 4-tuple of its boundaries (same convention used by grid()): (southern, northern, western, eastern). """ sinc = 0.5 * (math.sin(box[0] * math.pi / 180) + math.sin(box[1] * math.pi / 180)) return math.asin(sinc) * 180 / math.pi, 0.5 * (box[2] + box[3]) def boxcontains(box, p): """True iff *box* (4-tuple of (s,n,w,e) ) contains point *p* (pair of (lat,lon).""" s, n, w, e = box return s <= p[0] < n and w <= p[1] < e class GridCounter: def __init__(self): """An object that bins points into cells, keeping a count of how many points are in each cell. To count a point at (lat, lon) call this object with lat,lon as arguments. To get the list of (count,cell) pairs, call the .boxes method. """ self.box = [(box, list(cells)) for box, cells in gridsub()] self.count = [[0 for _ in cells] for _, cells in self.box] def __call__(self, lat, lon): p = (lat, lon) for i, (box, cells) in enumerate(self.box): if boxcontains(box, p): for j, cell in enumerate(cells): if boxcontains(cell, p): self.count[i][j] += 1 return raise Exception("No cell for %r." % [p]) def boxes(self): for (_, cells), counts in zip(self.box, self.count): for cell, count in zip(cells, counts): yield count, cell def main(): # http://www.python.org/doc/2.3.5/lib/module-doctest.html import doctest import eqarea return doctest.testmod(eqarea) if __name__ == '__main__': main()
4544382ae2d171e544bf693e0f84d632df1e1a8f
egorov-oleg/hello-world
/task36.py
450
3.765625
4
m=int(input('Введите 2 натуральных числа: \n')) n=int(input()) if m>n: mini=n else: mini=m mindiv=0 i=2 while i<=mini: if n%i==0 and m%i==0: mindiv=i break else: i=i+1 if mindiv!=0: print('Наименьший нетривиальный делитель данных чисел:',mindiv) else: print('Наименьшего нетривиального делителя нет')
51a0fb3465dfc09150fa00db37fecb5bb9277ce9
egorov-oleg/hello-world
/task25.py
163
3.71875
4
x=int(input('Введите число и его степень: \n')) n=int(input()) r=1 while n!=1: if n%2!=0: r=r*x x=x*x n=n//2 print(x*r)
6e26a991dae4e695874e3744a09f4b8dee29c693
egorov-oleg/hello-world
/task46.py
152
3.734375
4
n=int(input('Введите n: ')) fib0=0 fib1=1 i=2 while i<=n: fib=fib1+fib0 fib0=fib1 fib1=fib i=i+1 if n==0: fib1=0 print(fib1)
f2e80b4dfe9683fb3acba1272bde622fc4d55bc0
egorov-oleg/hello-world
/task38.py
408
3.828125
4
n=int(input('Введите натуральное число: ')) a=n digits=0 while a!=0: a=a//10 digits=digits+1 i=1 right=0 while i<=digits//2: right=right*10+n%10 n=n//10 i=i+1 if digits%2==1: n=n//10 if n==right: print('Данное число является палиндромом') else: print('Данное число не является палиндромом')
1c9a70bd869ed86792485f45a8e9b9a649c70042
egorov-oleg/hello-world
/task31.py
128
3.625
4
n=int(input('Введите натуральное число: ')) r=0 while n!=0: r=r*10 r=r+n%10 n=n//10 print(r)
8380193b3ae6c07d2468b2914b353b75f23424f0
egorov-oleg/hello-world
/task42.py
377
3.6875
4
a=int(input('Введите последовательность чисел:\n')) count1=0 while a!=0: count=0 b=1 while a>=b: if a%b==0: count=count+1 b=b+1 else: b=b+1 if count==2: count1=count1+1 a=int(input()) print('Простых чисел в последовательности:',count1)
0a91701ab33752409a27a9a242025a6f68025a10
egorov-oleg/hello-world
/task16.py
253
3.71875
4
a=int(input('Введите натуральное число: ')) count=0 b=1 while a-b>-1: if a%b==0: count=count+1 b=b+1 else: b=b+1 print('Количество делителей у данного числа:',count)
1cd6467c387ad89b19c6d34ecac63ccae15b2e4e
vasugarg1710/Python-Programs
/fibonachi.py
304
3.890625
4
# 0 1 1 2 3 5 8 13 def fibonachi(n): if n==1: return 0 elif n==2: return 1 else: return fibonachi(n-1)+fibonachi(n-2) print(fibonachi(5)) def factorial_iterative(n): fac = 1 for i in range(n): fac = fac * (i+1) return fac print(factorial_iterative(5))
6577851c9f791b876a6b7d7fc09f5e725d911091
vasugarg1710/Python-Programs
/2.py
335
4.03125
4
# Variables a = 10 b = 20 # Typecasting y = "10" # This is a string value z = "20" # print(int(y)+int(z)) # Now it it converted into integer """ str int float """ # Quiz # Adding two numbers print ("Enter the first number") first = int(input()) print ("Enter the second number") second = int(input()) print ("The sum is",first+second)
504c061e4c8e3a19dc54ce43005b902b1cce23f8
SK9415/Python
/loops.py
794
4.09375
4
#there are only two types of loop: for and while def main(): x = 0 print("while loop output") #while loop while(x<5): print(x) x = x+1 print("for loop output") #for loop #here, 5 is inlusive but 10 is excluded for x in range(5,10): print(x) #for loop over a collection #this includes everything from starting to end days=["Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"] for d in days: print(d) #break and contunue for x in range(1,10): #if(x== 4): break if(x%2 == 0): continue print(x) #using enumerate() to get the index days=["Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"] for x,d in enumerate(days): print(x,d) if __name__ == "__main__": main()
31a4cbc00d468ecffbf4d4963ef68dca9015d6ee
citcheese/aws-s3-bruteforce
/progressbar.py
3,922
3.640625
4
#!/usr/bin/python # # Forked from Romuald Brunet, https://stackoverflow.com/questions/3160699/python-progress-bar # from __future__ import print_function import sys import re import time, datetime class ProgressBar(object): def __init__(self, total_items): """Initialized the ProgressBar object""" #Vars related to counts/time self.total_items = total_items self.current = 0 self.finished = False self.start_epoch = None #Set to none, start when first iteration occurs #Vars related to output self.width = 40 #Length of progress bar self.symbol = "#" #Needs to be 1 char self.output = sys.stderr self.fmt = '''%(percent)3d%% %(bar)s %(current)s/%(total_items)s %(items_per_sec)s ETA: %(eta)s''' assert len(self.symbol) == 1 #If higher, progress bar won't populate properly assert self.width <= 150 #If higher, it'll takeup more than one line of text def __call__(self, num_compelted=1): """Actions to run when progress is run""" #Initialize the start time as the first iteration (just in case progress bar is initialized early) if self.start_epoch is None: self.start_epoch = int(time.time()) #Update calculations/values self.current += num_compelted try: percent = self.current / float(self.total_items) except: percent = 0 size = int(self.width * percent) run_time = time.time() - self.start_epoch remaining = self.total_items - self.current try: time_left = (run_time/self.current) * remaining except: time_left = 0 #Args to populate into fmt args = { 'percent': (percent * 100), 'bar': '''[{symbols}{spaces}]'''.format(symbols=(self.symbol * size), spaces=' ' * (self.width - size)), 'current': "{:,}".format(self.current), 'total_items': "{:,}".format(self.total_items), 'items_per_sec': "{items_per_sec}/sec".format(items_per_sec="{:,}".format(int(self.current / run_time))), 'eta': self.get_eta(int(time_left)), 'run_time': self.get_eta(run_time), } #Print the update print('\r' + self.fmt%args, file=self.output, end=' ') def get_eta(self, time_left): """Print the num hour, min and/or sec for the given number of seconds""" time_remaining = time.gmtime(time_left) days_left = time_remaining.tm_mday-1 if days_left > 0: return "{days_left}d {hr}h {min}m {sec}s".format(days_left=days_left, hr=time_remaining.tm_hour, min=time_remaining.tm_min, sec=time_remaining.tm_sec) if time_remaining.tm_hour: return "{hr}h {min}m {sec}s".format(hr=time_remaining.tm_hour, min=time_remaining.tm_min, sec=time_remaining.tm_sec) elif time_remaining.tm_min: return "{min}m {sec}s".format(min=time_remaining.tm_min, sec=time_remaining.tm_sec) else: return "{sec}s".format(sec=time_remaining.tm_sec) def done(self): """Prints completion statement, only once""" #Be sure done hasn't already been called, set if not if not self.finished: self.finished = True run_time = time.gmtime(time.time() - self.start_epoch) final_output = ''' FINISHED at {date_time} Total time: {total_time} Total completed: {total_items_done}'''.format( date_time = str(datetime.datetime.now()), total_items_done = self.current, total_time = "{hr}h {min}m {sec}s".format(hr=run_time.tm_hour, min=run_time.tm_min, sec=run_time.tm_sec) ) #Print final output print('\n{final_output}\n'.format(final_output=final_output), file=self.output)
da0858bbaa399f271317a1bc72db9bc496741a7c
RicardoPereiraIST/Design-Patterns
/Behavioral Patterns/Interpreter/example.py
2,546
3.796875
4
import abc class RNInterpreter: def __init__(self): self.thousands = Thousand(1) self.hundreds = Hundred(1); self.tens = Ten(1); self.ones = One(1); def interpret(self, _input): total = [0] self.thousands.parse(_input, total) self.hundreds.parse(_input, total) self.tens.parse(_input, total) self.ones.parse(_input, total) if _input != [""]: return 0 return total[0] def parse(self, _input, total): index = 0 if _input[0][:2] == self.nine(): total[0] += 9 * self.multiplier() index += 2 elif _input[0][:2] == self.four(): total[0] += 4 * self.multiplier() index += 2 else: if _input[0][0] == self.five(): total[0] += 5 * self.multiplier() index = 1 else: index = 0 end = index + 3 if end > len(_input[0]): end = len(_input[0]) while index < end: if _input[0][index] == self.one(): total[0] += 1 * self.multiplier() else: break index += 1 _input[0] = _input[0][index::] @abc.abstractmethod def one(self): pass @abc.abstractmethod def four(self): pass @abc.abstractmethod def five(self): pass @abc.abstractmethod def nine(self): pass @abc.abstractmethod def multiplier(self): pass class Thousand(RNInterpreter): def __init__(self, value): pass def one(self): return 'M' def four(self): return "" def five(self): return '\0' def nine(self): return "" def multiplier(self): return 1000 class Hundred(RNInterpreter): def __init__(self, value): pass def one(self): return 'C' def four(self): return "CD" def five(self): return 'D' def nine(self): return "CM" def multiplier(self): return 100 class Ten(RNInterpreter): def __init__(self, value): pass def one(self): return 'X' def four(self): return "XL" def five(self): return 'L' def nine(self): return "XC" def multiplier(self): return 10 class One(RNInterpreter): def __init__(self, value): pass def one(self): return 'I' def four(self): return "IV" def five(self): return 'V' def nine(self): return "IX" def multiplier(self): return 1 def main(): interpreter = RNInterpreter() print("Enter Roman Numeral:") value = [input()] while value != ['']: print(" Interpretation is: " + str(interpreter.interpret(value))) print("Enter Roman Numeral:") value = [input()] if __name__ == "__main__": main()
3d6e9293a05058f88e080a1ca82c5c0640c3a0ff
RicardoPereiraIST/Design-Patterns
/Structural Patterns/PrivateClassData/private_class_data.py
551
3.84375
4
''' Control write access to class attributes. Separate data from methods that use it. Encapsulate class data initialization. ''' class DataClass: def __init__(self): self.value = None def __get__(self, instance, owner): return self.value def __set__(self, instance, value): if self.value is None: self.value = value class MainClass: attribute = DataClass() def __init__(self, value): self.attribute = value def main(): m = MainClass(True) m.attribute = False if __name__ == "__main__": main()
0637d75b9e1a1968a0e5420e81c25834a5be6e81
RicardoPereiraIST/Design-Patterns
/Behavioral Patterns/Null Object/example.py
678
3.5
4
import abc class AbstractStream(metaclass=abc.ABCMeta): @abc.abstractmethod def write(self, b): pass class NullOutputStream(AbstractStream): def write(self, b): pass class NullPrintStream(AbstractStream): def __init__(self): self.stream = NullOutputStream() def write(self, b): self.stream.write(b) class Application: def __init__(self, debug_out): self.debug_out = debug_out def do_something(self): s = 0 for i in range(10): s += i self.debug_out.write("i = " + str(i)) print("sum = " + str(s)) def main(): app = Application(NullPrintStream()) app.do_something() if __name__ == "__main__": main()
949c75b95b53ea80f89808de44e048b8d35c46b2
lBenevides/CS50
/pset6/credit.py
951
3.6875
4
from cs50 import get_int card_number = get_int("Number: ") card = card_number count = 1 sum1 = 0 checksum = 0 c = card while card_number >= 10: # loop to know how many digits card_number /= 10 count += 1 i = count/2 card = int(card * 10) for x in range(int(i)+1): # iterates the number, diving by 10 and add the sumcheck every division card = int(card/10) sum1 = sum1 + int((card % 10)) card = int(card/10) sum1 = sum1 + int((((card % 10) * 2) / 10)) + int((((card % 10) * 2) % 10)) # dictionary to find the values cards = { 34: "AMEX", 37: "AMEX", 51: "MASTERCARD", 52: "MASTERCARD", 53: "MASTERCARD", 54: "MASTERCARD", 55: "MASTERCARD", 4: "VISA" } # first last digits to check the card brand c = int(card_number * 10) if c in cards: print(f"{cards[c]}") elif int(c/10) in cards: # as VISA is only for 4 not 4x print(f"{cards[int(c/10)]}") else: print("INVALID")
83807f66e3b59665593c9f8f0afa45f1f795d5b1
superlisohou/aspect-term-extraction
/add_pos_tag.py
1,364
3.5
4
#-*-coding:utf-8-*- """ Created on Sat Feb 24 2018 @author: Li, Supeng Use nltk package to perform part-of-speech tagging """ from xml_data_parser import xml_data_parser import nltk def add_pos_tag(input_file_name, split_character_set): # xml_data_parser(input_file_name=input_file_name, split_character_set=split_character_set) # read the input file infile = open(input_file_name.split('.')[0] + '.txt') # outfile = open(input_file_name.split('.')[0] + '.data', 'w') # store the token within a sentence token_list = [] label_list = [] for line in infile.readlines(): # do pos tagging for each sentence if line == '\n': outfile.write pos_tag_list = nltk.pos_tag(token_list) # output the result for i in range(len(token_list)): outfile.write(token_list[i] + '\t') outfile.write(pos_tag_list[i][1] + '\t') outfile.write(label_list[i] + '\n') # use '\n' to indicate the end of sentence outfile.write('\n') token_list = [] label_list = [] else: line_list = line.strip('\n').split('\t') # append token token_list.append(line_list[0]) # append label label_list.append(line_list[1]) outfile.close()
5c154be5da45623e64754aea0b096f32c30ea47a
chapman-cs510-2017f/cw-04-cpcw3
/primes.py
1,295
3.96875
4
#!/usr/bin/env python3 # Name: Chelsea Parlett & Chris Watkins # Student ID: 2298930 & 1450263 # Email: parlett@chapman.edu & watki115@mail.chapman.edu # Course: CS510 Fall 2017 # Assignment: Classwork 4 def eratosthenes(n): """ uses eratosthenes sieve to find primes""" potential_primes = list(i for i in range(2,n)) for item in potential_primes: for item2 in potential_primes: if item != item2: if item2%item == 0: potential_primes.remove(item2) return potential_primes def era2(n): """ uses generator to find next prime""" p = [] i = 2 k = gen_eratosthenes() while i < n: i = next(k) p.append(i) return p # def main(argv): # n = int(argv) # if n <=0: # print("You chose a negative number") # else: # return eratosthenes(n) def gen_eratosthenes(): """ uses while loop to define primes""" i = 2 l_of_primes = [] while True: a = list(i%x for x in l_of_primes) if 0 in a: i += 1 else: l_of_primes.append(i) yield i i += 1 # f = gen_eratosthenes() # print([next(f) for _ in range(9)]) # print(len([next(f) for _ in range(9)])) if __name__ == "__main__": import sys main(sys.argv[1])
5f0faab3f8ab77137a26b7767c0b45aa8d1ff12e
ThaisSouza411/ac3_arquitetura
/ac3_teste.py
994
3.5
4
import unittest from ac3 import Calculadora class PrimoTeste(unittest.TestCase): def teste_soma(self): calculadora = Calculadora() resultado = calculadora.calcular(20, 4, 'soma') self.assertEqual(24, resultado) def teste_subtracao(self): calculadora = Calculadora() resultado = calculadora.calcular(5, 2, 'subtracao') self.assertEqual(3, resultado) def teste_multiplicacao(self): calculadora = Calculadora() resultado = calculadora.calcular(7, 7, 'multiplicacao') self.assertEqual(49, resultado) def teste_divisao(self): calculadora = Calculadora() resultado = calculadora.calcular(100, 10, 'divisao') self.assertEqual(10, resultado) def teste_deve_retornar_0_caso_operador_invalido(self): calculadora = Calculadora() resultado = calculadora.calcular(2, 6, 'erro') self.assertEqual(0, resultado) if __name__ == '__main__': unittest.main()
584a23a449e725e67f40ac8888b91359737e4a97
ARTC-RatLord/Puzzles
/collatz conjecture.py
338
3.625
4
# coding: utf-8 # In[5]: def collatz(a): collatz_conjecture=[a] while collatz_conjecture[-1]>1: if collatz_conjecture[-1]%2 == 0: collatz_conjecture.append(collatz_conjecture[-1]//2) else: collatz_conjecture.append(collatz_conjecture[-1]*3+1) return collatz_conjecture collatz(20)
fec505b5d8d11af5ff062722996be56342931a5a
ARTC-RatLord/Puzzles
/chess.py
1,336
3.9375
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 7 13:35:20 2020 @author: 502598 """ def ValidChessBoard(move): valid_pieces = ['pawn', 'bishop', 'king', 'queen', 'knight', 'rook'] valid_letters = ['a','b','c','d','e','f','g','h'] valid_colors = ['w', 'b'] square_flag = True for square in move.keys(): if int(square[0]) not in range(1,9) or square[1] not in valid_letters: square_flag = False piece_flag = True for piece in move.values(): if piece[0] not in valid_colors or piece[1:] not in valid_pieces: piece_flag = False if square_flag and piece_flag == True: return('VALID') else: return('NOT VALID') board = {'1h': 'bking', '4c':'wqueen', '2g':'bbishop', '5h':'bqueen', '3e':'wking'} print('what piece do you want to move') piece = input() for square_check, piece_check in board.items(): if piece_check==piece: square=square_check print(square) del(board[square]) print(board) print('where to?') square = input() if square in board.keys(): print(board[square]+' is removed') del(board[square]) else: pass board[square] = piece print(str(board) + ' IS ' + ValidChessBoard(board))
ebb9cedc7c5ab5fe70d00d81b91daad46cdfac55
Zokhira/basics
/functions/functions_exercises.py
315
3.53125
4
def favorite_book(book_title): print(f"One of my favorite books is '{book_title}'") favorite_book("Harry Potter") def multi_num(a: int, b: int): c = a * b print(f"product of {a} and {b} is {c}.") multi_num(5, 6) multi_num(0,6) multi_num(-1, -1) multi_num(True, True) def swap(a,b): return a, b swap(5,6)
df03b5998aa5f44ee50831fc37137489c6248f77
Zokhira/basics
/classes/cars_exec.py
1,134
3.984375
4
# 04/03/2021 # This file is for executing the cars.py classes from classes.cars import Car # Execution # drive() we will not have an access to this function yet # mycar = Car() # Car is the class, mycar is an object...in this line we are creating instance of the (instantiation) mycar = Car("BMW", "530xi", "black") yourcar = Car("Lexus", "Lexus IS", "silver") print("=====================================================") mycar.get_description() mycar.drive() mycar.set_odometer_reader(50) mycar.odo_reader = 20 # this is direct access to the instance variables mycar.color = 'RED' mycar.get_description() # yourcar.do_something() print("=====================================================") yourcar.get_description() yourcar.drive() yourcar.set_odometer_reader(30) yourcar.get_description() print("--- Electric car instances ---------") my_ev = ElectricCar("tesla", "model x", "blue") my_ev.drive() my_ev.get_description() print('Battery size : ', my_ev.battery_size) # mycar.battery_size # only child has battery_size attribute, parent does not see that attribute # Car (state, behaviour) -> ElectricCar(state, behaviour)
fbfd41c416a36b7435a0cfab07969af7468500ad
Zokhira/basics
/dictionaries_loops.py
213
3.890625
4
rivers = {'nile': 'Egypt', 'tigres': 'Iraq', 'amazon': 'Brazil', 'mississippi': 'Usa'} for river, country in rivers.items(): #or key for values print(f"The {river.title()} runs through {country.title()}. ")
9274b177898d108ffe4b872c3a7e9c9bd70ad50e
MeeSeongIm/computational_complexity_py
/discrete_fourier_transform.py
722
3.59375
4
# Discrete Fourier Transform: only for the case when the signal length is a power of two. from cmath import exp, pi, sqrt x = 3 # change this to any nonnegative integer. N = 2**x j = sqrt(-1) data = [] # for the moment, let all x_n = 1 for all n and for each DFT sample. for p in list(range(int(N))): sample_p = sum((exp(-j*2*pi/N))**(n*p) for n in list(range(int(N)))) print(sample_p) for p in list(range(int(N))): data.append([]) for p in list(range(int(N))): for n in list(range(int(N))): data[p].append((exp(-j*2*pi/N))**(n*p)) for p in list(range(int(N))): print("These entries are the coeffs of the terms in the %sth DFT sample: %s " % (p, data[p]))
a5fa1b5ffe4d5c21331d4773736bdd7939bb729e
keepmoving-521/LeetCode
/程序员面试金典/面试题 02.03. 删除中间节点.py
1,718
4.03125
4
""" 实现一种算法,删除单向链表中间的某个节点(即不是第一个或最后一个节点), 假定你只能访问该节点。 示例: 输入:单向链表a->b->c->d->e->f中的节点c 结果:不返回任何数据,但该链表变为a->b->d->e->f """ # Definition for singly-linked list. class LinkNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): # create a linklist def creat_linklist(self, li): if not li: print('This is an empty list') return head = p = LinkNode(li[0]) for i in li[1:]: p.next = LinkNode(i) p = p.next return head def print_linklist(self, head): if not head: print('This is an empty list') return while head: print(head.val, end="->") head = head.next print('None') def del_node(self, head, node): if not head: print('This is an empty list') return while head: if head.val == node: head.val = head.next.val head.next = head.next.next head = head.next # test li = ['a', 'b', 'c', 'd', 'e', 'f'] obj = Solution() head = obj.creat_linklist(li) obj.print_linklist(head) obj.del_node(head, 'c') obj.print_linklist(head) ''' 这题的核心思想其实就是把node的下一位的值覆盖给node,然后跳过node的下一位 因为我们无法访问到head节点,所以除了直接从node开始往下找,其他都是不现实的 即 a->b->c->d->e->f 变为 a->b->d->d->e->f 然后把第一个d的next设为e,跳过第二个d '''
25d76b3da92239864774bebd5d2c47ddce06974e
kknnn/ProjectEuler
/SummationOfPrimes.py
293
3.59375
4
def esPrimo(numero): for i in range(2,numero): if ((numero%i)==0): return False return True suma = 0 for i in range(2, 2000001): if (esPrimo(i)): suma += i print(suma) #NO TERMINA DE EJECUTAR NUNCA -.- HAY QUE BUSCAR UNA SOLUCION MAS EFICIENTE
b0e2d53e58c970e711f06a7ae3715181d070f3f7
jugal13/Design_And_Analysis_Algorithms
/Programs/Breadth First Search(Layers).py
832
3.625
4
graph={ 1 : [ 2, 3 ], 2 : [ 1, 3, 4, 5 ], 3 : [ 1, 2, 6, 7 ], 4 : [ 2, 5, 8, 9], 5 : [ 2, 4, 9], 6 : [ 3, 7 ], 7 : [ 3, 6 ], 8 : [ 4, 9 ], 9 : [ 4, 5, 8, 10 ], 10 : [9] } source = 1 def bfs(graph,source): tree = [] traversal = [] layer = [] i = 0 visited = [0]*11 visited[source] = 1 layer.append([source]) traversal.append(source) while layer[i]: r = [] for u in layer[i]: for v in graph[u]: if visited[v] == 0: traversal.append(v) tree.append([u,v]) visited[v] = 1 r.append(v) layer.append(r) i += 1 return traversal,tree,layer[:i] traversal,tree,layer = bfs(graph,source) print ("Graph Input:") for i in graph: print(str(i)+": "+str(graph[i])) print ("\nBFS Tree") print (tree) print ("\nBFS Layers") print (layer) print ("\nBFS Traversal") for i in traversal: print (i)
c1c431abb02873134f13691a27cef1d4ad842600
jugal13/Design_And_Analysis_Algorithms
/Programs(User Input)/Breadth First Search(Layers).py
871
3.6875
4
def bfs(graph,source,n): tree = [] traversal = [] layer = [] i = 0 visited = [0]*(n+1) visited[source] = 1 layer.append([source]) traversal.append(source) while layer[i]: r = [] for u in layer[i]: for v in graph[u]: if visited[v] == 0: traversal.append(v) tree.append([u,v]) visited[v] = 1 r.append(v) layer.append(r) i += 1 return traversal,tree,layer[:i] graph = {} n = int(input("Enter number of nodes: ")) for i in range(n): nodes = list(map(int,input("Enter the nodes connected to %d: " % (i+1)).split())) graph.update({i+1:nodes}) source = int(input("Enter source node: ")) traversal,tree,layer = bfs(graph,source,n) print ("Graph Input:") for i in graph: print(str(i)+": "+str(graph[i])) print ("\nBFS Tree") print (tree) print ("\nBFS Layers") print (layer) print ("\nBFS Traversal") for i in traversal: print (i)
bca96439911f431aab27a193f351a810c6424436
jugal13/Design_And_Analysis_Algorithms
/Programs/Knapsack.py
731
3.546875
4
items = { 1 : [ 3, 10 ], 2 : [ 5, 4 ], 3 : [ 6, 9 ], 4 : [ 2, 11] } W = 7 M = [[0]*(W+1)] def matrix(items,M,W): for i in range(1,len(items)+1): row = [0] wi = items[i][0] vi = items[i][1] for w in range(1,W+1): if w < wi: row.append(M[i-1][w]) else: row.append(max(M[i-1][w],vi+M[i-1][w-wi])) M.append(row) return M,M[len(items)][W] def knapsack(items,M,W): result = [] i = len(items) k = W while i > 0 and k > 0: wi = items[i][0] if M[i][k]!=M[i-1][k]: result.append(i) k = k-wi i = i-1 return result M,mat = matrix(items,M,W) result = knapsack(items,M,W) for i in M: print (i) print ("Max value for knapsack: "+str(mat)) print ("Items selected for knapsack: "+str(result))
27f2639a391a5e7ad4d6a25e6f6b5da9fe74a97c
luisjimenezlinares/AGConsta
/Fuentes/funciones_AG/comasaf/mutation.py
1,930
3.515625
4
# -*- coding: utf-8 -*- import random def mutation(G): #Muta un 1% de los genes genes_a_mutar = [] genes1p = len(G) / 100 #Si el 1% es 0, se selecciona un gen al azar if genes1p == 0: genes_a_mutar = [random.randint(0, len(G)-1)] #Sino se selecciona un 1% de los genes else: genes_a_mutar = random.sample(range(len(G)), genes1p) for i in genes_a_mutar: gen = G[i] c = random.randint(0, len(gen)-1) mutado = False #Si el alelo seleccionado tiene longitud 1 se prueba a borrar if len(gen[c]) == 1: if c > 0 and gen[c][0] in gen[c-1]: gen.pop(c) mutado = True elif c < len(gen) - 1 and gen[c][0] in gen[c+1]: gen.pop(c) mutado = True #Si no se ha mutado todavia se une aleatoriamente, en caso de que sea posible, con el alelo de la izquierda o el de la derecha if not mutado: if random.random < 0.5: if c > 0 and not(c > 1 and len(gen[c-1]) == 1 and gen[c-1][0] in gen[c-2]): gen[c] = gen[c-1] + gen[c] gen.pop(c-1) mutado = True elif not mutado: if c < len(gen) - 1 and not(c < len(gen) - 2 and gen[c+1][0] in gen[c+2]): gen[c] = gen[c] + gen[c+1] gen.pop(c+1) mutado = True #Si se ha mutado, se divide aleatoriamente algun alelo en dos if mutado: c1 = random.randint(0, len(gen)-1) if len(gen[c1]) == 1: gen = gen[:c1] + [gen[c1]] + gen[c1:] else: #c2 selecciona en que punto se parte el conjunto c2 = random.randint(0, len(gen[c1])-2) gen = gen[:c1] + [gen[c1][:c2+1]] + [gen[c1][c2+1:]] + gen[c1+1:] G[i] = gen return G,
9bd622894d7e1dde61b4957a91975f4cbced94fb
benv587/baseML
/LinearRegression/LinearRegression_bgd.py
2,039
3.8125
4
import numpy as np class LinearRegression(object): """ 根据批量梯度下降法求线性回归 """ def __init__(self, alpha, max_iter): self.alpha = alpha self.max_iter = max_iter def fit(self, X, y): X = self.normalize_data(X) # 标准化数据,消除量纲影响 X = self.add_x0(X) # 增加系数w0的数据,就不需要对w区别对待了 self.w_ = np.zeros((X.shape[1], 1)) self.cost_ = [] for i in range(self.max_iter): output = self.predict(X) # 预测值 errors = output - y # 误差 gradient = X.T @ errors # 梯度值 self.w_ -= self.alpha * gradient / len(X) # self.w_ = self.w_ - X.T @ (X @ self.w_ - y) * self.alpha / len(X) cost = (errors**2).sum() / (2.0 * len(X)) self.cost_.append(cost) return self def predict(self, X): """ 计算数据预测label """ return X @ self.w_ def normalize_data(self, X): return (X - X.mean()) / X.std() def add_x0(self, X): return np.insert(X, 0, values=1, axis=1) def loadDataSet(): """ 读取数据 """ data = np.loadtxt('ex1data2.txt', delimiter=',') return data[:, :-1], data[:, -1] if __name__ == '__main__': # 吴恩达机器学习数据 X, y = loadDataSet() X = np.array(X) y = np.reshape(np.array(y), (len(X), 1)) print(X.shape, y.shape) # 训练模型 model = LinearRegression(alpha=0.02, max_iter=2000) model.fit(X, y) print("模型系数:", model.w_) print("模型误差", model.cost_[-1]) # 两个数据集得到最后的损失值与解析解相等 from sklearn.linear_model import LinearRegression from sklearn.preprocessing import StandardScaler standard = StandardScaler() X = standard.fit_transform(X) # X = (X - X.mean()) / X.std() model = LinearRegression() model.fit(X, y) print("模型系数:", model.coef_) print("模型误差", model.intercept_)
6305227ae30aa254fc14bbe65e646b3ecfc38224
guingomes/Linguagem_Python
/1.operadores_aritmeticos.py
385
4.125
4
#objetivo é criar um programa em que o usuário insere dois valores para a mensuração de operações diversas. n1 = int(input('Digite um valor: ')) n2 = int(input('Digite outro valor: ')) s = n1+n2 m = n1*n2 d = n1/n2 di = n1//n2 e = n1**n2 print('A soma é: {}, o produto é: {} e a divisão é: {:.3f}'.format(s, m, d)) print(f'A divisão inteira é: {di} e a potência: {e}')
6724a08be69d5429e28bbf028f3cafe78337b8f2
zzfima/GrokkingAlgorithms
/Rec_sum_p81.py
357
4.125
4
def main(): print(SummArrayNumbers([3, 5, 2, 10])) def SummArrayNumbers(arr): """Sum array of numbers in recursive way Args: arr (array): numerical array Returns: int: sum of numbers """ if len(arr) == 1: return arr[0] return arr[0] + SummArrayNumbers(arr[1:]) if __name__ == "__main__": main()
01af00a403187b6b3a2e68e0c1a3c82b475b8794
walleri18/Programming-tasks-Python-3.x
/Programming tasks/The first paragraph/Six tasks/Six tasks.py
1,177
4.21875
4
# Ипортирование мматематической библиотеки import math # Катеты прямоугольного треугольника oneCathetus, twoCathetus = 1, 1 # Получение данных oneCathetus = float(input("Введите первый катет прямоугольного треугольника: ")) twoCathetus = float(input("Введите второй катет прямоугольного треугольного: ")) oneCathetus = math.fabs(oneCathetus) twoCathetus = math.fabs(twoCathetus) # Вычисление гипотенузы прямоугольного треугольника hypotenuse = math.sqrt((oneCathetus ** 2) + (twoCathetus ** 2)) # Вычисление площади прямоугольного треугольника area = (oneCathetus * twoCathetus) / 2.0 # Вывод результата print("\nГипотенуза прямоугольного треугольника: ", hypotenuse) print("\nПлощадь прямоугольного треугольника: ", area) input("\nДля завершения программы нажмите любую клавишу...")
2c4ecba0227a2e6c535e541e91ca1d1ab822ba8c
walleri18/Programming-tasks-Python-3.x
/Programming tasks/The first paragraph/One tasks/One tasks.py
496
4
4
# Действительные числа a и b a, b = 0.0, 0.0 # Получение данных a = float(input("Пожалуйста введите число A: ")) b = float(input("Пожалуйста введите число B: ")) # Ответы задачи print("\n", a, " + ", b, " = ", (a + b)) print("\n", a, " - ", b, " = ", (a - b)) print("\n", a, " * ", b, " = ", (a * b)) input("\nДля завершения программы нажмите любую клавишу...")
6b560a28e34a507c79d88f04995fc7dd0bd4571a
walleri18/Programming-tasks-Python-3.x
/Programming tasks/The first paragraph/Twenty one tasks/Twenty one tasks.py
1,276
3.96875
4
# Импортирование математической библиотеки import math # Действительные числа c, d = 0, 0 # Корни уравнения x_one, x_two x_one, x_two = 0, 0 # Получаем данные c = float(input("Введите коэффициент C: ")) d = float(input("Введите коэффициент D: ")) # Находим корни уравнения D = (-3) ** 2 - 4 * (-math.fabs(c * d)) if D == 0: x_one = x_two = 3 / 2 elif D > 0: tmpX_one = (3 + math.sqrt(D)) / 2 tmpX_two = (3 - math.sqrt(D)) / 2 x_one = max(tmpX_one, tmpX_two) x_two = min(tmpX_one, tmpX_two) del tmpX_one, tmpX_two # Вычисление главного ответа задачи result = math.fabs((math.sin(math.fabs(c * (x_one ** 3) + d * (x_two ** 2) - c * d))) / math.sqrt((c * (x_one ** 3) + d * (x_two ** 2) - x_one) ** 2 + 3.14)) \ + math.tan(c * (x_one ** 3) + d * (x_two ** 2) - x_one) # Вывод результата print("\nРезультат вычислений равен", result) input("\nДля завершения программы нажмите любую клавишу...")
bfc77608f4fff3bf16b36463a0a34debfe4052d6
Adva-Bootcamp21/google-project-efrat-noa
/data.py
356
3.703125
4
class Data: """ Save all the sentences can be searched in a dictionary format that includes all the word as the keys """ def __init__(self): self.__list = [] def get_sentence(self, index): return self.__list[index] def add(self, sentence): self.__list.append(sentence) return len(self.__list) - 1
d350f927573693cfbf32b423e7d41150ea61ef2d
callmebg/arcade
/arcade/examples/perlin_noise_1.py
4,490
3.546875
4
""" Perlin Noise 1 If Python and Arcade are installed, this example can be run from the command line with: python -m arcade.examples.perlin_noise_1 TODO: This code doesn't work properly, and isn't currently listed in the examples. """ import arcade import numpy as np from PIL import Image # Set how many rows and columns we will have ROW_COUNT = 30 COLUMN_COUNT = 30 # This sets the WIDTH and HEIGHT of each grid location WIDTH = 10 HEIGHT = 10 # This sets the margin between each cell # and on the edges of the screen. MARGIN = 2 # Do the math to figure out our screen dimensions SCREEN_WIDTH = (WIDTH + MARGIN) * COLUMN_COUNT + MARGIN SCREEN_HEIGHT = (HEIGHT + MARGIN) * ROW_COUNT + MARGIN SCREEN_TITLE = "Perlin Noise 1 Example" # Perlin noise generator from: # https://stackoverflow.com/questions/42147776/producing-2d-perlin-noise-with-numpy def perlin(x, y, seed=0): # permutation table np.random.seed(seed) p = np.arange(256, dtype=int) np.random.shuffle(p) p = np.stack([p, p]).flatten() # coordinates of the top-left xi = x.astype(int) yi = y.astype(int) # internal coordinates xf = x - xi yf = y - yi # fade factors u = fade(xf) v = fade(yf) # noise components n00 = gradient(p[p[xi] + yi], xf, yf) n01 = gradient(p[p[xi] + yi + 1], xf, yf - 1) n11 = gradient(p[p[xi + 1] + yi + 1], xf - 1, yf - 1) n10 = gradient(p[p[xi + 1] + yi], xf - 1, yf) # combine noises x1 = lerp(n00, n10, u) x2 = lerp(n01, n11, u) # FIX1: I was using n10 instead of n01 return lerp(x1, x2, v) # FIX2: I also had to reverse x1 and x2 here def lerp(a, b, x): """linear interpolation""" return a + x * (b - a) def fade(t): """6t^5 - 15t^4 + 10t^3""" return 6 * t ** 5 - 15 * t ** 4 + 10 * t ** 3 def gradient(h, x, y): """grad converts h to the right gradient vector and return the dot product with (x,y)""" vectors = np.array([[0, 1], [0, -1], [1, 0], [-1, 0]]) g = vectors[h % 4] return g[:, :, 0] * x + g[:, :, 1] * y class MyGame(arcade.Window): """ Main application class. """ def __init__(self, width, height, title): """ Set up the application. """ super().__init__(width, height, title) self.shape_list = None arcade.set_background_color(arcade.color.BLACK) self.grid = None self.recreate_grid() def recreate_grid(self): lin = np.linspace(0, 5, ROW_COUNT, endpoint=False) y, x = np.meshgrid(lin, lin) self.grid = (perlin(x, y, seed=0)) self.grid *= 255 self.grid += 128 # for row in range(ROW_COUNT): # for column in range(COLUMN_COUNT): # print(f"{self.grid[row][column]:5.2f} ", end="") # print() self.shape_list = arcade.ShapeElementList() for row in range(ROW_COUNT): for column in range(COLUMN_COUNT): color = self.grid[row][column], 0, 0 x = (MARGIN + WIDTH) * column + MARGIN + WIDTH // 2 y = (MARGIN + HEIGHT) * row + MARGIN + HEIGHT // 2 current_rect = arcade.create_rectangle_filled(x, y, WIDTH, HEIGHT, color) self.shape_list.append(current_rect) im = Image.fromarray(np.uint8(self.grid), "L") im.save("test.png") def on_draw(self): """ Render the screen. """ # This command has to happen before we start drawing arcade.start_render() self.shape_list.draw() def on_mouse_press(self, x, y, button, modifiers): """ Called when the user presses a mouse button. """ # Change the x/y screen coordinates to grid coordinates column = x // (WIDTH + MARGIN) row = y // (HEIGHT + MARGIN) print(f"Click coordinates: ({x}, {y}). Grid coordinates: ({row}, {column})") # Make sure we are on-grid. It is possible to click in the upper right # corner in the margin and go to a grid location that doesn't exist if row < ROW_COUNT and column < COLUMN_COUNT: # Flip the location between 1 and 0. if self.grid[row][column] == 0: self.grid[row][column] = 1 else: self.grid[row][column] = 0 self.recreate_grid() def main(): MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) arcade.run() if __name__ == "__main__": main()
c412c9b5239cab36c3d23beffcf2c6429de45701
callmebg/arcade
/arcade/examples/texture_transform.py
3,380
3.75
4
""" Sprites with texture transformations Artwork from http://kenney.nl If Python and Arcade are installed, this example can be run from the command line with: python -m arcade.examples.sprite_texture_transform """ import arcade from arcade import Matrix3x3 import math import os SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 SHIP_SPEED = 5 ASPECT = SCREEN_HEIGHT / SCREEN_WIDTH SCREEN_TITLE = "Texture transformations" class MyGame(arcade.Window): """ Main application class. """ def __init__(self, width, height, title): """ Initializer """ super().__init__(width, height, title) # Set the working directory (where we expect to find files) to the same # directory this .py file is in. You can leave this out of your own # code, but it is needed to easily run the examples using "python -m" # as mentioned at the top of this program. file_path = os.path.dirname(os.path.abspath(__file__)) os.chdir(file_path) self.ship = None self.camera_x = 0 self.t = 0 self.stars = None self.xy_square = None def setup(self): """ Setup """ self.ship = arcade.Sprite(":resources:images/space_shooter/playerShip1_orange.png", 0.5) self.ship.center_x = SCREEN_WIDTH / 2 self.ship.center_y = SCREEN_HEIGHT / 2 self.ship.angle = 270 self.stars = arcade.load_texture(":resources:images/backgrounds/stars.png") self.xy_square = arcade.load_texture(":resources:images/test_textures/xy_square.png") # Set the background color arcade.set_background_color(arcade.color.BLACK) def on_update(self, delta_time: float): """ Update """ self.ship.update() self.camera_x += 2 self.t += delta_time * 60 def on_draw(self): """ Render the screen. """ # This command has to happen before we start drawing arcade.start_render() for z in [300, 200, 150, 100]: opacity = int(math.exp(-z / 1000) * 255) angle = z scale = 150 / z translate = scale / 500 self.stars.draw_transformed( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, opacity, Matrix3x3().rotate(angle).scale(scale * ASPECT, scale).translate(-self.camera_x * translate, 0)) self.ship.draw() for i, pair in enumerate([ ['identity', Matrix3x3()], ['rotate(30)', Matrix3x3().rotate(30)], ['scale(0.8, 0.5)', Matrix3x3().scale(0.8, 0.5)], ['translate(0.3, 0.1)', Matrix3x3().translate(0.3, 0.1)], ['rotate(10).\nscale(0.33, 0.33)', Matrix3x3().rotate(10).scale(0.7, 0.7)], ['scale(-1, 1)', Matrix3x3().scale(-1, 1)], ['shear(0.3, 0.1)', Matrix3x3().shear(0.3, 0.1)], [f'rotate({int(self.t) % 360})', Matrix3x3().rotate(self.t)], ]): x = 80 + 180 * (i % 4) y = 420 - (i // 4) * 320 arcade.draw_text(pair[0], x, y - 20 - pair[0].count('\n') * 10, arcade.color.WHITE, 10) self.xy_square.draw_transformed(x, y, 100, 100, 0, 255, pair[1]) def main(): """ Main method """ window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) window.setup() arcade.run() if __name__ == "__main__": main()
e7836387e0f7799a52b6ed24c912e502cb1b4066
callmebg/arcade
/arcade/geometry.py
2,384
3.890625
4
""" Functions for calculating geometry. """ from typing import cast from arcade import PointList _PRECISION = 2 def are_polygons_intersecting(poly_a: PointList, poly_b: PointList) -> bool: """ Return True if two polygons intersect. :param PointList poly_a: List of points that define the first polygon. :param PointList poly_b: List of points that define the second polygon. :Returns: True or false depending if polygons intersect :rtype bool: """ for polygon in (poly_a, poly_b): for i1 in range(len(polygon)): i2 = (i1 + 1) % len(polygon) projection_1 = polygon[i1] projection_2 = polygon[i2] normal = (projection_2[1] - projection_1[1], projection_1[0] - projection_2[0]) min_a, max_a, min_b, max_b = (None,) * 4 for poly in poly_a: projected = normal[0] * poly[0] + normal[1] * poly[1] if min_a is None or projected < min_a: min_a = projected if max_a is None or projected > max_a: max_a = projected for poly in poly_b: projected = normal[0] * poly[0] + normal[1] * poly[1] if min_b is None or projected < min_b: min_b = projected if max_b is None or projected > max_b: max_b = projected if cast(float, max_a) <= cast(float, min_b) or cast(float, max_b) <= cast(float, min_a): return False return True def is_point_in_polygon(x, y, polygon_point_list): """ Use ray-tracing to see if point is inside a polygon Args: x: y: polygon_point_list: Returns: bool """ n = len(polygon_point_list) inside = False p1x, p1y = polygon_point_list[0] for i in range(n+1): p2x, p2y = polygon_point_list[i % n] if y > min(p1y, p2y): if y <= max(p1y, p2y): if x <= max(p1x, p2x): if p1y != p2y: xints = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x # noinspection PyUnboundLocalVariable if p1x == p2x or x <= xints: inside = not inside p1x, p1y = p2x, p2y return inside
152e9cbfbd601c868fd22ed95b71745f0fcf377f
mchrzanowski/ProjectEuler
/src/python/Problem112.py
995
3.59375
4
''' Created on Mar 15, 2012 @author: mchrzanowski ''' from time import time def main(): LIMIT = 0.99 iteration = 101 # 101 is the first bouncy number bouncies = 0 while float(bouncies) / iteration != LIMIT: strIteration = str(iteration) monoIncrease = monoDecrease = True for digitPlace in xrange(0, len(strIteration) - 1): if strIteration[digitPlace] < strIteration[digitPlace + 1]: monoDecrease = False elif strIteration[digitPlace] > strIteration[digitPlace + 1]: monoIncrease = False if not monoIncrease and not monoDecrease: bouncies += 1 break iteration += 1 print "Number for which ", (LIMIT * 100), "% of numbers are bouncies:", print iteration if __name__ == '__main__': start = time() main() end = time() print "Runtime:", end - start, "seconds."
2e0b949e98c20620649d095cd49012fe9266a323
mchrzanowski/ProjectEuler
/src/python/Problem138.py
993
3.671875
4
def main(): ''' God, I hate these recurrence relation problems. We are given the first two Ls: 17, 305. Note that: 305 = 17 * 17 + 16 * 1 5473 = 17 * 305 + 16 * 18 .... Let P = [1, 18]. Then, the general formula, found with much trial and error, is: L_new = 17 * L[-1] + 16 * P[-1] P_new = L[-2] + L[-1] + P[-2] ''' LIMIT = 12 Ls = [17, 305] remainders = [1, 18] for _ in xrange(LIMIT - len(Ls)): quotient = 17 * Ls[-1] remainder = Ls[-2] + Ls[-1] + remainders[-2] Ls.append(quotient + 16 * remainders[-1]) remainders.append(remainder) print "Solution: {}".format(sum(Ls)) if __name__ == '__main__': import argparse import time start = time.time() parser = argparse.ArgumentParser(description="Problem 138. URL: http://projecteuler.net/problem=138") main() end = time.time() print "Runtime: {} seconds.".format(end - start)
6b03bb6a11c7d281b149df1f39c25239e6161dbf
mchrzanowski/ProjectEuler
/src/python/Problem135.py
2,511
3.5
4
''' Created on Sep 20, 2012 @author: mchrzanowski ''' def produce_n(z, k): return 2 * k * z + 3 * k ** 2 - z ** 2 def main(max_n, solution_number): solutions = dict() # we can write x ** 2 - y ** 2 - z ** 2 = n as: # (z + 2 * k) ** 2 - (z + k) ** 2 - z ** 2 == n # if you find the partial derivative with respect # to z, you see that z = k is the maximum value of the # function. Furthermore, if you look at the output for small k, # you see that the function is symmetric about the maximum: # k=2, z=1, n=15 # k=2, z=2, n=16 # k=2, z=3, n=15 # k=2, z=4, n=12 # k=2, z=5, n=7 # k=2, z=6, n=0 # k=3, z=1, n=32 # k=3, z=2, n=35 # k=3, z=3, n=36 # k=3, z=4, n=35 # k=3, z=5, n=32 # k=3, z=6, n=27 # k=3, z=7, n=20 # k=3, z=8, n=11 # k=3, z=9, n=0 # Finally, note that the last z value before n = 0 is, for a k: # last_z = 2 + 3 * (k - 1) # Therefore, the strategy is to count from last_z to # k. We cache the n values up until then. If # n is >= max_n along the way, we stop and increment k. # We have finished once the last value of z for a given k is >= max_n. last_z_is_larger_than_or_equal_to_max_n = False k = 1 while not last_z_is_larger_than_or_equal_to_max_n: for z in xrange(2 + 3 * (k - 1), k - 1, -1): n = produce_n(z, k) if n >= max_n: if z == 2 + (k - 1) * 3: last_z_is_larger_than_or_equal_to_max_n = True break if n not in solutions: solutions[n] = 0 if z > k and z <= 2 * k - 1: solutions[n] += 2 else: solutions[n] += 1 k += 1 valuable_keys = 0 for key in solutions: if solutions[key] == solution_number: valuable_keys += 1 print "Values of n < %d that have %d solutions: %d" % \ (max_n, solution_number, valuable_keys) if __name__ == '__main__': import argparse import time start = time.time() parser = argparse.ArgumentParser( description="Problem 135. URL: http://projecteuler.net/problem=135") parser.add_argument('-n', type=int, help="The max value of n.") parser.add_argument('-s', type=int, help="# of solutions to look for.") args = vars(parser.parse_args()) main(args['n'], args['s']) end = time.time() print "Runtime: %f seconds." % (end - start)
8a0fc1fe53bd0be86da21a304645c84fa192c215
mchrzanowski/ProjectEuler
/lib/python/ProjectEulerLibrary.py
5,447
3.765625
4
''' Created on Jan 19, 2012 @author: mchrzanowski ''' from ProjectEulerPrime import ProjectEulerPrime def generate_next_prime(start=2): ''' generator that spits out primes ''' # since 2 is the only even number, # immediately yield it and start # the below loop at the first odd prime. if start == 2: yield 2 start = 3 prime_object = ProjectEulerPrime() while True: if prime_object.isPrime(start): yield start start += 2 def pi(number): ''' naive implementation of the prime counting function''' return len(sieveOfEratosthenes(number)) def sieveOfEratosthenes(number, storedList=[]): ''' naive implementation of sieve algo ''' from math import sqrt if len(storedList) < number: del storedList[:] storedList.extend([0 for number in xrange(number + 1)]) storedList[0] = storedList[1] = 1 for i in xrange(2, int(sqrt(number)) + 1): if storedList[i] == 1: continue currentValue = i ** 2 while currentValue < len(storedList): storedList[currentValue] = 1 currentValue += i return tuple(number for number in xrange(number + 1) if storedList[number] == 0) def isNumberPalindromic(number): ''' check if number is a palindrome ''' number = str(number) if number[: len(number) / 2] == number[:: -1][: len(number) / 2]: return True return False def isNumberPandigital(number, lastNumberToVerify=9, includeZero=False): ''' check if number is pandigital ''' numberLimit = lastNumberToVerify if includeZero: startingNumber = 0 numberLimit += 1 else: startingNumber = 1 number = str(int(number)) # convert to int to get rid of initial zeroes. then convert to string. if len(number) != numberLimit: return False listOfNumbers = [char for char in number] for i in xrange(startingNumber, lastNumberToVerify + 1): stringifiedNumber = str(i) if stringifiedNumber in listOfNumbers: listOfNumbers.remove(stringifiedNumber) else: return False if len(listOfNumbers) == 0: return True else: return False def generatePentagonalNumbers(numberLimit, startingNumber=1): ''' generator that produces pentagonal numbers for 1..numberLimit ''' for i in xrange(startingNumber, numberLimit + 1): yield i * (3 * i - 1) / 2 def generateHexagonalNumbers(numberLimit, startingNumber=1): ''' generator that produces hexagonal numbers for 1..numberLimit ''' for i in xrange(startingNumber, numberLimit + 1): yield i * (2 * i - 1) def generateTriangleNumbers(numberLimit, startingNumber=1): ''' generator that produces triangle numbers for 1..numberLimit ''' for i in xrange(startingNumber, numberLimit + 1): yield i * (i + 1) / 2 def generateOctagonalNumbers(numberLimit, startingNumber=1): ''' generator that produces octagonal numbers for 1..numberLimit ''' for i in xrange(startingNumber, numberLimit + 1): yield i * (3 * i - 2) def generateHeptagonalNumbers(numberLimit, startingNumber=1): ''' generator that produces heptagonal numbers for 1..numberLimit ''' for i in xrange(startingNumber, numberLimit + 1): yield i * (5 * i - 3) / 2 def generateSquareNumbers(numberLimit, startingNumber=1): ''' generator that produces square numbers for 1..numberLimit ''' for i in xrange(startingNumber, numberLimit + 1): yield i ** 2 def phi(number, primeObject=ProjectEulerPrime()): ''' return totient(n). this is a naive implementation. look at problem 72 for an efficient way to do this for multiple numbers you want phi() for. ''' result = number for prime in frozenset(primeObject.factorize(number)): result *= 1 - float(1) / prime return int(result) def eea(a, b): """ Extended Euclidean Algorithm for GCD returns [gcd, x, y] such that: x * a + y * b = gcd(a, b) from: http://mail.python.org/pipermail/edu-sig/2001-August/001665.html """ from operator import sub v1 = (a, 1, 0,) v2 = (b, 0, 1,) while v2[0] != 0: p = v1[0] // v2[0] v2, v1 = map(sub, v1, (p * vi for vi in v2)), v2 return v1 def modular_inverse(m, k): """ Return b such that b * m mod k = 1, or 0 if no solution from: http://mail.python.org/pipermail/edu-sig/2001-August/001665.html """ v = eea(m, k) return (v[0] == 1) * (v[1] % k) def crt(ms, az): """ Chinese Remainder Theorem: ms = list of pairwise relatively prime integers az = remainders when x is divided by ms (ai is 'each in az', mi 'each in ms') The solution for x modulo M (M = product of ms) will be: x = a1*M1*y1 + a2*M2*y2 + ... + ar*Mr*yr (mod M), where Mi = M/mi and yi = (Mi)^-1 (mod mi) for 1 <= i <= r. from: http://mail.python.org/pipermail/edu-sig/2001-August/001665.html """ from operator import add, mul M = reduce(mul, ms) # multiply ms together Ms = tuple(M / mi for mi in ms) # list of all M/mi ys = tuple(modular_inverse(Mi, mi) for Mi, mi in zip(Ms, ms)) # uses inverse,eea return reduce(add, tuple(ai * Mi * yi for ai, Mi, yi in zip(az, Ms, ys))) % M
f9d31311fa563aacdbb541583f00ac178d2b1cdc
mchrzanowski/ProjectEuler
/src/python/Problem019.py
1,268
3.78125
4
''' Created on Jan 16, 2012 @author: mchrzanowski ''' from time import time YEAR_LIMIT = 2001 YEAR_BASE = 1900 daysInMonth = { 1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31 } def main(): start = time() runningDayCounter = 1 sundayCount = 0 for year in xrange(YEAR_BASE, YEAR_LIMIT): for month in xrange(1, len(daysInMonth) + 1): if year > YEAR_BASE and runningDayCounter % 7 is 0: sundayCount += 1 runningDayCounter += daysInMonth[month] # leap years occur in years divisible by 4 and, for centuries, only when divisible by 400 if month == 2 and year % 4 is 0: if year % 100 is not 0: runningDayCounter += 1 elif year % 400 is 0: runningDayCounter += 1 end = time() print "Sunday Count: ", sundayCount print "Runtime: ", end - start, " seconds." if __name__ == '__main__': main()
3648ca0b5536bcc00bb779e8a023079364e19003
iljones00/TicTacToe
/TicTacToe.py
1,409
3.71875
4
import Model from View import View, ConsoleView, MiniView from Strategies import * def main(): model = Model.Model(3, 3) view = MiniView(model) strategy = playAnyOpenPosition(model) print("This is the game of Tic Tac Toe") print("Moves must be made in the format 'x,y' where x and y are the coordinates of your move") gameIsPlaying = True while True: players = model.setStart() turn = model.chooseStart() currentTurn = -1 if turn: print("You will start") currentTurn = 0 else: print("I will start") currentTurn = 1 while gameIsPlaying: if turn: model.receiveInput(players[0]) view.display() if model.isWinner(players[0]): print("You won.") gameIsPlaying = False else: print("Thinking...") time.sleep(2) strategy.makeMove(players[1]) view.display() if model.isWinner(players[1]): print("I won!!!") gameIsPlaying = False turn = not turn if model.isGameOver(): print("No one wins") break if not model.playAgain(): print("Thanks for playing!") break main()
4ef7941c333484fc25c4b37e9cfd8a58993e6722
ykmc/contest
/atcoder-old/2015/0818_abc027/b.py
730
3.578125
4
# Python3 (3.4.3) import sys input = sys.stdin.readline # ------------------------------------------------------------- # function # ------------------------------------------------------------- # ------------------------------------------------------------- # main # ------------------------------------------------------------- N = int(input()) A = list(map(int,input().split())) # N で割り切れなければ端数が出るので不可能 if sum(A)%N != 0: print(-1) else: ans = 0 # ある島までの合計人数 total = 0 # 島あたりの目標人数 avg = sum(A)/N for i in range(N): total += A[i] if total/(i+1) == avg: continue ans += 1 print(ans)
0d304747aaae387f0fe931a0f1ca1f9666faaaba
prtk94/Python-Scripts
/hangman.py
1,497
3.796875
4
#A basic hangman game. import random #dict with keys as movie name and values as a list of clues. movie_db={'Inception' : ['Sci fi movie','Directed by Chirstopher Nolan'], 'Spiderman' : ['Superhero movie','Features a friendly neighbourhood guy'], 'Home Alone' : ['Kids movie'] } gameOver= False themovie = random.choice(list(movie_db.keys())) mlist= list(themovie) print(mlist) mcount= len(mlist) guesses=7 inputclist=[] def printchars(cguess): dispstr=[] #str as a list where items will be added and then joined at the end inputclist.append(cguess) for i in range(mcount): if mlist[i] not in inputclist: dispstr.append('_') else: dispstr.append(mlist[i]) s=' '.join([str(x) for x in dispstr]) print(s) s2=''.join([str(x) for x in dispstr]) mstr=''.join([str(j) for j in mlist]) if s2==mstr: global gameOver gameOver=True print(gameOver) print( ''' ***** WELCOME TO HANGMAN v0.1 ***** =================================== ***** GUESS THE MOVIE ***** =================================== ''' ) while guesses!=0: if gameOver == True: print("Congrats you guessed it correctly!! You WON!!") exit() print("You have "+str(guesses)+" guesses remaining!") char_guess = input("Enter a character: ") if char_guess in mlist: print("Correct!") printchars(char_guess) else: print("Wrong guess! Try again") guesses -=1 continue print("You couldnt guess the movie. Play again?")
d4638e1949299167c8580b8f61c1b0d9f5b43280
yenjenny1010/homework
/EX04_22.py
412
3.953125
4
#s0951034 顏禎誼 x,y=eval(input("Enter a point with two coordinates:(seperate by comma) ")) distance=(x**2+y**2)**(1/2)#計算與原點距離 if distance<10: print("Point (" ,x,",",y, ") is in the circle") elif distance==10: print("Point (" ,x,",",y, ") is on the circle") else: print("Point (" ,x,",",y, ") is not in the circle") '''心得: 除了題目要求外,加入distance==10的條件 '''
2abf36f2f383c05c27879d59394dc2b326a31e7a
thanhtd91/proso-apps
/proso/list.py
980
4.09375
4
""" Utility functions for manipulation with Python lists. """ import proso.dict def flatten(xxs): """ Take a list of lists and return list of values. .. testsetup:: from proso.list import flatten .. doctest:: >>> flatten([[1, 2], [3, 4]]) [1, 2, 3, 4] """ return [x for xs in xxs for x in xs] def group_by(what, by): """ Take a list and apply the given function on each its value, then group the values by the function results. .. testsetup:: from proso.list import group_by .. doctest:: >>> group_by([i for i in range(10)], by=lambda x: x % 2 == 0) {False: [1, 3, 5, 7, 9], True: [0, 2, 4, 6, 8]} Args: what: a list which will be transformed by: a function which will be applied on values of the given list Returns: dict: values groupped by the function results """ return proso.dict.group_keys_by_values({x: by(x) for x in what})
70d05ab9ca90e384aaa08eb3699dc5f1e9e718de
Zokol/blackhat-python
/src/task2.py
958
3.625
4
import sys import re sample = "$8:2>9#2%2$#>90$#%>90" def is_printable(s): if len(set(s)) < 4: return False return bool(re.match('^[a-zA-Z0-9]+$', s)) #return not any(repr(ch).startswith("'\\x") or repr(ch).startswith("'\\u") for ch in s) def testXOR(s): for i in range(0, 255): s2 = "" for c in s: if isinstance(c, str): tmp = ord(c) elif isinstance(c, int): tmp = c s2 = s2 + chr(i ^ tmp) if (is_printable(s2)): print(str(i) + ": " + s2) def list_words(word_length): print("Looking for words with length", word_length) with open(sys.argv[1], 'rb') as input_file: while True: buf = input_file.read(word_length) if not buf: break testXOR(buf) input_file.close() if __name__ == '__main__': list_words(20)
0077eae25b7f9731ffa985e5f7a8e079e417c27b
ScottBlaine/mycode
/fact/loopingch.py
808
4.28125
4
#!/usr/bin/env python3 farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]}, {"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]}, {"name": "SE Farm", "agriculture": ["chickens", "carrots", "celery"]}] Farm = farms[0] for animals in Farm["agriculture"]: print(animals) InFarm = input("what farm are you interested in: NE Farm, W Farm, SE Farm?") if InFarm == "W Farm": Index = 1 elif InFarm == "NE Farm": Index = 0 elif InFarm == "SE Farm": Index = 2 else: print("Invalid Value") for animals in farms[Index]["agriculture"]: print(animals) print() for animals in farms[Index]["agriculture"]: if animals != "carrots" : if animals != "celery": print(animals)
53b199987de8d0e6982fda66e1def7226d44a1ff
ChrisMusson/Problem-Solving
/HackerRank/RegEx/0-Easy/17-alternative-matching.py
293
3.59375
4
''' Given a test string, S, write a RegEx that matches S under the following conditions: S must start with Mr., Mrs., Ms., Dr. or Er.. The rest of the string must contain only one or more English alphabetic letters (upper and lowercase). ''' regex_pattern = r"^(Mr|Mrs|Ms|Dr|Er)\.[a-zA-Z]+$"
db4ad5a5c2dec491b9d50a14aaf617b2cebe5ebe
ChrisMusson/Problem-Solving
/Project Euler/032_Pandigital_products.py
1,622
4
4
''' We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.' ''' # there must be 9 digits in total, so that must mean either a 1-digit * 4-digit = 4-digit qualifies, # or a 2-digit * 3-digit qualifies. Can ignore 4x1 and 3x2 as symmetrical solutions are ignored def is_pandigital(n1, n2, n3): n = str(n1) + str(n2) + str(n3) return set(n) == set("123456789") def main(): pan_products = set() # set so I can add to it without worrying about duplicates # 1-digit * 4-digit = 4-digit for i in range(1, 10): for j in range(1000, 10000): prod = i * j if prod >= 10000: # no longer interested if the product becomes 5 digits long break if is_pandigital(i, j, prod): pan_products.add(prod) # 2-digit * 3-digit = 4-digit for i in range(10, 100): for j in range(100, 1000): prod = i * j if prod >= 10000: break if is_pandigital(i, j, prod): pan_products.add(prod) return sum(pan_products) if __name__ == "__main__": print(main()) # Output: 45228
9ac7cd01376277bb2c276880b8127768a967acf7
ChrisMusson/Problem-Solving
/Project Euler/050_Consecutive_prime_sum.py
1,628
3.84375
4
''' The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? ''' # IDEA: # go through the primes from 2 until their sum is >= 10**6 to get an upper bound U of the length # of the longest possible chain. Then, sum each chain of length U - 1 and check if any of these # are primes below 10**6. If any one is, that's the answer. Otherwise, do the same for U - 2, etc. # until a solution is foun from sympy import sieve def get_upper_bound(primes): counter = 0 cumulative_sum = 0 while cumulative_sum < 10**6: cumulative_sum += primes[counter] counter += 1 return counter def main(): primes = list(sieve.primerange(2, 10**6)) primes_set = set(primes) # created for faster lookup in main loop U = get_upper_bound(primes) - 1 while True: # OK to ascend in this loop because the question implies that there is a single # prime that is the sum of consec. primes with the maximum length # Also likely that the terms in the final sum will be low, so ascending should be slightly faster for i in range(len(primes) - U): p = sum(primes[i:i + U]) if p >= 10**6: break if p in primes_set: return p U -= 1 print(main()) # Output: 997651
b70f2af3499fde9447ec8739f19601e97671c4c6
ChrisMusson/Problem-Solving
/Project Euler/014_Longest_Collatz_sequence.py
1,250
4.03125
4
''' The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. ''' # Collatz is recursively called so it's a good idea to use a cache to stop repeating calculations def Collatz(n, cache): if n in cache: return cache[n] if n % 2 == 0: cache[n] = Collatz(n // 2, cache) + 1 else: cache[n] = Collatz(3 * n + 1, cache) + 1 return cache[n] def main(): max_num_reached = 1 max_i = 1 cache = {1: 0} for i in range(1, 10**6): cache[i] = Collatz(i, cache) if cache[i] > max_num_reached: max_num_reached = cache[i] max_i = i return max_i if __name__ == "__main__": print(main()) # Output: 837799
33d66808b44b182de3a9978dee9a8e88ce2d8b83
kranthikiranm67/TestWorkshop
/question_03.py
1,044
4.1875
4
#question_03 = """ An anagram I am Given two strings s0 and s1, return whether they are anagrams of each other. Two words are anagrams when you can rearrange one to become the other. For example, “listen” and “silent” are anagrams. Constraints: - Length of s0 and s1 is at most 5000. Example 1: Input: s0 = “listen” s1 = “silent” Output: True Example 2: Input: s0 = “bedroom” s1 = “bathroom” Output: False Write your code here """ # my own code with new functions def isanagram(x,s1): if(s1.find(x)==-1): return 0 else: return 1 def anagram(s0,s1): length = len(s0) count=0 for x in s0: if(isanagram(x,s1)==1): count = count+1 if(count==length): print('TRUE') else: print('FALSE') s0 = input() s1 = input() anagram(s0,s1) #using counter from collections import Counter def anagram1(input1, input2): return Counter(input1) == Counter(input2) input1 = 'abcd' input2 = 'dcab' print(anagram1(input1, input2))
c29b943b165450a4c087cb85e5b2c40c67661b8d
AlenaRyzhkova/CS50
/pset6/sentimental/crack.py
1,680
3.6875
4
import sys import crypt def findPassword(hash, salt, guessPass): # trying for 1-letter key for fst in range(ord('A'), ord('z')): guessPass=chr(fst) tryingHash = crypt.crypt(guessPass,salt) if tryingHash == hash: print(guessPass) return # trying for 2 letters key for fst in range(ord('A'), ord('z')): for snd in range(ord('A'), ord('z')): guessPass=chr(fst)+chr(snd) tryingHash = crypt.crypt(guessPass,salt) if tryingHash == hash: print(guessPass) return # trying for 3 letters key for fst in range(ord('A'), ord('z')): for snd in range(ord('A'), ord('z')): for thd in range(ord('A'), ord('z')): guessPass=chr(fst)+chr(snd)+chr(thd) tryingHash = crypt.crypt(guessPass,salt) if tryingHash == hash: print(guessPass) return # trying for 4 letters key for fst in range(ord('A'), ord('z')): for snd in range(ord('A'), ord('z')): for thd in range(ord('A'), ord('z')): for fth in range(ord('A'), ord('z')): guessPass = chr(fst) + chr(snd) + chr(thd) + chr(fth) tryingHash = crypt.crypt(guessPass,salt) if tryingHash == hash: print(guessPass) return # get the hashed password if not len(sys.argv) == 2: print("Usage: python crack.py <hash>") sys.exit(1) hash = sys.argv[1] salt = hash[0:2] # crack the password guessPass="" findPassword(hash, salt, guessPass)
26c06e9f868010768bdc7c7248cd1bf69032b1c4
AlenaRyzhkova/CS50
/pset6/sentimental/caesar.py
628
4.21875
4
from cs50 import get_string import sys # 1. get the key if not len(sys.argv)==2: print("Usage: python caesar.py <key>") sys.exit(1) key = int(sys.argv[1]) # 2. get plain text plaintext = get_string("Please, enter a text for encryption: ") print("Plaintext: " + plaintext) # 3. encipter ciphertext="" for c in plaintext: if c.isalpha()==True: if c.isupper()==True: p = chr((ord(c) - ord('A') + key)%26 + ord('A')) else: p = chr((ord(c) - ord('a') + key)%26 + ord('a')) else: p=c ciphertext+=p print() # 4. print ciphertext print("Ciphertext: " + ciphertext)
8820e78c180b4a61dfcd417047605a0dba15a1fe
Imonymous/Practice
/Interviews/Amazon/automata.py
666
3.546875
4
#!/usr/bin/env python def exor(a, b): if a == b: return 0 else: return 1 def cellCompete(states, days): # WRITE YOUR CODE HERE n = len(states) if states == [0]*(n) or days <= 0: return states for i in range(days): new_states = [0]*(n) for j in range(n): if j == 0: new_states[j] = exor(0, states[j+1]) elif j == n-1: new_states[j] = exor(states[j-1], 0) else: new_states[j] = exor(states[j-1], states[j+1]) states = new_states print states states=[1,1,1,0,1,1,1,1] days = 2 cellCompete(states, days)
130ec723c0d1278ea92bf3f3f56b294f358e199c
Imonymous/Practice
/Recursion/pattern_matching.py
1,075
3.5625
4
#!/usr/bin/env python3 # Mock 8 def check_for_all_stars(pattern, pattern_idx): i = pattern_idx while i < len(pattern): if pattern[i] != "*": return False i += 1 return True def doesMatch(string, pattern): return doesMatchRecursive(string, 0, pattern, 0) def doesMatchRecursive(string, string_idx, pattern, pattern_idx): if string_idx == len(string) and pattern_idx == len(pattern): return True if pattern_idx == len(pattern): return False if string_idx == len(string): return check_for_all_stars(pattern, pattern_idx) if pattern[pattern_idx] == "." or string[string_idx] == pattern[pattern_idx]: return doesMatchRecursive(string, string_idx+1, pattern, pattern_idx+1) if pattern[pattern_idx] == "*": return doesMatchRecursive(string, string_idx+1, pattern, pattern_idx) or doesMatchRecursive(string, string_idx+1, pattern, pattern_idx+1) return False print(doesMatch("abcd", ".*cd")) print(doesMatch("abcdpodfor", "a*.")) print(doesMatch("abcddefgab", ".b*."))
bde17e2a75b7c65cc0ae6d0676ae7f6319f9e45f
Imonymous/Practice
/Trees/printAllPaths.py
2,519
3.546875
4
#!/usr/bin/env python import sys from collections import deque class TreeNode(): def __init__(self, val=None, left_ptr=None, right_ptr=None): self.val = val self.left_ptr = left_ptr self.right_ptr = right_ptr class BinaryTree(): class Edge(): def __init__(self, parentNodeIndex = None, childNodeIndex = None, leftRightFlag = None): self.BinaryTree = BinaryTree self.parentNodeIndex = parentNodeIndex self.childNodeIndex = childNodeIndex self.leftRightFlag = leftRightFlag def __init__(self): self.root = None; self.noOfNodes = 0 self.noOfEdges = 0 self.rootIndex = -1 self.nodeValues=[] self.edges=[] def readRawValues(self): self.noOfNodes = int(input()) if self.noOfNodes > 0: nodeValueString = input().split(' ') for val in nodeValueString: self.nodeValues.append(int(val)) self.rootIndex = int(input()) self.noOfEdges = int(input()) for i in range(self.noOfEdges): edgeInput = input().split(' ') self.edges.append(self.Edge(int(edgeInput[0]), int(edgeInput[1]), edgeInput[2])) def buildFormRawValues(self): if self.noOfNodes == 0: root = None return nodes = [] for i in range(self.noOfNodes): nodes.append(TreeNode(self.nodeValues[i])) for i in range(self.noOfEdges): if self.edges[i].leftRightFlag == "L": nodes[self.edges[i].parentNodeIndex].left_ptr = nodes[self.edges[i].childNodeIndex] else: nodes[self.edges[i].parentNodeIndex].right_ptr = nodes[self.edges[i].childNodeIndex] self.root = nodes[self.rootIndex] def readBinaryTree(): inputBinaryTree = BinaryTree() inputBinaryTree.readRawValues() inputBinaryTree.buildFormRawValues() return inputBinaryTree.root def preOrder(root, so_far): if root is None: return elif root.left_ptr is None and root.right_ptr is None: so_far.append(root.val) print(" ".join(str(x) for x in so_far)) so_far.pop() return so_far.append(root.val) preOrder(root.left_ptr, so_far) preOrder(root.right_ptr, so_far) if len(so_far) > 0: so_far.pop() return def printAllPaths(root): preOrder(root, []) return def main(): root = readBinaryTree() printAllPaths(root) main()
f4b77306a9d41e8bf77b05b590c73452ec2cfd4b
Imonymous/Practice
/Sorting/Mock_1.py
1,609
3.96875
4
#!/usr/bin/env python3 # 1st Mock - sort(arr, k) where k=max distance of an element from its original position # Actual attempt (Selection sort) a = [2, 3, 1, 6, 5, 4] k = 2 # def sel_sort(arr, k): # for i in range(len(arr)): # min_idx = i # for j in range(i+1, i+k+1): # if j < len(arr): # if arr[j] < arr[min_idx]: # min_idx = j # arr[i], arr[min_idx] = arr[min_idx], arr[i] # return arr # print(sel_sort(a, k)) def swap(a, b): a, b = b, a def heapifyUp(h, i): smallest = i l = 2*i+1 r = 2*i+2 if l < len(h) and h[l] < h[smallest]: smallest = l if r < len(h) and h[r] < h[smallest]: smallest = r if smallest != i: swap(h[i], h[smallest]) heapifyUp(h, smallest) def heapifyDown(h, i, last): l = i*2+1 r = i*2+2 if r < last: if h[l] < h[r]: min_kid = l else: min_kid = r if h[min_kid] < h[i]: swap(h[min_kid], h[i]) heapifyDown(h, min_kid, last) elif l < last: min_kid = l if h[min_kid] < h[i]: swap(h[min_kid], h[i]) heapifyDown(h, min_kid, last) def delete_min(h, elem, last): min_val = h[0] del h[0] h.append(elem) print(h) heapifyDown(h, 0, last) print(h) return min_val def heap_sort_k(a, k): out = [] h = [] for i in range(k, -1, -1): h.append(a[i]) heapifyUp(h, i) #print(out) for j in range(len(a)-1, k, -1): out.append(delete_min(h, a[j], len(h)-1)) #print(out) remaining = k while remaining >= 0: out.append(delete_min(h, None, remaining)) remaining -= 1 #print(out) return out print(heap_sort_k(a, k))
0047e4e9211409c8c94e9f20494f72f35f6d60e6
itf/led-curtain-2
/Patterns/ExtraPatterns/StatePatterns.py
5,640
3.703125
4
import random import math import colorsys import Patterns.Pattern as P import Patterns.StaticPatterns.basicPatterns as BP import Patterns.Function as F ''' State Patterns are patterns that have an internal state ''' import Config import random import copy StateCanvas = Config.Canvas _dict_of_state_patterns={} def getStatePatternDic(): return _dict_of_state_patterns def statePattern(name): ''' To add your pattern to the dictionary of patterns add the decorator @pattern(name) on your pattern. ''' def builder(patternFunction): _dict_of_state_patterns[name]=patternFunction return patternFunction return builder def makeStatePattern(*args): ''' Takes a patternFunction, init, isDone and returns a decorator that creates a pattern. See simpleSnakePattern ''' patternFunction, init, isDone= args pattern = statePatternAbstract(patternFunction, init, isDone) def substitutePattern(patternPlaceHolder): pattern.__doc__ = patternPlaceHolder.__doc__ pattern.__name__ = patternPlaceHolder.__name__ def runPatternOrConstructor(*patternInput): if len(patternInput)==0: #Run constructor! return statePatternAbstract(patternFunction, init, isDone) else: #Run already constructed pattern return pattern(patternInput[0]) return runPatternOrConstructor return substitutePattern def statePatternAbstract(patternFunction, init, isDone): ''' Helper function to create statePatterns. A a statePattern is defined by 3 things: 1- a patternFunction, i.e. a function that takes: (patternInput, statePatternDict) It modifies statePatternDict as desired to keep its own state, and uses it and the patternInput to return a new pattern input. The statePatternDict is a dict used for the pattern to save its state. 2- A init function, i.e. a function that takes (transitionDict, patternInput) The init function is the function responsible for initializing/restarting the statePatternDict So that the patternFunction has a working statePatternDict that it can use/ so that the patternDunction can be restarted. 3- A IsDone function, i.e. a function that takes (statePatternDict) And decides if the pattern should be restarted ''' doneContainer=[False] statePatternContainer=[None] statePatternDict={} def statePattern(patternInput): frame = patternInput['frame'] #Resets the pattern when the frame==0 done = doneContainer[0] #Resets the pattern when the frame==0 or done if frame ==0 or done: doneContainer[0] = False statePatternContainer[0]=None statePatternDict.clear() pattern = statePatternContainer[0] if (pattern == None): #This means that the pattern has just initialized or has just restarted statePatternContainer[0]=patternFunction pattern = statePatternContainer[0] init(statePatternDict,patternInput) newPatternInput = pattern(patternInput,statePatternDict) done = isDone(statePatternDict) doneContainer[0]=done return newPatternInput return statePattern ########### #Begin simple snake def simpleSnakeInit(statePatternDict, patternInput): ''' Initializes/restarts the dict for the fade transition ''' statePatternDict['previousTotalBeats']=patternInput['totalBeats'] statePatternDict['snakeBody']=[[0,0]] statePatternDict['snakeMax']=patternInput['width'] * patternInput['height'] / 8. statePatternDict['direction'] =0 def simpleSnakePatternFunction(patternInput,statePatternDict): UP=0 DOWN=3 RIGHT=1 LEFT=2 height =patternInput['height'] width =patternInput['width'] previousBeats=int(statePatternDict['previousTotalBeats']) thisBeats = int(patternInput['totalBeats']) snakeBody = statePatternDict['snakeBody'] if (thisBeats>previousBeats): statePatternDict['previousTotalBeats'] = thisBeats direction = statePatternDict['direction'] newDirection = random.randint(1,3) newDirection=((3-direction)+newDirection)%4 statePatternDict['direction'] = newDirection snakeBody.append(snakeBody[-1]) statePatternDict['snakeBody']=snakeBody direction = statePatternDict['direction'] snakeBodySize = len(snakeBody) for i in xrange(snakeBodySize-1,0,-1): snakeBody[i]=snakeBody[i-1] y,x = snakeBody[0] if direction==UP: head= [y-1,x] if direction==DOWN: head = [y+1,x] if direction==RIGHT: head= [y,x+1] if direction==LEFT: head= [y,x-1] head[0]=head[0]%height head[1]=head[1]%width if head not in snakeBody: snakeBody[0]=head else: statePatternDict['direction'] = (direction+1)%4 patternInput = BP.blackPattern(patternInput) canvas = patternInput['canvas'] for yx in snakeBody: y,x = yx canvas[y,x]=(1,0,0) y,x = snakeBody[0] canvas[y,x]=(0,0,1) return patternInput def simpleSnakeIsDone(statePatternDict): snakeBody=statePatternDict['snakeBody'] done = (len(snakeBody) > statePatternDict['snakeMax']) return done @statePattern('simpleSnake') @makeStatePattern(simpleSnakePatternFunction,simpleSnakeInit,simpleSnakeIsDone) def simpleSnakePattern(): ''' A simple snake that turns and grows with the beat ''' pass
53139e4c82ea5ba946ba0e1099f550855a3c054d
IvanMerejko/3-semestr
/КГ/lab3.py
2,043
3.65625
4
from tkinter import * PIXEL_SIZE = 2 HEIGHT = 400 WIDTH = 400 black_rbg = 123456 dots = [] window = Tk() # Place canvas in the window canvas = Canvas(window, width=WIDTH, height=HEIGHT) canvas.pack() def is_point_in_line(point, start_line, end_line): x, y = point[0], point[1] x0, y0 = start_line[0], start_line[1] x1, y1 = end_line[0], end_line[1] find_x = (int)((y - y0)*(x1 - x0) / (y1 - y0) + x0) return x == find_x and ( x0 < x < x1 or x1 < x < x0) def find_left_barrier(x_help,y , start_line, end_line): x_left = x_help while x_help > 0: if is_point_in_line([x_help, y], start_line, end_line): x_left = x_help x_help -= 1 return x_left def find_right_barrier(x_help, y , start_line, end_line): x_right = x_help while x_help < WIDTH: if is_point_in_line([x_help, y], start_line, end_line): x_right = x_help x_help += 1 return x_right def fill_by_line(x, y): print(y) for i in range(0, len(dots) - 1): start_line = dots[i] if i == len(dots) - 1: end_line = dots[0] else: end_line = dots[i+1] x_help = x x_left = find_right_barrier(x_help, y, start_line, end_line) x_help = x x_right = find_left_barrier(x_help, y, start_line, end_line) if x_left > 0 and x_right < WIDTH: canvas.create_line(x_left, y, x_right, y, fill="black") def create_one_line(x, y): dots_count = len(dots) if dots_count == 0: canvas.create_oval(x, y, x, y, width=0, fill="black") else: canvas.create_line(dots[dots_count-1][0], dots[dots_count-1][1], x, y, fill="black") dots.append([x, y]) def left_click(event): create_one_line(event.x, event.y) def fill(event): fill_by_line(event.x, event.y) def right_click(event): create_one_line(dots[0][0], dots[0][1]) window.bind('<Button-1>', left_click) window.bind('<Button-2>', fill) window.bind('<Button-3>', right_click) window.mainloop()
17e7494fcbb225659e4e6add6d0f4874fdf87f59
dannslima/MundoPythonGuanabara
/MUNDO3/ex072.py
561
4.25
4
#Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extenso, # de zero até vinte. #Seu programa deverá ler um numero pelo teclado (entre 0 e 20) e motra-lo por extenso. cont = ('zero','um','dois','tres','quatro','cinco','seis','sete','oito','nove','dez','onze','doze', 'treze','quatorze','quinze','dezesseis','dezessete','dezoito','dezenovo','vinte') while True: num = int(input('Digite um numero de 0 a 20 ')) if 0<= num <= 20: break print('Tente novamente') print(f' Você digitou o número {cont[num]}')
8f47a65043ee96d8ef02c731343b5d103d178edf
navlalli/colour-soap-films
/src/decorators.py
314
3.625
4
""" Decorators """ import time def timeit(func): def wrapper(*args, **kwargs): start_time = time.time() output = func(*args, **kwargs) end_time = time.time() print(f"{func.__name__}() --> {end_time - start_time:.2f} s execution time") return output return wrapper
adb324d9193027da91f64735499ed88bbfb2aa9e
Manish-bit/Fresh
/birth.py
112
3.5625
4
birth_date = input('birth date:') print(type(birth_date)) age = 2020-int(birth_date) print(type(age)) print(age)