blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
feed2799aaf5178b405a50d033a57382e37de6be
YanHengGo/python
/33_except/lesson.py
883
3.703125
4
#可以捕获所有异常,但不推荐 try: int('abc') sum=1+'1' f=open('abc.txt') print(f.read()) f.close() except : print('出错了T_T') #分别捕获异常 try: sum=1+'1' f=open('abc.txt') print(f.read()) f.close() except OSError as reason: print('文件出错了T_T',reason) except TypeError as reason: print('类型出错了T_T',reason) #同时捕获异常 try: sum=1+'1' f=open('abc.txt') print(f.read()) f.close() except (OSError,TypeError) as reason: print('出错了T_T',reason) #关于finally try: f=open('abc.txt','w') f.write('write sth') sum=1+'1' except OSError as reason: print('文件出错了T_T',reason) except TypeError as reason: print('类型出错了T_T',reason) finally: f.close() #抛出异常 关于raise 可以有参数 raise ZeroDivisionError('除数为0')
045dbac82a08a9490849ef0e36f9e9788014c6de
mobenjamin/replpy
/lexer.py
948
3.875
4
def lex_input(input_string): token = "" output_list = [] i = 0 while i < len(input_string): char = input_string[i] if char == "\"": i += 1 token = char while i < len(input_string) and input_string[i] != "\"": token += input_string[i] i += 1 token += char output_list.append(token) token = "" elif char == "(" or char == ")" or char == "'": # Add more if needed if token != "": output_list.append(token) token = "" output_list.append(char) elif char == " " or char == "\n" or char == "\t" or char == "\r": if token != "": output_list.append(token) token = "" else: token += char i += 1 if token != "": output_list.append(token) return output_list
f402197274f3908d9209ebd9605551a7c9128a2c
swang99/CS1
/Cities Visualizer/city.py
528
3.796875
4
# name: Stephen Wang # date: November 7, 2020 # purpose: City class class City: def __init__(self, code, name, region, population, latitude, longtitude): self.code = code self.name = name self.region = region self.population = int(population) self.latitude = float(latitude) self.longtitude = float(longtitude) def __str__(self): return self.name + "," + str(self.population) + "," + str(self.latitude) + "," + str(self.longtitude)
60c02435ade1624dab567d0d2b837558e78389e2
maps16/ProgramacionF
/Producto2/Python/juego.py
399
3.640625
4
import time print "Hola, es hora de jugar ADIVINA EL NUMERO. Primero piensa en un numero entre 1 y 10" import time time.sleep(5) print "Multiplicalo por 9" import time time.sleep(5) print "Si el numero es de dos digitos, sumalos entre si. Por ejemplo si es 25 -> 2+5=7" import time time.sleep(5) print "El numero resultante sumale 4" import time time.sleep(10) print "Bien. El resultado es 13"
ac7b2b9725522f9f52c0d33be5634661b3e281ad
hawahe/leran_frank
/practice/list_comprehension.py
678
3.875
4
a = [x*x for x in range(10)] print(a) a= [x*x for x in range(10) if x % 3 ==0] print(a) a = [(x,y) for x in range(3) for y in range(3)] print(a) result = [] for x in range(3): for y in range(3): result.append((x,y)) print(result) girls = ['alice','bernice','clarice'] boys = ['chris','arnold','bob'] a = [b+'+'+g for b in boys for g in girls if b[0] == g[0]] #只打印首字母相同的男孩和女孩的名字 print(a) girls = ['alice','bernice','clarice'] boys = ['chris','arnold','bob'] letterGirls = {} for girl in girls: letterGirls.setdefault(girl[0],[]).append(girl) print(letterGirls) print([b+'+'+g for b in boys for g in letterGirls[b[0]]])
96b2bf88d8bafc984c98057ece6eee2584d2b053
cezary4/LearningPython
/projects/fdic/scraper.py
2,904
3.953125
4
#!/usr/bin/env python """ This scrape demonstrates some Python basics using the FDIC's Failed Banks List. It contains a function that downloads a single web page, uses a 3rd-party library to extract data from the HTML, and packages up the data into a reusable list of data "row". NOTE: The original FDIC data is located at the below URL: http://www.fdic.gov/bank/individual/failed/banklist.html In order to be considerate to the FDIC's servers, we're scraping a copy of the page stored on Amazon S3. """ # Import a built-in library for working with data on the Web # http://docs.python.org/library/urllib.html import urllib # Import a 3rd-party library to help extract data from raw HTML # http://www.crummy.com/software/BeautifulSoup/documentation.html from bs4 import BeautifulSoup # Below is a re-usable data scraper function that can be imported and used by other code. # http://docs.python.org/2/tutorial/controlflow.html#defining-functions def scrape_data(): # URL of the page we're going to scrape (below is the real URL, but # we'll hit a dummy version to be kind to the FDIC) #URL = 'http://www.fdic.gov/bank/individual/failed/banklist.html' URL = 'https://s3.amazonaws.com/python-journos/FDIC_Failed_Bank_List.html' # Open a network connection using the "urlopen" method. # This returns a network "object" # http://docs.python.org/library/urllib.html#high-level-interface web_cnx = urllib.urlopen(URL) # Use the network object to download, or "read", the page's HTML html = web_cnx.read() # Parse the HTML into a form that's easy to use soup = BeautifulSoup(html) # Use BeautifulSoup's API to extract your data # 1) Fetch the table by ID table = soup.find(id='table') # 2) Grab the table's rows rows = table.findAll('tr') # Create a list to store our results results = [] # 3) Process the data, skipping the initial header row for tr in rows[1:]: # Extract data points from the table row data = tr.findAll('td') # Pluck out the text of each field, and perform a bit of clean-up row = [ data[0].text, data[1].text, data[2].text, data[3].text, data[4].text, data[5].text.strip(), data[6].text.strip(), 'http://www.fdic.gov/bank/individual/failed/' + data[0].a['href'], ] # Add the list of data to our results list (we'll end up with a list of lists) results.append(row) # Let's package up the results with the field names headers = [ 'bank_name', 'city', 'state', 'cert_num', 'acq_inst', 'closed', 'updated', 'url' ] return [headers, results] if __name__ == '__main__': results = scrape_data() for row in results[1]: print row
9f8e199968a12fa56c7dfc47b82f1c79538f01f5
PLivdan/gender
/genderize.py
8,152
3.53125
4
""" Created on Tue Sep 10 14:07:15 2019 @author: tickc """ import csv import os import nltk import random ############################################################################# # # A necessary utility for accessing the data local to the installation. # ############################################################################# _ROOT = os.path.abspath(os.path.dirname(__file__)) def get_data(path): return os.path.join(_ROOT, 'data', path) get_data("filename") #using .split() will give incorrect values since it does not split whitespace def split(values): return [char for char in values] #removes vowels from features def remove_vowels(s): vowels = "aeiouAEIOU" s_without_vowels = "" for letter in s: if letter not in vowels: s_without_vowels += letter return s_without_vowels #removes consonants from features def only_vowels(s): vowels = "aeiouAEIOU" only_vowels = "" for letter in s: if letter in vowels: only_vowels += letter return only_vowels #extracts features from name def extract_features(name): name = name.lower() return { 'last_char': name[-1], 'last_two': name[-2:], 'last_three': name[-3:], 'first': name[0], 'first2': name[:2], 'first3': name[:3], 'no_vowels': remove_vowels(name), 'only_vowels': only_vowels(name), } class Genderizer: def __init__(self): self.genderDict = {} self.listmale = [] self.listfem = [] self.buildDict() self.trainClassifier() #Initializes dictionary for names def buildDict(self): genderDict = {} shortNames = [] listmale = [] listfem =[] Count = 0 #Acceses country_pop to get current population estimates for the population of each country pop = dict(filter(None, csv.reader(open(get_data("country_pop.csv"))))) f = open(get_data("nam_dict.txt")) #List of countries from countries = u"""great_britain ireland usa italy malta portugal spain france belgium luxembourg the_netherlands east_frisia germany austria swiss iceland denmark norway sweden finland estonia latvia lithuania poland czech_republic slovakia hungary romania bulgaria bosniaand croatia kosovo macedonia montenegro serbia slovenia albania greece russia belarus moldova ukraine armenia azerbaijan georgia the_stans turkey arabia israel china india japan korea vietnam other_countries """.split() for line in f: if Count >= 362: #DOCUMENTATION_LENGTH = 362 text = line[0:86] mf = text[:2].strip() # M,1M,?M, F,1F,?F, ?, = # = <short_name> <long_name> name = text[2:29].lower().strip() sortingFlag = text[29] # +,-; ignore + unsortedf = text[30:85] frequencies = split(unsortedf) if sortingFlag != '+': if mf == '=': continue else: if name.find('+') != -1: names = [name.replace('+','-'), name.replace('+',' '), name.replace('+','').capitalize()] else: names = [name] for name in names: if name not in genderDict: genderDict[name] = {} genderDict[name][mf] = {} else: if mf not in genderDict[name]: genderDict[name][mf] = {} for country,freq in zip(countries,frequencies): if freq != ' ': norm_freq = int((float(pop[country]) * 1000) * 0.02 * (2 ** (int(freq,16) - 10))) #norm_freq = int(((float(pop[country]))*1000) * (math.log(int(freq,16)))) # print(int(float(pop[country]) * 1000)) # print((math.log(int(freq,16),2))) genderDict[name][mf][country] = norm_freq Count += 1 for [name, frequencies] in shortNames: shortName, longName = name.lower().split() if shortName in genderDict and not longName in genderDict: for nameList in genderDict[shortName]: if longName in genderDict: genderDict[longName].append(nameList) else: genderDict[longName] = [nameList] elif longName in genderDict and not shortName in genderDict: for nameList in genderDict[longName]: if shortName in genderDict: genderDict[shortName].append(nameList) else: genderDict[shortName] = [nameList] #Sorts names for male and female with values for key in genderDict.keys(): if 'M' in genderDict[key]: listmale.append(key) else: if 'F' in genderDict[key]: listfem.append(key) #loop to generate data for classifier #while val <= len(all_names) * 0.8: self.genderDict = genderDict self.listmale = listmale self.listfem = listfem #Trains classifer for NLTK def trainClassifier(self): all_names = [(i, 'm') for i in self.listmale] + [(i, 'f') for i in self.listfem] for x in range(0, 1): Val = 2000 #DOCUMENTATION_LENGTH = 2000 random.shuffle(all_names) #splits feature sets into training and test sets test_set = all_names[Val:] train_set= all_names[:Val] # The training set is used to train a new "naive Bayes" classifier. test_set_feat = [(extract_features(n), g) for n, g in test_set] train_set_feat= [(extract_features(n), g) for n, g in train_set] self.classifier = nltk.NaiveBayesClassifier.train(train_set_feat) self.accuracy = nltk.classify.accuracy(self.classifier, test_set_feat) def genderize(self,name,location = None): name = name.lower() for key in self.genderDict.keys(): # if name in self.genderDict.keys() and location != None: # if location in self.genderDict[name].keys(): # if 'M' in self.genderDict[key]: # return 'm' # else: # return 'f' # # else: # print(self.genderDict[name]) # return 'location not found' if name in self.genderDict.keys(): print(name) if 'M' in self.genderDict[key]: print(self.genderDict[key]) return 'm' else: return 'f' if name not in self.genderDict.keys(): print('classified') return self.classifier.classify(extract_features(name))
cbcd33917e029920d425ec24df9cdddb8418ddd2
rronakk/Python-3-exercies
/treehouse/pick_a_num.py
1,310
4.0625
4
import random def computer_choice(): return random.randint(1, 10) def user_choice(): num = input("Guess a number between 1 to 10: ") return int(num) def game_rules(): print("Welcome to Guess a number game") print("Guess a number between 1 to 10, if your guess matches the number guessed by computer, You win") print("You get only 5 chances to guess") def game(): count = 1 game_rules() actual_num = computer_choice() while True: if count <= 5 : guess_num = user_choice() if guess_num == actual_num: print("Bravo! you nailed it in {} attempt" .format(count)) break elif guess_num <= actual_num: print("Your number is lower than actual number, Please try again.") print("you made {} attempt".format(count)) count+=1 continue elif guess_num >= actual_num: print("your number is greater than actual number, Please try again") print("you made {} attempt".format(count)) count+=1 continue else: print("You exceeded your allowed attempt") break game()
9198042369289921a55ec43c065975618941301d
toejellyfutbol/childdir
/ex15a.py
301
3.875
4
# import the argument variables from sys import argv # designates variables to be unpacked script, filename = argv #designates txt as the content of the filename txt = open(filename) #print presentation of file's name print "Here's your file %r:" % filename #print content of file print txt.read()
da88d7bc35b92671a35dfea43cd6cdbffc89e037
devNaresh/DS-Algo
/stringSerching/RabinKarpSearch.py
1,831
3.6875
4
__author__ = '__naresh__' # Implementation of Rabin Karp substring Search """ Time Complexibility O(m*n) https://www.youtube.com/watch?v=H4VrKHVG5qI Application -- Generally used for serching of multiple patterns """ PRIME_NUMBER = 101 def create_hash(pattern): length = len(pattern) hash = 0 for x in range(length): hash += (PRIME_NUMBER ** x) * ord(pattern[x]) return hash def recreate_hash(old_hash, orignal_string, postion, pattern_len): """ For generating new hash from old hash follow below three steps 1) Minus value of element which got out from pattern 2) Divide new hash value with prime number 3) Added new value with new hash value """ if old_hash is 0: return create_hash(orignal_string[:pattern_len]) else: value = ord(orignal_string[postion + pattern_len - 1]) * (PRIME_NUMBER ** (pattern_len - 1)) new_hash = old_hash - ord(orignal_string[postion - 1]) new_hash /= PRIME_NUMBER new_hash += value return new_hash def find_substing(orignal_string, pattern): pattern_hash = create_hash(pattern) string_hash = 0 for i in range(len(orignal_string) - len(pattern)): string_hash = recreate_hash(string_hash, orignal_string, i, len(pattern)) if string_hash == pattern_hash: found = True for x, y in zip(orignal_string[i:i + len(pattern)], pattern): if x != y: found = False break if found: return i return None if __name__ == "__main__": data = "jim saw me in a barber parlour" pattern = "barber" start = find_substing(data, pattern) end = start + len(pattern) print data[start:end]
0769d3cd2170d8af918a5bc9dc48275d1b413dcd
agarwalsanket/TheBalancePuzzle
/balances.py
10,401
3.875
4
import turtle import os __author__ = "Sanket Agarwal" """ This program is the implementation of the problem stated in HW7. Authors: Sanket Agarwal (sa3250@rit.edu) """ class Beam: """ Beam class contains data about a beam. """ __slots__ = 'beam', 'beam_name_objects', 'beam_draw' def __init__(self, li_beam, draw): """ Constructor for the Beam class. :param li_beam: list of constituent weights/beams for a particular beam. :param draw: flag which controls if a beam is to be drawn (=true) or not (=false) """ self.beam = {} self.beam_draw = {} if draw == 'false': self.makebeam(li_beam) elif draw == 'true': self.makebeam_draw(li_beam) else: print("improper inputs") def makebeam(self, li_beam): """ This function creates a beam object if it is part of a bigger beam. :param li_beam: list of constituent weights/beams for a particular beam. :return: None """ if li_beam is []: return None beam_name = li_beam.pop(0) count = 0 for i in range(len(li_beam)): self.beam[li_beam[i + count]] = li_beam[i + 1 + count] count += 1 if (i + count + 1) > (len(li_beam) - 1): self.beam["name"] = beam_name break def makebeam_draw(self, li_beam): """ This function creates a beam object so that it can be drawn later. :param li_beam: list of constituent weights/beams for a particular beam. :return: None """ if li_beam is []: return None beam_name_draw = li_beam.pop(0) count = 0 for i in range(len(li_beam)): self.beam_draw[li_beam[i + count]] = li_beam[i + 1 + count] count += 1 if (i + count + 1) > (len(li_beam) - 1): self.beam_draw["name"] = beam_name_draw break @staticmethod def weight(beam): """ This function computes the weight of a beam. :param beam: Beam object whose weight is to be computed. :return: Weight of the beam object. """ sum_weight = 0 for k in beam: if k != 'name': sum_weight += int(beam[k]) return sum_weight def draw(self, name_dict_dict, beams_list, absent_weight, unit_v, unit, t): """ This is the function to be invoked for the drawing of beam. :param name_dict_dict: A dictionary of dictionaries containing data about beam. :param beams_list: A list of dictionaries containing data about beam. :param absent_weight: Missing weight :param unit_v: Length of vertical beam. :param t: Turtle object :return: None :pre: (0,0) relative facing East, pen up :post: (0,0) relative facing East, pen up """ writable_unit = 30 reverse_beams_list = beams_list[::-1] t.penup() t.left(90) t.pendown() t.forward(-unit_v) t.penup() t.right(90) for i in range(len(reverse_beams_list)): for k in reverse_beams_list[i]: if k != 'name': t.pendown() t.forward(int(k) * unit) t.penup() if reverse_beams_list[i][k] in name_dict_dict: self.draw(name_dict_dict, [name_dict_dict[reverse_beams_list[i][k]]], absent_weight, unit_v * 1.5, unit/3, t) t.penup() t.left(90) t.forward(1.5 * unit_v) t.right(90) t.forward(-(int(k) * unit)) elif int(reverse_beams_list[i][k]) == -1: reverse_beams_list[i][k] = absent_weight t.left(90) t.pendown() t.backward(unit_v) t.penup t.backward(writable_unit) t.pendown() t.write(reverse_beams_list[i][k], font=("Arial", 12, "bold")) t.penup() t.forward(unit_v + writable_unit) t.right(90) t.forward(-(int(k) * unit)) else: t.left(90) t.pendown() t.backward(unit_v) t.penup t.backward(writable_unit) t.pendown() t.write(reverse_beams_list[i][k], font=("Arial", 12, "bold")) t.penup() t.forward(unit_v + writable_unit) t.right(90) t.forward(-(int(k) * unit)) break class Weight: """ Weight class to compute torque and missing weights for a beam. """ __slots__ = 'weight', 'beam_name_dict_with_obj', 'beam_dict_list', 'name_dict_dict', 'absent_weight' def __init__(self, beam_name_dict_with_obj, beam_dict_list, name_dict_dict): """ Constructor function for the Weight class. :param beam_name_dict_with_obj: Dictionary of dictionaries containing data of beam. :param beam_dict_list: A list of dictionaries containing data about beam. :param name_dict_dict: Dictionary of dictionaries containing data of beam. """ self.beam_dict_list = beam_dict_list self.beam_name_dict_with_obj = beam_name_dict_with_obj self.name_dict_dict = name_dict_dict self.absent_weight = 0 self.balance() def balance(self): """ Function to compute whether a beam is balanced or not, and if not, to compute the missing weight. :return: None """ for i in range(len(self.beam_dict_list)): calculate_balance = 'true' balance = 0 for k in self.beam_dict_list[i]: if k != 'name': if self.beam_dict_list[i][k] in self.beam_name_dict_with_obj: self.beam_dict_list[i][k] = Beam.weight(self.beam_name_dict_with_obj.get( self.beam_dict_list[i][k]).beam) if int(self.beam_dict_list[i][k]) == -1: k_temp = k balance = 0 temp = i partial_sum_weight = 0 print("The beam " + self.beam_dict_list[temp][ 'name'] + " has an empty pan, at distance " + k_temp) for k in self.beam_dict_list[temp]: if k != 'name' and self.beam_dict_list[temp][k] != '-1': if self.beam_dict_list[temp][k] in self.beam_name_dict_with_obj: self.beam_dict_list[temp][k] = Beam.weight(self.beam_name_dict_with_obj.get( self.beam_dict_list[temp][k]).beam) partial_sum_weight += int(k) * int(self.beam_dict_list[temp][k]) self.beam_dict_list[temp][k_temp] = str(-partial_sum_weight // int(k_temp)) self.absent_weight = self.beam_dict_list[temp][k_temp] print("It should be filled with weight of " + self.beam_dict_list[temp][ k_temp] + " units to be balanced. Now " + self.beam_dict_list[temp][ 'name'] + " will also be balanced") break if calculate_balance != 'false': balance += int(k) * int(self.beam_dict_list[i][k]) if balance == 0: print(self.beam_dict_list[i]['name'] + ' is balanced') else: print(self.beam_dict_list[i]['name'] + ' is not balanced') for i in range(len(self.beam_dict_list)): for k in self.beam_dict_list[i]: if self.beam_dict_list[i][k] in self.beam_name_dict_with_obj: self.beam_dict_list[i][k] = self.beam_name_dict_with_obj.get(self.beam_dict_list[i][k]) def main(): """ Main function of the implementation. :return: None """ while 1: file_puzzle = input("Enter the file name having the description of the Balance Puzzle ") if not os.path.isfile(file_puzzle): print("File does not exist") else: break beams_name_obj_dict = {} name_beam_dict = {} beams_list = [] beams_name_obj_dict_draw = {} name_beam_dict_draw = {} beams_list_draw = [] with open(file_puzzle) as beam: for line in beam: li_beam_local = line.split() if len(li_beam_local) % 2 == 0: print("Invalid entries in line ", li_beam_local) lextent = 0 rextent = 0 li_name = li_beam_local[0] li_temp = li_beam_local[1::2] for i in range(len(li_temp)): if int(li_temp[i]) < lextent: lextent = int(li_temp[i]) if int(li_temp[i]) > rextent: rextent = int(li_temp[i]) beam = Beam(li_beam_local, 'false') beams_name_obj_dict[line.split()[0]] = beam name_beam_dict[line.split()[0]] = beam.beam beams_list.append(beam.beam) print("Length of beam ", li_name, "is: ", (abs(lextent) + abs(rextent))) print("Left extent of beam ", li_name, "is: ", lextent, " and the right extent is: ", rextent) with open(file_puzzle) as beam: for line in beam: li_beam_local_draw = line.split() beam_draw = Beam(li_beam_local_draw, 'true') beams_name_obj_dict_draw[line.split()[0]] = beam_draw name_beam_dict_draw[line.split()[0]] = beam_draw.beam_draw beams_list_draw.append(beam_draw.beam_draw) wt = Weight(beams_name_obj_dict, beams_list, name_beam_dict) beam_draw.draw(name_beam_dict_draw, beams_list_draw, wt.absent_weight, 10, 30, turtle) turtle.exitonclick() if __name__ == "__main__": main()
c171aecc5ede4d84e5c26cae33ad668873c6f031
Navarroo/Algoritimos
/Aulas/aula25escrita.py
420
3.625
4
# ========MODOS DE LEITURA DE ARQUIVOS========= # r = read ( leitura) # a = write (escrita) # w = delete and create new (escrita em arquivo em branco) # open retorna um endereço para o arquivo arq = open("arquivos/nomes.txt", "w") # escreve alguma coisa no arquivo arq.write("Navarro\n") nome = input("Informe seu nome: ") arq.write(nome) arq.write("\n") # salva as notificações e salva os arquivos arq.close()
330221a75ec044bea63629ba2a28db4c5ee228b6
grassit/leetcode
/46.py
572
3.640625
4
# ref: https://leetcode.com/discuss/18212/my-elegant-recursive # -c-solution-with-inline-explanation # ref: https://discuss.leetcode.com/topic/17277/one-liners-in-python class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ return nums and [p[:i] + [nums[0]] + p[i:] for p in self.permute(nums[1:]) for i in xrange(len(nums))] or [[]] if __name__ == '__main__': sol = Solution() print sol.permute([1, 2])
4ac3fb5a6a42d5cc90316b34b9f78acb0a531a21
TimotheusJX/Algo_code
/twoSum.py
592
3.515625
4
''' example: Given num array [2, 7, 11, 15], target = 9 return [0, 1] assumption: each input has one soln and same element may not use twice ''' class TwoSumSolution(object): def twoSum(self, nums, target): mapping = {} for index, value in enumerate(nums): result = target - value print(mapping) if result in mapping: print('yes') return [index, mapping[result]] else: mapping[value] = index solution = TwoSumSolution() print(solution.twoSum([2,7,11,15], 9))
f285b74cd89ca95b08d2fdbe20c166ac13e5fa82
arkellmer/python-4-5-class
/meaningoflife.py
1,465
3.890625
4
from tkinter import * class Application(Frame): """gui application which can reveal the secret of longevity""" def __init__(self, master): """initialize the frame""" super(Application, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): #create instruction label self.inst_lbl = Label(self, text="enter password for the secret life") self.inst_lbl.grid(row=0, column=0, columnspan=2, sticky = W) #create label for password self.pw_lbl = Label(self, text= "Password:") self.pw_lbl.grid(row=1,column=0, sticky = W) #create input box for password self.pw_ent = Entry(self) self.pw_ent.grid(row= 1, column=1, sticky=W) self.submit_bttn = Button(self, text = "Submit", command = self.reveal) self.submit_bttn.grid(row=2,column=0, sticky=W) #create text widget to display message self.secret_txt = Text(self, width=35, height=5, wrap = WORD) self.secret_txt.grid(row=3,column=0,columnspan=2,sticky=W) def reveal(self): contents = self.pw_ent.get() if contents == "secret": message = "42" else: message = ("thats not the correct password") self.secret_txt.delete(0.0,END) self.secret_txt.insert(0.0,message) root = Tk() root.title("Longevity") root.geometry("300x150") app = Application(root) root.mainloop()
a9c9a2dbd646460fcc048e71e4e14a47dc49ef4f
seanaleid/Intro-Python-I
/src/11_args.py
2,981
4.46875
4
# Experiment with positional arguments, arbitrary arguments, and keyword # arguments. # Write a function f1 that takes two integer positional arguments and returns # the sum. This is what you'd consider to be a regular, normal function. # YOUR CODE HERE def f1(num1, num2): return num1 + num2 # print(f1(1, 2)) # Write a function f2 that takes any number of integer arguments and returns the # sum. # Note: Google for "python arbitrary arguments" and look for "*args" # YOUR CODE HERE def f2(*args): result = 0 for x in a: result += x return result #print(f2(1)) # Should print 1 #print(f2(1, 3)) # Should print 4 #print(f2(1, 4, -12)) # Should print -7 #print(f2(7, 9, 1, 3, 4, 9, 0)) # Should print 33 # a = [7, 6, 5, 4] # How do you have to modify the f2 call below to make this work? def f2(a): result = 0 for x in a: result += x return result # print(f2(a)) # Should print 22 # change *args --> a and uncomment the a list # Write a function f3 that accepts either one or two arguments. If one argument, # it returns that value plus 1. If two arguments, it returns the sum of the # arguments. # Note: Google "python default arguments" for a hint. # YOUR CODE HERE def f3(num1, num2=1): return num1 + num2 #print(f3(1, 2)) # Should print 3 #print(f3(8)) # Should print 9 # Write a function f4 that accepts an arbitrary number of keyword arguments and # prints out the keys and values like so: # # key: foo, value: bar # key: baz, value: 12 # # Note: Google "python keyword arguments". # YOUR CODE HERE def f4(**vals): # print("key: a, value: " + str(vals["a"])) # print("key: b, value: " + str(vals["b"])) ### loop through and print each value ### review the .items() --> dictionaries .items(), .keys(), 1 more for args, items in vals.items(): print(args, items) # Should print # key: a, value: 12 # key: b, value: 30 # f4(a=12, b=30) ### not need, f4 on 63 - 69 works for both # def f4(**vals): # print("key: city, value: " + vals["city"]) # print("key: population, value: " +str(vals["population"])) # print("key: founded, value: " +vals["founded"]) # Should print # key: city, value: Berkeley # key: population, value: 121240 # key: founded, value: "March 23, 1868" # f4(city="Berkeley", population=121240, founded="March 23, 1868") d = { "monster": "goblin", "hp": 3 } # works, but doesn't use **kwargs # def f4(d): # print(d) def f4(**vals): print(vals["d"]) # How do you have to modify the f4 call below to make this work? # f4(d = { "monster": "goblin", "hp": 3}) # example from lecture Tuesday, July 7th # def stupid_add(a, b): # if type(a) == str and type(b) == str: # print(int(a) + int(b)) # elif type(a) == int and type(b) == int: # print(str(a) + str(b)) # else: # print(None) # stupid_add("1", "2") # stupid_add(1, 2) # stupid_add(1, "2")
065c6161a7438d6ed9559cea4e18c2bf9ac86480
taddes/AlgoChallenge
/bubble_sort/py/bubble_sort.py
360
3.96875
4
""" Implementation of Bubble Sort """ def bubble_sort(arr): for i in range(len(arr)): for j in range(len(arr) - i - 1): if j < arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] print(arr) return arr test_arr_1 = [14, 78, 2587, 3, 687, 21] test_arr_2 = [85, 14, 36, 6 , 18, 55] bubble_sort(test_arr_1)
6c438d4c19fed278778d3ca38603046cc4d749bb
waredeepak/python_basic_beginners_programs
/in.python.basic/ExponentialProgram.py
185
4.15625
4
num=int(input("enter any number you want to : ")) exp=int(input("enter exponential number: ")) result=1 for i in range(1,(exp+1)): result=result*num print("The result is : ",result)
c360cbc38f7f6600915a9fc2413bcbbbedf38f85
EwanThomas0o/Self_teaching
/SEMF.py
668
3.609375
4
def binding_energy_calculator(A,Z): #All in MeV BE1 = 15.56*A - 17.23*(A**(2/3)) - 0.697*(Z**2)*(A**(-1/3)) - 23.285*((A-2*Z)**2)/A if (A-Z)%2 != 0 and Z%2 != 0: #This if statement deals with the pairing term BE2 = BE1 + (12/(A**0.5)) elif A%2 !=0: BE2 = BE1 else: BE2 = BE1 - (12/(A**0.5)) return Z*938.28 + (A-Z)*939.57 - BE2 #mass energy of the nucleus minus BE #Lets use this to get an answer! m_sb = binding_energy_calculator(111,51) m_sn = binding_energy_calculator(111,50) q = m_sb - (m_sn + 0.511) #0.511 is mass of electron so this is Q value for beta decay print("The Q value for this reaction is", q)
fa98f9b2ec32cec12e8d010a8c94d65583693a17
Masetto97/PROCESADORES_DE_LENGUAJE
/Moore/environment.py
626
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import Player from player from random import randint class Square(object): def __init__(self, size, n_treasures): self.place = [range(size) for i in range(size)] self.n_treasures = n_treasures self.treasure_position = {} def hide_treasure(self, total, limit_x, limit_y): for i in range(0, total): pos_x = randint(0, limit_x) pos_y = randint(0, limit_y) self.treasure_position[i+1] = [pos_x, pos_y] self.place[pos_x, pos_y] = 1 def print_pos(self): print("jaajjaja")
70351c2b399d750a83132744b01592cae2af073c
ashikurcmt126/python-basic
/program27.py
192
3.640625
4
# map function() def square(x): return x*x num = [10,20,30,40] a = list(map(square,num)) print(a) # filter() num = [1,2,3,4,5] result = list(filter(lambda x:x%2==0,num)) print(result)
219ef2757f4e612eb5968345651e371c8ba081df
mnogom/python-project-lvl1
/brain_games/games/calc.py
1,250
4.09375
4
"""Description of the rules for game 'brain-calc'.""" import random # -- Description DESCRIPTION = "What is the result of the expression?" # -- Constants MIN = 0 MAX = 100 OPERATIONS = "+-*" def _calculate_result(number_1: int, number_2: int, operation: str) -> int: """Returns result of calculation a mathematical expression. :param number_1: number #1 :param number_2: number #2 :param operation: mathematical operation :return: result of expression """ if operation == "+": return number_1 + number_2 if operation == "-": return number_1 - number_2 if operation == "*": return number_1 * number_2 raise ValueError("Action on '{operation}' is not defined. ".format( operation=operation)) # -- Task generator def generate_round() -> (str, str): """Generate question and right answer. :return: question and answer """ number_1 = random.randint(MIN, MAX) number_2 = random.randint(MIN, MAX) operation = random.choice(OPERATIONS) question = "{n1} {op} {n2}".format( n1=number_1, n2=number_2, op=operation) right_answer = _calculate_result(number_1, number_2, operation) return question, str(right_answer)
236bf9c996e83985e8dd1a0afc75db16ea180e14
manhar336/manohar_learning_python_kesav
/Datatypes/Strings/Strings_Methods2.py
800
4.15625
4
1. lower() method--lower method returns string in lower case. 2. upper() method-- upper method returns string in upper case. 3. replace() method--replace method replaces with other string 4. Split() method --splits the string into substrings if it finds instances of the separator. 5. rfind() method --- it will search substring from right to left 6. find() method --It will search substring from left to right 7. index() method --It will search substring from left to right index. 8. rindex() method -- It will search substring from right to left index. Note: In find method if we did not get the value it wont through any error and print as -1 but in Index method it will through error. 9. split() method: it will split elements into list based on parameter 10.splitlines() : It will do splitlines
0d6f6338b02f2432b8306ba215697de7e88ec067
neeraj70/Hello-World
/cowbull.py
1,620
3.90625
4
import random WORDLENGTH = 6 WORDFILE = "sixwords.txt" FILELENGTH = 17443 def findcowsandbulls(inputword, guessword): word = inputword.upper() bull, cow = 0, 0 for w in word: # type: object if guessword.find(w) == -1: continue if word.find(w) == guessword.find(w): bull = bull + 1 else: cow = cow + 1 return cow, bull def validateword(inputword): if len(inputword) != WORDLENGTH: print("Error - enter a word with exactly six characters") return False if inputword.isalpha() == False: print ("Error - enter only alphabetic characters") return False for w in inputword: if inputword.count(w) > 1: print("Error - enter a six letter word with unique letters") return False return True def randomword(): i = random.randint(1,FILELENGTH) with open (WORDFILE, "r") as f: line = f.readlines()[i] temp = line[:-1] return temp def readinputword(): inputword = raw_input("Enter a six letter word ") while (validateword(inputword) != True): inputword = raw_input("Enter a six letter word ") return inputword def main(): guessword = randomword() cow, bull, attempts = 0,0,0 while bull != WORDLENGTH: inputword = readinputword() attempts = attempts + 1 cow, bull = findcowsandbulls(inputword, guessword) print "cow = ", cow , "bull = ", bull print ("You cracked the word in ", +attempts, "chances!") main()
17a8a9ef9a8dddbf7ec98a212ae92b66f35dab33
leolahara/leolahara
/assignment3.py
6,530
4.28125
4
# assignment3.py # # Student name: Leola Hara # Student id: V00923578 import math # imports Python's math library for your use (ie. math.sqrt) THRESHOLD = 0.1 # to be used to compare floating point values passed = 0 # number of tests passed tests = 0 # number of tests run def main(): ''' Complete this assignment by doing the following for each function: - uncommenting one test function call in main NOTE: each test function has at least one test, but you should add additional tests where you feel necessary - implement the function (write the documentation and define the function) NOTE: follow the documentation provided for implementing each function in the assignment pdf - repeat until all functions are tested and implemented ''' test_get_rectangle_area() test_get_average() test_append() test_distance() test_get_shipping_cost() # implement each of the 5 functions after it's corresponding test function # We have provided you with one test for each function # You must add more to ensure you have consider all cases def test_get_rectangle_area(): result = get_rectangle_area(0,0) expected = 0 print_test("get_rectangle_area", abs(expected-result)<THRESHOLD) result = get_rectangle_area(3.2,5.5) expected = 17.6 print_test("get_rectangle_area", abs(expected-result)<THRESHOLD) result = get_rectangle_area(7.29,8.8) expected = 64.152 print_test("get_rectangle_area", abs(expected-result)<THRESHOLD) ''' Purpose: design a function that takes two flaoting point numbers that represent length and width of a rectangle in cm and returns the area in cm squared. Arguements: length, width, (flaoting point numbers) Example: If length 3.2 and width 4.5, area returned would be 14.4 ''' def get_rectangle_area(length, width): area = length * width return area # TODO: define get_rectangle_area... def test_get_average(): result = get_average(0,0,0) expected = 0 print_test("get_average", abs(expected-result)<THRESHOLD) result = get_average(1.5,0.3,5.2) expected = 2.33333333 print_test("get_average", abs(expected-result)<THRESHOLD) result = get_average(7.9,7.9,3.8) expected = 6.5333333 print_test("get_average", abs(expected-result)<THRESHOLD) ''' Purpose: design a function that takes three flaoting point numbers and returns the average three numbers. Arguements: num1, num2, num3 (flaoting point numbers) Example: if num1 is 4.4, num2 is 5.5, num3 is 6.6, the returned value would be 5.5 ''' def get_average(num1, num2, num3): average = (num1 + num2 + num3)/ 3 return average # TODO: define get_average... def test_append(): result = append("", "") print_test("append", result == "") result = append("no way", "jose") print_test("append", result == "no wayjose") result = append("holy moly", "guacamole") print_test("append", result == "holy molyguacamole") ''' Purpose: design a function that takes two phrases and appends them into one new phrase and returns the new phrase with no space between the two phrases joined. Arguements: str1, str2 (both strings) Example: if str1 was 'you are' and str2 is 'awesome', the resulting string would be 'you areawesome' ''' def append(str1, str2): phrase1 = str1 phrase2 = str2 append_1 = (str1.strip()+str2.strip()) return append_1 # TODO: define append.. def test_distance(): result = distance(3, 0, 0, 4) print_test("distance", abs(5-result)<THRESHOLD) result = distance(3, 5, 6, 8) print_test("distance", abs(2.8282427-result)<THRESHOLD) ''' Purpose: design a function called distance that takes four floating point numbers as arguements that represent 2 points and calculates and returns the distance between the two points. Arguements: x1, x2, y1, y2, (all floating point numbers) Example: if x1 = 2.2, x2= 4.2, y1= 8.4, y2= 9.1, the returned number would be, 1.57797..... ''' def distance(x1, x2, y1, y2): distance_1 = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) return distance_1 # TODO: define distance... def test_get_shipping_cost(): std_len = 28.2 std_wid = 10 wt03 = 0.03 result = get_shipping_cost(wt03, std_len, std_wid) expected = 1.05 print_test("get_shipping_cost", abs(expected-result)<THRESHOLD) std_len = 10 std_wid = 5 wt03 = 0.06 result = get_shipping_cost(wt03, std_len, std_wid) expected = 1.90 print_test("get_shipping_cost", abs(expected-result)<THRESHOLD) ''' Purpose: design a function that takes the weight of the letter in kgs and the length and width of a letter in cm and calculates and returns the cost of shipping that letter. Arguements: weight, length, width (all floating point numbers) Example: if the weight is 0.24kg and the length is 12cm and width is 10cm it would be 1/90 + 1.4 * 0.5 = 2.6 ''' def get_shipping_cost(weight, length, width): area= get_rectangle_area(length, width) if (area <= 282 and weight <= 0.05): base_rate = 1.05 if (weight <= 0.03): return(base_rate) else: return(1.05 + (((weight-.03)/.01) * .20)) elif (weight <= 0.1): base_rate = 1.90 return(base_rate) else: return(1.90 + (((weight - 0.1)/0.1) * 0.50)) # if (area < 282 and wt03 < 0.05): # print(1.05 +((wt03 > 0.03)/ 10) * 20 ) # else: # print(1.90 +((wt03 > 0.1)/ 100) * 50 ) # return get_shipping_cost # TODO: define get_shipping_cost... ''' Purpose: prints test_name followed by "passed" if expression evaluates to True, prints test_name followed by "failed" if expression evaluates to False Args: test_name (str): the name of the test expression (bool): a boolean expression' ''' def print_test(test_name, expression): global tests global passed tests += 1 if(expression): print(test_name + ': passed') passed += 1 else: print(test_name + ': failed') # The following code will call your main function # It also allows our grading script to call your main # DO NOT ADD OR CHANGE ANYTHING PAST THIS LINE # DOING SO WILL RESULT IN A ZERO GRADE if __name__ == '__main__': main()
724199b337b479515c43b433aa72bd2b0a3d27de
akashdeep-chitransh/Python-basic-programms
/Introduction/add.py
191
4.15625
4
# this program wil add two numbers.. print("Enter two numbers below..") a = int(input("Enter first number:")) b = int(input("Enter second number:")) print("Sum of this two numbers is ",a+b)
8c74e32212904d2f95aeddc8b12fdc476f051883
EnriqueZepeda/Python_Skills
/Chapter7/Ex_7_1.py
255
3.859375
4
file = input('Enter a file name:') try: fileHandle = open(file) except: print('Error: file', file, 'no found') quit() count = 0 for lines in fileHandle: lines = lines.rstrip() print(lines.upper()) count = count + 1;
608e9a4dc43ca3a3bf5e3ff585c387166f877b98
Oldby141/learning
/shopping/__init__.py
1,178
3.921875
4
product_list=[ ('Iphone',5000), ('MacPro',9000), ('Bike',500), ('watch',200), ('cofe',20), ] shopping_list=[] salary=input("请输入你的薪水") if salary.isdigit(): salary = int(salary) while True: for index,item in enumerate(product_list): print(index,item) user_choice = input("选择买的物品?") if user_choice.isdigit(): user_choice=int(user_choice) if user_choice<len(product_list) and user_choice >=0: p_item=product_list[user_choice] if salary>=p_item[1]:#买得起 shopping_list.append(p_item) salary-=p_item[1] print("购买成功,剩余金额:\033[31;1m%s\033[0m" %(salary)) else: print("金额不足") else: print("商品不存在") elif user_choice == 'q': print("--------------------shopping list----------------------------------") print(shopping_list) print("你的剩余余额:",salary) exit() else: print("invalid option")
b95ea023b8fd04ff5d5849b27181b0fe23400c0f
yuks0810/cloud9-python-course-TA
/Lesson13/def2.py
311
3.609375
4
def introduce(name = "N/A", age = "??"): print("Hello!") print(f"My name is {name}.") print(f"I'm {age} years old.") introduce("tanaka", 25) # 引数を全て指定 introduce("suzuki") # age を省略 introduce(age = 30) # name を省略 introduce() # name も age も省略
afe8e849fcbd9952846ad145abc46cb4552f7578
LearnCodingTogether/PythonAdvanced
/DataFraming_Using_PANDAS/DropingDataFrame.py
400
4.09375
4
import pandas df1=pandas.read_json("supermarkets.json") df1=df1.set_index("Address") print(df1) #Deleting row(0 is for row) having address "3666 21st St" print(df1.drop("3666 21st St",0)) #drop column(1 is for column) named as City print(df1.drop("City",1)) #Drop row from 0 to 2 print(df1.drop(df1.index[0:3],0)) #Drop Columns from 0 to 2 print(df1.drop(df1.columns[0:3],1))
087305d0e24886384841d6bf0eb421ffe6d75a8e
Xisouyang/CS_1.3
/Lessons/source/sets.py
2,420
4.09375
4
#!python # this implementation of the Set class is backed by hash tables from hashtable import HashTable class Set(object): def __init__(self, elements=None): # initialize a new empty set structure, and add each element if a sequence is given self.hash_set = HashTable() if elements != None: for item in elements: self.add(item) def size(self): # property that tracks the number of elements in constant time return self.hash_set.size def contains(self, element): # return a boolean indicating whether element is in this set return self.hash_set.contains(element) def add(self, element): # add element to this set, if not present already if self.contains(element) == False: self.hash_set.set(element, None) def remove(self, element): # remove element from this set, if present, or else raise KeyError return self.hash_set.delete(element) def union(self, other_set): # return a new set that is the union of this set and other_set new_set = Set() for item in self.hash_set.keys(): new_set.add(item) for item in other_set.hash_set.keys(): new_set.add(item) return new_set def intersection(self, other_set): # return a new set that is the intersection of this set and other_set new_set = Set() if other_set.size() > self.size(): big_set = other_set small_set = self else: big_set = self small_set = other_set for item in small_set.hash_set.keys(): if big_set.contains(item): new_set.add(item) return new_set def difference(self, other_set): # return a new set that is the difference of this set and other_set new_set = Set() for item in self.hash_set.keys(): if other_set.contains(item): continue new_set.add(item) return new_set def is_subset(self, other_set): # return a boolean indicating whether other_set is a subset of this set if other_set.size() > self.size(): return False is_a_subset = True for item in other_set.hash_set.keys(): if not self.contains(item): is_a_subset = False return is_a_subset
b9cf5887120a5658bd955995fc5ff2627a827e26
shamurti/Python_Class
/class_test.py
1,228
3.75
4
# Creating a simple dictionary ''' def netw_device(ip, username, password): net_dev = {} net_dev['ip'] = ip net_dev['username'] = username net_dev['password'] = password return net_dev ''' # Now creating the same but using Classes ''' Creating the class object. "object" below refers to base object. If inherting from another, then the class name would go in the paranthesis ''' class NetworkDevice(object): # The "def" below defines a 'method' within the class # "__init__" is the method automatically invoked when the object is created def __init__(self, ip, username, password): self.ip = ip self.username = username self.password = password # write code to telnet as a part of the class # def connect_telnet(self): # code to telnet using above information # write code to go to enable mode # def connect_enable(self): # code here for enable mode # write code to execute a command # def show_version(self): # code to execute show version rtr1 = NetworkDevice('10.1.1.1', 'admin', 'boo') rtr2 = NetworkDevice('10.1.1.2', 'admin', 'boo') print('Router1: %s %s %s') % (rtr1.ip, rtr1.username, rtr1.password) print "Router2: {0} {1} {2}".format(rtr2.ip, rtr2.username, rtr2.password)
813c48a19ca8e979b66c95fba95fe1a815586570
drekuru/CSUS-CPE-CSC-EEE-Materials
/PHYS 162/Homework/Solutions/HW05-Plotting/HW05-Problem3.py
3,663
3.625
4
#!python 3 # Problem 3-b on Matplotlib-I HW # Because of the "if" statements, the "ground" function does not work for arrays, and a loop is necessary to # apply to xdata before plotting. "numpy.piecewise" make it possible to go around this (see online documentation). import numpy as np import matplotlib.pyplot as plt plt.figure(figsize=(8,6), dpi=80) ax = plt.subplot(111) # define trajectory function h0 = 1.54 # in m g = 9.8 # in m/s^2 d1 = 6 # in m alpha = 30 # in degrees (slope of slanted ground) d2 = 4 # in m tanAlpha = np.tan(np.radians(alpha)) # calculate onces instead of every time a ground position is needed H = d2*tanAlpha # Height of the plateau in m def y( x, v0, th0 ): "This function will return the y-coordinate for a given x-coordinate and initial velocity." th0rad = th0 * np.pi/180 return h0 + np.tan(th0rad) * x - g * x**2 / (2 * v0**2 * np.cos(th0rad)**2) # set up domain variables xmin = 0.0 xmax = 12.0 xrange = xmax - xmin # set discretization step dx = 0.1 # calculate number of points needed (standard formula; take note of it) numpoints = int(xrange/dx+0.001) + 1 # Generate x values xdata = np.linspace(xmin,xmax,numpoints) # The ground data, using conditional statements: def ground( x ): "This function returns the height of the ground at a given value of x." retval = 0.0 if( d1 < x <= d1+d2 ): retval = np.tan(np.radians(alpha)) * (x-d1) elif( x > d1+d2 ): retval = H return retval # Since our function expects a single float, we have to use a loop to calculate the data: ydata = [] for x in xdata: ydata.append(ground(x)) # Plot the ground plt.plot(xdata,ydata,color='black', linewidth=3.0) # Lists of values of v0 to be explored and corresponding colors th0s = [0, 40, 50] # in degrees v0s = [8.0,9.0,11.0] # in m/s ranges = [xmax, xmax, xmax] # default values used before ranges are determined ranges = [4.5, 8.3, 11.5] # correct ranges, comments if unknown colors = ['red','blue','green'] # set title plt.title(r'Trajectories for various $v_0$ and $\theta_0$',fontsize=20,color='blue') ymin = 0.0 # no point in plotting anything below the ground ymax = -1 # we're going to find the largest y value among all the trajectories # use a loop to make the plots for v0,th0,col,xdist in zip(v0s,th0s,colors,ranges): # Generate x values for trajectories xdata = np.linspace(xmin,xdist,numpoints) # generate data for each trajectory to end it when rock hits ground # plug the xdata into the trajectory function ydata = y(xdata,v0,th0) if( np.max(ydata) > ymax): ymax = np.max(ydata) # Plot the data plt.plot(xdata,ydata,color=col, linewidth=1.0, label=r'$v_0=%.1f$ m/s, $\theta_0=%.0f^\circ$' % (v0,th0)) plt.scatter([xdist,],[ground(xdist),],color="black") plt.annotate(r'r=%.1f m'%(xdist), xy=(xdist, ground(xdist)), xycoords='data', xytext=(-120, 30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="angle3,angleA=10,angleB=80")) print('For theta0 = %.0f degrees, v0=%.0f m/s, the range is %.1f m'%(v0,th0,xdist)) yrange = ymax - ymin # Set the axis labels plt.xlabel(r'$x$ (m)',fontsize=16) plt.ylabel(r'$y$ (m)',fontsize=16) # Set the axis limits with a bit of a margin margin = 0.1 plt.xlim(xmin, xmax) plt.ylim(ymin-0.025, ymax + yrange * margin) #prepare tick labels for vertical axis: yticks = [] ylabels = [] for x in ranges: y = ground(x) yticks.append(y) ylabels.append(f'{y:.1f}') plt.yticks(yticks, ylabels, fontsize=16) # Turn on legend plt.legend(loc='upper right',frameon=True) # Save figure to file plt.savefig("prob3.pdf",dpi=72) # Display figure plt.show()
77e79dab65a34a0faac460b86de59ffb9b7686e1
Faiznurullah/HacktoberFest-Python
/codes/AI-Summer-Course/py-master/Basics/Exercise/16_class_and_objects/16_class_and_objects.py
534
4.0625
4
class Employee: def __init__(self, id, name): self.id = id self.name = name def display(self): print(f"ID: {self.id} \nName: {self.name}") # Creating a emp instance of Employee class emp = Employee(1, "coder") emp.display() # Deleting the property of object del emp.id # Deleting the object itself try: print(emp.id) except NameError: print("emp.id is not defined") del emp try: emp.display() # it will gives error after deleting emp except NameError: print("emp is not defined")
3cd6ec2b1c18f26b6f2bfd0a2c85e7a8a67f4f38
mehdiebrahim/Stanford-Algorithms---Coursera
/Divide and Conquer, Sorting and Searching, and Randomized Algorithms/Week 2/noofinversions.py
2,008
3.9375
4
import pandas as pd import sys import os os.chdir('/Users/mehdiebrahim/Desktop/Coding/Stanford Algorithms - Data') data = pd.read_csv('numbers.txt',sep=' ',header=None) data.columns = ['a'] L = list(data['a']) n = len(L) inv_count = 0 def Merge(L,R,mid): global inv_count result = [0]*(len(L)+len(R)) #temporary list in which to merge L and R i=j=k=0 # print(L,R) # below is the main loop for comparing two sorted arrays to merge into result while i < len(L) and j < len(R): if L[i] < R[j]: result[k] = L[i] i+=1 else: result[k] = R[j] inv_count+=mid-(i) j+=1 k+=1 # If you reach the end of either array, then you can # add the remaining elements from the other array to # the result and break the loop # this is necessary i.e if L=[1,2,4,9] R=[3,4,5,6] gives res # [1,2,3,4,4,5,6,6] without the below step. # In this case,i=3,j=4,k=7 so final element of L which is 9 # needs to be added. This step below would be necessary when # an element in L is bigger than all of elems in R # so the above loop breaks before 9 is copied in while i<len(L): result[k]=L[i] i+=1 k+=1 while j<len(R): result[k]=R[j] j+=1 k+=1 return result def MergeSort(array): if len(array)==1: return array #this way when the L or R inputted into Merge func has len=1 (after enough divides i.e array[:mid] and array[mid:], #MergeSort outputs the array which can be then sorted and merged by the Merge func. #Otherwise, MergeSort outputs None when the L or R has #which cannot be sorted and merged mid = len(array)//2 L = array[:mid] R = array[mid:] return Merge(MergeSort(L),MergeSort(R),mid) MergeSort(L) print(inv_count)
3e6a1d132bbcd9e1420b259fdcecd8db15111960
sakshi2829/job-recruitment-and-selection
/str.py
93
3.8125
4
n=6 def square(n) return n*n print "the square of "+str(n)+"is"+str(square(n))
8d70f88650df97853f8b48aef48d8652fe7413f9
himanshusoni30/PythonProjects
/PythonBootCamp/isOrEqualTo.py
633
4.0625
4
a = [1,2] b = [1,2] print(f"type of variable 'a' is: {type(a)}, the value of variable 'a' is: {a}") print() print(f"type of variable 'b' is: {type(b)}, the value of variable 'b' is: {b}") print() if(a == b): print("Condition: a == b") print(f"a: {a} is equal to the value of b: {b}") else: print("Condition: a == b") print(f"a: {a} is not equal to the value of b: {b}") print() if(a is b): print("Condition: a is b") print(f"a: {hex(id(a))} contains the same reference in memory as b: {hex(id(b))}") else: print("Condition: a is b") print(f"a: {hex(id(a))} does not contain the same reference in memory as b: {hex(id(b))}")
a9dbea13d1a3aa2bcaca321e63573c7d137d6f30
sanstwy777/Leetcode
/MySolutions/836. Rectangle Overlap/836.py
914
3.890625
4
# ============================================================================ # Name : Leetcode.836. Rectangle Overlap # Author : sanstwy27 # Version : Version 1.0.0 # Copyright : # Description : Any % # Reference : # ============================================================================ from typing import collections, List class Solution: def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool: if((rec2[0] < rec1[0] and rec1[0] < rec2[2]) or (rec1[0] <= rec2[0] and rec2[0] < rec1[2])): if((rec2[1] < rec1[1] and rec1[1] < rec2[3]) or (rec1[1] <= rec2[1] and rec2[1] < rec1[3])): return True return False rec1 = [0,0,2,2] rec2 = [1,1,3,3] # rec1 = [0,0,1,1] # rec2 = [1,0,2,1] # rec1 = [7,8,13,15] # rec2 = [10,8,12,20] print(Solution().isRectangleOverlap(rec1, rec2))
1753b9826e8ef787883b566a21bc9a0b6c180c2c
icoding2016/study
/PY/free_exercise/find_intersection_of_2_linked_list.py
2,064
3.859375
4
# Find intersection node of 2 linked lists # Easy class LinkedNode(object): def __init__(self, value=None): self.value = value self.next = None @classmethod def generate(cls, data:list) -> 'LinkedNode': head = None cur = None for d in data: if not cur: head = LinkedNode(d) cur = head else: cur.next = LinkedNode(d) cur = cur.next return head def tail(self) -> 'LinkedNode': cur = self while cur: if not cur.next: return cur cur = cur.next def find(self, value) -> 'LinkedNode': cur = self while cur: if cur.value == value: return cur cur = cur.next return None @classmethod def show(cls, head: 'LinkedNode') -> None: cur = head while cur: print(cur.value, end='') cur = cur.next if cur: print(', ', end='') print('') def __str__(self) -> str: s = '' cur = self while cur: s += str(cur.value) cur = cur.next if cur: s += ', ' return s # T(M+N) M=len(l1), N=len(l2) # S(M+N) def find_intersect_node(l1: LinkedNode, l2: LinkedNode) -> LinkedNode: p1 = l1 p2 = l2 path1 = dict() path2 = dict() while p1 or p2: if p2 and p2 in path1: return p2 if p1 and p1 in path2: return p1 if p1: path1[p1] = True p1 = p1.next if p2: path2[p2] = True p2 = p2.next return None def test(): l1 = LinkedNode.generate([i for i in range(10)]) l2 = LinkedNode.generate([i for i in range(20,25)]) l2.tail().next = l1.find(7) print(f'l1: {l1}') print(f'l2: {l2}') isn = find_intersect_node(l1, l2) print(f'intersection: {isn.value if isn else None}') test()
80718805bad3d0030c2edf8b64c279cd90038010
paul-pias/Euler-Problem-Practice-
/Smallest Multiple.py
138
3.765625
4
def gcd(x,y): return y and gcd(y,x%y) or x def lcm(x,y): return x*y / gcd(x,y) n=1 for i in range(1,10): n=lcm(n,i) print(n)
10dcda47418a22bb6545b625589d419b1b0ba2a7
jomazu/PythonNotes
/03-Numbers.py
1,359
4.34375
4
# Calculate the area of a rectangle (Area = Width x Length) Width = float(input('What is the width of your rectangle? ')) Length = float(input('What is the length of your rectangle? ')) Area = Width * Length print('The area of your rectangle is %.2f' %Area) print('\n') # Calculate the area of a triangle (Area = Width x Height/2) Width = float(input('What is the base length of your triangle? ')) Height = float(input('What is the height of your triangle? ')) Area = Width * Height / 2 print('The area of your triangle is %.2f' %Area) print('\n') # How to format numbers to display to users # f stands for float and d stands for decimal print('I have %d cats' % 6) # This will print 'I have 6 cats' print('I have %3d cats' % 6) # This will print 'I have 6 cats' print('I have %03d cats' % 6) # This will print 'I have 006 cats' print('I have %f cats' % 6) # This will print 'I have 6.000000 cats' print('I have %.2f cats' % 6) # This will print 'I have 6.00 cats' (2 decimal places) print('I have %.3f cats' %6) # This will print 'I have 6.000 cats' (3 decimal places) print('\n') # Calculate the value of z, based on user-input for x and y print('You will enter values for the following equation: x * y = z') x = float(input('Enter a value for x? ')) y = float(input('Enter a value for y? ')) z = x * y print('The value for z is %.2f' %z)
15dc5f957a6ec22f397b9ea05da5813c32ce2a45
benchen0955/c_call_python
/hello_e.py
373
3.546875
4
# hello.py class HHello_c: def __init__(self, x): self.x=x print("init") # self.x=x # self.x = x # print("====") def printt(self,a=None): print("====") print(a) return str(a) # return def xprint(): print("hello world") # if __name__ == "__main__": # xprint() # h = HHello_c(1) # a=h.printt(8) # print(a)
d1c79747239540536114ea0289cea3ca9924d7fa
KChen-lab/Cyclum
/cyclum/hdfrw.py
1,710
3.65625
4
"""Read write HDF.""" import h5py import pandas import numpy from typing import Type, Union, List def hdf2mat(filepath: str, dtype: Type = float) -> pandas.DataFrame: """Read hdf generated by hdfrw.R mat2hdf function to a data frame. Note that due to how python and R handles data differently, colnames are for index and rownames are for columns, and the matrix is also tacitly transposed. :param filepath: path of hdf file :param dtype: type of data; default is float :return: a pandas data frame """ with h5py.File(filepath, 'r') as f: df = pandas.DataFrame(f['matrix'][:], dtype=dtype, copy=False) if 'colnames' in f.keys(): df.index = [x.decode() for x in f['colnames'][:]] if 'rownames' in f.keys(): df.columns = [x.decode() for x in f['rownames'][:]] return df def mat2hdf(data: Union[pandas.DataFrame, numpy.array, List[str]], filepath: str) -> None: """Write dataframe to an hdf file which can be read by hdfrw.R hdf2mat function. :param data: data frame or numpy array to be written :param filepath: path of hdf file to be written :return: None """ with h5py.File(filepath, 'w') as f: if type(data) is pandas.DataFrame: f['matrix'] = data.values f['colnames'] = [x.encode('ASCII') for x in data.index.tolist()] f['rownames'] = [x.encode('ASCII') for x in data.columns.tolist()] elif type(data) is numpy.ndarray: f['matrix'] = data elif type(data) is list: f['matrix'] = [x.encode('ASCII') for x in data] else: raise TypeError("only pandas.DataFrame and numpy.ndarray are supported.")
578c4bc5f64facf7141a0bb5bffe235e17d49376
cloeffler745/back-up
/code/test/ditance_func/test_alg.py
1,183
3.875
4
import Levenshtein import numpy as np import random import string import sys first = sys.argv[1] second = sys.argv[2] ## Algorithm ------------------------------------------------------------------- def edit_distance(s, t): """Edit distance of strings s and t. O(len(s) * len(t)). Prime example of a dynamic programming algorithm. To compute, we divide the problem into overlapping subproblems of the edit distance between prefixes of s and t, and compute a matrix of edit distances based on the cost of insertions, deletions, matches and mismatches. """ prefix_matrix = np.zeros((len(s) + 1, len(t) + 1)) prefix_matrix[:, 0] = list(range(len(s) + 1)) prefix_matrix[0, :] = list(range(len(t) + 1)) for i in range(1, len(s) + 1): for j in range(1, len(t) + 1): insertion = prefix_matrix[i, j - 1] + 1 deletion = prefix_matrix[i - 1, j] + 1 match = prefix_matrix[i - 1, j - 1] if s[i - 1] != t[j - 1]: match += 1 # -- mismatch prefix_matrix[i, j] = min(insertion, deletion, match) return int(prefix_matrix[i, j]) print(edit_distance(first, second))
231dea1fd60d3a3c29cc8eef1c9d8dbd2ed5bf29
superwenqistyle/1803
/07day/练习/计算器条件.py
400
3.890625
4
x = float(input("请输入数字")) y = float(input("请输入数字")) tar = input("请输入运算符号:+-*/**") if tar == "+": print(x+y) else: if tar == "-": print(x-y) else: if tar == "*": print(x*y) else: if tar == "/": print(x/y) else: if tar == "**": print(x**y)
3af78491444628d97e3b2e8a5481939986befec2
danieljohnson107/EmpDat-Payroll
/Checkpoints/Sprint Something/FindEmployee.py
11,398
3.859375
4
from tkinter import * # from PIL import imageTk, Image from UserData import * from GuiValues import * from tkinter.filedialog import askopenfilename ud = UserData() gv = GuiValues() ''' to use images yoy need to install pillow install with "pip install pillow" on your python to use ImageTk.PhotoImage(Image.open("imagename.png")) put image in widget then put on page ''' ''' everything is a widget start with a self widget this shoudl be first every time you use tkinter''' '''define the action the function will take''' class FindEmployee(Frame): def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller # Object list ''' to create anyting you need to do two things first create the item then put it in a location''' fNameLabel = Label(self, text="First Name:") lNameLabel = Label(self, text="Last Name:") addressLabel = Label(self, text='Address:') addressLineTwoLabel = Label(self, text='Address Line 2:') cityLabel = Label(self, text='City:') stateLabel = Label(self, text='State:') zipCodeLabel = Label(self, text='Zip:') phoneLabel = Label(self, text='Phone Number:') classificationLabel = Label(self, text='Classification:') empNumberLabel = Label(self, text='Employee Number:') passwordLabel = Label(self, text='Password:') departmentLabel = Label(self, text='Department:') payRateLabel = Label(self, text='Pay Rate:') payYTDLabel = Label(self, text='Pay YTD:') securityAccessLabel = Label(self, text='Security Access:') spacer = Label(self, text=" ") # button employeesButton = Button(self, text="Employee's", width=gv.buttonWidth, bg=gv.buttonColor, height=gv.buttonHeight, command=self.employees, state=DISABLED) timeCardsButton = Button(self, text='Timecards', width=gv.buttonWidth, height=gv.buttonHeight, bg=gv.buttonColor, command=lambda: self.openNewWindow('Timecards')) salesButton = Button(self, text=' Sales ', width=gv.buttonWidth, height=gv.buttonHeight, command= lambda: self.openNewWindow('Sales'), bg=gv.buttonColor) myProfileButton = Button(self, text='My Profile', width=gv.buttonWidth, height=gv.buttonHeight, command=self.myProfile, bg=gv.buttonColor) newEmployeeButton = Button(self, text='Enter New\nEmployee', width=gv.buttonWidth, height=gv.buttonHeight, command=self.newEmployee, bg=gv.buttonColor) findEmployeeButton = Button(self, text='Find Employee', width=gv.buttonWidth, height=gv.buttonHeight, command=self.findEmployee, bg=gv.buttonColor) importEmployeeButton = Button(self, text='Import txt of\nnew Employees', width=gv.buttonWidth, height=gv.buttonHeight, command=self.importEmployee, bg=gv.buttonColor) saveProfileButton = Button(self, text='Save', width=gv.buttonWidth, height=gv.buttonHeight, command=self.saveChanges, bg=gv.buttonColor) payrollButton = Button(self, text="Payroll", width=gv.buttonWidth, height=gv.buttonHeight, command=self.pay, bg=gv.buttonColor) # input box for client data input # e.get() will retreive the input from the field fNameInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) lNameInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) addressInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) addressTwoInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) cityInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) stateInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) zipInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) phoneInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) classInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) empNumInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) passwordInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) departmentInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) payRateInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) payYTDInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) securityInput = Entry(self, bg=gv.inputEditColor, borderwidth=gv.inputBorderWidth) # location of items on the screen ''' you can put things into specific locations, but for now we will pack it in. we will usually use a place system to define locations of items on the interface. everything is a place with ys up and down and xs left to right. consider this like a table with 0 - N on the locations You can add these commands to the creation above as well if you would like. ie spacer = Label(self , text='').place(x=0,y=0) ''' # set all locations on form # buttons employeesButton.place(x=0, y=0) timeCardsButton.place(x=185, y=0) salesButton.place(x=370, y=0) payrollButton.place(x=555, y=0) myProfileButton.place(x=740, y=0) newEmployeeButton.place(x=0, y=40) findEmployeeButton.place(x=0, y=80) importEmployeeButton.place(x=0, y=120) saveProfileButton.place(x=0, y=160) # Labels fNameLabel.place(x=200, y=40) lNameLabel.place(x=200, y=65) addressLabel.place(x=200, y=90) addressLineTwoLabel.place(x=200, y=115) cityLabel.place(x=200, y=140) stateLabel.place(x=200, y=165) zipCodeLabel.place(x=200, y=190) phoneLabel.place(x=200, y=215) classificationLabel.place(x=200, y=240) empNumberLabel.place(x=200, y=265) passwordLabel.place(x=200, y=290) departmentLabel.place(x=200, y=315) payRateLabel.place(x=200, y=340) payYTDLabel.place(x=200, y=365) securityAccessLabel.place(x=200, y=390) # Inputs fNameInput.place(x=340, y=40, width=gv.inputWidth, height=gv.inputHeight) lNameInput.place(x=340, y=65, width=gv.inputWidth, height=gv.inputHeight) addressInput.place(x=340, y=90, width=gv.inputWidth, height=gv.inputHeight) addressTwoInput.place(x=340, y=115, width=gv.inputWidth, height=gv.inputHeight) cityInput.place(x=340, y=140, width=gv.inputWidth, height=gv.inputHeight) stateInput.place(x=340, y=165, width=gv.inputWidth, height=gv.inputHeight) zipInput.place(x=340, y=190, width=gv.inputWidth, height=gv.inputHeight) phoneInput.place(x=340, y=215, width=gv.inputWidth, height=gv.inputHeight) classInput.place(x=340, y=240, width=gv.inputWidth, height=gv.inputHeight) empNumInput.place(x=340, y=265, width=gv.inputWidth, height=gv.inputHeight) passwordInput.place(x=340, y=290, width=gv.inputWidth, height=gv.inputHeight) departmentInput.place(x=340, y=315, width=gv.inputWidth, height=gv.inputHeight) payRateInput.place(x=340, y=340, width=gv.inputWidth, height=gv.inputHeight) payYTDInput.place(x=340, y=365, width=gv.inputWidth, height=gv.inputHeight) securityInput.place(x=340, y=390, width=gv.inputWidth, height=gv.inputHeight) def pay(self): self.controller.show_frame("PayrollProcessing") def employees(self): self.controller.show_frame("FindEmployee") def timecards(self): pass def sales(self): pass def myProfile(self): self.controller.show_frame("MyProfile") def newEmployee(self): self.controller.show_frame("EnterNewEmployee") def findEmployee(self): self.controller.show_frame("FindEmployee") def importEmployee(self): pass def saveChanges(self): pass def getFileName(self): return askopenfilename(filetypes=[("CSV files", "*.csv"), ("Text files", "*.txt")]) def setFileName(self, name): selectedFile = name return n def openNewWindow(self, title): print("HI World") master = Tk() # sets the geometry of main # root window master.geometry("925x500") # Toplevel object which will # be treated as a new window # newWindow = Toplevel(master) # sets the title of the # Toplevel widget master.title(title) # # sets the geometry of toplevel # newWindow.geometry("200x200") # A Label widget to show in toplevel timecardLabel = Label(master, text=title+" file must be a .txt or .csv file.") timecardInputLabel = Label(master, text="File for import:") timecardInput= Entry(master, bg=gv.inputEditColor, state='disabled',width=50) timecardSubmitButton = Button(master, text="Import", width=gv.buttonWidth, bg=gv.buttonColor, height=gv.buttonHeight, command=lambda:[ timecardInput.config(state='normal'),timecardInput.delete(0,END), timecardInput.insert(0, self.getFileName()), timecardInput.config(state='readonly')] ) timecardLabel.place(x=200, y=100) timecardInputLabel.place(x=200, y=150) timecardInput.place(x=300, y=150) timecardSubmitButton.place(x=200, y=200) ''' last thing is create an event loop to watch the interface track location of mouse ''' '''get buttons to do something create function'''
30672def0094e409e25c488e8ac5b062bd88a48f
rish987/Pokemon-NLP-Research-Project
/code_re/keyword_finder.py
4,487
3.65625
4
# File: keyword_finder.py # Author(s): Rishikesh Vaishnav, Jessica Iacovelli, Bonnie Chen # Created: 13/06/2018 # Description: An interactive program that finds forwards/backwards keywords and # forwards/backwards descriptor label pairs for a certain relation. from constants import *; import re; import pickle; from difflib import SequenceMatcher; keywords = []; triples = get_raw_triples(); # list of triples that have not yet been classified unknown_triples = triples; # list of triples that are known to imply this relation valid_triples = []; # list of triples that are known to not imply this relation invalid_triples = []; with open(TRIPLES_TO_DESC_TUPS_FILE, 'rb') as f: triples_to_desc_tups = pickle.load(f); def correct_triples(triple_list): global unknown_triples; global valid_triples; global invalid_triples; # - display all triples, marked with a number - triple_i = 0; nums_to_triples = {}; for triple in triple_list: nums_to_triples[triple_i] = triple; print(str(triple_i) + ": " + str(triple)); triple_i += 1; # - # - separate correct/incorrect triples - # get list of numbers of incorrect triples bad_nums_str = input("Enter space-separated list of incorrect triples: "); bad_nums = [int(x) for x in bad_nums_str.split(' ') if x != ""]; # all triples in nums_to_triples have been manually classified, so mark # them as known triples for triple in nums_to_triples.values(): unknown_triples.remove(triple); #separate valid and invalid triples for bad_num in bad_nums: triple_to_remove = nums_to_triples[bad_num]; invalid_triples.append(triple_to_remove); del nums_to_triples[bad_num]; valid_triples += nums_to_triples.values(); # - # initialize the program with a known keyword init_keyword = input("Enter initialization keyword: "); while(True): # - find all unknown triples containing the initialization keyword in the # action - init_keyword_triples = []; for triple in unknown_triples: found = re.search(r'\b%s\b' % re.escape(init_keyword), triple[1]); if (found != None): init_keyword_triples.append(triple); # - correct_triples(init_keyword_triples); triple_i = 0; # - find all unknown triples with matching descriptors as those of the valid # triples - # to store mapping from descriptor tuples to triples containing those # descriptors on either side desc_tup_to_triples = {}; # go through all valid triples for triple in valid_triples: desc_tup = triples_to_desc_tups[triple]; # there are two descriptors and there isn't already an entry for this # tuple if (desc_tup[0] != None) and (desc_tup[1] != None) and \ (desc_tup not in desc_tup_to_triples): # find all unknown triples with this descriptor tuple desc_tup_to_triples[desc_tup] = [t for t in unknown_triples \ if triples_to_desc_tups[t] == desc_tup]; # get list of all triples desc_tup_triples = [x for tup_trips in desc_tup_to_triples.values() \ for x in tup_trips]; # - correct_triples(desc_tup_triples); # - extract keywords from valid list - # mapping from substring to the number of times it was seen in common between # two distinct valid triples substring_to_commonality_count = {}; # go through all distrinct pairs of triples, looking at their actions for triple_i1 in range(len(valid_triples)): action_1 = valid_triples[triple_i1][1].lower(); for triple_i2 in range(triple_i1 + 1, len(valid_triples)): action_2 = valid_triples[triple_i2][1].lower(); match = SequenceMatcher(None, action_1, action_2).find_longest_match(\ 0, len(action_1), 0, len(action_2)) largest_common_substring = action_1[match.a: match.a + match.size]; if largest_common_substring not in substring_to_commonality_count: substring_to_commonality_count[largest_common_substring] = 1; else: substring_to_commonality_count[largest_common_substring] += 1; # - sorted_substrings = sorted(\ substring_to_commonality_count.items(), key=lambda x: x[1]); print([d for d in sorted_substrings if len(d[0]) > 2]); init_keyword = input("Enter the next keyword to iterate on: "); if init_keyword == "_quit": break;
e9cb8e7afafae54376631a9702bd8102f233498e
wnsgur1198/python_practice
/ex10.py
194
3.515625
4
# 편의점 재고 관리 items = {"커피":7, "펜":3, "종이컵":2, "우유":1, "콜라":4, "책":5} item = input("물건의 이름을 입력하시오: ") print("개수: " + str(items[item]))
e32d0f69f813b1ab43699664e3a657caffd7e1d8
weifanhaha/leetcode
/python3/q151-200/189_Rotate_Array.py
747
3.734375
4
from typing import List class Solution: def rotate(self, nums: List[int], k: int) -> None: def reverse(l, i, j): while i < j: l[i], l[j] = l[j], l[i] i, j = i + 1, j - 1 k = k % len(nums) reverse(nums, 0, len(nums) - 1) reverse(nums, 0, k-1) reverse(nums, k, len(nums) - 1) # def rotate(self, nums: List[int], k: int) -> None: # """ # Do not return anything, modify nums in-place instead. # """ # k = k % len(nums) # for _ in range(k): # nums.insert(0, nums.pop()) if __name__ == "__main__": nums = [1, 2, 3, 4, 5, 6, 7] k = 3 sol = Solution() sol.rotate(nums, k) print(nums)
fb74ec16a879cd4c2a5e30d98f95d24084a143ec
Baistan/FirstProject
/training/ОЗ1.py
230
3.890625
4
s = input() upper = 0 lower = 0 for i in s: if i.isupper(): upper += 1 elif i.islower(): lower += 1 if upper > lower: s1 = s.upper() print(s1) elif lower >= upper: s2 = s.lower() print(s2)
088e0395759008cb5003693510dc29a5e002968b
ojcoder/hangman-game
/hangman.py
1,554
3.703125
4
import random print("Welcome to hangman! You will have 10 attempts at guessing the word.\n") print("_", end=" ") print("_", end=" ") print("_", end=" ") print("_", end=" ") print("_") l1="_" l2="_" l3="_" l4="_" l5="_" n1="" n2="" n3="" n4="" n5="" counter = 0 wordlist=["night","fried","shelf","frame"] x=random.choice(wordlist) while counter<10: userguess=str(input("Please type in a letter\n")) if x=="shelf": n1="s" n2="h" n3="e" n4="l" n5="f" if x=="frame": n1="f" n2="r" n3="a" n4="m" n5="e" if x=="fried": n1="f" n2="r" n3="i" n4="e" n5="d" if x=="night": n1="n" n2="i" n3="g" n4="h" n5="t" if userguess==n1: l1= l1.replace(l1,userguess) if userguess==n2: l2 = l2.replace(l2,userguess) if userguess==n3: l3= l3.replace(l3,userguess) if userguess==n4: l4 = l4.replace(l4,userguess) if userguess==n5: l5 = l5.replace(l5,userguess) print(l1, end = " ") print(l2, end = " ") print(l3, end = " ") print(l4, end = " ") print(l5, end = "\n") if l1!= "_" and l2!="_" and l3!="_" and l4!="_" and l5!="_": print("Congrats!") break counter = counter + 1 if l1== "_" or l2=="_" or l3=="_" or l4=="_" or l5=="_": print("You ran out of guesses") ''' def split(x): return list(x) splitword=split(x) '''
b566c68c442ab063e76fcab84c6add9db818e3d0
scottberke/data-structures
/test/trees/binary_tree_traversal_test.py
2,134
3.640625
4
import unittest from io import StringIO from contextlib import * from data_structures.basic_composites.trees.binary_search_tree import * from data_structures.basic_composites.trees.binary_tree_traversal import * class BinaryTreeTraversalTest(unittest.TestCase): # Helpers def create_tree(self): # Lets create this tree: # 50 # / \ # 30 70 # / \ / \ # 20 40 60 80 nodes = [50, 30, 20, 40, 70, 60, 80] bst = BinarySearchTree() for node in nodes: bst.insert(node) return bst def test_in_order_traversal(self): bst = self.create_tree() # Expected node order as output should appear nodes_in_order = [20, 30, 40, 50, 60, 70, 80] n = "\n" expected = n.join(str(i) for i in nodes_in_order) + n # Capture output of in_order_traversal out = StringIO() with redirect_stdout(out): in_order_traversal(bst.root) self.assertEqual( out.getvalue(), expected ) def test_pre_order_traversal(self): bst = self.create_tree() # Expected node order as output should appear nodes_in_order = [50, 30, 20, 40, 70, 60, 80] n = "\n" expected = n.join(str(i) for i in nodes_in_order) + n # Capture output of in_order_traversal out = StringIO() with redirect_stdout(out): pre_order_traversal(bst.root) self.assertEqual( out.getvalue(), expected ) def test_post_order_traversal(self): bst = self.create_tree() # Expected node order as output should appear nodes_in_order = [20, 40, 30, 60, 80, 70, 50] n = "\n" expected = n.join(str(i) for i in nodes_in_order) + n # Capture output of in_order_traversal out = StringIO() with redirect_stdout(out): post_order_traversal(bst.root) self.assertEqual( out.getvalue(), expected ) if __name__ == "__main__": unittest.main()
f550f4f7410410efa2bbb23bc320be317d6d9b05
llliuer/my-leetcode
/leetcode-python/将有序数组转化为二叉搜索树.py
543
3.6875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: def dfs(nums): if len(nums) == 0: return None index = len(nums)//2 newNode = TreeNode(nums[index]) newNode.left = dfs(nums[:index]) newNode.right = dfs(nums[index+1:]) return newNode return dfs(nums)
bada2378c98df9e8bd110052029ca73215239233
miyukozuki07/Paola_Avila_1358
/arrays/Array_2D.py
1,314
3.75
4
""" Array 2D(filas,columnas) get_num_rows() ----> regresa una fila get_num_cols() ----> regresa columnas clearing(value) set_item(r,c,valor) get_item(r,c) """ class Array2D: #Los nombres de las clases inician con la primera letra en mayúscula def __init__(self,filas,columnas): #La clase array posee dos objetos: filas y columnas self.__data = [] self.__fila = filas self.__columna = columnas for i in range(filas): tmp = [] for j in range(columnas): tmp.append(None) self.__data.append(tmp) def to_string(self): print(f"{self.__data}") def get_num_rows(self): return self.__fila def get_num_cols(self): return self.__columna #Checar esta linea de código def clearing(self, valor): for fila in range(self.__fila): for columna in range(self.__columna): self.__data[fila][columna] = valor def set_item(self,fila,columna,valor): if fila >= 0 and fila <self.__fila and columna >= 0 and columna < self.__columna: self.__data[fila][columna] = valor else: print("error en longitud") def get_item(self,r,c): return self.__data[r][c]
95d34d68a1216f65bda8d7db662136a2dce20ad4
W3BGUY/CodeEval_w3bguy
/01.Easy/Python/097.20170226_FindAWriter.py
1,191
4.1875
4
#!Python3 ''' FIND A WRITER Description You have a set of rows with names of famous writers encoded inside. Each row is divided into 2 parts by pipe char (|). The first part has a writer's name. The second part is a "key" to generate a name. Your goal is to go through each number in the key (numbers are separated by space) left-to-right. Each number represents a position in the 1st part of a row. This way you collect a writer's name which you have to output. INPUT SAMPLE: Your program should accept as its first argument a path to a filename. Input example is the following osSE5Gu0Vi8WRq93UvkYZCjaOKeNJfTyH6tzDQbxFm4M1ndXIPh27wBA rLclpg| 3 35 27 62 51 27 46 57 26 10 46 63 57 45 15 43 53 3Kucdq9bfCEgZGF2nwx8UpzQJyHiOm0hoaYP6ST1WM7Nks5XjrR4IltBeDLV vA| 2 26 33 55 34 50 33 61 44 28 46 32 28 30 3 50 34 61 40 7 1 31 This input had 2 rows. OUTPUT SAMPLE: Print results in the following way. Stephen King 1947 Kyotaro Nishimura 1930 ''' import sys with open(sys.argv[1],'r') as test_cases: for test in test_cases: if test.strip(): res='' splitLine=test.split('|') numList=map(int,splitLine[1].split()) for num in numList: res+=splitLine[0][num-1] print(res)
79b54aa7eab62a1c5270c632e3b8e3e642c1451c
pernici/sympy
/sympy/series/residues.py
1,962
3.859375
4
""" This module implements the Residue function and related tools for working with residues. """ from sympy import Wild, sympify, Integer, Add def residue(expr, x, x0): """ Finds the residue of ``expr`` at the point x=x0. The residue is defined as the coefficient of 1/(x-x0) in the power series expansion about x=x0. Examples: >>> from sympy import Symbol, residue, sin >>> x = Symbol("x") >>> residue(1/x, x, 0) 1 >>> residue(1/x**2, x, 0) 0 >>> residue(2/sin(x), x, 0) 2 This function is essential for the Residue Theorem [1]. The current implementation uses series expansion to calculate it. A more general implementation is explained in the section 5.6 of the Bronstein's book [2]. For purely rational functions, the algorithm is much easier. See sections 2.4, 2.5, and 2.7 (this section actually gives an algorithm for computing any Laurent series coefficient for a rational function). The theory in section 2.4 will help to understand why the resultant works in the general algorithm. For the definition of a resultant, see section 1.4 (and any previous sections for more review). [1] http://en.wikipedia.org/wiki/Residue_theorem [2] M. Bronstein: Symbolic Integration I, Springer Verlag (2005) """ expr = sympify(expr) if x0 != 0: expr = expr.subs(x, x+x0) s = expr.series(x, 0, 0).removeO() # TODO: this sometimes helps, but the series expansion should rather be # fixed, see #1627: if s == 0: s = expr.series(x, 0, 6).removeO() if x0 != 0: s = s.subs(x, x-x0) a = Wild("r", exclude=[x]) c = Wild("c", exclude=[x]) r = s.match(a/(x-x0)+c) if r: return r[a] elif isinstance(s, Add): # TODO: this is to overcome a bug in match (#1626) for t in s.args: r = t.match(a/(x-x0)+c) if r: return r[a] return Integer(0)
447381d6e7f770a14e244bf2b675991036736d8e
monanks/DailyCodingChallange
/Problem#4/solution.py
705
3.59375
4
def solution(arr): """ time complexity: O(N) space complexity: O(1) """ if not arr: return 1 #shifting all negative elements to left j = 0 for i in range(len(arr)): if arr[i] <= 0: arr[i], arr[j] = arr[j], arr[i] j += 1 for i in range(j,len(arr)): if abs(arr[i]) - 1 < len(arr) - j and arr[abs(arr[i]) + j - 1] > 0: arr[abs(arr[i]) + j - 1] = -arr[abs(arr[i]) + j - 1] for i in range(j,len(arr)): if arr[i] > 0: return i - j + 1 return len(arr) - j + 1 l1 = [3, 4, -1, 1] print(solution(l1)) l1 = [1, 2, 0] print(solution(l1)) l1 = [2, 5] print(solution(l1))
3a4b4021c621f8bc380d678831a3f9acf30237cf
pulosez/Python-Crash-Course-2e-Basics
/#6: Dictionaries/human.py
720
3.953125
4
# 6.1. human_0 = { 'first_name': 'john', 'last_name': 'connor', 'age': 44, 'city': 'los angeles', } print(human_0) print(human_0['first_name'].title()) print(human_0['last_name'].title()) print(human_0['age']) print(human_0['city'].title()) # 6.7. human_1 = { 'first_name': 'sofi', 'last_name': 'monet', 'age': 25, 'city': 'paris', } human_2 = { 'first_name': 'daichi', 'last_name': 'arai', 'age': 31, 'city': 'tokio', } people = [human_0, human_1, human_2] for human in people: name = f"{human['first_name'].title()} {human['last_name'].title()}" age = human['age'] city = human['city'].title() print(f"{name}, of {city}, is {age} years old.")
5dc072e89b68b964eafe58210818807af1f69573
inverseundefined/DataCamp
/01-Introduction_to_Python/03-Functions_and_Packages/02-Help!.py
909
3.78125
4
''' Help! Maybe you already know the name of a Python function, but you still have to figure out how to use it. Ironically, you have to ask for information about a function with another function: help(). In IPython specifically, you can also use ? before the function name. To get help on the max() function, for example, you can use one of these calls: help(max) ?max Use the Shell on the right to open up the documentation on complex(). Which of the following statements is true? Instructions 50 XP Possible Answers complex() takes exactly two arguments: real and [, imag]. complex() takes two arguments: real and imag. Both these arguments are required. -> complex() takes two arguments: real and imag. real is a required argument, imag is an optional argument. complex() takes two arguments: real and imag. If you don't specify imag, it is set to 1 by Python. Take Hint (-15 XP) '''
5354706a818b2accec51f8267740098c80ed6fe5
nikonoff16/learn2code
/Stepik - Begginers Python/football.py
2,924
3.53125
4
#! /usr/bin/python3 #! python3 # -*- coding: utf-8 ''' ЧАСТЬ ПЕРВАЯ - ВВОД ДАННЫХ В ПРОГРАММУ Создаем двумерный массив из данных, удобный для последовательной обработки. ''' matches_quantity = int(input()) list_of_matches = [] for match in range(matches_quantity): list_of_matches += [[foo for foo in input().split(';')]] ''' ЧАСТЬ ВТОРАЯ - СОЗДАНИЕ ТАБЛИЦЫ ОТЧЕТНОСТИ И ОБРАБОТКА ДАННЫХ ''' otchet = {} for foo in range(len(list_of_matches)): first = 1 second = 3 for egg in range(0, 3, 2): if list_of_matches[foo][egg] not in otchet: otchet[list_of_matches[foo][egg]] = [1, 0, 0, 0, 0] else: otchet[list_of_matches[foo][egg]].insert(0, (otchet[list_of_matches[foo][egg]].pop(0) + 1)) # continue # Эта хер-пойми-что-за конструкция итерирует количество сыграных матчей в уже имеющихся записях for egg in range(0, 3, 2): score = 0 if list_of_matches[foo][first] > list_of_matches[foo][second]: # число в списке побед итерируется на один, если победа имела место otchet[list_of_matches[foo][egg]].insert(1, (otchet[list_of_matches[foo][egg]].pop(1) + 1)) score = 3 elif list_of_matches[foo][first] < list_of_matches[foo][second]: # число в списке поражений итеритуется на 1, если поражение имело место otchet[list_of_matches[foo][egg]].insert(3, (otchet[list_of_matches[foo][egg]].pop(3) + 1)) elif list_of_matches[foo][first] == list_of_matches[foo][second]: # число в списке ничьих итерируется на один, если ничья имела место otchet[list_of_matches[foo][egg]].insert(2, (otchet[list_of_matches[foo][egg]].pop(2) + 1)) score = 1 otchet[list_of_matches[foo][egg]].insert(4, (otchet[list_of_matches[foo][egg]].pop(4) + score)) first = 3 second = 1 ''' ЧАСТЬ ТРЕТЬЯ - ВЫВОД ИНФОРМАЦИИ Не самая легкая часть проекта из-за неизвестной проблемы - величина второй секции вдруг оказывалась больше, чем размер списка в нем, и возникала IndexError. Решил использовать предопределенные численные границы во внутреннем цикле, и все надалилось. ''' for item in otchet: print(item, end=':') for foo in range(0, 5): print(otchet[item][foo], end=' ') print()
4eeca2afef712415b09b5d463523fa4360b62a46
sungminoh/algorithms
/leetcode/solved/210_Course_Schedule_II/solution.py
3,618
4.1875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 sungminoh <smoh2044@gmail.com> # # Distributed under terms of the MIT license. """ There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array. Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: [0,1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. Example 2: Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] Output: [0,2,1,3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. Example 3: Input: numCourses = 1, prerequisites = [] Output: [0] Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= numCourses * (numCourses - 1) prerequisites[i].length == 2 0 <= ai, bi < numCourses ai != bi All the pairs [ai, bi] are distinct. """ import sys from collections import defaultdict from typing import List import pytest class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: """03/15/2019 22:54""" next_courses = defaultdict(set) num_prerequisites = defaultdict(int) for cur, pre in prerequisites: next_courses[pre].add(cur) num_prerequisites[cur] += 1 basics = set(range(numCourses)).difference(num_prerequisites.keys()) curriculum = [] while basics: course = basics.pop() curriculum.append(course) for next_course in next_courses[course]: num_prerequisites[next_course] -= 1 if num_prerequisites[next_course] == 0: basics.add(next_course) if len(curriculum) == numCourses: return curriculum else: return [] def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: pre = {i: set() for i in range(numCourses)} post = {i: set() for i in range(numCourses)} for a, b in prerequisites: pre[a].add(b) post[b].add(a) ret = [] degree_zero = [a for a, bs in pre.items() if len(bs) == 0] while degree_zero: new_degree_zero = [] ret.extend(degree_zero) for b in degree_zero: for a in post[b]: pre[a].discard(b) if len(pre[a]) == 0: new_degree_zero.append(a) degree_zero = new_degree_zero return ret if len(ret) == numCourses else [] @pytest.mark.parametrize('numCourses, prerequisites, expected', [ (2, [[1,0]], [0,1]), (4, [[1,0],[2,0],[3,1],[3,2]], [0,2,1,3]), (1, [], [0]), (3, [[1,0],[1,2],[0,1]], []), ]) def test(numCourses, prerequisites, expected): assert expected == Solution().findOrder(numCourses, prerequisites) if __name__ == '__main__': sys.exit(pytest.main(["-s", "-v"] + sys.argv))
58e507318867f3708edb82e4d25a479006b72f88
feremore/classes-exercise
/OrangeTree.py
1,092
4.125
4
class OrangeTree: # Trees should start at the age of 0. # Trees should start at a height of 0. def __init__(self): self.age = 0 self.height = 0 # Each growing season. # A tree should age one year. # A tree should grow 2.5 feet taller until it reaches its maximum height, say 25 feet. # A tree should bear fruit if it is mature ( at least six years old ) # Between 100 and 300 oranges of fruit. # All oranges from the previous year drop off the tree. def pass_growing_season(self): self.age += 1 self.height += 2.5 if self.height > 25: self.height = 25 # Checks if a tree is old enough to bear fruit ( at least 6 years ) def is_mature(self): return self.age >= 6 # Add instance method: has_oranges() which returns whether or not a tree has any oranges on it. def has_oranges(self): pass # Should pick an orange of a tree and return it. # Or throw an error if there are no oranges. def harvest_orange(self): pass def __str__(self): return 'OrangeTree age={0}, height={1}'.format(self.age, self.height)
79d971085beeb3009d2db5e9887510056d0fe168
mjancen/sudoku-solver
/sudoku-solver.py
4,985
3.578125
4
#!/usr/bin/env python3 # solver.py - takes a sudoku puzzle, outputs the solution # NOTE: cell rows and columns will be 0-indexed, # while boxes will be 1-indexed import random import time from collections import deque import numpy as np LINE = '|' BOX_LINE = '||' HLINE = '-----------------------------------------\n' SOLUTION_STACK_SIZE = 5000 sample_board = np.array([ [0, 0, 5, 1, 0, 3, 6, 0, 0], [0, 9, 7, 6, 0, 5, 0, 8, 3], [8, 0, 0, 0, 0, 0, 1, 2, 0], [0, 0, 0, 3, 9, 7, 0, 0, 2], [0, 0, 8, 0, 0, 0, 9, 0, 0], [7, 0, 0, 5, 6, 8, 0, 0, 0], [0, 7, 1, 0, 0, 0, 0, 0, 4], [4, 8, 0, 2, 0, 1, 5, 6, 0], [0, 0, 2, 9, 0, 4, 7, 0, 0] ]) # boxes is indexed by cell row and col to obtain box number boxes = np.array([ [1, 1, 1, 2, 2, 2, 3, 3, 3], [1, 1, 1, 2, 2, 2, 3, 3, 3], [1, 1, 1, 2, 2, 2, 3, 3, 3], [4, 4, 4, 5, 5, 5, 6, 6, 6], [4, 4, 4, 5, 5, 5, 6, 6, 6], [4, 4, 4, 5, 5, 5, 6, 6, 6], [7, 7, 7, 8, 8, 8, 9, 9, 9], [7, 7, 7, 8, 8, 8, 9, 9, 9], [7, 7, 7, 8, 8, 8, 9, 9, 9], ]) # box_num_to_view is a dict that maps box number to a slice of the puzzle of the box box_num_to_view = { 1 : np.s_[0:3, 0:3], 2 : np.s_[0:3, 3:6], 3 : np.s_[0:3, 6:9], 4 : np.s_[3:6, 0:3], 5 : np.s_[3:6, 3:6], 6 : np.s_[3:6, 6:9], 7 : np.s_[6:9, 0:3], 8 : np.s_[6:9, 3:6], 9 : np.s_[6:9, 6:9], } def show_board(b): board_view = '\n'.join([ '-------------------------------', '| {} {} {} | {} {} {} | {} {} {} |'.format(*b[0]), '| {} {} {} | {} {} {} | {} {} {} |'.format(*b[1]), '| {} {} {} | {} {} {} | {} {} {} |'.format(*b[2]), '-------------------------------', '| {} {} {} | {} {} {} | {} {} {} |'.format(*b[3]), '| {} {} {} | {} {} {} | {} {} {} |'.format(*b[4]), '| {} {} {} | {} {} {} | {} {} {} |'.format(*b[5]), '-------------------------------', '| {} {} {} | {} {} {} | {} {} {} |'.format(*b[6]), '| {} {} {} | {} {} {} | {} {} {} |'.format(*b[7]), '| {} {} {} | {} {} {} | {} {} {} |'.format(*b[8]), '-------------------------------', ]) board_view = board_view.replace('0', '.') print(board_view) def which_box(row, col): '''Returns which box board[row][col] is in''' return boxes[row, col] def get_box(board, box_num): '''Returns a view of the board corresponding to a box number''' return board[box_num_to_view[box_num]] def cell_is_empty(board, row, col): '''Returns whether or not cell at (row, col) is empty''' return (board[row, col] == 0) def move_is_valid(board, num, row, col): # assumes square is empty - 0 in board[row][col] return ( num not in board[row, :] and num not in board[:, col] and num not in get_box(board, which_box(row, col)) ) def board_is_full(board): '''Returns whether or not board is complete''' return np.all(board) def next_unassigned_cell(board): '''Returns the row and column of next unassigned cell''' return np.argwhere(board == 0)[0] def gen_possible_boards(board, row, col): '''Generates possible next boards, given current board and unassigned cell''' next_boards = [] for num in range(1, 10): if move_is_valid(board, num, row, col): new_board = np.copy(board) new_board[row, col] = num next_boards.append(new_board) return next_boards def solve_backtracking(init_board): solution_stack = deque([init_board]) while len(solution_stack) > 0: board = solution_stack.pop() show_board(board) # if board is full, then it has met all the sudoku constraints if board_is_full(board): return board print('\r' + '\033[1A' * 14) # used to print over previous iteration # generate next possible boards, push them onto stack next_row, next_col = next_unassigned_cell(board) next_boards = gen_possible_boards(board, next_row, next_col) for b in next_boards: solution_stack.append(b) return None def parse_from_string(s): '''Returns a sudoku matrix from a 81-character string, with 0s as empty cells''' board = np.zeros(81, dtype=np.uint8) for i in range(len(board)): board[i] = int(s[i]) if s[i].isdigit() else 0 board = board.reshape(9, 9) return board def main(): with open('puzzles.sdm', 'r') as f: lines = f.readlines() print('Sudoku Solver') print('This script solves sudoku puzzles using a stack-based backtracking algorithm.') random_puzzle = parse_from_string(random.choice(lines)) print('Given puzzle:') show_board(random_puzzle) print() print('Solution:') solution = solve_backtracking(random_puzzle) if solution is None: print('No solution!') if __name__ == '__main__': main()
6873225a8843395a24a756922f81ac87b7fd5135
ejohnso9/programming
/kattis/python/other/anagramcounting.py
1,221
3.609375
4
#!/usr/bin/env python # Python 3 (dev under Python 3.6.1) """ 2019Apr24 https://open.kattis.com/problems/anagramcounting """ import sys, math import operator from functools import reduce import pdb def nAnagrams(s): n = len(s) d = {} for c in list(s): if not c in d.keys(): d[c] = 1 else: d[c] += 1 # build list of non-1 counts l = [] for c, count in d.items(): if count > 1: l.append(count) if len(l): # this branch only needed if 's' has repeated symbols l = map(math.factorial, l) denom = reduce(operator.mul, l, 1) rv = int(math.factorial(n) / denom) else: rv = math.factorial(n) return rv # # main # # TEST branch if False: los = [ "at", "ordeals", "abcdefghijklmnopqrstuvwxyz", "abcdefghijklmabcdefghijklm", "abcdABCDabcd", ] for s in los: print(nAnagrams(s)) # should output(cut from Kattis' web page) """ 2 5040 403291461126605635584000000 49229914688306352000000 29937600 """ # "production" branch else: s = sys.stdin.readline().rstrip() print(nAnagrams(s))
f1428c5651932ae9711a5304c14874616a57e72e
X-H-W/xhw
/所有.py/作业/定义二.py
641
3.984375
4
# 汽车类 class car: def __init__(self,newname): self.name = newname self.price = '50000000' def move(self): print(self.name,'移动') def toot(self): print('鸣叫') # 创建一个实例对象 red_car = car('宝马') red_car.move() red_car.color = 'red' print('内存地址1:',id(red_car),red_car.color) blue_car = car('悍马') blue_car.move() blue_car.toot() blue_car.color = 'bule' print('内存地址2:',id(blue_car),blue_car.color) yellow_car = car('法拉利') yellow_car.move() yellow_car.toot() yellow_car.color = 'yellow' print('内存地址3:',id(yellow_car),yellow_car.color)
d77a0d998f80e2f515a237c524b3a688bfb7def3
ranafge/all-documnent-projects
/scrapy_projt/regex_onely/regex_positive_lookahead.py
141
3.640625
4
import re text ="""SAMAndMAX SAMAndMax SamAndMax SamAndMAX""" res = re.split(r"(?=[A-Z][a-z])|(?=[a-z])(?=[A-Z])|[\n]", text) print(res)
55284b062bfce8486d3955d107f02cac93a0ddf8
Shirleybini/Python-Projects
/Ping-Pong/line.py
372
3.578125
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 28 19:55:26 2020 @author: Shirley Sinha """ from turtle import Turtle class Line(Turtle): def __init__(self,pos): super().__init__() self.shape("square") self.penup() self.shapesize(stretch_len=0.25,stretch_wid=1) self.color("white") self.goto(pos)
be21a8cf15b425fe600cfbe8f3c7439b94de62db
PyStudyGroup/clases
/Unidad 4/Ejercicios/Sem4Eje3_DiegoCaraballo.py
815
4.125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # @autor: Diego Caraballo # @date: 10/05/13 # @version: python 2.7.4 # Grupo Estudio Python """Escriba un programa que pida el año actual y un año cualquiera y que escriba cuántos años han pasado desde ese año o cuántos años faltan para llegar a ese año.""" def main(): print "Comparador de años" actual = input ("En que año estamos?: ") cualquiera = input ("Escriba un año cualquiera: ") x = diferencia (actual, cualquiera) if x == 0: print "Son el mismo año" elif x == 1: print "Para llegar al", (cualquiera + 1), "falta 1 año" elif x > 0: print "Para llegar al año", cualquiera, "faltan", x, "años" elif x < 0: print "Dese el año", cualquiera, "han pasado", (-x), "años" def diferencia (a1, a2): dif = a2 - a1 return dif main()
242312df5d9a1400d3c949e30faf934df4ad64f2
devashish9599/PythonPractice
/searchmatt.py
191
3.53125
4
a=[[2,43,5], [2,5,8]] count=0 for i in range(len(a)): for j in range(len(a)): if(a[i][j]==a[i]): count=count+1 print count
79ff4446a276fcb2261e5cfe6d1c046c0d593fc5
lizkarimi/day-2
/data type latest.py
392
3.796875
4
def data_type(n): if type(n)==int: if n>100: return n,"more than 100" elif n<100: return n,"less than 100" else: return n,"equal to 100" elif type(n) == str: return len(n) elif n==None: return "no value" elif type(n)==bool: return n elif type(n)==list: try: return n[2] except Exception as e: return None if __name__ == '__main__': print(data_type(None))
363e4e5c2f5707f8dac721ae83163e9b29b22428
KanagasabapathiE2/PythonLearn
/Assignment2/PrintPattern__8.py
478
4.1875
4
""" Write a program which accept one number and display below pattern. Input : 5 Output : 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 """ def printMatrics(no, char="*"): for row in range(no): for col in range(no): if col > row: break print(col+1, end=" ") print() def main(): inputno=int(input("Enter Number :")) printMatrics(inputno) #Entry Function if __name__ == "__main__": main()
e830dbc35ba94b5ebc298bf0503b952c763d9bed
chenfangstudy/data_analysis
/chapter_8/01-任务程序/code/任务8.2 分析财政收入数据特征的相关性.py
535
3.59375
4
# -*- coding: utf-8 -*- ############################################################################### ####################### 任务实现 ####################### ############################################################################### # 代码 8-1 import numpy as np import pandas as pd inputfile = '../data/data.csv' ## 输入的数据文件 data = pd.read_csv(inputfile) ## 读取数据 ## 保留两位小数 print('相关系数矩阵为:',np.round(data.corr(method = 'pearson'), 2))
692ce9734c25b5ef9c7a669648983ecfeb7cbfc4
Jan-zou/LeetCode
/python/String/28_implement_strstr.py
2,576
4
4
# !/usr/bin/env python # -*- coding: utf-8 -*- ''' Description: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Tags: Two Pointers, String 返回needle在haystack中第一次出现的位置,如果needle不在haystack中,则返回-1。(子串长度为m) + 暴力匹配 Time: O(n*m) Space: O(1) + KMP Time: O(n+m) Space: O(m) + Boyer-Mooer + Rabin-Karp ''' class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ n = len(haystack) - len(needle) + 1 i = 0 while i < n: j, k = i, 0 # index: 字符串j ; 子串k while j < len(haystack) and k < len(needle) and haystack[j] == needle[k]: j += 1 k += 1 if k == len(needle): return i i += 1 return -1 # KMP class Solution2(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if not needle: return 0 if len(haystack) < len(needle): return -1 i = self.KMP(haystack, needle) if i > -1: return i else: return -1 # 不回溯,haystach中的i不动,移动needle中的j跳到k, k=next(j)表示子串中每个j不匹配时可能跳转的位置 def KMP(self, text, pattern): next = self.getNext(pattern) j = -1 for i in xrange(len(text)): while j > -1 and pattern[j + 1] != text[i]: j = next[j] if pattern[j + 1] == text[i]: j += 1 if j == len(pattern) - 1: return i - j return -1 def getNext(self, pattern): next = [-1] * len(pattern) # 当前不匹配为首位时,next(j)=-1 j = -1 for i in xrange(1, len(pattern)): while j > -1 and pattern[j + 1] != pattern[i]: j = next[j] if pattern[j + 1] == pattern[i]: j += 1 next[i] = j return next if __name__ == '__main__': print Solution().strStr('a', '') print Solution().strStr('mississippi', 'a') print Solution().strStr('abababcdab', 'bcd') print Solution2().strStr('a', '') print Solution2().strStr('mississippi', 'a') import pdb pdb.set_trace() print Solution2().strStr('abababcdab', 'bcd')
322a8d6a705e1061dca4444921ac45c86e540876
MattheusOliveiraBatista/Python3_Mundo03_CursoEmVideo
/Aulas Python/Aula018_02_Lista.py
705
4.1875
4
"""Nessa aula, vamos aprender o que são LISTAS e como utilizar listas em Python. As listas são variáveis compostas que permitem armazenar vários valores em uma mesma estrutura, acessíveis por chaves individuais. """ galera = list() dado = [] maior = menor = 0 for c in range(0, 3): dado.append(str(input('Digite seu nome: '))) dado.append(int(input('Digite sua idade: '))) galera.append(dado[:]) dado.clear() print(galera) for p in galera: if p[1] >= 21: print(f'{p[0]} é maior de idade!') maior += 1 else: print(f'{p[0]} é menor de idade!') menor += 1 print(f'Temos {maior} maiores e {menor} menores de idade.')
287309bd5babdfff01a715865afe8da83dbc9314
lnsz/Pathfinder
/grid.py
1,794
3.578125
4
import tile as t class Grid: def __init__(self, window, length, height, start, end): self.length = length self.height = height self.start = (start[0], start[1]) self.end = (end[0], end[1]) self.tiles = [] for y in range(height): self.tiles.append([]) for x in range(length): self.tiles[y].append(t.Tile(x, y, window.getWidth() // self.length, window.getHeight() // height)) self.tiles[start[1]][start[0]].set_value("S") self.tiles[end[1]][end[0]].set_value("E") print("Initialized {0} x {1} grid. Start: {2}. End: {3}.". format(length, height, start, end), end="") def __str__(self): s = "" for x in self.tiles: for y in x: if type(y.get_value()) == float: s += str(round(y.get_value(), 2)) else: s += str(y) + " " s += "\t" s += "\n" return s def get_length(self): return self.length def get_height(self): return self.height def get_start(self): return self.start def get_end(self): return self.start def value_at(self, x, y): return self.tiles[y][x].get_value() def tile_at(self, x, y): return self.tiles[y][x] def modify_tile(self, x, y, value): self.tiles[y][x].set_value(value) def get_tiles(self): return self.tiles def clean_grid(self, empty): for x in self.tiles: for y in x: if type(y.get_value()) == int or type(y.get_value()) == float: y.set_value(empty)
c4cc2dc0c763beca4e008daa4ca7be406232bddb
hyh1750522171/ML
/二叉树/广度优先-层次遍历/广度优先.py
1,424
3.78125
4
class Node: def __init__(self, number): self.number = number self.lchild = None self.rchild = None class Tree: lis = [] def __init__(self): self.root = None def add(self, number): node = Node(number) if self.root == None: self.root = node Tree.lis.append(self.root) else: while True: point = Tree.lis[0] if point.lchild == None: point.lchild = node Tree.lis.append(point.lchild) return elif point.rchild == None: point.rchild = node Tree.lis.append(point.rchild) Tree.lis.pop(0) return #层次遍历-广度优先 def bfs(root): stack = [root] while stack: p = stack.pop() print(p.number) if p.lchild: stack.insert(0,p.lchild) if p.rchild: stack.insert(0,p.rchild) def find_deep(root): if root.rchild == None and root.lchild == None: return 1 if root.lchild: llength = find_deep(root.lchild) else: llength = 0 if root.rchild: rlength = find_deep(root.rchild) else: rlength = 0 return 1+max(llength,rlength) nums = [1,2,3,4,5,6,7] a = Tree() for i in nums: a.add(i) print(find_deep(a.root))
bf0b9943c5622d0b0a283758ffbba6a669a008fc
maciejmoskala/python
/algorithms/elevator_stops_counting.py
953
3.859375
4
def count_elevator_stops(people_weights, people_floores, M, max_people, max_weight): people_count = 0 weight_count = 0 floores = [] solution = 0 for person_weight, person_floor in zip(people_weights, people_floores): if weight_count+person_weight<=max_weight and people_count<max_people: if person_floor not in floores: floores.append(person_floor) weight_count += person_weight people_count += 1 else: solution += len(floores)+1 floores = [person_floor] weight_count = person_weight people_count = 1 return solution + len(floores)+1 people_weights = [40, 40, 100, 80, 20] people_floores = [3, 3, 2, 2, 3] M = 3 max_people = 5 max_weight = 200 count = count_elevator_stops(people_weights, people_floores, M, max_people, max_weight) print("Elevator stopped {0} times.".format(count))
eadd1789cd883dbebb91a03c50907090ba7e5f89
Kevin-De/cardgame
/Card_Game.py
7,198
3.84375
4
__author__ = 'Kevin' # save testing 2 import random import time def get_players(): number_of_players = int(input("how many people are playing?")) players = [] # list of players while len(players) < number_of_players: players.append([]) # adds empty sets for each player in the game return players def deal_cards(players, deck): count_cards = 0 cards_per_person = int(input("how many starting cards per player")) while count_cards < cards_per_person: # while loop gives cards from deck to players current_player = 0 while current_player < len(players): temp_card = random.randint(0, len(deck) - 1) players[current_player].append(deck[temp_card]) deck.remove(deck[temp_card]) current_player += 1 count_cards += 1 return players def give_cards(deck, players, player_turn, cardeffect): temp_card = random.randint(0, len(deck) - 1) players[player_turn].append(deck[temp_card]) deck.remove(deck[temp_card]) return players, deck def place_cards(players, playerturn, deck, pile, first_go, cardeffect): card_choice = int(input("pick a card (the leftmost card being 1): ")) - 1 valid, first_go = checkcard(pile, players, playerturn, card_choice, first_go, deck, cardeffect) if valid: print("this is a valid card") pile.append(players[playerturn][card_choice]) players[playerturn].remove(players[playerturn][card_choice]) players, pile, deck = turn(playerturn, players, deck, pile, cardeffect, first_go) return pile, players def checkcard(pile, players, playerturn, cardchoice, firstgo, deck, cardeffect): print("checking if choice is valid...") time.sleep(2) valid = False if firstgo: if players[playerturn][cardchoice][0] == pile[len(pile) - 1][0]: valid = True firstgo = False elif players[playerturn][cardchoice][1] == pile[len(pile) - 1][1]: valid = True firstgo = False else: valid = False if valid == False: print("this is not a valid choice, please try again") players, pile, deck = turn(playerturn, players, deck, pile, cardeffect, firstgo) else: if players[playerturn][cardchoice][0] == "jack": if (pile[len(pile) - 1][0] == 10 or "queen" or "jack") and players[playerturn][cardchoice][1] == \ pile[len(pile) - 1][1]: valid = True else: valid = False elif players[playerturn][cardchoice][0] == "queen": if (pile[len(pile) - 1][0] == "jack" or "king" or "queen") and players[playerturn][cardchoice][1] == \ pile[len(pile) - 1][1]: valid = True else: valid = False elif players[playerturn][cardchoice][0] == "king": if (pile[len(pile) - 1][0] == 1 or "queen" or "king") and players[playerturn][cardchoice][1] == \ pile[len(pile) - 1][1]: valid = True else: valid = False elif players[playerturn][cardchoice][0] == 10: if (pile[len(pile) - 1][0] == 9 or "jack" or 10) and players[playerturn][cardchoice][1] == \ pile[len(pile) - 1][1]: valid = True else: valid = False elif players[playerturn][cardchoice][0] == 1: if (pile[len(pile) - 1][0] == 2 or "king" or 1) and players[playerturn][cardchoice][1] == \ pile[len(pile) - 1][1]: valid = True else: valid = False elif players[playerturn][cardchoice][0] == pile[len(pile) - 1][0]: valid = True elif players[playerturn][cardchoice][0] == pile[len(pile) - 1][0] + 1 and players[playerturn][cardchoice][1] == \ pile[len(pile) - 1][1]: valid = True elif players[playerturn][cardchoice][0] == pile[len(pile) - 1][0] - 1 and players[playerturn][cardchoice][1] == \ pile[len(pile) - 1][1]: valid = True else: valid = False if valid == False and firstgo == False: print("this is not a valid choice") choice = int(input("press 1 to try again or 2 to end go")) if choice == 1: pile, players = place_cards(players, playerturn, deck, pile, firstgo, cardeffect) else: pass return valid, firstgo def turn(playerturn, players, deck, pile, cardeffect, firstgo): print("The current card ontop of the pile is:", pile[len(pile) - 1]) print("player", playerturn + 1, "has these cards:", players[playerturn]) if firstgo: print("what would you like to do?: ") print("1. place a card") print("2. pickup a card") choice = int(input("choice : ")) if choice == 1: pile, players = place_cards(players, playerturn, deck, pile, firstgo, cardeffect) else: players, deck = give_cards(deck, players, playerturn, cardeffect) else: print("what would you like to do?: ") print("1. place a card") print("2. end turn") choice = int(input("choice : ")) if choice == 1: # noinspection PyTypeChecker pile, players = place_cards(players, playerturn, deck, pile, firstgo, cardeffect) else: pass return players, pile, deck def cardeffect(cardnumber, playerturn): print() def gameloop(start, end, step, playerturn, deck, players, pile): while start <= end - 1: playerturn = start firstgo = True players, pile, deck = turn(playerturn, players, deck, pile, cardeffect, firstgo) start += step if start == end: start = 0 if start < 0: start = len(players) - 1 if step >= 2: step = 1 if step <= -2: step = 1 deck = [[1, "hearts"], [1, "diamonds"], [1, "spades"], [1, "clubs"], [2, "hearts"], [2, "diamonds"], [2, "spades"], [2, "clubs"], [3, "hearts"], [3, "diamonds"], [3, "spades"], [3, "clubs"], [4, "hearts"], [4, "diamonds"], [4, "spades"], [4, "clubs"], [5, "hearts"], [5, "diamonds"], [5, "spades"], [5, "clubs"], [6, "hearts"], [6, "diamonds"], [6, "spades"], [6, "clubs"], [7, "hearts"], [7, "diamonds"], [7, "spades"], [7, "clubs"], [8, "hearts"], [8, "diamonds"], [8, "spades"], [8, "clubs"], [9, "hearts"], [9, "diamonds"], [9, "spades"], [9, "clubs"], [10, "hearts"], [10, "diamonds"], [10, "spades"], [10, "clubs"], ["jack", "hearts"], ["jack", "diamonds"], ["jack", "spades"], ["jack", "clubs"], ["queen", "hearts"], ["queen", "diamonds"], ["queen", "spades"], ["queen", "clubs"], ["king", "hearts"], ["king", "diamonds"], ["king", "spades"], ["king", "clubs"]] pile = [] players = get_players() players = deal_cards(players, deck) pile.append(deck[random.randint(0, len(deck) - 1)]) gameloop(0, len(players), 1, 0, deck, players, pile)
7ad057b8c76e9e140ef565887a35317cb0b40472
AlexGlau/pythonCourse
/functions/age.py
294
4.3125
4
age = input('Enter your age: ') def define_age(age): age = int(age) if 3 <= age < 7: return 'Kindergarten' elif 7 <= age <= 18: return 'School' elif 18 < age <= 23: return 'College' else: return 'Some job' res = define_age(age) print(res)
922360f81680bbac47bc20af00e96d8b7dae059e
tayloa/CSCI1100_Fall2015
/Homeworks/hw2/hw2_part1.py
877
4.15625
4
import math length = raw_input("Length of rectangular prism (m) ==> " ) print length width = raw_input("Width of rectangular prism (m) ==> ") print width height = raw_input("Height of rectangular prism (m) ==> ") print height def volume_prism(length, width, height): volume = length * width * height return volume v = volume_prism(float(length), float(width), float(height)) total_water = float(6300.0 * float(v)) print "Water needed for","("+str(float(length))+"m,"+str(float(width))+"m,"+str(float(height))+"m) locks is "+str(total_water)+"m^3." radius = int(raw_input("Radius of cylinder (m) ==> ")) print radius def find_length(radius, total_water): height_2 = total_water/(math.pi * radius**2) return height_2 h = find_length(float(radius), total_water) print "Lake with radius",str(float(radius))+"m will lose %.1f"%(h)+"m depth in three months."
1e645ba4477146155bd4620363e16ebf006c7bc9
Chrlol/Chrlol
/first2/src/var.py
154
3.84375
4
for i in range(1, 5): print(i) else: print('The for loop is over') def sayHi(): print('Hi, I am a module and my name is', __name__)
08a845047e76fc8d951b18c74642a0356e0a1a64
ai-rafique/MorseCode
/main.py
695
3.828125
4
from data import Morse from art import logo morse = Morse() print(logo) while input('Do you wanna do this ? (y or n) :') == 'y': morse.ops() option = input('Which operation do you wish to perform ? :') if option =='a': morse.print_key() elif option =='b': plaintext = input('Enter some text please : ').upper() answer = morse.encode_process(plaintext) print(answer) elif option == 'c': encoded = input('Enter some text please : ').upper().split(' ') answer = morse.decode_process(encoded) print(answer) else: print('Illegal Option') print('Thank you come again')
b9c00bae3a891ba8807e150baaa6534c3d35df48
rdbruyn/shell-eco-gps-tracker
/gps_system.py
5,752
3.609375
4
import RPi.GPIO as gpio import time import serial import adafruit_gps import math from pathlib import Path def getDistance(coord1, coord2): """ Uses the Haversine formula to calculate the distance between two coordinates given in the (latitude, longitude) in decimal format """ lat1 = math.radians(coord1[0]) lat2 = math.radians(coord2[0]) lon1 = math.radians(coord1[1]) lon2 = math.radians(coord2[1]) delta_lat = lat2 - lat1 delta_lon = lon2 - lon1 a = (math.pow(math.sin(delta_lat / 2), 2) + math.cos(lat1) * math.cos(lat2) * math.pow(math.sin(delta_lon / 2), 2)) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) R = 6371 * (10 ** 3) return R * c def getVelocity(coord1, coord2): """ Returns the velocity travelled between two coordinates. Format should resemble (latitude, longitude, time) """ distance = getDistance(coord1, coord2) delta_t = abs(coord1[2] - coord2[2]) return distance / delta_t def checkValidity(coord1, coord2): """ If the adafruit gps is not working properly, None coordinate values may be returned through the serial port. This function returns True if coordinates are valid, and False if coordinates aren't. """ for i in coord1: if i is None: return False for i in coord2: if i is None: return False return True def main(): # Set up file logging based on timestamp base_path = Path() / 'log' if not base_path.is_dir(): base_path.mkdir() log_path = base_path / '{}.log'.format(time.strftime('%m-%d_%H:%M')) if not log_path.is_file(): log_path.touch() log = log_path.open('a') # Set up RPi board for signaling bottom_pin = 22 middle_pin = 18 top_pin = 16 gpio.setmode(gpio.BOARD) gpio.setup(bottom_pin, gpio.OUT) gpio.setup(middle_pin, gpio.OUT) gpio.setup(top_pin, gpio.OUT) # PWM stuff bottom = gpio.PWM(bottom_pin, 1) middle = gpio.PWM(middle_pin, 1) top = gpio.PWM(top_pin, 1) # Establish GPS connection uart = serial.Serial('/dev/ttyS0', timeout=3000) gps = adafruit_gps.GPS(uart) # Turn on GPS functionality gps.send_command(b'PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0') gps.send_command(b'PMTK220,1000') prev_t = time.time() prev_coords = None total_distance = 0 start_time = time.time() track_distance = 9600 max_time = 24 * 60 v_margin = 0.5 while True: gps.update() try: current_t = time.time() # If 1 second has passed, read data from gps if current_t - prev_t >= 1: prev_t = current_t # Make sure we have a fix if not gps.has_fix: print('Waiting for fix...') continue # Print data print('=' * 20) print('Latitude: {}'.format(gps.latitude)) print('Longitude: {}'.format(gps.longitude)) print('Fix quality: {}'.format(gps.fix_quality)) if gps.satellites is not None: print('# of satellites: {}\n'.format(gps.satellites)) # Calculate distance and speed if prev_coords is not None: # We have previous coordinates. Calculate current_coords = (gps.latitude, gps.longitude, current_t) if not checkValidity(current_coords, prev_coords): continue distance = getDistance(current_coords, prev_coords) total_distance += distance velocity = getVelocity(current_coords, prev_coords) # Get ideal speed ideal_velocity = ( (track_distance - total_distance) / (max_time - (current_t - start_time)) ) # Output GPIO if velocity < ideal_velocity - v_margin: # Go faster top.start(20) top.ChangeFrequency(1) middle.stop() bottom.stop() if velocity > ideal_velocity + v_margin: # Go slower top.stop() middle.stop() bottom.start(20) bottom.ChangeFrequency(1) if ( velocity > ideal_velocity - v_margin and velocity < ideal_velocity + v_margin ): # Keep steady top.stop() middle.start(20) middle.ChangeFrequency(1) bottom.stop() print('Distance: {:.3f}m'.format(distance)) print('Velocity: {:.3f} m/s'.format(velocity)) print('Ideal Velocity: {:.3f} m/s'.format(ideal_velocity)) else: # We're just starting up. Assign initial coordinates current_coords = (gps.latitude, gps.longitude, current_t) log.write( '{},{},{}\n'.format( current_coords[0], current_coords[1], current_coords[2] ) ) prev_coords = current_coords except Exception as e: raise e continue if __name__ == '__main__': try: main() finally: gpio.cleanup()
66601718aae2cade2ce9e2b9c376a50e60775e71
David92p/Python-workbook
/repetition/Exercise68.py
1,656
4.15625
4
#Compute a Grade Point Average of A, A+, A-, B, B+, B-, C, C+, C-, D, D+, F media = 0 total = 0 while True: letter = input('Enter the grade letter to calculate your average (press esc to exit) ') letter = letter.lower() if letter != 'esc': if letter == 'a' or letter == 'a+' or letter == 'a-': if letter == 'a' or letter == 'a+': media += 4.0 total += 1 elif letter == 'a-': media += 3.7 total += 1 continue if letter == 'b' or letter == 'b+' or letter == 'b-': if letter == 'b': media += 3.0 total += 1 elif letter == 'b+': media += 3.3 total += 1 elif letter == 'b-': media += 2.7 total += 1 continue if letter == 'c' or letter == 'c+' or letter == 'c-': if letter == 'c': media += 2.0 total += 1 elif letter == 'c+': media += 2.3 total += 1 elif letter == 'c-': media += 1.7 total += 1 continue if letter == 'd' or letter == 'd+': if letter == 'd': media += 1.0 total += 1 elif letter == 'd+': media+= 1.3 total += 1 continue if letter =='f': media += 0 total += 1 continue else: break print('The total average of your grades is equal to', round(media/total,2))
405f97a440e95014ab53388629b8837fa2d028ea
Ch4uwa/PythonPracEx
/product_sum.py
334
3.953125
4
array = [5, 2, [7, -1], 3, [6, [-13, 8], 4]] def productSum(array, multiplier=1): # Write your code here. total = 0 for ele in array: if type(ele) is list: total += productSum(ele, multiplier + 1) else: total += ele return total * multiplier print(productSum(array=array))
63395c443634c131018b1e0561783ab62b3df042
raghumina/Python_basics
/ElifProblem1.py
351
4.25
4
# Python problem using if else # finding the largest number in three numbers print("Please give three numbers") a = 1 b = 5 c = 3 if a>b: print("a is greater than b") if a>c: print("a is greate than c ") print("a is the largest number ") elif b>c: print(" b is the largest number ") else: print("c largest number ")
bb1765519d32289d79a8750b80d0ec822cbe2130
Adasumizox/ProgrammingChallenges
/codewars/Python/8 kyu/TipCalculator/calculate_tip_test.py
1,333
3.625
4
from calculate_tip import calculate_tip import unittest class TestTipCalculator(unittest.TestCase): def test(self): self.assertEqual(calculate_tip(30, "poor"), 2) self.assertEqual(calculate_tip(20, "Excellent"), 4) self.assertEqual(calculate_tip(20, "hi"), 'Rating not recognised') self.assertEqual(calculate_tip(107.65, "GReat"), 17) self.assertEqual(calculate_tip(20, "great!"), 'Rating not recognised') def test_rand(self): from random import randint from math import ceil calculate_sol = lambda amount, rating: ceil(amount*["terrible", "poor", "good", "great", "excellent"].index(rating.lower())*0.05) if rating.lower() in ["terrible", "poor", "good", "great", "excellent"] else "Rating not recognised" base = ["terrible", "poor", "good", "great", "excellent"] for _ in range(40): amount = randint(1,10**randint(1,10)) rating = [w if randint(0,1) else w.upper() for w in base[randint(0,4)]] if randint(0,1)==0: rating[randint(0,len(rating)-1)] = "!?.,"[randint(0,3)] rating = "".join(rating) self.assertEqual(calculate_tip(amount, rating),calculate_sol(amount, rating),"It should work for random inputs too") if __name__ == '__main__': unittest.main()
53a42169b80a6f53b32d9d1c04fbe3ebce9bd6f5
Vineet2000-dotcom/Competitive-Programming
/CODEFORCES/Young Physicist.py
226
3.65625
4
x1 = y1 = z1 = 0 for _ in range(int(input())): x, y, z = map(int, input().split()) x1 += x y1 += y z1 += z if(x1 == 0 and y1 == 0 and z1 == 0): print("YES") else: print("NO")
aae2d77baf959d378b4ce895c770b8c1be0b174b
thelmuth/cs-101-spring-2021
/Class16/functions.py
663
4.25
4
import matplotlib.pyplot as plt import math ### Gets integers from the user until they enter a blank line ### Store these integers in a list, so we can graph them. # # integers = [] # x = input("Enter an integer: ") # # while x != "": # integers.append(int(x)) # x = input("Enter an integer: ") # # print(integers) # # plt.plot(integers) # plt.show() def area_of_circle(radius): """Calculates the area of a circle based on the radius.""" return math.pi * (radius ** 2) r = 5 answer = area_of_circle(r) print(answer) def say_hello(name): """Prints hello to name""" print("Hello", name) say_hello("Bill") say_hello("Nancy")
9fb31245fd7be7ff5f848361ecb9c457f51545e4
pshoxxx/2002capstone
/menu.py
2,763
3.71875
4
#!/usr/bin/env python3 import webbrowser # Function for port scanner menu def scanner_menu(): # Print out options for client to choose (How many hosts they want to scan? One or multiple) print("How many hosts will you be scanning?") print("1. Single") print("2. Custom") print("3. Return to previous menu.") # Ask for selection input how_many = input("Please enter a selection. ") # Redirect to appropriate functions (Common Scan/Custom scan) if how_many == "1": # Ask how many ports will they be scanning print("Which ports will you be scanning?") print("1. Common ports (1-1024)") print("2. Custom range") how_many2 = input("Please enter a selection. ") # Redirect to appropriate functions if how_many2 == "1": common_port_scanner() elif how_many2 == "2": custom_port_scanner() elif how_many == "2": # Redirect to appropriate function (custom ip function) custom_ip_scan() # Return to main menu elif how_many == "3": main_menu() # Error handling of invalid selections else: print("Invalid selection.") exit() # Google Dorking Redirect Function def tool_google(): webbrowser.open("http://www.google.com") webbrowser.open_new_tab("https://cdn-cybersecurity.att.com/blog-content/GoogleHackingCheatSheet.pdf") exit() # Netcraft redirect function def tool_netcraft(): webbrowser.open("https://www.netcraft.com") exit() # Shodan redirect function def tool_shodan(): webbrowser.open("https://www.shodan.io") exit() # Web tools Menu def web_tools_menu(): # Print out menu layout and options print("-" * 60) print("{:^60}".format("Web tools")) print("-" * 60) print("1. Google Dorking") print("2. Netcraft") print("3. Shodan") # Ask for selection input web_selection = input("Please select an option. ") # Redirect to appropriate option if web_selection == "1": tool_google() elif web_selection == "2": tool_netcraft() elif web_selection == "3": tool_shodan() # Error handling else: print("Invalid option.") exit() # Function for main menu def main_menu(): # Print out layout for menu print("-" * 60) print("{:^60}".format("Welcome to Fancy Advanced Recon Tool")) print("-" * 60) print("1. Port Scan") print("2. Web Tools") # Ask for selection input selection = input("Please select an option. ") # Redirect to appropriate path if selection == "1": scanner_menu() elif selection == "2": web_tools_menu() else: print("Invalid selection.") exit() main_menu()
b22e6d7c1c1ac1bce59594731d0d1cc3598b6a18
Prad06/Python-DSA
/Arrays and Strings/Arr05.py
452
3.921875
4
# Pradnyesh Choudhari # Sat May 29 19:16:07 2021 # Distribute Candies # Time Complexity O(n) Space Complexity O(n). from itertools import combinations candyType = list(map(int, input().split())) n = len(candyType) possibleTypes = set(candyType) print(min(n//2, len(possibleTypes))) ## Additional question. Print all the possible types of candies. if n//2 >= len(possibleTypes): print(*possibleTypes) else: print(*list(combinations(possibleTypes, n//2)))
5227b7cc6cc853529d6bf5899c4ee51197bbcb3a
prkapadnis/Python
/Tuple.py
287
4.25
4
mytuple = tuple() mytuple = (5,4,3,2,1) print(mytuple.__sizeof__()) print(mytuple) print(type(mytuple)) print("The length of Tuple: ", mytuple.__len__()) print(mytuple.__sizeof__()) print(tuple(sorted(mytuple))) # It returns a list after sorting and it creates a new tuple print(mytuple)
a068dbeecbd5c8da0ab040c3455690d73dbf8426
dikyindrah/Python-Basic-02
/100-Latihan Membuat Program Permainan Batu Gunting Kertas Dengan Pemrograman Modular/Permainan.py
825
3.5625
4
import Komputer import Periksa import Status pilihan = ['batu', 'gunting', 'kertas',] print('====={}=====\n'.format('Permainan Batu Gunting Kertas')) user = str(input('Pilih salah satu (batu, gunting, kertas) : ')) pilihan_user = str.lower(user) pilihan_komputer = Komputer.komputer(pilihan) pilihan_user_ada = Periksa.periksa_pilihan_user(pilihan, pilihan_user) if pilihan_user_ada == True: status = Status.status_permainan(pilihan, pilihan_komputer, pilihan_user) print('\n==========================') print('Kamu memilih = {}'.format(pilihan_user)) print('Komputer memilih = {}'.format(pilihan_komputer)) print('====={}====='.format('Status Permainan')) print(status) print('==========================\n') else: print('Kamu tidak boleh memilih selain batu, guntung, dan kertas.')
4929f9eb2d244e334c5e2bd4952a1c26e9beba6c
ejimenezdelgado/ext_logico_algoritmo_1_2019
/Semana 9/ejercicio4.py
500
3.65625
4
#Creado por:Efrén Jiménez #Fecha:28/03/2019 #Objetivo: Ejercicio 3 def NumerCercano(): contador=1 menor=0 lista=[] for variable in range(0,5): lista.append(int(input("Digite un numero"))) diferencia=-1 while contador<4: resultado=lista[contador]-lista[0] if resultado<diferencia or diferencia ==-1: diferencia=resultado menor=lista[contador] contador=contador+1 print("El numero mas cercano es",menor) NumerCercano()
ae9507b3e8aa1739d25a286229508f7014137a45
Lance0404/my_leetcode_study_group
/python/easy/implement_strStr.py
706
3.515625
4
""" https://leetcode.com/problems/implement-strstr/ Runtime: 24 ms, faster than 95.46% of Python3 online submissions for Implement strStr(). Memory Usage: 14.1 MB, less than 8.00% of Python3 online submissions for Implement strStr(). """ class Solution: def strStr(self, haystack: str, needle: str) -> int: if not len(needle): return 0 if needle not in haystack: return -1 # edge cases handled above for i in range(len(haystack)): for j in range(i+len(needle), len(haystack)+1): if haystack[i:j] == needle: # return the first occurance return i s = Solution() ret = s.strStr('aaaaaaaaaaaaaaaabc', 'ab') print(ret)
918b9fce261694c3a5bb1c806aba3b434c17f38d
RoshaniPatel10994/ITCS1140---Python-
/Modular program/Practice/dog day afternoon 2.py
840
3.8125
4
DogDay class(): Class DogDay: #initialize DogDay object def __init__(self, quantity, size): self.quantity = quantity self.size = size #Determine price of each bone based on size def DeterminePrice(self): if (self.size == 'A'): self.price = 2.29 elif (self.size == 'B'): self.price = 3.50 elif (self.size == 'C'): self.price = 4.95 elif (self.size == 'D'): self.price = 7.00 else: self.price = 9.95 #determine the total cost def DetermineTotal(self): self.total = round(self.quantity*self.price, 2) #return the total cost def ReturnTotal(self): return self.total # Testing class myDog = DogDay(6, 'C') myDog.DeterminePrice() myDog.DetermineTotal() print(str(myDog.ReturnTotal()))
254ebe4e986396ae8a8cd79bc66d5f5f14d78017
axpak7/NumericalMerhods
/task1/mnps.py
2,046
4.25
4
""" Метод наискорейшего покоординатного спуска """ import numpy as np def polynomValue(X): """ Нахождение значения полинома :param X: задание неизвестных переменных x, y, z :return: значение полинома """ x = X[0] y = X[1] z = X[2] return 2 * x ** 2 + 3.1 * y ** 2 + 4.1 * z ** 2 + x * y - y * z + x * z + x - 2 * y + 3 * z + 1 def stepValue(A, x, b, e): """ Вычисление шага m :param A: матрица А :param x: вектор х :param b: вектор b :param e: вектор направления спуска :return: """ e_transpose = e.transpose() numerator = np.dot(e_transpose, (np.dot(A, x) + b)) denominator = np.dot(e_transpose, np.dot(A, e)) return -numerator / denominator print("Method of fastest coordinate descent") # constants A = np.array([[4, 1, 1], [1, 6.2, -1], [1, -1, 8.2]]) b = np.array([[1], [-2], [3]]) epsilon = 0.0000000001 # first member x = np.array([[0], [0], [0]]) new_f = polynomValue(x) f = 0 # Direction of descent e1 = np.array([[1], [0], [0]]) e2 = np.array([[0], [1], [0]]) e3 = np.array([[0], [0], [1]]) print("iteration: 1") print("vector x = \n", x) print("polynom value = ", new_f, "\n") i = 2 while abs(f - new_f) > epsilon: print("iteration: ", i) f = new_f m1 = stepValue(A, x, b, e1) m2 = stepValue(A, x, b, e2) m3 = stepValue(A, x, b, e3) x1 = x + m1 * e1 x2 = x + m2 * e2 x3 = x + m3 * e3 f1 = polynomValue(x1) f2 = polynomValue(x2) f3 = polynomValue(x3) new_f = min(f1, min(f2, f3)) if new_f == f1: x = x1 m = m1 e = e1 elif new_f == f2: x = x2 m = m2 e = e2 elif new_f == f3: x = x3 m = m3 e = e3 print("direction = \n", e) print("step = ", m) print("vector x = \n", x) print("polynom value = %.11f" % new_f, "\n") i = i + 1
0e21853bea08b986eb4033499712c9dea92efd8d
artthedeath/Estudo-em-Python
/Probability_Calculator.py
1,585
3.546875
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 11 16:15:56 2020 @author: Arthur DOnizeti Rodrigues Dias """ from copy import deepcopy import random class Hat: def __init__(self, **balls): self.balls = balls self.lista_cor =[] self.lista_remove=[] self.contents = self.contents() def contents(self): for k,v in self.balls.items(): n = v while n > 0: self.lista_cor.append(k) n -=1 return self.lista_cor def draw(self,num): if num >len(self.lista_cor): self.lista_remove = self.lista_cor.copy() else: while num > 0: x = random.choice(self.lista_cor) self.lista_remove.append(x) self.lista_cor.remove(x) num -= 1 return self.lista_remove def experiment(hat,expected_balls, num_balls_drawn, num_experiments): m = 0 n = num_experiments while n > 0: x = deepcopy(hat) x.contents y = {} for cor in x.draw(num_balls_drawn): y.setdefault(cor,0) y[cor] = y[cor]+1 aux = 0 for keys2 in y.keys(): for keys in expected_balls.keys(): if keys == keys2: if y[keys] >= expected_balls[keys]: aux += 1 if aux == len(expected_balls): m += 1 n -= 1 return float(m)/float(num_experiments)
ac74c05eee800987dcb3096e3a060d7389b3b986
jaredkhan/tighten-tricky-types
/2-overloading/before.py
1,201
4.34375
4
""" Goal: Define a Circle class which does nothing but storing a radius. It should be initialisable with either a radius or a circumference. """ import math from typing import Optional class Circle: radius: float # Note the use of 'keyword-only' arguments (arguments after *) # This means users must use the keyword radius= or circumference= when calling. # Otherwise there'd be no clear way to tell which they meant. def __init__( self, *, radius: Optional[float] = None, circumference: Optional[float] = None ): if radius is not None and circumference is not None: raise ValueError("Cannot use both radius and circumference") if radius is not None: self.radius = radius elif circumference is not None: self.radius = circumference / math.tau else: raise ValueError("Must give either a radius or circumference") # Valid things (are they all allowed by mypy?) Circle(radius=1.0) Circle(circumference=math.tau) # Invalid things (are they all caught by mypy?) Circle(radius=None) Circle(circumference=None) Circle(radius=1.0, circumference=None) Circle(radius=1.0, circumference=3.0)
5c1bb9572e468a56a46f11c61c54a651b39ffbda
bryand1/snippets
/python/algorithms/search/binarysearch.py
391
3.859375
4
def binary_search(A, x): # Initialize search region to the entire array # [lo, hi) lo, hi = 0, len(A) while hi - lo > 1: mid = (hi + lo) // 2 if x < A[mid]: hi = mid elif x == A[mid]: return True else: # x > A[mid] lo = mid + 1 if lo == hi: return False else: return x == A[lo]