blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
6c1f21f06a5ce2bbbe03ab9a7a468628673ee29b
senbagaraman04/pythonfordatascience
/listlab.py
698
3.703125
4
print ("\n\nAuthor: Senbagaraman") print ("Lines printed with # are actual coding line, which will provide the desired result beneath it") print ("*************************************") L=["Michael Jackson" , 10.1,1982] #print('the same element using negative and positive indexing:\n Postive:',L[0],'\n Negative:' , L[-3] ) #print('the same element using negative and positive indexing:\n Postive:',L[1],'\n Negative:' , L[-2] ) #print('the same element using negative and positive indexing:\n Postive:',L[2],'\n Negative:' , L[-1] ) j = 'hard rock'.split() print (j) #a_list = [1,"hello",[1,2,3],true] #print (a_list) B =L [:] print B L.append(["test"]) print L x = len(("disco",10)) print (x)
a66a874e71d7fcd94befa52b0f881864421b4419
Ayush181005/Intermediate-and-Advance-Python
/lambda function.py
285
3.625
4
# Syntax - lambda argument : manipulate the argument, it is a single line function # def add(a, b): # return a+b # print(add(4, 6)) add = lambda x,y : x+y print(add(4, 6)) add = lambda x,y:x>y print(add(4, 6)) a = [(1, 2), (4, 5), (555, 34)] a.sort(key=lambda x:x[1]) print(a)
05b95c929104fdecd3dc1ec64d062c42445cbc25
Huako7/ProgramacionEstructurada
/Unidad 2-Estructuras de Control/Ejercicio 41.py
1,649
4
4
<<<<<<< HEAD #Ejercicio 41 - #Autor: Jorge Limón #Entrada: Cantidad de números por evaluarse y los números en sí #Salida: El número mayor y el menor de los números dados n = int(input("¿Cuántos Números va a usar?")) #N números for x in range (0, n): numero = int(input("Ingrese un número:")) #Se verifica cuales son mayores y menores para reemplazarse entre sí conforme se superen if x == 0: mayor = numero menor = numero #Me basé para esto en el ejemplo encontrado en el repositorio para el primer número a comparar if numero > mayor: mayor = numero else: if numero < menor: menor = numero print("El número mayor es: ", mayor, " y el menor es: ", menor, ".") #Se imprimen el menor y el mayor ======= #Ejercicio 41 - #Autor: Jorge Limón #Entrada: Cantidad de números por evaluarse (n) y los números en sí (numero) #Salida: El número mayor y el menor de los números dados n = int(input()) #Se pide la cantidad de N números para generar la for loop for x in range (0, n): numero = int(input()) #Se pide que se ingrese un número para analizarse y comprararse en el trono #Se verifica cuales son mayores y menores para reemplazarse entre sí conforme se superen if x == 0: mayor = numero menor = numero #Me basé para esto en el ejemplo encontrado en el repositorio para el primer número a comparar if numero > mayor: mayor = numero else: if numero < menor: menor = numero print(mayor, menor) #Se imprimen el menor y el mayor >>>>>>> b59401ad4195ebbde55d550f0d4ba0b9ab9a1219
00103bb0d6182794e8b78ebfada6fe2884edfc7c
Huako7/ProgramacionEstructurada
/Unidad 2-Estructuras de Control/Ejercicio43.py
1,194
3.78125
4
#Ejercicio #43 # Programa que lea N valores y que cuente cuantos de ellos son positivos y cuantos # son negativos (0 es condici'on de fin de lectura) # Audny D. Correa Ceballos (Equipo 'about:blank') #ENTRADAS: #Cuantos valores va a ingresar lengLista = int(input()) listaNumeros = [] #Asignar los numeros que se van a comparar for i in range(1, lengLista + 1): numero = int(input()) listaNumeros.append(numero) #Lista de numeros valores = listaNumeros #PROCESO: evaluar si los numeros asignados son positivos (>0), negativos(<0) o 0 def main (valores): #Inicializar los contadores contadorPositivo = 0 contadorNegativo = 0 for i in valores: if (numero != 0): #Si es positivo if (numero > 0): contadorPositivo += 1 #Si es negativo else: contadorNegativo += 1 #Si el numero es 0 else: #Se detiene el for break return (contadorPositivo, contadorNegativo) #SALIDAS: los contadores de los numeros positivos y negativos positivo, negativo = main(valores) print ("Positivos: ", positivo) print ("Negativos: ", negativo)
8c32515f31e32f713ae7dfc09e0234d1b89485da
J4Jeffort/Jeffort
/coffee_machine_data.py
2,579
4.09375
4
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { "ingredients": { "water": 250, "milk": 100, "coffee": 24, }, "cost": 3.0, } } resources = { "water": 300, "milk": 200, "coffee": 100, } espresso = "espresso" latte = "latte" cappuccino = "cappuccino" money = 0 def sufficient_resources(order_ingredients): """Returns true if enough resources. false if short.""" for item in order_ingredients: if order_ingredients[item] >= resources[item]: print(f"Sorry, there is not enough {item}. ") return False return True def is_transaction_successful(money_received, drink_cost): """Return true if enough money. False if short""" if money_received >= drink_cost: change = round(money_received - drink_cost, 2) print(f"Here is ${change} in change. ") global money money = + drink_cost return True else: print("Sorry that's not enough money. Money refunded.") return False def process_change(): """Returns sum of coins""" print("Please insert change") total = int(input("how many quarters?: ")) * 0.25 total += int(input("how many dimes?: ")) * 0.10 total += int(input("how many nickles?: ")) * 0.05 total += int(input("how many pennies?: ")) * 0.01 return total def make_coffee(drink_name, order_ingredients): """deduct ingredients from resources""" for item in order_ingredients: resources[item] -= order_ingredients[item] print(f"Here is your {drink_name} ") is_on = True while is_on: order = input(f"What would you like? \n{espresso}, {latte}, or a {cappuccino} ").lower() if order == "off": is_on = False elif order == "report": print(f"Water:{resources['water']}ml") print(f"Milk:{resources['milk']}ml") print(f"Coffee:{resources['coffee']}g") print(f"Money: ${money}") else: drink = MENU[order] if sufficient_resources(drink["ingredients"]): payment = process_change() if is_transaction_successful(payment, drink["cost"]): make_coffee(order, drink["ingredients"])
d6e3afe057f97951d4f8499f2cc7d958e8861f2a
anobil/pytimecop
/timecop/__init__.py
2,731
3.953125
4
import time import datetime class fake_datetime(datetime.datetime): """Like datetime.datetime, but always defer to time.time() These implementations of now and utcnow are lifted straight from the standard library documentation, which states that they are "equivalent" to these expressions, but may provide higher resolution on systems which support it. """ @classmethod def now(cls, tz=None): if tz is None: return cls.fromtimestamp(time.time()) else: return tz.fromutc(cls.utcnow().replace(tzinfo=tz)) @classmethod def utcnow(cls): return cls.utcfromtimestamp(time.time()) class freeze(object): """ Context to freeze time at a given point in time """ def __init__(self, time_spec): """ Initialize ourselves to be a context for the given alternate time. """ if isinstance(time_spec, datetime.timedelta): self.secs_ = time.time() + time_spec.total_seconds() else: self.secs_ = float(time_spec) def time_(self): """ A version of time.time() that will return the value we want the system to think it is. """ return self.secs_ def __enter__(self): """ Alter time.time() to return the time we want it to be. Save current time function so can be replaced outside our context. """ if hasattr(self, 'old_time_func_'): # looks like someone is trying to use us again inside ourselves # for another nested context raise ValueError('cannot nest time travel with the same instance') # replace datetime.datetime self.old_datetime_ = datetime.datetime datetime.datetime = fake_datetime self.old_time_func_ = time.time # save old time.time = self.time_ # set new def __exit__(self, error_type, value, traceback): """ Reset time.time() to the value when we found it. """ time.time = self.old_time_func_ # reset old del(self.old_time_func_) # forget it # restore datetime.datetime datetime.datetime = self.old_datetime_ del(self.old_datetime_) def actual_time_(self): return self.old_time_func_() class travel(freeze): """ Context to travel to another time, letting time continue to pass """ def __init__(self, time_spec): freeze.__init__(self, time_spec) # at this point, time.time() *is* actual time self.time_travel_offset_ = self.secs_ - time.time() # amount of time (in seconds) we're travelling in future (positive values) or past (negative value) def time_(self): return self.actual_time_() + self.time_travel_offset_
cf21267f0f65593c910953cce92db9e08096d36b
jackandsnow/BasicProject
/data_struct/queue.py
3,026
4.40625
4
class Queue: """ Sequential Queue implement """ def __init__(self): """ initialize an empty Queue, __queue means it's a private member """ self.__queue = [] def first(self): """ get the first element of Queue :return: if Queue is empty return None, else return the first element """ return None if self.isEmpty() else self.__queue[0] def enqueue(self, obj): """ enqueue an element into Queue :param obj: object to be enqueued """ self.__queue.append(obj) def dequeue(self): """ dequeue the first element from Queue :return: if Queue is empty return None, else return the dequeued element """ return None if self.isEmpty() else self.__queue.pop(0) def clear(self): """ clear the whole Queue """ self.__queue.clear() def isEmpty(self): """ judge the Queue is empty or not :return: bool value """ return self.length() == 0 def length(self): """ get the length of Queue :return: """ return len(self.__queue) class PriorQueue: """ Priority Queue implement """ def __init__(self, objs=[]): """ initialize a Priority Queue, and the default queue is empty :param objs: object list for initializing """ self.__prior_queue = list(objs) # sort from maximum to minimum, and the minimum has the highest priority # so that the efficiency of "dequeue" will be O(1) self.__prior_queue.sort(reverse=True) def first(self): """ get the highest priority element of Priority Queue, O(1) :return: if Priority Queue is empty return None, else return the highest priority element """ return None if self.isEmpty() else self.__prior_queue[-1] def enqueue(self, obj): """ enqueue an element into Priority Queue, O(n) :param obj: object to be enqueued """ index = self.length() while index > 0: if self.__prior_queue[index - 1] < obj: index -= 1 else: break self.__prior_queue.insert(index, obj) def dequeue(self): """ dequeue the highest priority element from Priority Queue, O(1) :return: if Priority Queue is empty return None, else return the dequeued element """ return None if self.isEmpty() else self.__prior_queue.pop() def clear(self): """ clear the whole Priority Queue """ self.__prior_queue.clear() def isEmpty(self): """ judge the Priority Queue is empty or not :return: bool value """ return self.length() == 0 def length(self): """ get the length of Priority Queue :return: """ return len(self.__prior_queue)
3d9bc6f7ede7eda2420a82ce6019f690b8605347
clarasdfgh/Curso_python
/Condicionales/Evaluacion/pertenece.py
193
4.1875
4
#No modifiques esto para que podamos evaluarte numero = int(input("Numero: ")) if numero > -3 and numero < 0 : print("Pertenece") elif numero >= 3 and numero < 6 : print("Pertenece")
2f8a9df2c2a7df6b9b2e927750bad8d2a0fa9747
mscandizzo/CorpFinBook
/FinanceApp/finratiosFull.py
14,232
3.84375
4
import pandas as pd import numpy as np class FinRatios(object): """ This class contains all the financial ratios which contain 2 input variables. A dictionary (variables2V) has been created where each financial ratio (key) has a tuple value with the input variables name as well as the formula to calculate ratios can be used calculate time series in a pandas dataframe as well as cross sectional data by calling the function or assigning the desired values to each input attibute and later on run the formula. """ def __init__(self, long_term_debt = None, equity = None, current_assets = None, debt = None, current_liabilities = None, assets = None, depreciation = None, amortization = None, dividends_per_share = None, earnings_per_share = None, stock_price = None, market_cap = None, debt_issued = None, debt_repayments = None, sales = None, sales_deductions = None, retained_earnings = None, liabilities = None): self.long_term_debt = long_term_debt self.equity = equity self.current_assets = current_assets self.debt = debt self.current_liabilities = current_liabilities self.assets = assets self.depreciation = depreciation self.amortization = amortization self.dividends_per_share = dividends_per_share self.earnings_per_share = earnings_per_share self.stock_price = stock_price self.market_cap = market_cap self.debt_issued = debt_issued self.debt_repayments = debt_repayments self.sales = sales self.sales_deductions = sales_deductions self.retained_earnings = retained_earnings self.liabilities = liabilities self.variables2V = {'current_assets_to_debt':('current_assets','debt',self.current_assets_to_debt), 'current_ratio':('current_assets','current_liabilities',self.current_ratio), 'debt_ratio':('debt','assets',self.debt_ratio), 'debt_to_equity':('debt','equity',self.debt_to_equity), 'dividends_payout':('dividends_per_share','earnings_per_share',self.dividends_payout), 'dividends_yield':('dividends_per_share','stock_price',self.dividends_yield), 'earnings_yield':('earnings_per_share','stock_price',self.earnings_yield), 'equity_to_debt':('equity','debt',self.equity_to_debt), 'financial_leverage_index':('assets','equity',self.financial_leverage_index), 'long_term_debt_to_capitalization':('long_term_debt','equity',self.long_term_debt_to_capitalization), 'market_to_book_ratio':('market_cap','equity',self.market_to_book_ratio), 'net_borrowings':('debt_issued','debt_repayments',self.net_borrowings), 'net_sales':('sales','sales_deductions',self.net_sales), 'retained_earnings_to_equity':('retained_earnings','equity',self.retained_earnings_to_equity), 'retained_earnings_to_assets':('retained_earnings','assets',self.retained_earnings_to_assets), 'stockholders_equity':('equity','assets',self.stockholders_equity), 'debt_to_assets':('debt','assets',self.debt_to_assets), 'working_capital':('current_assets','current_liabilities',self.working_capital)} def formulas(self,dataframe): for k,v in self.variables2V.items(): try: dataframe[k]= dataframe.apply(lambda row: self.variables2V[k][2]\ (row[self.variables2V[k][0]], row[self.variables2V[k][1]]),axis =1) except: print("Fields don't exist") pass def current_assets_to_debt(self,current_assets = None, debt = None): """ Current assets over Total Debt Current assets = Debt = """ try: if current_assets != None and debt != None: self.current_assets = current_assets self.debt = debt if self.current_assets == None or self.debt == None: ratioval = np.nan else: ratioval = self.current_assets / self.debt return ratioval except: pass def current_ratio(self,current_assets = None, current_liabilities = None): """ Current assets over current liabilities """ try: if current_assets != None and current_liabilities != None: self.current_assets = current_assets self.current_liabilities = current_liabilities if self.current_assets == None or self.current_liabilities == None: ratioval = np.nan else: ratioval = self.current_assets / self.current_liabilities return ratioval except: pass def debt_ratio(self,debt = None, assets = None): """ Debt over assets """ try: if debt != None and assets != None: self.debt = debt self.assets = assets if self.debt == None or self.assets == None: ratioval = np.nan else: ratioval = self.debt / self.assets return ratioval except: pass def dividends_payout(self,dividends_per_share = None, earnings_per_share = None): """ Dividends per share over earnings per share """ try: if dividends_per_share != None and earnings_per_share != None: self.dividends_per_share = dividends_per_share self.earnings_per_share = earnings_per_share if self.dividends_per_share == None or self.earnings_per_share == None: ratioval = np.nan else: ratioval = self.dividends_per_share / self.earnings_per_share return ratioval except: pass def dividends_yield(self,dividends_per_share = None, stock_price = None): """ Dividends per share over current stock price """ try: if dividends_per_share != None and stock_price != None: self.dividends_per_share = dividends_per_share self.stock_price = stock_price if self.dividends_per_share == None or self.stock_price == None: ratioval = np.nan else: ratioval = self.dividends_per_share / self.stock_price return ratioval except: pass def earnings_yield(self,earnings_per_share = None, stock_price = None): """ earnings per share over stock price """ try: if earnings_per_share != None and stock_price != None: self.earnings_per_share = earnings_per_share self.stock_price = stock_price if self.earnings_per_share == None or self.stock_price == None: ratioval = np.nan else: ratioval = self.earnings_per_share / self.stock_price return ratioval except: pass def equity_to_debt(self,equity = None, debt = None): """ Current assets over current liabilities """ try: if equity != None and debt != None: self.equity = equity self.debt = debt if self.equity == None or self.debt == None: ratioval = np.nan else: ratioval = self.equity / self.debt return ratioval except: pass def financial_leverage_index(self,assets = None, equity = None): """ assets over equity """ try: if assets != None and equity != None: self.assets = assets self.equity = equity if self.assets == None or self.equity == None: ratioval = np.nan else: ratioval = self.assets / self.equity return ratioval except: pass def long_term_debt_to_capitalization(self,long_term_debt = None, equity = None): """ long term debt over long term debt plus equity """ try: if long_term_debt != None and equity != None: self.long_term_debt = long_term_debt self.equity = equity if self.long_term_debt == None or self.equity == None: ratioval = np.nan else: ratioval = self.long_term_debt / (self.long_term_debt + self.equity) return ratioval except: pass def market_to_book_ratio(self,market_cap = None, equity = None): """ Market capitalization over book value of equity """ try: if market_cap != None and equity != None: self.market_cap = market_cap self.equity = equity if self.market_cap == None or self.equity == None: ratioval = np.nan else: ratioval = self.market_cap / self.equity return ratioval except: pass def net_borrowings(self,debt_issued = None, debt_repayment = None): """ Debt issued during fiscal year less debt repayments """ try: if debt_issued != None and debt_repayment != None: self.debt_issued = debt_issued self.debt_repayments = debt_repayment if self.debt_issued == None or self.debt_repayments == None: ratioval = np.nan else: ratioval = self.debt_issued - self.debt_repayments return ratioval except: pass def net_sales(self,sales = None, sales_deductions = None): """ Current assets over current liabilities """ try: if sales != None and sales_deductions != None: self.sales = sales self.sales_deductions = sales_deductions if self.sales == None or self.sales_deductions == None: ratioval = np.nan else: ratioval = self.sales - self.sales_deductions return ratioval except: pass def retained_earnings_to_equity(self,retained_earnings = None, equity = None): """ Current assets over current liabilities """ try: if retained_earnings != None and equity != None: self.retained_earnings = retained_earnings self.equity = equity if self.retained_earnings == None or self.equity == None: ratioval = np.nan else: ratioval = self.retained_earnings / self.equity return ratioval except: pass def retained_earnings_to_assets(self,retained_earnings = None, assets = None): """ Current assets over current liabilities """ try: if retained_earnings != None and assets != None: self.retained_earnings = retained_earnings self.assets = assets if self.retained_earnings == None or self.assets == None: ratioval = np.nan else: ratioval = self.retained_earnings / self.assets return ratioval except: pass def stockholders_equity(self,equity = None, assets = None): """ Current assets over current liabilities """ try: if equity != None and assets != None: self.equity = equity self.assets = assets if self.equity == None or self.assets == None: ratioval = np.nan else: ratioval = self.equity / self.assets return ratioval except: pass def debt_to_assets(self,debt = None, assets = None): """ Current assets over current liabilities """ try: if debt != None and assets != None: self.debt = debt self.assets = assets if self.debt == None or self.assets == None: ratioval = np.nan else: ratioval = self.debt / self.assets return ratioval except: pass def working_capital(self,current_assets = None, current_liabilities = None): """ Current assets over current liabilities """ try: if current_assets != None and current_liabilities != None: self.current_assets = current_assets self.current_liabilities = current_liabilities if self.current_assets == None or self.current_liabilities == None: ratioval = np.nan else: ratioval = self.current_assets - self.current_liabilities return ratioval except: pass
a865462f32bdc2ee0b4a3efe27c458cc1e308a93
The-One-And-Only-H/TREP
/Alphabetgenerator.py
905
3.71875
4
#!/usr/bin/env python # For every letter: write the body into body then for every letter: save the body alphabet = list(map(chr, range(ord('a'), ord('z')+1))) # Not using import string string.ascii_lowercase as I want to be able to include/exclude letters manually def main(): for c in alphabet: # Read the template of the page template = "Template/alphabettemplate.html" with open(template) as f: alphabettemplate = f.read() # Read the body of the page body = "Bodies/{}-body.html".format(c) with open(body) as f: body = f.read() # Write the complete page filename = "docs/{}.html".format(c) page = alphabettemplate.format(filename=filename, body=body) with open(filename, "w") as f: f.write(page) if __name__ == '__main__': main()
f3adfc660b4c7c83e8d45f08773195514518d413
luxiya01/CodeU_Assignments
/assignment1/string_permutation.py
608
4.03125
4
import string import collections def string_permutation(str1, str2): """Checks whether str1 and str2 are permutations of each other. Note that the function is case insensitive. """ if not ((str.isalpha(str1) or str1 == "") and (str.isalpha(str2) or str2 == "")): raise ValueError("The inputs strings shall only consist of English alphabets") str1 = str1.lower() str2 = str2.lower() inputs = collections.defaultdict(lambda: 0) for c in str1: inputs[c] += 1 for c in str2: inputs[c] -= 1 return all(c == 0 for c in inputs.values())
9354234b81db69e37096e66c37f68b14acdbf142
arkiz/py
/lab1-5.py
713
3.8125
4
year01 = input("Enter the number of 1st year") wins01 = input("Enter the number of wins in 1st year") year02 = input("Enter the number of 2nd year") wins02 = input("Enter the number of wins in 2nd year") year03 = input("Enter the number of 3rd year") wins03 = input("Enter the number of wins in 3rd year") year04 = input("Enter the number of 4th year") wins04 = input("Enter the number of wins in 4th year") year05 = input("Enter the number of 5th year") wins05 = input("Enter the number of wins in 5th year") avgWins = (wins01 + wins02 + wins03 + wins04 + wins05) / 5 print "The average number of wins year period in ", year01, ", ", year02, ", ", year03, ", ", year04, ", ", year05, " is ", avgWins
abdff8d3bf6c1e1cc39a24519587e5760294bdc6
arkiz/py
/lab1-4.py
413
4.125
4
studentName = raw_input('Enter student name.') creditsDegree = input('Enter credits required for degree.') creditsTaken = input('Enter credits taken so far.') degreeName = raw_input('Enter degree name.') creditsLeft = (creditsDegree - creditsTaken) print 'The student\'s name is', studentName, ' and the degree name is ', degreeName, ' and There are ', creditsLeft, ' credits left until graduation.'
a0eb11daa6aa1f642541eea86601d0c4ebe29a6b
insoo67park/bigdata
/d2/word_count/.ipynb_checkpoints/reducer-checkpoint.py
961
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys prev_word = None counts = 0 # (keyword, count)하나의 pair가 입력 됨 # 같은 keyword가 묶여서 연속으로 입력 됨 # ex) (백신, 1) (백신, 1) (코로나, 1) (거리두기, 1) for word_count in sys.stdin: word, count = word_count.split("\\") # map에서 보낸 "key$value"를 $로 나눠서 저장 count = int(count) # string 형식을 int형식으로 다시 바꿔 줌 if prev_word == word: # 이전 입력과 같은 keyword가 들어오면 count함 counts += count else: # 새로운 keyword가 들어왔을 때 if prev_word: # 첫 입력이 아니면, keyword랑 keyword 수 파일로 출력 print("%s: %s"%(prev_word, counts)) # 새로운 keyword에 대해 count 함 counts = count prev_word = word if prev_word: # 마지막 keyword에 대해 저장 print("%s: %s"%(prev_word, counts))
79b163e645ae2030938f3accadcd502d2cb4610a
jocelyneterrazas/socialnetwork
/socialnetwork.py
3,056
3.5
4
## Made by: Jocelyne Terrazas ## My Social Network class User: def __init__(self, username): self.username = username self.firstName = "" self.lastName = "" self.bio = "" ##self.userID = userID self.friendsList = [] self.posts = [] self.userID = "" def addfirstName(self, firstName): self.firstName = firstName def addlastName(self, lastName): self.lastName = lastName def addbio(self, bio): self.bio = bio def addFriend(self, person): self.friendsList.append(person) def addposts(self, posts): self.posts.append(post) def unFriend(self, obj): for friend in self.friendsList: if friend.username == obj.username: self.friendsList.remove(obj) def showUsernames(self): for friend in self.friendsList: print (friend.username) def viewNewsFeed(self): for friends in self.friendsList: print (friends.posts) def createPost(self, content): myPost = post(content) self.post.append(myPost) myPost.createPostID(len(posts)) def createUserID(self, num): self.userID = num class Post: def __init__(self, content): self.content = content self.postID = "" self.comments = [] def createPostID(self, num): self.postID = num class Network: def __init__(self): self.users = [] print("User Created") def createUser(self, username): for i in users: if(i.username == username): print("username taken") myUser = User(username) self.users.append(myUser) mySize = len(self.users) myUser.createID(len(users)) print("user.created") if __name__ == "__main__": network = Network() network.createUser("jocelyne") username = "jocelyne" jocelyne = User("jocelyne") lucy = User("lucy") churrosanchez = User("churrosanchez") thejazziestjaz = User("thejazziestjaz") ## print(jocelyne.firstName) ## print(lucy.firstName) ## print(churrosanchez.firstName) ## print(thejazziestjaz.firstName) jocelyne.addFriend(lucy) jocelyne.addFriend(churrosanchez) jocelyne.addFriend(thejazziestjaz) ## print(jocelyne.friendsList) lucy.posts.append("THIS IS MY FIRST POST") churrosanchez.posts.append("goodnight") thejazziestjaz.posts.append("music can end war") ## print(lucy.posts) ## print(churrosanchez.posts) ## print(thejazziestjaz.posts) print("This is your News Feed:") jocelyne.viewNewsFeed() print("This is your friends list:") jocelyne.showUsernames() jocelyne.unFriend(churrosanchez) print("This is your UPDATED friends list:") jocelyne.showUsernames()
d85ea99814d0f990fcb8ec6261e604dd59180902
kyeongeun25/Python
/py_02/p001/연산자.py
1,610
4.0625
4
# 연산자 # 4칙연산 num1 = 40 num2 = 3 print("덧셈 : "+str(num1+num2)) print("뺄셈 : "+str(num1-num2)) print("곱셈 : "+str(num1*num2)) print("나눗셈 : "+str(num1/num2)) print("나머지 : "+str(num1%num2)) # 특별한 산수 연산자 print("나버지 버림 : "+str(num1 // num2)) print("제곱 : " + str(num1 ** 3)) # VB, C#에서는 num1^3 print("num1 : " + str(num1)) print("num2 : " + str(num2)) # num1과 num2의 값을 서로 바꿀 때 num1, num2 = num2 , num1 print("num1 : " + str(num1)) print("num2 : " + str(num2)) # 비교 연산자 if(num1 == num2) : #같은가? print("같다") if(num1 != num2) : #다른가? print("다르다") if(num1 > num2) : # num1이 큰가 print("num1이 크다") if(num1 >= num2) : # num1이 크거나 같은가 print("num1과 num2가 같거나 num1이 크다") if(1 == 1) : print("참") if(1 == 1 and 2 == 2) : print("참") if( 1 == 1 or 2 == 3) : print("참") if ( 1 == 1 and 2 != 3) : print("참") # 참 and 반전(거짓) if( 1 == 1 and not (2 == 3)) : # not => ! print("참") # 할당 연산자 num1 = 3 num1 += 4 # num1 = num1 + 4 num1 -= 4 # num1 = num1 - 4 # 멤버연산자(배열과 관련된 연산자) list = [1,2,3,4,5,6,7] if(3 in list) : #list내에 3이 있냐? print("있다") if(10 not in list) : # list내에 10이 없냐? print("그래 없다") # 저장소(기억장소)와 관련된 연산자 num1 = 3 num2 = 4 if( num1 is num2 ) : #저장소 주소가 같은곳이냐 print("아니다")
12fc80e09e5d6cc61b33171d30102042784dc212
vigitia/VIGITIA-Toolkit
/VIGITIA_toolkit/utility/get_ip.py
664
3.5
4
from urllib import request, error # https://stackoverflow.com/questions/2311510/getting-a-machines-external-ip-address-with-python def get_ip_address(): # try: # # Try to get the public IP address of the computer # ip = request.urlopen('https://ident.me').read().decode('utf8') # except error.URLError as e: # # If no Internet connection is available, use the local IP address instead # import socket # ip = socket.gethostbyname(socket.gethostname()) # # if ip == "127.0.0.1": import subprocess ip = subprocess.check_output(['hostname', '-s', '-I']).decode('utf-8')[:-1].split(' ')[0] return ip
1d4071a8dbcff5752d1941863e3d6a424a61b7f5
KiD21606/HackerRank
/python/Regex_and_Parsing/Detect_Floating_Point_Number.py
1,391
3.8125
4
''' constrains: 1. Consist of numbers, "+", "-", and ".". 2. Contain at most one of "+" and "-". 3. Have exactly one "." symbol, and must have a number after ".". 4. must contain at least 1 decimal value. ''' for _ in range(int(input())): dot = False number = False string = input() if string[0] in '0123456789': number = True elif string[0] in '+-': pass elif string[0] == '.': dot = True else: print(False) continue result = True for i in range(1,len(string)): if string[i] in '0123456789': number = True elif string[i] == '.' and dot == False : if i+1 == len(string): result = False elif string[i+1] in '0123456789': dot = True else: result = False break if number == False or dot == False: result = False print(result) ''' import re for _ in range(int(input())): print(bool(re.match(r'^[-+]?[0-9]*\.[0-9]+$', input()))) ''' ''' ^ : start of the expression. [-+]? : start with either - or +. [0-9] : any number from 0-9 can be followed after it. * : the process ([0-9]) can repeat arbitrarily times (even 0 times). \. : '\' is the skip char that is used for ".". + : the process ([0-9]) can repeat arbitrarily times, but atleast one time. $ : ending symbol. '''
65a3751044e9098230c71112828444f1d317cb76
KiD21606/HackerRank
/python/Sets/Check_Strict_Superset.py
186
3.515625
4
A = set(input().split()) result = True for _ in range(int(input())): B = set(input().split()) if B-A != set() or A-B == set(): result = False break print(result)
d5dcfba7aaa1057e45d45a3d009c6b50b730cb8d
KiD21606/HackerRank
/python/Regex_and_Parsing/Validating_Credit_Card_Numbers.py
269
3.515625
4
import re def varify(s): if not re.match(r'^[456]\d{3}(-?\d{4}){3}$',s): return 'Invalid' s = s.replace('-','') if re.search(r'(\d)\1{3}',s): return 'Invalid' return 'Valid' for _ in range(int(input())): print(varify(input()))
9308608e093885d0aef426e5ff2ad834c349ee94
KiD21606/HackerRank
/python/Date_and_Time/Calendar_Module.py
240
4.09375
4
import calendar day_name = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY'] date = input().split() year = int(date[2]) month = int(date[0]) day = int(date[1]) print(day_name[calendar.weekday(year,month,day)])
a8d1170910fa9c49eefba50a19ae0a5483d5b9f2
KiD21606/HackerRank
/python/Python_Functionals/Map_and_Lambda_Function.py
394
4.09375
4
cube = lambda x: x**3 def fibonacci(n): if n==0: return [] fib = [1]*n fib[0] = 0 for i in range(3,n): fib[i] = fib[i-1] + fib[i-2] return fib ''' def fibonacci(n): fib = [0,1] for i in range(2,n): fib.append(fib[i-1]+fib[i-2]) return fib[0:n] ''' if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n))))
0939885322d9a139e117d9ab92e7e008fe254a1f
KiD21606/HackerRank
/python/Strings/Text_Wrap.py
353
3.75
4
import textwrap def wrap(string, n): result = '' k = len(string)//n for i in range(k): result += string[n*i:n*(i+1)]+'\n' if len(string)%n != 0: result += string[n*k:]+'\n' return result if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result)
2abbf5f56a47bd8041b38221e33de5aa16fe5dd9
stoneriver/AtCoder-Python
/AtCoder Beginners Selection/ABC049C.py
1,512
3.5625
4
# ABC049C - 白昼夢 S = input() while True: if S[0:5] == "dream": if S == "dream": # この単語がdream、次の単語は存在しない S = "" elif S == "dreamer": # この単語がdreamer、次の単語は存在しない S = "" elif S[5:8] == "dre": # この単語がdream、次の単語はdreamかdreamer S = S[5:] elif S[5:8] == "era": # この単語がdream、次の単語はeraseかeraser S = S[5:] elif S[5:8] == "erd": # この単語がdreamer、次の単語はdreamかdreamer S = S[7:] elif S[5:8] == "ere": # この単語がdreamer、次の単語はeraseかeraser S = S[7:] elif S[0:5] == "erase": if S == "erase": # この単語がerase、次の単語は存在しない S = "" elif S == "eraser": # この単語がeraser、次の単語は存在しない S = "" elif S[5:8] == "dre": # この単語がerase、次の単語はdreamかdreamer S = S[5:] elif S[5:8] == "era": # この単語がerase、次の単語はeraseかeraser S = S[5:] elif S[5:8] == "rdr": # この単語がeraser、次の単語はdreamかdreamer S = S[6:] elif S[5:8] == "rer": # この単語がeraser、次の単語はeraseかeraser S = S[6:] elif S == "": print("YES") break else: print("NO") break
517f231a66c9d977bc5a34eaa92b6ad986a8e340
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
/Module-3/3-1-2-12-Python-loops-else-The-while-loop-and-the-else-branch.py
356
4.15625
4
#!/usr/bin/python3 """ Both loops, while and for, have one interesting (and rarely used) feature. As you may have suspected, loops may have the else branch too, like ifs. The loop's else branch is always executed once, regardless of whether the loop has entered its body or not. """ i = 1 while i < 5: print(i) i += 1 else: print("else:", i)
6920b44453655be0855b3977c12f2ed33bdb0bc3
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
/Module-4/4-1-3-10-LAB-Converting-fuel-consumption.py
1,432
4.4375
4
#!/usr/bin/python3 """ A car's fuel consumption may be expressed in many different ways. For example, in Europe, it is shown as the amount of fuel consumed per 100 kilometers. In the USA, it is shown as the number of miles traveled by a car using one gallon of fuel. Your task is to write a pair of functions converting l/100km into mpg, and vice versa. The functions: are named l100kmtompg and mpgtol100km respectively; take one argument (the value corresponding to their names) Complete the code in the editor. Run your code and check whether your output is the same as ours. Here is some information to help you: 1 American mile = 1609.344 metres; 1 American gallon = 3.785411784 litres. Test Data Expected output: 60.31143162393162 31.36194444444444 23.52145833333333 3.9007393587617467 7.490910297239916 10.009131205673757 """ def l100kmtompg(liters): """ 100000 m * 3.785411784 l [ mi ] ________________________ ________ 1609.344 m * liters [ g ] """ return ((100000*3.785411784)/(1609.344*liters)) def mpgtol100km(miles): """ 100000 m * 3.785411784 l [ l ] ________________________ _________ 1609.344 m * miles [ 100Km ] """ return ((100000*3.785411784)/(1609.344*miles)) print(l100kmtompg(3.9)) print(l100kmtompg(7.5)) print(l100kmtompg(10.)) print(mpgtol100km(60.3)) print(mpgtol100km(31.4)) print(mpgtol100km(23.5))
c9bedff4032b89fbd4054b4f03093af06a3d01d0
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
/Module-2/2-1-4-10-LAB-Operators-and-expressions.py
567
4.5625
5
#!/usr/bin/python3 """ Take a look at the code in the editor: it reads a float value, puts it into a variable named x, and prints the value of a variable named y. Your task is to complete the code in order to evaluate the following expression: 3x3 - 2x2 + 3x - 1 The result should be assigned to y. """ x = 0 x = float(x) y = 3 * x ** 3 - 2 * x ** 2 + 3 * x - 1 print('x =', x, ' y =', y) x = 1 x = float(x) y = 3 * x ** 3 - 2 * x ** 2 + 3 * x - 1 print('x =', x, ' y =', y) x = -1 x = float(x) y = 3 * x ** 3 - 2 * x ** 2 + 3 * x - 1 print('x =', x, ' y =', y)
fd86bac9750e54714b1fe65d050d336dba9399ca
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
/Module-4/4-1-3-9-LAB-Prime-numbers-how-to-find-them.py
1,302
4.28125
4
#!/usr/bin/python3 """ A natural number is prime if it is greater than 1 and has no divisors other than 1 and itself. Complicated? Not at all. For example, 8 isn't a prime number, as you can divide it by 2 and 4 (we can't use divisors equal to 1 and 8, as the definition prohibits this). On the other hand, 7 is a prime number, as we can't find any legal divisors for it. Your task is to write a function checking whether a number is prime or not. The function: is called isPrime; takes one argument (the value to check) returns True if the argument is a prime number, and False otherwise. Hint: try to divide the argument by all subsequent values (starting from 2) and check the remainder - if it's zero, your number cannot be a prime; think carefully about when you should stop the process. If you need to know the square root of any value, you can utilize the ** operator. Remember: the square root of x is the same as x0.5 Complete the code in the editor. Run your code and check whether your output is the same as ours. Test Data Expected output: 2 3 5 7 11 13 17 19 """ def isPrime(num): for n in range(2, num): if ((num % n) == 0): return False return True for i in range(1, 20): if isPrime(i + 1): print(i + 1, end=" ") print()
a68c0ddd6f458d58084dee9810c34072a1312f71
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
/Module-3/3-1-6-2-Operations-on-lists-slices-Powerful-slices.py
459
3.796875
4
#!/usr/bin/python3 """ Powerful slices Fortunately, the solution is at your fingertips - its name is the slice. A slice is an element of Python syntax that allows you to make a brand new copy of a list, or parts of a list. It actually copies the list's contents, not the list's name """ # Copyng the whole list list1 = [1] list2 = list1[:] list1[0] = 2 print(list2) # Copyng part of the list myList = [10, 8, 6, 4, 2] newList = myList[1:3] print(newList)
3e7b84ff790a508534c03cdc878f6abdf2e32a53
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
/Module-3/3-1-6-1-Operations-on-lists-The-inner-life-of-lists.py
1,345
4.375
4
#!/usr/bin/python3 """ The inner life of lists Now we want to show you one important, and very surprising, feature of lists, which strongly distinguishes them from ordinary variables. We want you to memorize it - it may affect your future programs, and cause severe problems if forgotten or overlooked. Take a look at the snippet in the editor. The program: - creates a one-element list named list1; - assigns it to a new list named list2; - changes the only element of list1; - prints out list2. The surprising part is the fact that the program will output: [2], not [1], which seems to be the obvious solution. Lists (and many other complex Python entities) are stored in different ways than ordinary (scalar) variables. You could say that: - the name of an ordinary variable is the name of its content; - the name of a list is the name of a memory location where the list is stored. Read these two lines once more - the difference is essential for understanding what we are going to talk about next. The assignment: list2 = list1 copies the name of the array, not its contents. In effect, the two names (list1 and list2) identify the same location in the computer memory. Modifying one of them affects the other, and vice versa. How do you cope with that? """ list1 = [1] list2 = list() list2 = list1 list1[0] = 2 print(list2)
22d49020846e8a953364049ff95f348443100a81
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
/Module-3/3-1-4-12-Lists-collections-of-data-lists-and-loops-Lists-in-action.py
261
4.0625
4
#!/usr/bin/python3 """ Now you can easily swap the list's elements to reverse their order: """ myList = [10, 1, 8, 3, 5] print(myList) for i in range(len(myList) // 2): myList[i], myList[len(myList)-1-i] = myList[len(myList)-1-i], myList[i] print(myList)
946ec887e106dde979717832e603732ef85a750c
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
/Module-4/4-1-2-2-How-functions-communicate-with-their-environment-Parametrized-functions.py
1,358
4.375
4
#!/usr/bin/python3 """ It's legal, and possible, to have a variable named the same as a function's parameter. The snippet illustrates the phenomenon: def message(number): print("Enter a number:", number) number = 1234 message(1) print(number) A situation like this activates a mechanism called shadowing: parameter x shadows any variable of the same name, but... ... only inside the function defining the parameter. The parameter named number is a completely different entity from the variable named number. This means that the snippet above will produce the following output: Enter a number: 1 1234 """ def message(number): print("Enter a number:", number) message(4) number = 1234 message(1) print(number) """ A function can have as many parameters as you want, but the more parameters you have, the harder it is to memorize their roles and purposes. Functions as a black box concept Let's modify the function - it has two parameters now: def message(what, number): print("Enter", what, "number", number) This also means that invoking the function will require two arguments. The first new parameter is intended to carry the name of the desired value. Here it is: """ def message1(what, number): print("Enter", what, "number", number) message1("telephone", 11) message1("price", 6) message1("number", "number")
b6732e8d49b943a0391fe3d6521bdf29d2f840ee
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
/Module-3/3-1-1-11-LAB-Comparison-operators-and-conditional-execution.py
1,014
4.46875
4
#!/usr/bin/python3 """ Spathiphyllum, more commonly known as a peace lily or white sail plant, is one of the most popular indoor houseplants that filters out harmful toxins from the air. Some of the toxins that it neutralizes include benzene, formaldehyde, and ammonia. Imagine that your computer program loves these plants. Whenever it receives an input in the form of the word Spathiphyllum, it involuntarily shouts to the console the following string: "Spathiphyllum is the best plant ever!" Test Data Sample input: spathiphyllum Expected output: No, I want a big Spathiphyllum! Sample input: pelargonium Expected output: Spathiphyllum! Not pelargonium! Sample input: Spathiphyllum Expected output: Yes - Spathiphyllum is the best plant ever! """ word = input("Please input your string: ") if word == "Spathiphyllum": print("Yes - Spathiphyllum is the best plant ever!") elif word == "spathiphyllum": print("No, I want a big Spathiphyllum!") else: print("Spathiphyllum! Not " + word + "!")
7910f459e4fa3465fa210d3b7710c2d0269e55b7
kingsman142/Projects
/Udacity/smartcab/smartcab/smartcab/agent.py
5,486
3.625
4
import random from environment import Agent, Environment from planner import RoutePlanner from simulator import Simulator class LearningAgent(Agent): """An agent that learns to drive in the smartcab world.""" def __init__(self, env): super(LearningAgent, self).__init__(env) # sets self.env = env, state = None, next_waypoint = None, and a default color self.color = 'red' # override color self.planner = RoutePlanner(self.env, self) # simple route planner to get next_waypoint # TODO: Initialize any additional variables here from collections import defaultdict self.qTable = defaultdict(int) self.wins = 0 self.gamma = 1.0 self.total_reward = 0 #Initialize all qTable values to 10.0 so we can implement optimistic initialization instead of random exploration for a in [None, 'left', 'forward', 'right']: for b in ['red', 'green']: for c in [None, 'left', 'forward', 'right']: for d in [None, 'left', 'forward', 'right']: for e in [None, 'left', 'forward', 'right']: self.qTable[((a, b, c, d), e)] = 10.0 self.errors = 0 def reset(self, destination=None): self.planner.route_to(destination) # TODO: Prepare for a new trip; reset any variables here, if required def update(self, t): # Gather inputs self.next_waypoint = self.planner.next_waypoint() # from route planner, also displayed by simulator inputs = self.env.sense(self) deadline = self.env.get_deadline(self) # TODO: Update state #State consists of the agent's next waypoint, the status of the light (red or green), #traffic to the left (None, forward, left, right), and oncoming traffic (None, forward, left, right). #This leads to 4*2*4*4 = 128 possible states in our game! (this means quick learning because of the curse of dimensionality) self.state = (self.next_waypoint, inputs['light'], inputs['oncoming'], inputs['left']) # TODO: Select action according to your policy #list_of_actions stores the Q-values after all possible actions in the current state list_of_actions = {None: self.qTable[(self.state, None)], 'forward': self.qTable[(self.state, 'forward')], 'left': self.qTable[(self.state, 'left')], 'right': self.qTable[(self.state, 'right')]} #list_of_actions2 sorts list_of_actions and consists of the sorted order of actions with the last element being the "best" list_of_actions2 = sorted(list_of_actions, key=list_of_actions.__getitem__) #Print output print "\n",list_of_actions print list_of_actions2 print list_of_actions2[2],": ",list_of_actions[list_of_actions2[2]] print list_of_actions2[3],": ",list_of_actions[list_of_actions2[3]] #Assign action action = list_of_actions2[3] # Execute action and get reward reward = self.env.act(self, action) self.total_reward += reward if reward >= 10: #This is essentially the winning statement self.wins += 1 #Considering the average 96 wins, by the 56th win, there should be 60 trials. #So, within these last 40 trials, let's count how many errors there are if self.wins >= 56: if reward < 0: self.errors += 1 #More ouput print "Next waypoint: ", self.next_waypoint print "Chosen action: ", action print "Reward: ", reward # TODO: Learn policy based on state, action, reward self.alpha = 1.0 #Learning rate - keep it at 1.0 so we rely more on the most recent information of a state and action pair self.gamma -= .005 if self.gamma >= .2 else 0 #Don't let gamma go below .2 #Next 3 lines store the values for the agent's next state self.next_inputs = self.env.sense(self) self.next_waypoint = self.planner.next_waypoint() self.next_state = (self.next_waypoint, inputs['light'], inputs['right'], inputs['oncoming']) #Update the Q-table with the equation: Q(s, a) = r(s, a) + gamma*max(s', a') self.qTable[(self.state, action)] = (1.0 - self.alpha)*self.qTable[(self.state, action)] + self.alpha*(reward + self.gamma*max(self.qTable[(self.next_state, None)], self.qTable[(self.next_state, 'forward')], self.qTable[(self.next_state, 'left')], self.qTable[(self.next_state, 'right')])) #More output #print "LearningAgent.update(): deadline = {}, inputs = {}, action = {}, reward = {}".format(deadline, inputs, action, reward) # [debug] print "Wins: ", self.wins print "Gamma: ", self.gamma print "Total reward: ", self.total_reward print "Errors: ", self.errors def run(): """Run the agent for a finite number of trials.""" # Set up environment and agent e = Environment() # create environment (also adds some dummy traffic) a = e.create_agent(LearningAgent) # create agent e.set_primary_agent(a, enforce_deadline=True) # set agent to track # Now simulate it sim = Simulator(e, update_delay=.01) # reduce update_delay to speed up simulation sim.run(n_trials=100) # press Esc or close pygame window to quit if __name__ == '__main__': run()
ad07c957de435974775396e4cc0b8a793ffe4141
michellecby/learning_python
/week7/checklist.py
788
4.1875
4
#!/usr/bin/env python3 # Write a program that compares two files of names to find: # Names unique to file 1 # Names unique to file 2 # Names shared in both files import sys import biotools file1 = sys.argv[1] file2 = sys.argv[2] def mkdictionary(filename): names = {} with open(filename) as fp: for name in fp.readlines(): name = name.rstrip() names[name] = True return names d1 = mkdictionary(file1) d2 = mkdictionary(file2) u1 = [] u2 = [] both = [] for word in d1: if word in d2: both.append(word) else: u1.append(word) for word in d2: if word not in d1: u2.append(word) print("Names unique to file 1:") print(u1) print("Names unique to file 2:") print(u2) print("Names shared in both files:") print(both) """ python3 checklist.py file1.txt file2.txt """
93bb7d0991282aae1b16a4524f9428c3a6077c0d
riferman/epam_5
/laba 5-2 GUI.py
1,835
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from tkinter import * import os __author__ = "Sergey_Matusevich" # The program searches for files in the specified directory. # If the directory is not specified, the search is performed on # D: er, and the size of the required files is set to 0. That is, all files. def walk(dir_name="D:\\", min_size=100): for address, dirs, files in os.walk(dir_name): for file in files: addr = address + '/' + file if os.path.getsize(addr) >= min_size: yield addr def inserter(value): """ Inserts specified value into text widget """ output.delete("0.0", "end") output.insert("0.0", value) def interceptor(): try: a_val = str(a.get()) or "D:\\" b_val = int(b.get() or 0) inserter("\n".join(walk(dir_name=a_val, min_size=b_val))) except ValueError: inserter("""Fill in the correct search parameters. In the field "Specify the size:" enter the number""") root = Tk() root.title("Search files by size") root.minsize(600, 600) root.resizable(width=False, height=False) frame = Frame(root) frame.grid() def clear(event): """ Clears entry form """ caller = event.widget caller.delete("0", "end") a = Entry(frame, width=3) a.grid(row=1, column=1, padx=(10, 0), sticky=W + E) a.bind("<FocusIn>", clear) a_lab = Label(frame, text="Specify a folder:").grid(row=1, sticky=W) b = Entry(frame, width=3) b.grid(row=1, column=4, padx=(10, 0), sticky=W + E) b.bind("<FocusIn>", clear) b_lab = Label(frame, text="Specify the size:").grid(row=1, column=3, sticky=W) output = Text(frame, bg="lightblue", font="Arial 12", width=70, height=30) output.grid(row=2, columnspan=8) but = Button(frame, text="Search", command=interceptor).grid(row=1, column=7, padx=(10, 0)) root.mainloop()
0939070cf0430a2d3c79d94c04ef9d7886fcf46a
kai230/mPython
/examples/thread/thread_lock.py
749
3.734375
4
import _thread # 导入线程模块 import time # 导入时间模块 # 创建锁 lock=_thread.allocate_lock() # 定义线程函数,打印线程编号和运行时间 def print_time( threadName, delay): count = 0 # 获取锁 if lock.acquire(): while count < 5: time.sleep(delay) count += 1 print ("%s: %s sec" % ( threadName, time.localtime()[5] )) # 释放锁 lock.release() print("%s:End" %threadName) # 结束线程 _thread.exit() # 启动线程1 _thread.start_new_thread( print_time, ("Thread-1", 2, ) ) # 启动线程2 _thread.start_new_thread( print_time, ("Thread-2", 4, ) ) while True: # 主体循环 pass # 空指令
a0c765e6fbe2c954eb0d745c2e99301461e864ab
sveetch/video-registry
/tests/utils.py
728
3.5625
4
""" Test utilities """ from pyquery import PyQuery as pq def html_pyquery(content): """ Shortand to use Pyquery parsing on given content. This is more useful to dig in advanced HTML content. PyQuery is basically a wrapper around ``lxml.etree`` it helps with a more intuitive API (alike Jquery) to traverse elements but when reaching a node content it will return ``lxml.html.HtmlElement`` object which have a less intuitive API but with more features and more flexible with whitespaces. Arguments: content (TemplateResponse or string): HTML content to parse. Returns: pyquery.PyQuery: A PyQuery object. """ return pq( content, parser="html" )
a26660f14b5e65ecb68877a5fcc233d160e16271
sudobum/rectangle_triangle_info
/rectangle_info.py
1,228
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 29 19:31:22 2018 @author: IBM-Watson """ #this program displays information #about a rectangle drawn by the user. from graphics import * import math def main(): win = GraphWin('Rectangle Information', 400 , 400) win.setCoords(-10, -10, 10, 10) # get user inputs(two points/mouse clciks) # draw rectangle point1 = win.getMouse() point2 = win.getMouse() aRectangle = Rectangle(point1, point2) aRectangle.draw(win) #measuring length of a rectangle dx = point2.getX() - point1.getX() dy = point1.getY() - point1.getY() length = math.sqrt(dx * dx + dy * dy) #measuring width of a rectangle dxw = point1.getX() - point1.getX() dyw = point2.getY() - point1.getY() width = math.sqrt(dxw * dxw + dyw * dyw ) #perimeter and area area = length * width perimeter = 2 * (length + width) #Display texts Text(Point(-8.6,-7),'Perimeter: ').draw(win) Text(Point(-4,-7), perimeter).draw(win) Text(Point(-9,-8),'Area: ' ).draw(win) Text(Point(-5,-8), area).draw(win) win.getMouse() win.close() main()
69742bf185e0c29d592e1cddd36cf5a3789be8f6
lanhel/pyietflib
/pyietflib/iso8601/__init__.py
2,257
3.5625
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- """Package that will handle `ISO 8601:2004 Representation of dates and times <http://www.iso.org/iso/catalogue_detail?csnumber=40874>`_ parsing and formatting. """ __copyright__ = """Copyright 2011 Lance Finn Helsten (helsten@acm.org)""" from .__meta__ import (__version__, __author__, __license__) from .time import * from .date import * from .datetime import * #from .duration import * #from .recurring import * __all__ = ['isodate', 'isotime', 'isodatetime', 'CALENDAR', 'ORDINAL', 'WEEK', 'CENTURY', 'DECADE', 'YEAR', 'MONTH', 'DAYOFMONTH', 'DAYOFYEAR', 'WEEKOFYEAR', 'DAYOFWEEK', 'HOUR', 'MINUTE', 'SECOND' ] def parse_iso8601(value): """This will parse an ISO 8601 arbitrary representation and return a list of the component parts. All time representations must have the time designator [T] before the time starts. This is in accordance with ISO 8601 §5.3.1.5 where if time is not explicitly specified then the designator is required. Examples -------- 19660829 This will return an isodate object. 1966-08-29 This will return an isodate object. T05:11:23 This will return an isotime object. T051123 This will return an isotime object. 051123 This will return an isodate object even though it is a valid basic format complete representation of time because the time designator [T] is missing. 19660829T052436 This will return an isodatetime object. P1Y2M15DT12H30M0S This will return an isoduration object. 19660829/P1Y2M15DT12H30M0S This will return an isodate object and an isoduration object. P1Y2M15DT12H30M0S/19660829 This will return an isoduration object and an isodate object. """ ret = [] for p in value.split('/'): if p.startswith('P'): ret.append(isoduration.parse_iso(p)) elif p.startswith('R'): ret.append(isorecur.parse_iso(p)) elif p.startswith('T'): ret.append(isotime.parse_iso(p)) elif 'T' in p: ret.append(isodatetime.parse_iso(p)) else: ret.append(isodate.parse_iso(p)) return ret
ecf9b0bf9197c735047dda97d9c88734f16471af
profjrr/ev3
/ev3/robot/lego.py
1,588
3.609375
4
""" The interface class providing the way to configure an EV3 lego robot. The robot is represented by an instance of EV3Robot class. This is meant to be derived from and passed to EV3RobotDriver instance. """ class EV3RobotConfigurator(object): drive = None touch_sensor = None ir_sensor = None color_sensor = None touch_sensor = None def setup(self): pass def tear_down(self): pass def get_left_motors(self): return None def get_right_motors(self): return None """ The interface class providing the way to drive an EV3 lego robot. The robot is represented by an instance of EV3Robot class. This is meant to be derived from and passed to EV3Robot instance. """ class EV3RobotDriver(object): def __init__(self, configurator): self.configurator = configurator def setup(self): self.configurator.setup() def tear_down(self): self.configurator.tear_down() def start(self): pass def stop(self): pass """ The class representing an EV3 lego robot. """ class EV3Robot(object): _driver = None def setup(self, driver): if self._driver: self._driver.tear_down() self._driver = driver driver.setup() def tear_down(self): self._driver.tear_down() def start(self): self._driver.start() def stop(self): self._driver.stop() __all__ = ['EV3RobotConfigurator', 'EV3RobotDriver', 'EV3Robot']
f6510f19dc43e3374f3dfb5cb25b1ef5d6c2f2fe
profjrr/ev3
/ev3/motor/lego.py
12,725
3.96875
4
"""Classes for original Lego Mindstorms EV3 motors.""" from ..rawdevice import lms2012 from ..rawdevice import motordevice import collections MAX_SPEED_VALUE = 127 """Class for manipulating a single instance of a motor. Motor must be one of ev3.MOTOR_* where * is A-D.""" class EV3Motor(object): MOVE_NONE = -1 MOVE_BACKWARD = 0 MOVE_FORWARD = 1 MAX_SPEED = 100 UNKNOWN_SPEED = -1 def __init__(self, port): self._port = port; # Allowed to be accessed by EV3Drive self._port_mask = (1 << port); self.direction = self.MOVE_NONE """Private method for normalization the speed from 0-100 range to device's 0-127 range. (The device accepts values from 0-255 range however values above 128 causes polarization to be inverted this is why 0-127 values are used to respect the direction passed to start())""" def _to_max_speed(self, speed): speed = min(speed, self.MAX_SPEED) speed = max(speed, 0) speed = speed * MAX_SPEED_VALUE / self.MAX_SPEED; return speed """Private method for normalization the speed from device's 0-127 range to 0-100 range. See _to_max_speed().""" def _to_speed_range(self, speed): speed = min(speed, MAX_SPEED_VALUE) speed = max(speed, 0) speed = speed * self.MAX_SPEED / MAX_SPEED_VALUE; return speed """Starts the motor with the given direction and speed. The direction must be one of: MOVE_BACKWARD or MOVE_FORWARD. Speed must be in 1-100 range.""" def start(self, direction, speed): if (direction == self.MOVE_NONE): return speed = self._to_max_speed(speed) motordevice.reset(self._port_mask) self.set_direction(direction) motordevice.speed(self._port_mask, speed, True) """Sets motor's direction""" def set_direction(self, direction): self.direction = direction if (direction == self.MOVE_NONE): return motordevice.polarity(self._port_mask, direction) """Rotates the motor by the given angle at the given speed.""" def rotate(self, direction, speed, angle): motordevice.polarity(self._port_mask, direction) angle = max(0, angle); motordevice.step_speed(self._port_mask, speed, 0, angle, 0) """Stops the motor""" def stop(self): motordevice.stop(self._port_mask, False) self.direction = self.MOVE_NONE """Sets motor's speed. If the motor is stopped it's started with the given speed and MOVE_FORWARD direction.""" def set_speed(self, speed): if (speed <= 0): self.stop() return if (self.get_direction() == self.MOVE_NONE): self.start(self.MOVE_FORWARD, speed) return speed = self._to_max_speed(speed) motordevice.speed(self._port_mask, speed, True) """Accelerates the motor by the given delta. If (current speed + delta) exceeds the max speed limit the motor is accelerated to the max speed. If it runs with the max speed at time this is called this has no effect.""" def accelerate(self, delta): if (self.get_speed() == 0): self.start(self.MOVE_FORWARD, delta) return if (delta >= 0): delta = min(delta, self.MAX_SPEED) delta = max(delta, 0) else: delta = max(delta, -self.MAX_SPEED) self.set_speed(self.get_speed() + delta) """Same as accelerate() but it slows the motor down.""" def slow_down(self, delta): delta = abs(delta) self.accelerate(-delta) """Returns current speed of the motor.""" def get_speed(self): return self._to_speed_range(motordevice.get_speed(self._port)) """Returns current direction of the motor.""" def get_direction(self): return self.direction """Returns current tacho of the motor.""" def get_tacho(self): if (self.get_direction() == self.MOVE_NONE): return motordevice.get_tacho(self._port) else: return motordevice.get_sensor(self._port) """Class for manipulating EV3 mindstorm robot's drive consisting of couple of motors. Motors can be manipulated at once and every one separately.""" class EV3Drive(EV3Motor): TURN_LEFT = 2 TURN_RIGHT = 3 MOTOR_ALL = 0xFF def __init__(self, motors): if not isinstance(motors, collections.Iterable): motors = [motors] self._map = {} self._motors = [] self._port_mask = 0 for index, motor_port in enumerate(motors): self._map[motor_port] = index self._motors.insert(motor_port, EV3Motor(motor_port)) self._port_mask |= 1 << motor_port self.direction = self.MOVE_NONE # Helper allowing to avoid code duplication def _call_func(self, *args): which = args[len(args) - 1] # which must always be the last arg name = args[len(args) - 2] # name must always be the second arg from the end args = args[:len(args)-2] # remove which & name if not isinstance(which, collections.Iterable): which = [which] if (self.MOTOR_ALL in which): getattr(super(EV3Drive, self), name)(*args) else: for motor_index in which: if (motor_index in self._map): getattr(self._motors[self._map[motor_index]], name)(*args) """Similar to EV3Motor.start() with possibility to point at motor(s) which should be started.""" def start(self, direction, speed, which = [MOTOR_ALL]): self._make_sure_direction_is_consistent_everywhere(direction, which) self._call_func(direction, speed, "start", which) def _set_direction(self, direction, which): for motor_index in which: if (motor_index in self._map): self._motors[self._map[motor_index]].direction = direction def _make_sure_direction_is_consistent_everywhere(self, direction, which): if (self.MOTOR_ALL in which): self._set_direction(direction, self._map.keys()) """Similar to EV3Motor.direction() with possibility to point at motor(s) polarity pf which should be changed.""" def set_direction(self, direction, which = [MOTOR_ALL]): if (direction == self.MOVE_NONE): return self._make_sure_direction_is_consistent_everywhere(direction, which) self._call_func(direction, "set_direction", which) """Similar to EV3Motor.rotate() with possibility to point at motor(s) which should be rotated.""" def rotate(self, direction, speed, angle, which = [MOTOR_ALL]): self._call_func(direction, speed, angle, "rotate", which) """Similar to EV3Motor.stop() with possibility to point at motor(s) which should be stopped.""" def stop(self, which = [MOTOR_ALL]): self._make_sure_direction_is_consistent_everywhere(self.MOVE_NONE, which) self._call_func("stop", which) """Similar to EV3Motor.set_speed() with possibility to point at motor(s) which should be applied the speed change.""" def set_speed(self, speed, which = [MOTOR_ALL]): self._call_func(speed, "set_speed", which) """Similar to EV3Motor.accelerate() with possibility to point at motor(s) which should be accelerated.""" def accelerate(self, delta, which = [MOTOR_ALL]): if not isinstance(which, collections.Iterable): which = [which] # Not perfect but good enough. super(EV3Drive, self).accelerate() can't be called. if (self.MOTOR_ALL in which): for motor in self._motors: motor.accelerate(delta) else: for motor_index in which: if (motor_index in self._map): self._motors[self._map[motor_index]].accelerate(delta) """Similar to EV3Motor.accelerate() with possibility to point at motor(s) which should be slowed down.""" def slow_down(self, delta, which = [MOTOR_ALL]): if not isinstance(which, collections.Iterable): which = [which] # Not perfect but good enough. super(EV3Drive, self).slow_down() can't be called. if (self.MOTOR_ALL in which): for motor in self._motors: motor.slow_down(delta) else: for motor_index in which: if (motor_index in self._map): self._motors[self._map[motor_index]].slow_down(delta) """Gets speed of a one of the motors.""" def get_motor_speed(self, which): if (isinstance(which, collections.Iterable) or which == self.MOTOR_ALL or which not in self._map): return self.UNKNOWN_SPEED else: return self._motors[self._map[which]].get_speed() """Gets direction of a one of the motors.""" def get_motor_direction(self, which): if (isinstance(which, collections.Iterable) or which == self.MOTOR_ALL or which not in self._map): return self.MOVE_NONE else: return self._motors[self._map[which]].get_direction() """Turns the drive be slowing down some of the motors to the given |steady_speed| and accelerating the other ones to |moving speed| (so the assumption is the drive has some 'right' engine(s) and same 'left' one(s)). The direction of the turn is driven by |where| which either must be TURN_LEFT or must be TURN_RIGHT. If |in_place| is True motors which should be steady during the turn get the direction reverted to make turn faster (so when passing True as |in_place| it's recommended to pass same value as |steady_speed| and |moving_speed|.""" def turn(drive, where, moving_speed, steady_speed, left_motors, right_motors, in_place): if not drive: return if (not isinstance(left_motors, collections.Iterable)): left_motors = [left_motors] if (not isinstance(right_motors, collections.Iterable)): right_motors = [right_motors] direction = drive.direction left_dir = drive.get_motor_direction(left_motors[0]) right_dir = drive.get_motor_direction(right_motors[0]) if (where == drive.TURN_LEFT): left_speed = steady_speed right_speed = moving_speed if (in_place): if (direction != drive.MOVE_BACKWARD): right_dir = drive.MOVE_FORWARD left_dir = drive.MOVE_BACKWARD else: right_dir = drive.MOVE_BACKWARD left_dir = drive.MOVE_FORWARD else: left_speed = moving_speed right_speed = steady_speed if (in_place): if (direction != drive.MOVE_BACKWARD): right_dir = drive.MOVE_BACKWARD left_dir = drive.MOVE_FORWARD else: right_dir = drive.MOVE_FORWARD left_dir = drive.MOVE_BACKWARD drive.set_speed(left_speed, left_motors) drive.set_speed(right_speed, right_motors) drive.set_direction(left_dir, left_motors) drive.set_direction(right_dir, right_motors) """Class for manipulating EV3 mindstorm robot's canon.""" class EV3Canon(EV3Motor): STRAIGHT = EV3Motor.MOVE_FORWARD UP = EV3Motor.MOVE_BACKWARD MAX_POWER = EV3Motor.MAX_SPEED # |number_rotations_to_fire_one_bullet| depends on the construction i.e. # motor used cogwheels etc. def __init__(self, port, number_rotations_to_fire_one_bullet): super(EV3Canon, self).__init__(port) self._bullet_coef = number_rotations_to_fire_one_bullet def shoot(self, direction, power, number_of_bullets): rot = 360 * number_of_bullets * self._bullet_coef # current = abs(super(EV3Canon, self).get_tacho()) # super(EV3Canon, self).start(direction, power) # target = current + rot # blocks until done. # while (True): # current = abs(super(EV3Canon, self).get_tacho()) # if (current >= target): # break # self.cease_fire() super(EV3Canon, self).rotate(direction, power, rot) def cease_fire(self): super(EV3Canon, self).stop() __all__ = ['EV3Motor', 'EV3Drive', 'EV3Canon']
74943adb8248eee39850823f5d5bfe973937f8ad
trendscenter/coinstac-dpsvm
/scripts/common_functions.py
337
3.609375
4
"""Common functions used in COINSTAC scripts. """ import numpy as np def list_recursive(d, key): """Yields the value corresponding to key in a dict d.""" for k, v in d.items(): if isinstance(v, dict): for found in list_recursive(v, key): yield found if k == key: yield v
027e704ab7884402dbc4c4143f0dedde532d31ce
leetuckert10/CrashCourse
/chapter_4/exercise_4-8.py
196
3.765625
4
# Cubes # Make a list of the cubes of numbers 1 - 10. cubes = [] for value in range(1, 11): # check out this syntax for suppressing a new line. print(value**3, " ", end="") print("\nfinished")
c0c560ee4e39d1bd412a5506b4d850da12715ca1
leetuckert10/CrashCourse
/chapter_4/exercise_4-5.py
341
3.90625
4
# Summing a million numbers... # using functions min(), max(), and sum() one_million = [] for value in range(1, 1000001): one_million.append(value) print(f"Mininum value is {min(one_million)}") print(f"Maximum value is {max(one_million)}") print(f"The sum of adding one million numbers together is {sum(one_million)}!") print("\nfinished")
4418ca32623c1494633e5e78ab8d4ba716b93087
leetuckert10/CrashCourse
/chapter_9/exercise_9-14.py
421
3.6875
4
# Exercise 9:14: Lottery # # Create a list or tuple contain 10 numbers and 5 letters. Using choice(), # randomly select 4 values to generate a lottery ticket. from random import choice lottery_numbers = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd') ticket = "" for x in range(1, 7): ticket += choice(lottery_numbers) print(f"The winning number is: {ticket.upper()}...")
2f8d761707c15cef64f9e8b49aae03c733959d00
leetuckert10/CrashCourse
/chapter_9/exercise_9-6.py
1,668
4.375
4
# Exercise 9-6: Ice Cream Stand # Write a class that inherits the Restaurant class. Add and an attribute # called flavors that stores a list of ice cream flavors. Add a method that # displays the flavors. Call the class IceCreamStand. from restaurant import Restaurant class IceCreamStand(Restaurant): def __init__(self, name, cuisine, flavors=None): super().__init__(name, cuisine) self.flavors = flavors def add_flavor(self, flavor): """This method adds an ice cream flavor to the the flavors list.""" self.flavors.append(flavor) def remove_flavor(self, flavor): """This mehtod removes a flavor from the list of ice cream flavors.""" self.flavors.remove(flavor) def show_flavors(self): """This method displays all the flavors available at the ice cream stand.""" print("Available ice cream flavors are: ", end="") for flavor in self.flavors: if flavor == self.flavors[-1]: print(f"{flavor.title()}.", end="") else: print(f"{flavor.title()}, ", end="") print("") flavors = ["chocolate","vanilla","strawberry"] ics = IceCreamStand("Terry's Ice Cream Shop", "Ice Cream", flavors) ics.show_flavors() print("\nAdding new flavors!") ics.add_flavor("butter pecan") ics.add_flavor("cookie dough") ics.add_flavor("carmal") ics.show_flavors() print("\nOops! Out of Butter Pecan because Terry ate it all!\n") ics.remove_flavor("butter pecan") ics.show_flavors() ics.set_number_served(238_449) # Showing that we have this attribute from Restaurant. print(f"We have served {ics.number_served} customers!")
df70e46cceaa083c3a0545af8eb83463295b0b40
leetuckert10/CrashCourse
/chapter_11/test_cities.py
1,339
4.3125
4
# Exercise 11-1: City, Country # # Create a file called test_city.py that tests the function you just wrote. # Write a method called test_city_country() in the class you create for testing # the function. Make sure it passes the test. # # Remember to import unittest and the function you are testing. Remember that # the test class should inherit unittest.TestCase. Remember that the test # methods in the class need to begin with the word 'test' to be automatically # executed. import unittest from city_functions import get_formatted_city_country class CityCountryNameTestCase(unittest.TestCase): """Tests get_formatted_city_country().""" def test_city_country(self): """Do names like santiago chile work?""" formatted_city_country = get_formatted_city_country('santiago', 'chile') self.assertEqual(formatted_city_country, "Santiago, Chile") def test_city_country_population(self): """Does a city name, a country name, and a population work?""" formatted_city_country = get_formatted_city_country('santiago', 'chile', 50_000_000) self.assertEqual(formatted_city_country, "Santiago, Chile - " "Population 50000000") if __name__ == '__main__': unittest.main()
b678820b88d80d9ab8c120a620e441f75d457d4c
leetuckert10/CrashCourse
/chapter_9/user.py
3,202
4.125
4
"""A set of clases that can be used to represent users, specialized users and privileges.""" class User: """The User class is a simple attempt to model a computer user.""" def __init__(self, user_id, first_name, last_name, address_1=None, address_2=None, city=None, state=None, zip=None): """Initialize User attributes.""" self.user_id = user_id self.first_name = first_name self.last_name = last_name self.address_1 = address_1 self.address_2 = address_2 self.city = city self.state = state self.zip = zip self.login_attempts = 0 def describe_user(self): """Print out a description of User attributes.""" print(f"The user's id is: {self.user_id}.") print(f"Full name is {self.first_name.title()} {self.last_name.title()}.") print(f"{self.first_name.title()} lives in {self.city} in {self.state}") print(f"\tat {self.address_2}") if self.address_1: print(f"\tat {self.address_1}") print(f"Login attempts: {self.login_attempts}.") def greet_user(self): """Greet the user with a personalized message.""" print(f"Greetings {self.first_name.title()}! Glad to see you!") def increment_login_attempts(self): """This method increments the value of login_attempts by one.""" if self.login_attempts == 3: print(f"Maximum number of login attempts has been reached. " f"Please contact your system administrator.") else: self.login_attempts += 1 def reset_login_attempts(self): """This method resets the value of login_attempts to zero.""" self.login_attempts = 0 class Privileges: """This class models privileges that a user can have.""" def __init__(self, privileges=[]): self.privileges = privileges def set_privilege(self, privileges): """This method sets privileges for the admin user.""" self.privileges = privileges def add_privilege(self, privilege): """This method appends a privilege to the end of the privileges list.""" self.privileges.append(privilege) def remove_privilege(self, privilege): """This method removes privileges from the Admin user.""" if privilege in self.privileges: self.privileges.remove(privilege) def show_privileges(self): print("Privileges: ", end="") for privilege in self.privileges: if privilege == self.privileges[-1]: print(f"{privilege}.", end="") else: print(f"{privilege}, ", end="") print("") class Admin(User): """This class inherits User and is used to represent the specialized user Admin.""" def __init__(self, userid, first_name, last_name, privileges=[]): super().__init__(userid, first_name, last_name) self.privileges = Privileges(privileges) def describe_user(self): """This method displays the information we have on a user.""" super().describe_user() self.privileges.show_privileges()
b2df32b33c07286f9bf610a570903dbd6538ddf1
leetuckert10/CrashCourse
/DataVisualization/chapter_15/exercise_15-1.py
836
4.03125
4
# Exercise 15-1: Plot the first five cubic numbers and then plot the first # 5000 cubic numbers. import matplotlib.pyplot as plt # type: ignore from typing import List upper_bound: int = 5001 input_values: range = range(1, upper_bound) cubes: List[int] = [x**3 for x in range(1, upper_bound)] # Set the plot style. plt.style.use("bmh") fig, ax = plt.subplots() #ax.plot(input_values, cubes, linewidth=1, c='blue') # Emphasize certain points. ax.scatter(input_values, cubes, c=input_values, cmap=plt.cm.get_cmap( 'plasma'), s=10) # Setting labels and font sizes ax.set_title("Cubed Number", fontsize=24) ax.set_xlabel("Value", fontsize=14) ax.set_ylabel("Cube of Value", fontsize=14) ax.scatter(input_values, cubes, s=2) # Set size of tick labels. ax.tick_params(axis='both', which='major', labelsize=14) plt.show()
82779034d745269ff23f4effee830c70eae6b9b5
leetuckert10/CrashCourse
/chapter_4/exercise_4-9.py
269
3.84375
4
# Cube Comprehension # Make a list of the first 10 cubes using list comprehension. cubes = [value**3 for value in range(1, 11)] # list comprehension for value in cubes: # check out this syntax for suppressing a new line. print(value, " ", end="") print("\nfinished")
4b396840502cab41a8b3e75eb0e28250954546da
leetuckert10/CrashCourse
/chapter_10/exercise_10-9.py
439
3.796875
4
# Exercise 10-9: Silent Cats and Dogs # # Modify the except block in Exercise 10-8 to fail silently if either file is # missing. cats_file = 'cats.txt' dogs_file = 'dogs.txt' try: with open(cats_file) as cats: contents = cats.read() except FileNotFoundError: pass else: print(contents) try: with open(dogs_file) as dogs: contents = dogs.read() except FileNotFoundError: pass else: print(contents)
2114dd90d264f1ea5f77ea0f8444eb15957dd978
leetuckert10/CrashCourse
/chapter_9/exercise_9-5.py
775
3.640625
4
# Exercise 9-5: Login Attempts # This program uses the User class in user.py. Added the attribute # login_attempts and a method for increment by one. Also added a method to # rest to zero. from user import User #import user as u u1 = User("leetuckert", "terry", "tucker") u1.address_2 = "1690 Macedonia Church Rd." u1.city = "Sparta" u1.state = "NC" u1.zip = "28675" u1.describe_user() print("") u1.increment_login_attempts() # One attempt. u1.describe_user() print("") u1.increment_login_attempts() # Two attempts. u1.increment_login_attempts() # Three attempts, max for you buddy... u1.increment_login_attempts() # Class will generate an error. print("") u1.describe_user() print("") u1.reset_login_attempts() u1.describe_user() print("") u1.greet_user()
f4f669c12f07d0320e5d9a01fec7542e249d4962
leetuckert10/CrashCourse
/chapter_4/exercise_4-10.py
539
4.5625
5
# Slices # Use list splicing to print various parts of a list. cubes = [value**3 for value in range(1, 11)] # list comprehension print("The entire list:") for value in cubes: # check out this syntax for suppressing a new line. print(value, " ", end="") print('\n') # display first 3 items print(f"The first three items are: {cubes[:3]}") # display items from the middle of the list print(f"Three items beginning at index 3 are: {cubes[3:6]}") # display last three items in list print(f"The last three items are: {cubes[-3:]}") print()
86b4f7e1bfe9621bd3eff200a94e0cb2cfac364c
leetuckert10/CrashCourse
/chapter_6/exercise_6-10.py
851
4.03125
4
# Favorite Numbers Modified # Store the favorite number of five people in a dictionary using their # name as the key. In this version we have added a list of numbers. favorite_nums = { 'terry': [18, 21, 41, 60], 'carLee': [12, 16, 21, 25], 'linda': [16, 12, 44], 'rebekah': [21], 'nathan': [42, 25, 30, 35], } for name, numbers in favorite_nums.items(): if numbers: print(f"{name.title()}'s favorite numbers are:") print("\t", end="") # print tab with no newline for number in numbers: # doing trailing comma control... if number == numbers[-1]: # [-1] returns last item in list print(f"{number}", end="") else: print(f"{number}, ", end="") else: print(f"{name} has no favorite numbers defined.") print("\n")
1897ec6770bca8f6e0dc72abbcdcd70644e6f182
leetuckert10/CrashCourse
/chapter_8/exercise_8-14.py
764
4.3125
4
# Exercise 8-13: Cars # Define a function that creates a list of key-value pairs for all the # arbitrary arguments. The syntax **user_info tell Python to create a # dictionary out of the arbitrary parameters. def make_car(manufacturer, model, **car): """ Make a car using a couple positional parameters and and arbitrary number of arguments as car. """ car['manufacturer'] = manufacturer car['model'] = model return car def print_car(car): """ Print out key/value pairs in the user profile dictionary.""" for key, value in car.items(): print(f"{key}: {value}") car = make_car('Chevrolett', 'Denali', sun_roof=True, heated_sterring_wheel=True, color='Black', towing_package=True, ) print_car(car)
997df0520551de4bfb67665932840b09fa1a6d5a
leetuckert10/CrashCourse
/chapter_6/exercise_6-9.py
1,229
4.21875
4
# Favorite Places: # Make a dictionary of favorite places with the persons name as the kep. # Create a list as one of the items in the dictionary that contains one or # more favorite places. favorite_places = { 'terry': ['wild cat rock', 'mount mitchell', 'grandfather mountain'], 'carlee': ['blue ridge parkway', 'tweetsie', 'boone', 'carter falls', 'cave', 'burger king'], 'linda': ['thrift store', 'home', 'little switzerland', 'sparta'], 'rebekah': [], # let's have one blank and know how to check it } # If you leave off items, the default behavior of the for loop is to # return the key and the value. # for name, place in favorite_places.items(): for name, places in favorite_places.items(): if places: print(f"{name.title()} has {len(places)} favorite places:") print("\t", end="") for place in places: # doing trailing comma control... if place == places[-1]: # [-1] returns last item in list print(f"{place.title()}", end="") else: print(f"{place.title()}, ", end="") else: print(f"{name.title()} doesn't have any favorite places defined yet.") print("\n")
ab6b62451de82d2c52b1b994cfabab7893c4f64e
leetuckert10/CrashCourse
/chapter_8/exercise_8-3.py
541
4.125
4
# Exercise 8-3: T-Shirt # Write a function called make_shirt() that accepts a size and a string for # the text to be printed on the shirt. Call the function twice: once with # positional arguments and once with keyword arguments. def make_shirt(text, size): print(f"Making a {size.title()} T-Shirt with the text '{text}'...") make_shirt('Love You', 'large') # positional arguments # use keyword arguments: note the order does not matter make_shirt(text="Love YOU", size='Medium') make_shirt(size='extra large', text='Love YOU')
6a514ad94f999c1840fbffd3ea153bf8a1b22e47
leetuckert10/CrashCourse
/chapter_9/exercise_9-9.py
3,738
4.46875
4
# Exercise 9-9: Battery Upgrade # Using the example in the text defining a Car class and a Battery class, # create a new method that upgrades the battery from 75kWh to 100kWh. class Car: """A simple attempt to model a car.""" def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odomoeter = 0 print("Car constructor...") def get_descriptive_name(self): """Return a long descriptive name of the car.""" long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """Display the miles on the car.""" print(f"This car has {self.odomoeter} miles on it.") def update_odometer(self, miles): """Update the odometer insuring that we are not rolling the odometer back.""" if miles < self.odomoeter: print("You cannot roll back the odomoeter!") else: self.odomoeter += miles def increment_odomoter(self, miles): """Increment the odomoter by the miles argument insuring that the mileage passed is not negative.""" if miles > 0: self.odomoeter += miles else: print("You cannot roll back the odometer with a negative number!") class ElectricCarBattery: """A simple attempt to model an electric car battery.""" def __init__(self, size=75): self.size = size print("ElectricCarBattery constructor...") def describe_battery(self): """Print a message describing the battery.""" print(f"The battery size is {self.size}-kWh.") def upgrade_battery(self, size): """Upgrade the battery size insuring that the input we are getting is valid.""" if size != 100: print("Upgrade size can only be 100-kWh.") elif self.size == 100: print("Battery all upgraded to 100-kWh.") else: print("Battery upgraded to 100-kWh.") def show_range(self): """Display the mileage range of the car based on the battery size.""" if self.size == 75: range = 260 elif self.size == 100: range = 315 print(f"Range with {self.size}-kWh battery is {range} miles.") class ElectricCar(Car, ElectricCarBattery): """This class uses multiple inheritance to make a simple attempt to model and electric car.""" def __init__(self, make, model, year, battery_size=75): print("ElectricCar constructor...") Car.__init__(self, make, model, year) # doing it this way calls the Car constructor # super().__init__(make, model, year) ElectricCarBattery.__init__(self, battery_size) def test_car(): """Function for testing the Car class.""" car = Car("gmc", "denali yukon xl", 2012) description = car.get_descriptive_name() print(description) print("") car.read_odometer() print("") car.update_odometer(85_927) car.read_odometer() print("") print("Try to roll back the odomoeter to 60,999:") car.update_odometer(60_999) print("") print("Increment miles by 75 miles:") car.increment_odomoter(75) car.read_odometer() print("") print("Increment miles by a negative number:") car.increment_odomoter(-75) def test_electric_car(): """Function for testing the ElectricCar class.""" electric_car = ElectricCar("gmc", "denali yukon xl", 2012, 100) electric_car.describe_battery() print("") print("Try to upgrade to a value not recognized by ElectricCarBattery.") electric_car.upgrade_battery(60) print("") electric_car.show_range() #test_car() test_electric_car()
7dd4f0340dbcb616851c1872561e7c5b30ce5137
jcorb/bookstore_dashboard
/app/main.py
5,916
3.578125
4
import pandas as pd import numpy as np from bokeh.models import ColumnDataSource, HoverTool, Range1d, Div from bokeh.plotting import figure, curdoc from bokeh.layouts import column, row, widgetbox from bokeh.models.widgets import Select, Slider import os """ This code uses Bokeh and Pandas to display the top sellers based upon category for a bookstore TODO: add time series plot of top sellers """ def category_selector(attr, old, new): '''Update the plot when the category selection, date range, or number of top sellers is changed''' day_min = "2015-11-" + str(30 - day_slider.value).zfill(2) if cat_select.value == 'All': top_sales = sales[(sales["Invoice Date"] > day_min) & (sales["Invoice Date"] <= day_max)]['Title'].value_counts()[0:n_slider.value] else: top_sales = sales[(sales["Invoice Date"] > day_min) & (sales["Invoice Date"] <= day_max)]['Title'][sales.Category == cat_select.value].value_counts()[0:n_slider.value] no_data_text.visible = False top_sales = top_sales.to_frame() if top_sales.empty: #handle the case in which there is no data for the selection top_sales = pd.DataFrame({"Title":0}, index=['']) text_cds.data = ColumnDataSource(dict(x=[0.5], y=[''],text=['No Data'])).data no_data_text.visible = True top_sales.reset_index(inplace=True) top_sales.rename(columns={'index': 'title', 'Title': 'sales'}, inplace=True) top_sales['short_title'] = top_sales['title'].apply(trim_title) top_counts_plot.y_range.factors = top_sales.short_title.values.tolist()[::-1] top_counts_plot.x_range.end = np.max(top_sales.sales) + 1 top_sales_cds.data = ColumnDataSource(data=dict(titles=top_sales.short_title, counts=top_sales.sales, fulltitle=top_sales.title)).data def trim_title(str_x): '''Checks if string is longer than 30 characters, if it is it trims it to 27 and adds '...' ''' if len(str_x) > 30: str_x = str_x[0:27] + '...' return str_x else: return str_x div = Div(text="""<h1>Bookstore Dashboard</h1> The graph below interactively displays the top selling books by category for a bookstore over a number of days. <h3>To use:</h3> <ol> <li>Select the category you wish to display from the drop-down menu, or select "all" for all categories</li> <li>Use the "Last N Days" slider to select the number of days over which you want to determine the top-sellers. <i>Note: For this example it will display the top-sellers over the "N" number of days prior to November 30th 2015</i></li> <li>Use the "Number of Top Sellers" slider to select the number of top-sellers you want to display (1-25)</li> </ol> Changing any of these will update the plots to reflect the new selections. If the full title is not displayed, hover the mouse over the bar to display the full title. <i>Note: In order to anonymize the sales data the words in the book titles were randomly replaced, thus the titles are just jibberish.</i> """, width=600, height=285) ## Load the sales file sales_file = os.path.join(os.path.dirname(__file__), 'data', 'bookstore_clean_dataset.csv') sales = pd.read_csv(sales_file, parse_dates=['Invoice Date'], dayfirst=True) ## set up some selection widgets # Select by category options = ['All'] + sales['Category'].unique().tolist() cat_select = Select(title="Category:", value="All", options=options) cat_select.on_change('value', category_selector) #Select the number of days over which to display day_slider = Slider(start=1, end=29, value=29, step=1, title="Last N Days") day_slider.on_change('value', category_selector) day_max = "2015-11-30" #make this dynamic day_min = "2015-11-" + str(30 - day_slider.value).zfill(2) #Select the number of top-sellers to display n_slider = Slider(start=1, end=25, value=10, step=1, title="Number of Top Sellers") n_slider.on_change('value', category_selector) ## Calculate top sellers top_sales = sales[(sales["Invoice Date"] > day_min) & (sales["Invoice Date"] <= day_max)]['Title'].value_counts()[0:n_slider.value] top_sales = top_sales.to_frame() top_sales.reset_index(inplace=True) top_sales.rename(columns={'index':'title', 'Title':'sales'}, inplace=True) top_sales['short_title'] = top_sales['title'].apply(trim_title) top_sales_cds = ColumnDataSource(data=dict(titles=top_sales.short_title, counts=top_sales.sales, fulltitle=top_sales.title)) hover = HoverTool( tooltips=[("Title", "@fulltitle"), ("Sales", "@counts")]) top_counts_plot = figure(title="Top Sellers", x_axis_label='Sales', tools=[hover], toolbar_location='right', y_range=top_sales.short_title.values.tolist()[::-1], x_range=[0,np.max(top_sales.sales) + 5]) text_cds = ColumnDataSource(dict(x=[0], y=[0],text=['No Data'])) # Add the year in background (add before circle) no_data_text = top_counts_plot.text(x='x', y='y', text='text', text_color='tomato',alpha=1.0, text_font_size='30pt', text_baseline='middle',text_align='center', source=text_cds) no_data_text.visible = True top_counts_plot.hbar(y='titles', height=0.3, left=0, right='counts', source=top_sales_cds, color="deepskyblue" ) layout = column(widgetbox(div), row(widgetbox(cat_select, width=200), widgetbox(day_slider, width=200), widgetbox(n_slider, width=200)), top_counts_plot) curdoc().add_root(layout) curdoc().title = "Bookstore Dashboard"
928d97a0023a0a64773fb1df4c1e59bc20f01123
algorithms-21-devs/Interview_problems
/weekly_interview_questions/IQ_4/Q4_emmanuelcodev/Q4Medium_N.py
1,840
4.25
4
import node as n ''' Time complexity: O(n) Algorithm iterates through link list once only. It adds memory location as a key to a dictionary. As it iterates it checks if the current node memory matches any in the dictionary in O(1) time. If it does a cycle must be present. ''' def cycle(head_node): #must be a linked list if head_node is None: raise Exception('Cannot process an empty linked list') current_node = head_node nodes_dic = {}#stores memory locations as keys and data of node as value #iterate through the list once while current_node is not None: if current_node not in nodes_dic:#put in dictionary if node is not in dic nodes_dic[current_node] = current_node.data else:#we found a node twice meaning there is a cycle return True current_node = current_node.next#make sure we iterate through the list return False #Testing node_a = n.Node('A') node_b = n.Node('B') node_c = n.Node('C') node_d = n.Node('D') l1 = node_a l1.next = node_b l1.next.next = node_c l1.next.next.next = node_d l1.next.next.next.next = node_b #cycle print(cycle(l1)) node_a = n.Node('A') node_b = n.Node('B') node_c = n.Node('C') node_d = n.Node('D') #'A'->'B'-->'C'->'D'->'B' (different node with data b) l2 = node_a l2.next = node_b l2.next.next = node_c l2.next.next.next = node_d l2.next.next.next.next = n.Node('B') #cycle print(cycle(l2)) node_a = n.Node('A') node_b = n.Node('B') node_c = n.Node('C') node_d = n.Node('D') #your_function('A') returns False l3 = node_a print(cycle(l3)) node_a = n.Node('A') node_b = n.Node('B') node_c = n.Node('C') node_d = n.Node('D') #your_function('A'->'B'-->'C') returns False l4 = node_a l4.next = node_b l4.next.next = node_c print(cycle(l4)) #your_function(none) returns Exception l5 = None print(cycle(l5))
7248c2bc7108c4eff0f07f3171dab62000651988
algorithms-21-devs/Interview_problems
/weekly_interview_questions/IQ_5/Q5_maguil53/Q5Medium_O(logn).py
640
4.03125
4
# Time Complexity: O(n) def reverseIntArray(int_list): if int_list is None: raise Exception("Can't enter None") length = len(int_list) if length == 0: return None half = length // 2 for i in range(half): temp = int_list[i] # Swap element on left with one on the right int_list[i] = int_list[length - 1 - i] # Swap element on right with one on the left int_list[length - 1 - i] = temp return int_list print(reverseIntArray([5, 6, 9, 2])) print(reverseIntArray([-3, 4])) print(reverseIntArray([0])) print(reverseIntArray([])) print(reverseIntArray(None))
4374c169c241a96ef6fc26f74a3c514f4cc216ed
algorithms-21-devs/Interview_problems
/weekly_interview_questions/IQ_2/Q2_Emmanuelcodev/Q2Medium_Nsquared.py
2,634
4.1875
4
def unique_pairs(int_list, target_sum): #check for None ''' Time complexity: O(n^2). 1) This is because I have a nested for loop. I search through int_list, and for each element in int_list I search through int_list again. N for the outer and n^2 with the inner. 2) The second part of my algorithm which iteraters through the pairs and checks a dictionary is done in O(n) time. for x in pairs: if x in upairs I am checking n items (b/c of pairs), at O(1) time due to upairs being a dictionary. Overall, highest cost is O(n^2) Space complexity: O(n) 1) I create another array and dictionary in the worst case n size. ''' if None in (int_list, target_sum): raise Exception("int_list and target_sum cannot be of NoneType") if len(int_list) < 2: return [] pairs = [] for x in int_list: duplicate = False #only count num if it occurs more than once, since second loop will count current num as as second instance due it starting from begining and first loop counitng it as the first INSTANCE for y in int_list: if x == y:#counts current num in second loop, any more occurances are duplicates and therefore valid if duplicate == False: duplicate = True else: if x + y == target_sum: pairs.append((x,y)) else: if x + y == target_sum:#if current num (x) and y together == target_sum, then append group pairs.append((x,y)) #have duplicate pairs need to clean data upairs = {} #print(pairs) for x in pairs: if x[0] < x[1]:# sorts tuple of size 2 , so n operationgs for entire loop if x in upairs: pass else: upairs[str(x)]=1 else: if (x[1],x[0]) in upairs: pass else: upairs[str((x[1],x[0]))]=1 pairs = [] for x in upairs.keys(): pairs.append(x) return pairs #duplicate pairs print(unique_pairs([1, 3, 2, 2,3,5,5], 4)) # Returns [(3,1),(2,2)] print(unique_pairs([3, 4, 19, 3, 4, 8, 5, 5], 6))#returns 1,1 print(unique_pairs([-1, 6, -3, 5, 3, 1], 2)) # Returns [(-1,3),(5,-3)] print(unique_pairs([3, 4, 19, 3, 3, 3, 3], 6)) # Returns [(3,3)] print(unique_pairs([-1, 6, -3, 5, 3, 1], 5000)) # Returns [] print(unique_pairs([], 10)) # Returns Exception print(unique_pairs([4],54)) #returns [] print(unique_pairs(None,54))# raises Exception
3c7b9f0575cd89c95c1eb4a91b6655ae84c31221
ZaxR/100-people-in-a-circle-with-gun-puzzle
/100-people-in-a-circle-with-gun-puzzle.py
990
3.5625
4
""" http://quiz.geeksforgeeks.org/puzzle-100-people-in-a-circle-with-gun-puzzle/: 100 people standing in a circle in an order 1 to 100. No. 1 has a gun. He kills the next person (i.e. No. 2) and gives the gun to the next (i.e. No. 3). All people do the same until only 1 survives. Which number survives at the last? There are 100 people starting from 1 to 100. """ from collections import deque #Iterative solution that optimizes time complexity using deque def find_winner(participants): assert isinstance(participants, int), "Input needs to be in an integer" remaining_participants = deque(i for i in range(1, participants+1)) while True: if len(remaining_participants) <= 1: return "The last survivor is particiant #{0}".format(remaining_participants[0]) else: remaining_participants.append(remaining_participants.popleft()) remaining_participants.popleft() # Pop sounds better than murder... print(find_winner(100))
21b935d316daacdd26b6ee02b1bcf5d4b449e462
serafdev/codewars
/merged_string_checker/code.py
440
4.125
4
def is_merge(s, part1, part2): return merge(s, part1, part2) or merge(s, part2, part1) def merge(s, part1, part2): if (s == '' and part1 == '' and part2 == ''): return True elif (s != '' and part1 != '' and s[0] == part1[0]): return is_merge(s[1:], part1[1:], part2) elif (s != '' and part2 != '' and s[0] == part2[0]): return is_merge(s[1:], part1, part2[1:]) else: return False
0e8601398a0c45de5e781febbc2b4f9f2d174321
mis813/Power_system_analysis
/line_data_2_matrix.py
2,366
3.5
4
import pandas as pd from pandas.io.parsers import read_csv def line2list(data): ##this function convert row in Data to list #Data Type is Dictionary l = len(data['From_Bus']) line = [] header = ['From_Bus','To_Bus','R','X','G','B','Max_Mvar','Y/2'] for i in range(1,l+1): temp = [] for h in header: temp.append(data[h][i]) line.append(temp) return line def read_line(): #s = read_csv("line_data.csv",delimiter=';') data = pd.read_csv("line_data.csv",delimiter=';', index_col=0, skiprows=0) print(data) data = data.to_dict() line = line2list(data) return line def max_line(data): # Keymax = max(data['BusB'], key= lambda x: data['BusB'][x]) # maxi = data['BusB'][Keymax] # Keymax = max(data['BusE'], key= lambda x: data['BusE'][x]) # maxj = data['BusE'][Keymax] # return max(maxi,maxj) l = len(data) temp = [] for i in range(0,l): temp.append(data[i][0]) temp.append(data[i][1]) m = max(temp) return m def YMatrix(data,Max): Y=[] temp = [] for i in range(0,Max): temp = [] for j in range(0,Max): temp.append(0) Y.append(temp) for k in range(0,len(data)): i = data[k][0]-1 j = data[k][1]-1 Y[i][j] = -(data[k][4]+data[k][5]*1j) Y[j][i]=Y[i][j] Y[i][i] = Y[i][i] -Y[i][j] + (data[k][7])*1j Y[j][j] = Y[j][j] -Y[i][j] + (data[k][7])*1j return Y def Save_matrix(data): file = open('matrix.csv','a') s = "Index;" for i in range(1,len(data)+1): s = s+str(i)+";" file.write(s[:len(s)-1]+"\n") l = 1 for line in data: stru = "" for i in range(0,len(data)): stru = stru+str(line[i])+";" stru = stru.replace('(','') stru = stru.replace(')','') if line == data[len(data)-1]: file.write(str(l)+";"+stru[:len(stru)-1]) else: file.write(str(l)+";"+stru[:len(stru)-1]+"\n") l= l +1 file.close line = read_line() Max = max_line(line) matris = YMatrix(line,Max) Save_matrix(matris) # print(matris)
a9052948120ec2afb1d52d3c104abd526418e92a
fantenuc/SI-206-Project-1
/206project1.py
5,350
3.59375
4
import os import filecmp def getData(file): #Input: file name #Ouput: return a list of dictionary objects where #the keys will come from the first row in the data. #Note: The column headings will not change from the #test cases below, but the the data itself will #change (contents and size) in the different test #cases. #Your code here: read_file = open(file, 'r') lst = [] for line in read_file.readlines()[1:]: dic = {} line = line.split(',') dic['First'] = line[0] dic['Last'] = line[1] dic['Email'] = line[2] dic['Class'] = line[3] dic['DOB'] = line[4].strip() lst.append(dic) #print(lst) return lst #Sort based on key/column def mySort(data,col): #Input: list of dictionaries #Output: Return a string of the form firstName lastName #Your code here: sorted_data = sorted(data, key = lambda x: x[col]) return sorted_data[0]['First'] + ' ' + sorted_data[0]['Last'] #Create a histogram def classSizes(data): # Input: list of dictionaries # Output: Return a list of tuples ordered by # ClassName and Class size, e.g # [('Senior', 26), ('Junior', 25), ('Freshman', 21), ('Sophomore', 18)] #Your code here: fresh = 0 soph = 0 jun = 0 senior = 0 for dic in data: if dic['Class'] == 'Freshman': fresh += 1 if dic['Class'] == 'Sophomore': soph += 1 if dic['Class'] == 'Junior': jun += 1 if dic['Class'] == 'Senior': senior += 1 lst = [] fresh_tuple = ('Freshman', fresh) lst.append(fresh_tuple) soph_tuple = ('Sophomore', soph) lst.append(soph_tuple) jun_tuple = ('Junior', jun) lst.append(jun_tuple) senior_tuple = ('Senior', senior) lst.append(senior_tuple) sorted_lst = sorted(lst, key = lambda x: x[1], reverse = True) return sorted_lst # Find the most common day of the year to be born def findDay(a): # Input: list of dictionaries # Output: Return the day of month (1-31) that is the # most often seen in the DOB #Your code here: day_count = {} for day in a: birthday = day['DOB'] day = birthday.split('/') num = day[1] if num not in day_count: day_count[num] = 1 else: day_count[num] += 1 day_lst = [] for key in day_count.keys(): day_tup = (key, day_count[key]) day_lst.append(day_tup) sorted_lst = sorted(day_lst, key = lambda x: x[1], reverse = True) return int(sorted_lst[0][0]) # Find the average age (rounded) of the Students def findAge(a): # Input: list of dictionaries # Output: Return the day of month (1-31) that is the # most often seen in the DOB #Your code here: year = [] ages = [] count = 0 for date in a: birthday = date['DOB'] year_born = birthday[-4:] years = int(year_born) year.append(years) for date in year: age = 2017 - date ages.append(age) for elem in ages: count += elem average_age = count // len(ages) return average_age #Similar to mySort, but instead of returning single #Student, all of the sorted data is saved to a csv file. def mySortPrint(a,col,fileName): #Input: list of dictionaries, key to sort by and output file name #Output: None #Your code here: sorted_data = sorted(a, key = lambda x: x[col]) #print(sorted_data) csv_file = open(fileName, 'w') for data in sorted_data: csv_file.write('{},{},{}\n'.format(data['First'], data['Last'], data['Email'])) csv_file.close() ################################################################ ## DO NOT MODIFY ANY CODE BELOW THIS ################################################################ ## We have provided simple test() function used in main() to print what each function returns vs. what it's supposed to return. def test(got, expected, pts): score = 0; if got == expected: score = pts print(" OK ",end=" ") else: print (" XX ", end=" ") print("Got: ",got, "Expected: ",expected) return score # Provided main() calls the above functions with interesting inputs, using test() to check if each result is correct or not. def main(): total = 0 print("Read in Test data and store as a list of dictionaries") data = getData('P1DataA.csv') data2 = getData('P1DataB.csv') total += test(type(data),type([]),40) print() print("First student sorted by First name:") total += test(mySort(data,'First'),'Abbot Le',15) total += test(mySort(data2,'First'),'Adam Rocha',15) print("First student sorted by Last name:") total += test(mySort(data,'Last'),'Elijah Adams',15) total += test(mySort(data2,'Last'),'Elijah Adams',15) print("First student sorted by Email:") total += test(mySort(data,'Email'),'Hope Craft',15) total += test(mySort(data2,'Email'),'Orli Humphrey',15) print("\nEach grade ordered by size:") total += test(classSizes(data),[('Junior', 28), ('Senior', 27), ('Freshman', 23), ('Sophomore', 22)],10) total += test(classSizes(data2),[('Senior', 26), ('Junior', 25), ('Freshman', 21), ('Sophomore', 18)],10) print("\nThe most common day of the year to be born is:") total += test(findDay(data),13,10) total += test(findDay(data2),26,10) print("\nThe average age is:") total += test(findAge(data),39,10) total += test(findAge(data2),41,10) print("\nSuccessful sort and print to file:") mySortPrint(data,'Last','results.csv') if os.path.exists('results.csv'): total += test(filecmp.cmp('outfile.csv', 'results.csv'),True,10) print("Your final score is: ",total) # Standard boilerplate to call the main() function that tests all your code. if __name__ == '__main__': main()
84ce96ecca9c72d6442f5eafe1afc7ace3dc1ba3
deepu14d/ScriptAllTheThings
/StrongPasswordGenerator/password_generator.py
604
3.8125
4
""" Strong Password Generator - Generates a secure random password Author: Skyascii (https://github.com/savioxavier) Date : 1/10/2021 """ import secrets import string def generate_password(length=12): """Generates a random password Args: length (int, optional): Length of the generated password. Defaults to 12. Returns: str: The output generated password """ req_str = string.ascii_letters + string.digits secure_pass = "".join((secrets.choice(req_str) for i in range(length))) return secure_pass print(f"Your password: {generate_password(12)}")
8aab690e36890037d72ae050a1b967dd6afd6d86
cnrooofx/CS2516
/lab1/merge_sort.py
844
3.78125
4
from random import randint def merge_sort(mylist): n = len(mylist) if n > 1: list1 = mylist[:n//2] list2 = mylist[n//2:] merge_sort(list1) merge_sort(list2) merge(list1, list2, mylist) def merge(list1, list2, mylist): f1 = 0 f2 = 0 while f1 + f2 < len(mylist): if f1 == len(list1): mylist[f1+f2] = list2[f2] f2 += 1 elif f2 == len(list2): mylist[f1+f2] = list1[f1] f1 += 1 elif list2[f2] < list1[f1]: mylist[f1+f2] = list2[f2] f2 += 1 else: mylist[f1+f2] = list1[f1] f1 += 1 def main(): to_sort = [] for i in range(20): to_sort.append(randint(i, 100)) merge_sort(to_sort) print(to_sort) if __name__ == "__main__": main()
f453f370b0e4fae667198c49361ad84564fb10fe
kathyz08/RoadTrppn
/app/gmaps_util.py
4,164
3.625
4
import googlemaps import time import json # https://stackoverflow.com/questions/15380712/how-to-decode-polylines-from-google-maps-direction-api-in-php def decode_polyline(polyline_str): index, lat, lng = 0, 0, 0 coordinates = [] changes = {'latitude': 0, 'longitude': 0} # Coordinates have variable length when encoded, so just keep # track of whether we've hit the end of the string. In each # while loop iteration, a single coordinate is decoded. while index < len(polyline_str): # Gather lat/lon changes, store them in a dictionary to apply them later for unit in ['latitude', 'longitude']: shift, result = 0, 0 while True: byte = ord(polyline_str[index]) - 63 index+=1 result |= (byte & 0x1f) << shift shift += 5 if not byte >= 0x20: break if (result & 1): changes[unit] = ~(result >> 1) else: changes[unit] = (result >> 1) lat += changes['latitude'] lng += changes['longitude'] coordinates.append((lat/100000.0, lng/100000.0)) return coordinates def get_gmaps_coordinates(start_location, end_location, time_interval, start_time=None): """ Returns a list of coordinates along a route, filtered by a time interval Arguments --------- start_location : string Starting place name or address end_location : string Ending place name or address time_interval : tuple (begin epoch time, end epoch time) start_time : float Epoch time when trip begins Returns ------- filtered_points : list List of dictionaries with arrival time as key and (latitude, longitude) tuple as value """ secret = open('app/gmaps_key.txt', 'r') gkey = secret.read() secret.close() gmaps = googlemaps.Client(key=gkey) start_loc = start_location end_loc = end_location t_interval = (time.time(), time.time()+7200) if start_time is None: time_start = time.time() else: time_start = start_time result = gmaps.directions(start_loc, end_loc, mode='driving', departure_time=time_start) # print(json.dumps(result, indent=4)) legs = result[0]['legs'] points = decode_polyline(result[0]['overview_polyline']['points']) interval_time = legs[0]['duration']['value']/len(points) current_time = time_start filtered_points = {} for index, p in enumerate(points): current_time += interval_time if index % 8 != 0: # arbitrarily use every 8th point continue if (current_time > t_interval[0] and current_time < t_interval[1]): filtered_points[current_time] = (p[0], p[1]) # print("Lat: {} Long: {} Time: {}".format(p[0], p[1], current_time)) return filtered_points def get_gmaps_directions(start_location, end_location, start_time=None): """ Returns directions to a location Arguments --------- start_location : string Starting place name or address end_location : string Ending place name or address start_time : float Epoch time when trip begins Returns ------- directions : list Directions to the final location """ secret = open('app/gmaps_key.txt', 'r') gkey = secret.read() secret.close() gmaps = googlemaps.Client(key=gkey) start_loc = start_location end_loc = end_location if start_time is None: time_start = time.time() else: time_start = start_time result = gmaps.directions(start_loc, end_loc, mode='driving', departure_time=time_start) steps = result[0]['legs'][0]['steps'] directions = [] for s in steps: directions.append(s['html_instructions']) return directions # print(get_gmaps_directions('Vanderbilt University', 'Klaus Advanced Computing Center', time.time())) # print(get_gmaps_coordinates('Vanderbilt University, Nashville', 'Klaus Advanced Computing Center, Atlanta', (time.time(), time.time()+3600)))
12f8122c6fe4bca4c5d777534bbe4d87c63318d2
judyliou/LeetCode
/python/1108. Defanging an IP Address.py
442
3.53125
4
def defangIPaddr(self, address): defanged = '' for i in address: if i == '.': defanged += '[.]' else: defanged += i return defanged def defangIPaddr(self, address): return address.replace('.', '[.]') def defangIPaddr(self, address): add_split = address.split('.') new = '[.]'.join(add_split) return new
3e0c28d7e45a59c4911da3272e0fc85f1a9ee2f9
judyliou/LeetCode
/python/169. Majority Element.py
965
3.875
4
# Solution 1: Count with dict # Time Complexity: O(n), Space Complexity: O(n) def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ cnt = {} for i in nums: cnt[i] = cnt.get(i, 0) + 1 for k, v in cnt.items(): if v > len(nums) // 2: return k # Solution 2: Sorting # Time Complexity: O(nlogn), Space Complexity: O(n) def majorityElement(self, nums): nums.sort() return nums[len(nums)//2] # Solution 3: Divide and Conquer # Time Complexity: O(nlogn), Space Complexity: O(logn) def majorityElement(self, nums): if len(nums) == 1: return nums[0] left = self.majorityElement(nums[:len(nums)//2]) right = self.majorityElement(nums[len(nums)//2:]) if left == right: # if two side agree on the majority return left else: # otherwise, count one of the elements to decide return [left, right][nums.count(right) > len(nums)//2]
7e8f873e5aa3d44ba662c4a88c28e254ba6cd1db
CTEC-121-Spring-2020/mod-2-programming-assignment-gromo2
/Template.py
3,276
4.09375
4
""" CTEC 121 <Garrett> <Mod 2 Programming Assignment> <assignment/lab description """ """ IPO template Input(s): list/description Process: description of what function does Output: return value and description """ from math import * import math def main(): #Assignment Statements print() exampleString = "Here is some example text." print(exampleString) print(type(exampleString)) exampleInt = 8 print() print(exampleInt) print(type(exampleInt)) print() print("\n example formula") r = 5 v = (4/5)*pi*r**2 print("v:",v) #End and sep examples print() print("Here is some example text", end="_") print('1', '2', '3', sep="_") #Tab, quote, and backslash print() print("\t \"Example text\\!\"") #Input from user print() myString = input("Enter text: ") print(myString) print() myInt = int(input("Enter a number: ")) #Only numbers are accepted print(myInt) print() myFloat = float(input("Enter a decimal number: ")) #Only numbers with decimals should be accepted print(myFloat) print() myEval = eval(input("Enter an expression: ")) print(myEval) #Simultaneous Assignment print() x, y = eval(input("Enter two numbers separated by a comma: ")) print(x,y) print() x, y = input("Enter two numbers: ").split() print(x,y) #Integer Arithmetic print() x = 5/2 print(x) print() y = 5%2 print(y) #Definite Loops print() for i in [5, 3, 2]: print(i) print() for count in range(3): print(count) print() for i in range(11,26,3): print(i) #Demonstrating use of various functions, expressions, and values print("Here is pi!") print(math.pi) print() x = int(input("Enter a value for x to find the square root: ")) print(math.sqrt(x)) print() print("Here is pi rounded up!") print(math.ceil(math.pi)) print() print("Here is pi rounded down!") print(math.floor(math.pi)) #Square and Cube values print() x = int(input("Enter a value of x to square: ")) print(x**2) print() y = int(input("Enter a value of y to cube: ")) print(y**3) #Accumulator Pattern print() a, b, c, d = eval(input("Enter values for a, b, c, d, separated by commas: ")) sum = 0 for i in [a, b, c, d]: sum = sum + i print(sum) #Bonus! print() r = int(input("Enter a value for r to find the volume: ")) V = (4/3)*pi*(r**3) print(V) print() r = int(input("Enter a value for r to calculate area: ")) A = 4*pi*(r**2) print(A) print() x1, y1, x2, y2 = eval(input("Enter values for x1, y1, x2, and y2, separated by commas to calculate slope: ")) m = ((y2-y1)/(x2-x1)) print(m) print() a, b, c = eval(input("Enter values for a, b, and c, separated by commas to calculate s: ")) s = (a+b+c)/2 print(s) print() s, a, b, c = eval(input("Enter values for s, a, b, and c, separated by commas to calculate A: ")) A = sqrt(s*(s-a)*(s-b)*(s-c)) print(A) print() print("End of assignment.") main()
fc748f366fdae31f941ca0779b96d3a962955388
Aloi-6/Sudoku
/a.py
976
3.78125
4
rows = 'ABCDEFGHI' cols = '123456789' def cross(A, B): "Cross product of elements in A and elements in B." return [i+j for i in A for j in B] boxes = cross(rows, cols) row_units = [cross(r, cols) for r in rows] column_units = [cross(rows, c) for c in cols] square_units = [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')] unitlist = row_units + column_units + square_units units = dict((s, [u for u in unitlist if s in u]) for s in boxes) peers = dict((s, set(sum(units[s],[]))-set([s])) for s in boxes) def find_naked_twins(values, ls): """ given a list of units, find naked twins args: values(dict): a dictionary of the form {'box_name': '123456789', ...} ls: a list of lists of units (rows or columns or squares) """ for sub_list in ls: unit_values = [x for x in values[unit] for unit in sub_list] print(sub_list) print("hi") exit(0) d = ['4', '5', '8', '2379', '379', '23', '1', '5', '23']
8c586b54b079fbed0cacdd9daaec909738fe1696
zzclynn/Swiss-Tournament-Result
/tournament.py
4,023
3.671875
4
#!/usr/bin/env python # # tournament.py -- implementation of a Swiss-system tournament # import psycopg2 def connect(): """Connect to the PostgreSQL database. Returns a database connection.""" return psycopg2.connect("dbname=tournament") def deleteMatches(): """Remove all the match records from the database.""" conn=connect() curs=conn.cursor() curs.execute("UPDATE player SET player_matchs = 0, player_wins = 0") conn.commit() conn.close() def deletePlayers(): """Remove all the player records from the database.""" conn=connect() curs=conn.cursor() curs.execute("DELETE FROM player") conn.commit() conn.close() def countPlayers(): """Returns the number of players currently registered.""" conn=connect() curs=conn.cursor() curs.execute("SELECT count(*) as num from player") num=curs.fetchone()[0] conn.close() return num def registerPlayer(name): """Adds a player to the tournament database. The database assigns a unique serial id number for the player. (This should be handled by your SQL database schema, not in your Python code.) Args: name: the player's full name (need not be unique). """ conn=connect() curs=conn.cursor() curs.execute("INSERT INTO player (player_name) VALUES (%s)",(name,)) conn.commit() conn.close() def playerStandings(): """Returns a list of the players and their win records, sorted by wins. The first entry in the list should be the player in first place, or a player tied for first place if there is currently a tie. Returns: A list of tuples, each of which contains (id, name, wins, matches): id: the player's unique id (assigned by the database) name: the player's full name (as registered) wins: the number of matches the player has won matches: the number of matches the player has played """ conn=connect() curs=conn.cursor() curs.execute( "SELECT player_id, player_name, player_wins, player_matchs FROM \ player ORDER BY player_wins DESC") table=curs.fetchall() conn.close() return table def reportMatch(winner, loser): """Records the outcome of a single match between two players. Args: winner: the id number of the player who won loser: the id number of the player who lost """ conn=connect() curs=conn.cursor() curs.execute( "UPDATE player SET player_matchs = player_matchs + 1, \ player_wins = player_wins + 1 \ WHERE player_id = (%s)", (winner,)) curs.execute( "UPDATE player SET player_matchs = player_matchs + 1 \ WHERE player_id = (%s)", (loser,)) conn.commit() conn.close() def swissPairings(): """Returns a list of pairs of players for the next round of a match. Assuming that there are an even number of players registered, each player appears exactly once in the pairings. Each player is paired with another player with an equal or nearly-equal win record, that is, a player adjacent to him or her in the standings. Returns: A list of tuples, each of which contains (id1, name1, id2, name2) id1: the first player's unique id name1: the first player's name id2: the second player's unique id name2: the second player's name """ conn=connect() curs=conn.cursor() curs.execute( "SELECT player_id, player_name FROM \ player ORDER BY player_wins DESC") table=curs.fetchall() conn.close() # Store the selected data to the result list in a manner described above result=[] pair=[] pair_flag=False # The pair_flag decide every two players will be saved in a pair list. for row in table: for item in row: pair.append(item) if pair_flag: result.append(pair) pair=[] pair_flag=not pair_flag return result
586fb03d59826b643f5aa85b73c33d838c298356
abhising10p14/Image_processing_face_detection
/Faces/face_recognization_dlib_faces.py
3,959
3.5
4
import sys import dlib import numpy as np import cv2 # importing opencv which is c++ library for image processing from skimage import io # skimage is a python library for image processing '''The histogram of oriented gradients (HOG) is a feature descriptor used in computer vision and image processing for the purpose of object detection. The technique counts occurrences of gradient orientation in localized portions of an image. This method is similar to that of edge orientation histograms, scale-invariant feature transform descriptors, and shape contexts, but differs in that it is computed on a dense grid of uniformly spaced cells and uses overlapping local contrast normalization for improved accuracy. It actually calculates graident relatively to the nearby cells of the blocks of the image. https://www.youtube.com/watch?v=Dl5lPdoCXi8 Gradient points in the direction of most rapid increase in intensity Edge detection -> the point where there isa change in the intensity of the image . i.e from high to low or vice versa https://www.youtube.com/watch?v=V2z_x80xPzI Ramp edege and sharp edege ''' ''' How image is stored as data ? Resolution -> Dimension by which we can measure how many pixels are on the screen Density -> Allows you t store the same resolution image on different screen size A single pixel consists of three components of RED,GREEN and Blue colors which range from 0-255 . 0 is very dark and 255 would be very bright Triplets of these values together can roduce a single pixel for exapmle (255,255,255) will give you a value of pixel whose color is WHITE An Image file whether is a JPEG,GIF,PNG contains millions of these RGB triplets. All these data is stored as a bit i.e '0' or '1' Each color chanel of a RGB is represented by 8 bits i.e 1 BYTEas it ranges from 0-255.For example the RGB value of the color TURQUOISE are (64,224,208) respectively. A computer would store this as R:01000000 G:11100000 B:11010000 When the same data is stored in Hexadecimal : 40 E0 D0 which is way lot shorter How do we change the tone of colors? We just pass the RGB data of the image and pass it to a mapping function which changes the tone of the color as described in that function ''' file_name = "pic4.jpg" # Create a HOG face detector using the built-in dlib class face_detector = dlib.get_frontal_face_detector() #face_detector= dlib.cnn_face_detection_model_v1("mmod_human_face_detector.dat") # for side face detection side_face_cascade = cv2.CascadeClassifier('haarcascade_profileface.xml') win = dlib.image_window() # A window used to display the image # Load the image into an array image = io.imread("pic4.jpg") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Run the HOG face detector on the image data. # The result will be the bounding boxes of the faces in our image. detected_faces = face_detector(image, 1) side_faces = side_face_cascade.detectMultiScale(gray,1.1,5) print("I found {} front faces in the file {}".format(len(detected_faces), file_name)) print("I found {}side faces in the file {}".format(len(side_faces), file_name)) # Open a window on the desktop showing the image win.set_image(image) # Loop through each face we found in the image for i, face_rect in enumerate(detected_faces): # Detected faces are returned as an object with the coordinates # of the top, left, right and bottom edges print("- Face #{} found at Left: {} Top: {} Right: {} Bottom: {}".format(i, face_rect.left(), face_rect.top(), face_rect.right(), face_rect.bottom())) # Draw a box around each face we found win.add_overlay(face_rect) # for the side faces for (x,y,w,h) in side_faces: print(x) cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) #cv2.imshow('image',image) # Wait until the user hits <enter> to close the window dlib.hit_enter_to_continue() ''' Downloading the image data set from http://cswww.essex.ac.uk/mv/allfaces/faces94.html '''
a7f39ebcb80933999133e7c52279c3dbb335a8d4
dema501/adventofcode
/task1.py
2,123
3.515625
4
def calcDirection(d, s): if d == "N" and s == "L": return "W", "x-" if d == "N" and s == "R": return "E", "x+" if d == "E" and s == "L": return "N", "y+" if d == "E" and s == "R": return "S", "y-" if d == "S" and s == "L": return "E", "x+" if d == "S" and s == "R": return "W", "x-" if d == "W" and s == "L": return "S", "y-" if d == "W" and s == "R": return "N", "y+" def calcDistance(p): x, y = 0, 0 direction = "N" # uniq_coords = set() for i, step in enumerate(p.split(", ")): direction, op = calcDirection(direction, step[0]) if "x-" in op: x = x - int(step[1:]) elif "x+" in op: x = x + int(step[1:]) elif "y-" in op: y = y - int(step[1:]) elif "y+" in op: y = y + int(step[1:]) return x, y def calcPath(p): x, y = 0, 0 direction = "N" uniq_coords = ["(0, 0)"] for i, step in enumerate(p.split(", ")): direction, op = calcDirection(direction, step[0]) # print(step, direction, op, i) for j in range(0, int(step[1:])): if "x-" in op: x = x - 1 elif "x+" in op: x = x + 1 elif "y-" in op: y = y - 1 elif "y+" in op: y = y + 1 cord = "({}, {})".format(x, y) if cord not in uniq_coords: uniq_coords.append(cord) else: return x, y, i+1 return x, y, i+1 if __name__ == '__main__': cases={ """R5, L5, R5, R3""": 12, """R8, R4, R4, R8""": 4, """R2, R2, R5, R4, L2, R1, R3, R4, L3, L5, R2, R2, R3""": 1, """L2, R2, L3, R2, R5, R7, R1, R6, L1, R3""": 0, } #run tests for k in cases: x, y, i = calcPath(k) assert (abs(x) + abs(y)) == cases[k] #production with open("task1.in.txt") as f: content = f.read() x, y, i = calcPath(content.strip()) print("Answer", abs(x) + abs(y))
3f83e36343b8191b3e0bca5d61e4fc003e33ab8d
10258392511/SI507_Final_Project
/sites_scraper.py
4,037
3.6875
4
# This file implements the scraper import bs4 import requests import re from bs4 import BeautifulSoup from pprint import pprint from utilities import * def scrape_main_page(cache_filename): """ Scrapes the main page for detailed pages' urls. Parameters ---------- cache_filename: str Cache file to use. Don't scrape twice! Returns ------- dict A dict in the form: {"short title": "url"} """ cache = open_cache(cache_filename) key = "main_page" if key in cache: print("fetching from cache...") return cache[key] print("making new request...") main_url = "https://www.planetware.com/michigan-tourism-vacations-usmi.htm" base_url = "https://www.planetware.com" resp = requests.get(main_url) assert resp.status_code == 200, "GET failed" soup = BeautifulSoup(resp.text, "html.parser") excluding_pattern = re.compile(r".*(tents|where to stay in detroit|michigan in pictures).*") detail_urls = {} dest_anchors = soup.select("div.dest a") for anchor in dest_anchors: anchor_txt = anchor.text.lower().strip() if excluding_pattern.match(anchor_txt): continue detail_urls[anchor_txt] = base_url + anchor["href"] cache[key] = detail_urls save_cache(cache, cache_filename) return detail_urls def scrape_site(site_url, cache_filename): """ Scrape a detail page with caching. Parameters ---------- site_url: str URL for the detail page. cache_filename: str Cache filename. Returns ------- dict A dict containing all places on the page, in the form of: { "place name 1": {"name": str, "photo_url": str, "desc": list[str], "address": str, "info_url": list[str]}, "place name 2": {...} } """ cache = open_cache(cache_filename) key = site_url if key in cache: print("fetching from cache...") return cache[key] print("making new request...") base_url = "https://www.planetware.com" resp = requests.get(site_url) assert resp.status_code == 200, "GET failed" soup = BeautifulSoup(resp.text, "html.parser") blocks = soup.find_all("div", class_="article_block site") sites_on_page = {} for block in blocks: site_obj = dict() name = block.find("h2", class_="sitename").text # print(name) if not re.match(re.compile(r"^\d+"), name): break site_obj["name"] = re.findall(re.compile(r"[. ]+.*"), name)[0][1:].strip() # print(site_obj["name"]) img = block.find("img") if img is None: site_obj["photo_url"] = None else: site_obj["photo_url"] = base_url + img["src"] desc_paragraphs = block.find("div", class_="site_desc").find_all("p") site_obj["desc"] = [p.text for p in desc_paragraphs if not re.match(re.compile(r"^([a-zA-Z ]+:)"), p.text)] address = block.find(string=re.compile(r"Address: .*")) if address is not None: site_obj["address"] = address[len("Address: "):].strip() else: site_obj["address"] = None anchors = block.find_all("a") site_obj["info_url"] = [anchor["href"] for anchor in anchors] sites_on_page[site_obj["name"]] = site_obj cache[key] = sites_on_page save_cache(cache, cache_filename) return sites_on_page if __name__ == '__main__': # self-test cache_filename = "cache_scraper.json" detail_urls = scrape_main_page(cache_filename) print(f"main:") # print(json.dumps(detail_urls, indent=4)) pprint(detail_urls, indent=2) print("-" * 30) num_places = 0 for name, site_url in detail_urls.items(): print(f"{name}: {site_url}") sites_on_page = scrape_site(site_url, cache_filename) print(json.dumps(sites_on_page, indent=4)) num_places += len(sites_on_page) print("-" * 30) print(f"{num_places} places in total.")
5a2cd1098175ff8bc25c43dc628c7cd737f61dca
sgouda0412/AlgoExpert_Solutions
/Hard/Hard_DynamicProgramming.py
8,515
3.5
4
# 1 Longest Common Subsequence # first T: O(nm * min(n,m)) S: O(nm * min(n,m)) def longestCommonSubsequence(str1, str2): if len(str1) == 0 or len(str2) == 0: return [] arr = [[ [] for x in range(len(str1) + 1)] for y in range(len(str2) + 1)] for up in range(1, len(str2) + 1): for down in range(1, len(str1) + 1): if str1[down - 1] == str2[up - 1]: arr[up][down] = arr[up-1][down-1] + [str1[down-1]] else: upper = arr[up-1][down] left = arr[up][down-1] arr[up][down] = upper if len(upper) > len(left) else left return arr[-1][-1] # second T: O(nm) S: O(nm) def longestCommonSubsequence(str1, str2): arr = [[ [None, 0, None, None] for x in range(len(str1) + 1)] for y in range(len(str2) + 1)] for up in range(1, len(str2) + 1): for down in range(1, len(str1) + 1): if str1[down - 1] == str2[up - 1]: arr[up][down] = [str1[down-1], arr[up-1][down-1][1]+1, up-1, down-1] else: if arr[up-1][down][1] > arr[up][down-1][1]: arr[up][down] = [None, arr[up-1][down][1], up-1, down] else: arr[up][down] = [None, arr[up][down][1], up, down-1] return helper(arr) def helper(arr): result = [] i = len(arr) - 1 j = len(arr[0]) - 1 while i != 0 and j != 0: curr = arr[i][j] if curr[0] is not None: result.append(curr[0]) i = curr[2] j = curr[3] return list(reversed(result)) # 2 Knapsack Problem def knapsackProblem(items, capacity): arr = [[0 for x in range(capacity + 1)]\ for y in range(len(items) + 1)] print(arr) for up in range(1, len(items) + 1): curr_weight = items[up - 1][1] curr_value = items[up - 1][0] for down in range(0, capacity + 1): if down >= curr_weight: arr[up][down] = max(arr[up-1][down],\ arr[up-1][down - curr_weight] + curr_value) else: arr[up][down] = arr[up-1][down] return [arr[-1][-1], helper(arr, items)] def helper(arr, items): row = len(arr) - 1 col = len(arr[0]) - 1 result = [] while row > 0: if arr[row][col] == arr[row-1][col]: row -= 1 else: result.append(row-1) # (above) row - 1 as # we need to shift everything # by 1 due to additional row col -= items[row-1][1] row -= 1 if col == 0: break return list(reversed(result)) # 3 Max Sum Increasing Subsequence def maxSumIncreasingSubsequence(arr): sums = [x for x in arr] ref = [None for x in arr] sums[0] = arr[0] maxIdx = 0 for i in range(1, len(arr)): curr = arr[i] for j in range(0, i): prev = arr[j] if prev < curr and sums[i] < sums[j] + curr: # second part of `if statement` is # vital as without it unnecessary # indicies would be added to ref sums[i] = (sums[j] + curr) ref[i] = j if sums[maxIdx] < sums[i]: maxIdx = i return [sums[maxIdx], backTrack(ref, maxIdx, arr)] def backTrack(ref, idx, arr): result = [] while idx is not None: result.append(arr[idx]) idx = ref[idx] return list(reversed(result)) # 4 Min Number of Jumps # T: O(n^2) S: O(n) def minNumberOfJumps(array): jumps = [float('inf') for _ in array] jumps[0] = 0 for i in range(1, len(array)): for j in range(0, i): if array[j] + j >= i: # we take value(number of jumps) itself # and add the `range` within # which it can spread jumps[i] = min(jumps[i], jumps[j] + 1) # `+1` because we know from previous # that we're able to reach `i`, hence # we're to make jump from [j]. And this # jump will be represented by `+1` return jumps[-1] # T: O(n) S: O(1) def minNumberOfJumps(arr): if len(arr) == 1: return 0 max_reach = arr[0] jumps = 0 steps = arr[0] for i in range(1, len(arr) - 1): # `-1` because when we're at a final # index, we don't need to use it max_reach = max(max_reach, arr[i] + i) steps -= 1 if steps == 0: jumps += 1 steps = max_reach - i # as we don't iterate till last index # we need one more jump to reach final return jumps + 1 # 5 Water Area # mine def waterArea(heights): if len(heights) < 3 or sum(heights) < 2: return 0 nestedHeight = [] result = [] for x in range(len(heights)): helper(x, heights, nestedHeight) small = min(nestedHeight[x]) result.append(small - heights[x]) return sum([x for x in result if x > 0]) def helper(idx, heights, nestedHeight): l_idx = idx - 1 r_idx = idx + 1 left = float('-inf') if l_idx >= 0 else 0 right = float('-inf') if r_idx <= len(heights) - 1 else 0 while l_idx >= 0: left = max(heights[l_idx], left) l_idx -= 1 while r_idx <= len(heights) - 1: right = max(heights[r_idx], right) r_idx += 1 nestedHeight.append([left, right]) return # not mine def waterArea(heights): result = [0 for x in heights] leftMax = 0 for x in range(len(heights)): h = heights[x] result[x] = leftMax leftMax = max(leftMax, h) print(result) rightMax = 0 for x in reversed(range(len(heights))): h = heights[x] minHeight = min(rightMax, result[x]) # (above) we choose min(left, right) if h < minHeight: # find distance to the tallest pillar result[x] = minHeight - h else: result[x] = 0 rightMax = max(rightMax, h) return sum(result) # 6 Disk Stacking def diskStacking(disks): disks.sort(key=lambda x: x[2]) sums = [disks[x][2] for x in range(len(disks))] ref = [None for x in disks] for i in range(len(disks)): curr = disks[i] for j in range(0, i): prev = disks[j] if curr[0] > prev[0] and curr[1] > prev[1] and curr[2] > prev[2]: if sums[i] < sums[j] + curr[2]: sums[i] = (curr[2] + sums[j]) ref[i] = j value = max(sums) idx = sums.index(value) return backTrack(idx, ref, disks) def backTrack(idx, ref, disks): result = [] while idx is not None: result.append(disks[idx]) idx = ref[idx] return list(reversed(result)) # 7 Numbers in PI def numbersInPi(pi, numbers): ht = {x: True for x in numbers} result = helper(pi, ht, {}, 0) return result if result != float('inf') else -1 def helper(pi, ht, cache, idx): if idx == len(pi): return -1 if idx in cache: return cache[idx] fig = float('inf') for i in range(idx, len(pi)): chunk = pi[idx:i + 1] if chunk in ht: temp = helper(pi, ht, cache, i + 1) fig = min(fig, temp + 1) cache[idx] = fig return cache[idx] # 8 Maximum Sum Submatrix # mine def maximumSumSubmatrix(matrix, size): arr = [[0 for x in y] for y in matrix] # put value at very first idx arr[0][0] = matrix[0][0] # put values at first row for i in range(1, len(matrix[0])): arr[0][i] = (arr[0][i - 1] + matrix[0][i]) # put values at first column for j in range(1, len(matrix)): arr[j][0] = (arr[j - 1][0] + matrix[j][0]) # populate new array with values for i in range(1, len(arr)): for j in range(1, len(arr[i])): temp = arr[i][j - 1] + arr[i - 1][j] + \ matrix[i][j] - arr[i - 1][j - 1] arr[i][j] = temp maxSum = float('-inf') # do all the calculations for i in range(size - 1, len(arr)): for j in range(size - 1, len(arr[i])): top = i - size < 0 left = j - size < 0 if top and left: maxSum = max(maxSum, arr[i][j]) elif top and not left: maxSum = max(maxSum, arr[i][j] - arr[i][j - size]) elif not top and left: maxSum = max(maxSum, arr[i][j] - arr[i - size][j]) # else: elif not top and not left: maxSum = max(maxSum, arr[i][j] + arr[i - size][j - size] - arr[i - size][j] - arr[i][j - size]) return maxSum # not mine def maximumSumSubmatrix(matrix, size): arr = createArray(matrix) return calculations(matrix, arr, size) def calculations(matrix, arr, size): maxSum = float('-inf') for i in range(size - 1, len(matrix)): for j in range(size - 1, len(matrix[i])): total = arr[i][j] top = i - size < 0 if not top: total -= arr[i - size][j] left = j - size < 0 if not left: total -= arr[i][j - size] bothTouch = top or left # means we didn't touch upper and left borders if not bothTouch: total += arr[i - size][j - size] maxSum = max(maxSum, total) return maxSum def createArray(matrix): arr = [[0 for _ in loop] for loop in matrix] arr[0][0] = matrix[0][0] for i in range(1, len(matrix[0])): arr[0][i] = (arr[0][i - 1] + matrix[0][i]) for j in range(1, len(matrix)): arr[j][0] = (arr[j - 1][0] + matrix[j][0]) for i in range(1, len(arr)): for j in range(1, len(arr[i])): arr[i][j] = (arr[i - 1][j] + arr[i][j - 1] + matrix[i][j] - arr[i - 1][j - 1]) return arr
c050f0759aaa4cac06b57a04ca3288c9b41642e6
sgouda0412/AlgoExpert_Solutions
/Very_Hard/Very_Hard_BST.py
2,691
3.734375
4
# 1 Right Smaller Than # two optimal solutions with T: O(n*log(n)) S: O(n) # n - numbers smaller at insertion # l - left subtree # n | n l | n l | n l | n l | n l | n l # 0 1 1 1 1 0 0 0 4 2 4 0 5 0 # 2 4 3 -1 11 5 8 # `left subtree` will be added to values # (`.numsSmallerAtInsert`) that are # greater than self.value. `numbers` will # be used eventually # first def rightSmallerThan(arr): if len(arr) == 0: return arr lastIdx = len(arr) - 1 node = BST(arr[lastIdx], lastIdx, 0) for i in reversed(range(len(arr) - 1)): # `-1` as we already created one node node.insert(arr[i], i) # we'll start from root node every # time to calculate `smaller nodes` # and `left subtree` result = [0 for _ in arr] getResult(result, node) return result def getResult(arr, root): if root is None: return arr[root.idx] = root.numsSmallerAtInsert getResult(arr, root.left) getResult(arr, root.right) class BST: def __init__(self, value, idx, numsSmallerAtInsert, left=None, right=None): self.value = value self.idx = idx self.numsSmallerAtInsert = numsSmallerAtInsert self.left = left self.right = right self.leftSubtree = 0 def insert(self, value, idx, smaller=0): if self.value > value: self.leftSubtree += 1 if self.left is None: self.left = BST(value, idx, smaller) else: self.left.insert(value, idx, smaller) else: smaller += self.leftSubtree if value > self.value: smaller += 1 if self.right is None: self.right = BST(value, idx, smaller) else: self.right.insert(value, idx, smaller) # second def rightSmallerThan(arr): if len(arr) == 0: return arr result = arr[:] lastIdx = len(arr) - 1 node = BST(arr[lastIdx]) result[lastIdx] = 0 for i in reversed(range(len(arr) - 1)): node.insert(arr[i], i, result) return result class BST: def __init__(self, value, left=None, right=None): self.value = value self.leftSubtree = 0 self.left = left self.right = right def insert(self, value, idx, res, smaller=0): if self.value > value: self.leftSubtree += 1 if self.left is None: self.left = BST(value) res[idx] = smaller else: self.left.insert(value, idx, res, smaller) else: smaller += self.leftSubtree if value > self.value: smaller += 1 if self.right is None: self.right = BST(value) res[idx] = smaller else: self.right.insert(value, idx, res, smaller) # brute-force. T: O(n^2) S: O(n) def rightSmallerThan(arr): new = [0 for _ in arr] for up in range(len(arr)): curr = arr[up] for down in range(up + 1, len(arr)): compare = arr[down] if curr > compare: new[up] += 1 return new
7a4cecca76070805c157212d87003ecf4cb36028
sgouda0412/AlgoExpert_Solutions
/Medium/Medium_Graphs.py
10,948
4
4
# 1 Breadth-first search class Node: def __init__(self, name): self.children = [] self.name = name def addChild(self, name): self.children.append(Node(name)) return self def breadthFirstSearch(self, arr): curr = self queue = [curr] explored = {} explored[curr] = True while len(queue) != 0: node = queue.pop(0) arr.append(node.name) for x in node.children: if x not in explored: explored[x] = True queue.append(x) return arr # 2 Single Cycle Check # mine def hasSingleCycle(arr): if len(arr) <= 1: return True nums = [False for _ in arr] i = 0 while not all(nums): i = helper(arr, i) if nums[i]: return False nums[i] = True return True def helper(arr, i): new = arr[i] + i return new % len(arr) # not mine def hasSingleCycle(arr): explored = 0 curr = 0 while len(arr) > explored: if explored > 0 and curr == 0: return False explored += 1 curr = helper(arr, curr) return curr == 0 def helper(arr,curr): temp = arr[curr] return (temp + curr) % len(arr) # or if you write not in Python # as modulo in Python works the following way: # -x % y == -(x % y) + y # to_return = (temp + curr) % len(arr) # return to_return if to_return >= 0 else to_return + len(arr) # 3 River Sizes def riverSizes(matrix): explored = [[False for x in row] for row in matrix] result = [] for x in range(len(matrix)): for y in range(len(matrix[x])): if explored[x][y]: continue traverse(x,y,matrix,explored,result) return result def traverse(idx1, idx2, matrix, explored, result): curr = 0 stack = [[idx1,idx2]] while len(stack) != 0: curr_stack = stack.pop() i = curr_stack[0] j = curr_stack[1] if explored[i][j]: # nodes can twist in graph # hence we need this check continue explored[i][j] = True if matrix[i][j] == 0: continue curr += 1 unexplored = helper(i, j, matrix, explored) for temp in unexplored: stack.append(temp) if curr > 0: result.append(curr) def helper(i,j,matrix,explored): unvisitedNeigh = [] if i > 0 and not explored[i-1][j]: # if not upmost row and above not visited unvisitedNeigh.append([i-1,j]) if i < len(matrix) - 1 and not explored[i+1][j]: # if not downmost row and down not visited unvisitedNeigh.append([i+1,j]) if j > 0 and not explored[i][j-1]: unvisitedNeigh.append([i,j-1]) if j < len(matrix[i]) - 1 and not explored[i][j+1]: unvisitedNeigh.append([i,j+1]) return unvisitedNeigh # 4 Youngest common ancestor class AncestralTree: def __init__(self, name): self.name = name self.ancestor = None # mine def getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo): # edge case if ancestor == one of the descendant if topAncestor == descendantOne or topAncestor == descendantTwo: return topAncestor # calculate depths of both descendants index1 = traverse(topAncestor, descendantOne) index2 = traverse(topAncestor, descendantTwo) # check if one of them is deeper # hence whether further actions are required node = equalTo(index1, index2, descendantOne, descendantTwo) return node def traverse(top, desc): idx = 0 while top != desc: idx += 1 desc = desc.ancestor return idx def equalTo(idx1, idx2, desc1, desc2): while idx1 != idx2: if idx1 > idx2: idx1 -= 1 desc1 = desc1.ancestor elif idx2 > idx1: idx2 -= 1 desc2 = desc2.ancestor while desc1 != desc2: desc1 = desc1.ancestor desc2 = desc2.ancestor return desc1 # not mine def getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo): index1 = traverse(topAncestor, descendantOne) index2 = traverse(topAncestor, descendantTwo) if index1 > index2: # higher means lower in my code backTrack(descendantOne, descendantTwo, index1 - index2) else: backTrack(descendantTwo, descendantOne, index2 - index1) def traverse(top, desc): idx = 0 while top != desc: idx += 1 desc = desc.ancestor return idx def backTrack(higher, lower, idx): # bring difference to 0 while idx > 0: idx -= 1 higher = higher.ancestor while higher != lower: higher = higher.ancestor lower = lower.ancestor return higher # 5 Cycle in Graph # recursive with stack; T: O(v + e) S: O(v) def cycleInGraph(edges): # has cycle -> True else False explored = [False for x in range(len(edges))] # for overall track stack = [False for x inr ange(len(edges))] # for currrent traversal track len_graph = len(edges) for edge in range(len_graph): if not explored[edge]: cycle = dfs(edges, edge, explored, stack) if cycle: return True return False def dfs(edges, edge, explored, stack): stack[edge] = True explored[edge] = True for x in edges[edge]: if not explored[x]: cycle = dfs(edges, x, explored, stack) if cycle: return True elif stack[x]: return True stack[edge] = False return False # recursive with colours; T: O(v + e) S: O(v) white, grey, black = 0, 1, 2 # hence we can use them as variables # white -> unvisited # grey -> currently in stack # black -> visited def cycleInGraph(edges): colours = [white for x in range(len(edges))] len_edges = len(edges) for edge in range(len_edges): if colours[edge] != white: # if colours[edge] == black: continue cycle = dfs(edge, edges, colours) if cycle: return True return False def dfs(edge, edges, colours): colours[edge] = grey for x in edges[edge]: if colours[x] == grey: return True elif colours[x] == black: continue elif colours[x] == white: cycle = dfs(x, edges, colours) if cycle: return True colours[edge] = False return False # 6 Remove Islands # recursive def removeIslands(matrix): explored = [[False for x in rows] for rows in matrix] for row in range(len(matrix)): for col in range(len(matrix[row])): rowB = row == 0 or row == len(matrix) - 1 colB = col == 0 or col == len(matrix[row]) - 1 isBorder = rowB or colB if not isBorder: continue if matrix[row][col] != 1: continue traverse(row, col, matrix, explored) for row in range(1, len(matrix) - 1): for col in range(1, len(matrix[row]) - 1): if explored[row][col]: continue matrix[row][col] = 0 return matrix def traverse(idx1, idx2, matrix, explored): stack = [(idx1, idx2)] while len(stack) != 0: curr_stack = stack.pop() node1, node2 = curr_stack if explored[node1][node2]: continue explored[node1][node2] = True neigh = explore(node1, node2, matrix) for edge in neigh: row, col = edge if matrix[row][col] != 1: continue stack.append(edge) def explore(i, j, matrix): container = [] if i - 1 >= 0: # UP container.append((i - 1, j)) if j - 1 >= 0: # LEFT container.append((i, j - 1)) if i + 1 <= len(matrix) - 1: # DOWN # or i + 1 <= len(matrix): container.append((i + 1, j)) if j + 1 <= len(matrix[i]) - 1: # RIGHT # or j + 1 <= len(matrix[i]): container.append((i, j + 1)) return container # 7 Minimum Passses of Matrix # mine def minimumPassesOfMatrix(matrix): if len(matrix[0]) == 0: # `len(matrix) == 0` is also OK return 0 elif len(matrix) == 1: return 0 if matrix[0][0] >= 0 else -1 idx = 0 arr = [[True if x > 0 else False for x in y] for y in matrix] while True: if main(matrix, arr) is True: idx += 1 else: break # because eventually, even if we have # changed all to positive, there'll be # moment that no changes are made (everything) # is positive already => -1 will be an error for i in range(len(matrix)): for j in range(len(matrix[i])): if matrix[i][j] < 0: return -1 return idx def main(matrix, arr): count = 0 temp = [] for i in range(len(matrix)): for j in range(len(matrix[i])): if matrix[i][j] < 0: if helper(arr, i, j): matrix[i][j] *= -1 temp.append([i, j]) count += 1 else: continue else: continue flip(temp, arr) return True if count != 0 else False def helper(arr, i, j): if i > 0 and arr[i - 1][j] is True: return True if j > 0 and arr[i][j - 1] is True: return True if j < len(arr[0]) - 1 and arr[i][j + 1] is True: return True if i < len(arr) - 1 and arr[i + 1][j] is True: return True return False def flip(temp, arr): while len(temp) != 0: nodes = temp.pop() a, b = nodes[0], nodes[1] arr[a][b] = True # not mine def minimumPassesOfMatrix(matrix): positive_idx = getPositive(matrix) count = main(positive_idx, matrix) return count - 1 if noNegative(matrix) else -1 def main(pos, matrix): count = 0 while len(pos) != 0: new = pos pos = [] while len(new) != 0: row, col = new.pop(0) adjacent = getAdjacent(row, col, matrix) for ele in adjacent: r, c = ele if matrix[r][c] < 0: matrix[r][c] *= -1 pos.append([r, c]) count += 1 return count def getPositive(matrix): result = [] for x in range(len(matrix)): for y in range(len(matrix[x])): if matrix[x][y] > 0: result.append([x, y]) return result def noNegative(matrix): for x in range(len(matrix)): for y in range(len(matrix[x])): if matrix[x][y] < 0: return False return True def getAdjacent(i, j, matrix): temp = [] if i > 0: temp.append([i - 1, j]) if j > 0: temp.append([i, j - 1]) if i < len(matrix) - 1: temp.append([i + 1, j]) if j < len(matrix[i]) - 1: temp.append([i, j + 1]) return temp
9200bb98fc0fbbf27b9202490d8dcdf3fda66a92
sgouda0412/AlgoExpert_Solutions
/Medium/Medium_BST.py
6,638
3.6875
4
# 1 BST traversal def inOrderTraverse(tree, arr): def traverse(tree): if tree.left: traverse(tree.left) arr.append(tree.value) if tree.right: traverse(tree.right) traverse(tree) return arr def preOrderTraverse(tree, arr): def traverse(tree): arr.append(tree.value) if tree.left: traverse(tree.left) if tree.right: traverse(tree.right) traverse(tree) return arr def postOrderTraverse(tree, arr): def traverse(tree): if tree.left: traverse(tree.left) if tree.right: traverse(tree.right) arr.append(tree.value) traverse(tree) return arr # 2 Validate BST class BST: def __init__(self, value): self.value = value self.left = None self.right = None def validateBST(tree): return helper(tree, float('-inf'), float('inf')) def helper(tree, Min, Max): if tree is None: return True if tree.value < Min or tree.value >= Max: return False leftNode = helper(tree.left, Min, tree.value) return leftNode and helper(tree.right, tree.value, Max) # 3 Min Height BST # you can either use or not insert method class BST: def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, value): if value < self.value: if self.left is None: self.left = BST(value) else: self.left.insert(value) else: if self.right is None: self.right = BST(value) else: self.right.insert(value) def minHeightBST(arr): return helper(arr, 0, len(arr) - 1) def helper(arr, left, right): if left > right: return None middle = (left + right) // 2 node = BST(arr[middle]) node.left = helper(arr, left, middle - 1) node.right = helper(arr, middle + 1, right) return node # 4 BST construction class BST: def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, value): curr = self while curr: if curr.value > value: if curr.left is None: curr.left = BST(value) break curr = curr.left elif curr.value < value: if curr.right is None: curr.right = BST(value) break curr = curr.right return self def contains(self, value): curr = self while curr: if curr.value > value: curr = curr.left elif curr.value < value: curr = curr.right else: return True return False def remove(self, value, parent=None): # cases to deal with # 1. if both childs are in place # 2. if no parent (find at first try) + only one child (when both above is dealth with) # 3. if parent exists, but only 1 child curr = self while curr: if curr.value > value: parent = curr curr = curr.left elif curr.value < value: parent = curr curr = curr.right else: if curr.left is not None and curr.right is not None: curr.value = curr.right.minFind() # change itself happens here curr.right.remove(curr.value, curr) # remove smallest from the right tree as we put it in the root elif parent is None: # means we found the value instantly without if/elif + only one child if curr.left is not None: curr.value = curr.left.value curr.right = curr.left.right curr.left = curr.left.left # assign last as you'll need it elif curr.right is not None: curr.value = curr.right.value curr.left = curr.right.left curr.right = curr.right.right # assign last as you'll need it else: pass # no children elif parent.left == curr: # 5 # / #4 this to be removed # \ # 3 parent.left = curr.left if curr.left is not None else curr.right elif parent.right == cur: parent.right = curr.left if curr.left is not None else curr.right break return self def minFind(): curr = self while curr: if curr.left: curr = curr.left return curr.value # 5 Find Kth largest value in BST class BST: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right # Time & Space O(n) def findKthLargestValueInBst(tree, k): arr = [] def traverse(node, arr): if node.left: traverse(node.left, arr) arr.append(node.value) if node.right: traverse(node.right, arr) traverse(tree, arr) return arr[-k] # Time O(h + k) Space O(h) class Help: def __init__(self, count, prev): self.count = count self.prev = prev def findKthLargestValueInBst(tree, k): inst = Help(0, -1) traverse(tree, k, inst) return inst.prev def traverse(node, k, inst): if not node or inst.count == k: # base case return traverse(node.right, k, inst) if inst.count < k: # if == then we return to initial function inst.count += 1 inst.prev = node.value traverse(node.left, k, inst) # 6 Reconstruct BST class BST: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right # first: T: O(n^2); S: O(n) def reconstructBst(arr): if len(arr) == 0: return None curr = arr[0] rightTree = len(arr) # traverse till curr < 'some value' in array # if so, change right border for the index # of that 'some value' for x in range(1, len(arr)): if arr[x] >= curr: rightTree = x break # from next after arr[0] on current step leftNode = reconstructBst(arr[1:rightTree]) # if there is value > curr => 1) rightTree = len(arr) [suppose 4] # if last in this arr > than curr => 2) rightTree = 3 rightNode = reconstructBst(arr[rightTree:]) return BST(curr, leftNode, rightNode) # second: T: O(n); S: O(n) class Help: def __init__(self, idx): self.idx = idx def reconstructBst(values): inst = Help(0) return func(values, inst, float('-inf'), float('+inf')) def func(arr, inst, lower, upper): if inst.idx == len(arr): return None # if .idx == len(arr) -> done # .idx means what value from arr # we'll take on the current recursive call curr = arr[inst.idx] if curr < lower or curr >= upper: return None inst.idx += 1 leftNode = func(arr, inst, lower, curr) rightNode = func(arr, inst, curr, upper) return BST(curr, leftNode, rightNode)
dd67e60748c0c229a7ddc44539f3975938c8198b
sgouda0412/AlgoExpert_Solutions
/Medium/Medium_recursion.py
2,892
3.640625
4
# 1 Permutations def getPermutations(arr): perms = [] helper(0, arr, perms) return perms def helper(idx, arr, perms): if idx == len(arr) - 1: perms.append(arr[:]) else: for x in range(idx, len(arr)): swap(x, idx, arr) helper(idx + 1, arr, perms) swap(x, idx, arr) def swap(idx1, idx2, arr): arr[idx1], arr[idx2] = arr[idx2], arr[idx1] # 2 Powerset # a def powerset(arr): cont = [[]] for x in arr: for y in range(len(arr)): temp = cont[y] cont.append(temp + [x]) return cont # b def powerset(arr, idx=None): if idx is None: idx = len(arr) - 1 if idx < 0: return [[]] ele = arr[idx] subs = powerset(arr, idx-1) for x in range(len(subs)): temp = subs[x] subs.append(temp + [ele]) return subs # 3 Phone Number Mnemonics hashtable = {'1': ['1'], '2': ['a','b','c'], '3': ['d','e','f'], '4': ['g','h','i'], '5': ['j','k','l'], '6': ['m','n','o'], '7': ['p','q','r','s'], '8': ['t','u','v'], '9': ['w','x','y','z'], '0': ['0']} def phoneNumberMnemonics(phone): idx = 0 curr =['0'] * len(phone) arr = [] helper(idx, curr, arr, phone) return arr def helper(idx, curr, arr, phone): if idx == len(phone): temp = ''.join(curr) arr.append(temp) else: digit = phone[idx] letters = hashtable[digit] for x in letters: curr[idx] = x helper(idx+1, curr, arr, phone) # 4 Staircase traversal # recursive with memoization def staircaseTraversal(height, maxSteps): return func(height, maxSteps, {0: 1, 1:1}) def func(height, maxSteps, memo): if height in memo: return memo[height] # maxSteps points how many steps # below we can go and sum their ways # to receive number of ways for current # step curr = 0 for x in range(1, min(height, maxSteps) + 1): curr += func(height - x, maxSteps, memo) memo[height] = curr return curr # iterative with DP def staircaseTraversal(height, maxSteps): arr = [0 for x in range(height + 1)] arr[0], arr[1] = 1, 1 # + 1 in comprehension is because we # have base case with '0' for x in range(2, height + 1): step = 1 # indicies in array represent ways (amount of ways) # via which we can reach this step while step <= x and step <= maxSteps: # <= maxSteps: because maxSteps show # how many layers below we can sum to # attain the current level arr[x] = arr[x] + arr[x - step] step += 1 return arr[height] # using Sliding window def staircaseTraversal(height, maxSteps): arr = [1] curr = 0 # ways to get to '0' is '1' for x in range(1, height + 1): start = x - maxSteps - 1 # 'start' of the previous window # so as to subtract value that is # no longer in our window # '-1' here just enables to get the # value that we are to subtract end = x - 1 # to take the previos value # that we need to add to 'curr' if start >= 0: curr -= arr[start] curr += arr[end] arr.append(curr) return arr[height] # curr also is OK
8f5f902a00bec0a2f5490cada18911936bcacf34
Art-And/python_basics
/through_the_letters.py
261
4
4
def run(): # name = input("Please write your name: ") # for letter in name: # print(letter) sentence = input("Please write a sentence: ") for caracter in sentence: print(caracter.upper()) if __name__ == '__main__': run()
429dc963f813e2e84c30923d0740ccc0b0036c4f
Art-And/python_basics
/conversor_inverso.py
195
3.625
4
dolar = input('Introduce tus dolares: ') dolar = float(dolar) valor_peso = 20 pesos = dolar * valor_peso pesos = round(pesos, 2) pesos = str(pesos) print('Tienes $' + pesos + ' pesos mexicanos')
4b9debc3b6e466c1ae1e86b42fde816e4a3b143e
jkim2791/UC-berkeley-CS88
/proj/wheel/game.py
1,181
4.0625
4
from secret import SecretWord from board import Board class Game: """Run an entire game. Initialization defines the player who pickers secret word and one or more guessers. play - picker picks the secret word from the dictionary held by all players - guessers guess in turn looking at the state of the board until the game is done - each guesser continues as long as they guess currect letters - returns final board winner returns the player who picked the last letter. """ def __init__(self, picker, guessers): # BEGIN self.picker = picker self.guessers = guessers # END def play(self, verbose=True): # BEGIN s_word = self.picker.word() b = Board(SecretWord(s_word)) while b.done() == False: if verbose == True: b.display(b) guess = self.guessers[0].guess(b) b.guess(b,guess) if guess in b.misses(): self.guessers = self.guessers[1:]+[self.guessers.pop(0)] return b # END def winner(self): # BEGIN return self.guessers[0].name # END
f587e8614825a2d013715057bf7cffc0ed0cf287
Earazahc/exam2
/derekeaton_exam2_p2.py
1,032
4.25
4
#!/usr/bin/env python3 """ Python Exam Problem 5 A program that reads in two files and prints out all words that are common to both in sorted order """ from __future__ import print_function def fileset(filename): """ Takes the name of a file and opens it. Read all words and add them to a set. Args: filename: The name of the file Return: a set with all unique words in the file """ with open(filename, mode='rt', encoding='utf-8') as reading: hold = set() for line in reading: temp = line.split() for item in temp: hold.add(item) return hold def main(): """ Test your module """ print("Enter the name of a file: ", end='') file1 = input() print("Enter the name of a file: ", end='') file2 = input() words1 = fileset(file1) words2 = fileset(file2) shared = words1.intersection(words2) for word in shared: print(word) if __name__ == "__main__": main() exit(0)
9b646e8de6eccecff554062ff607dc63b96b003a
ramteja64/python_project
/word_game.py
3,233
4.15625
4
""" File: word_guess.py ------------------- Fill in this comment. """ import random LEXICON_FILE = "Lexicon.txt" # File to read word list from INITIAL_GUESSES = 8 # Initial number of guesses player starts with def play_game(secret_word): """ Add your code (remember to delete the "pass" below) """ secret_word=secret_word.strip() l=len(secret_word) print(l) d="" for i in range(l): d=d+"-" print("The word now looks like this: "+d) print("You have 8 guesses left") n=8 c=0 l=[] k=-1 while n>0: s=input("Type a single letter here, then press enter: ") s=s.upper() if s in secret_word: l.clear() k=-1 for i in secret_word: k=k+1 if i==s: c=c+1 l.append(k) k=-1 if c==1: print("That guess is correct.") res=secret_word.index(s) w=list(d) w[res]=s d="".join(w) if d==secret_word: print('Congratulations, the word is: '+secret_word) n=0 else: print("The word now looks like this: "+d) print('You have {} guesses left'.format(n)) c=0 else: print('That guess is correct.') for i in range(c): w=list(d) w[l[i]]=s d=''.join(w) if d==secret_word: print('Congratulations, the word is: '+secret_word) n=0 else: print("The word now looks like this: "+d) print('You have {} guesses left'.format(n)) c=0 else: print("There are no {}'s in the word".format(s)) n=n-1 if n!=0: print('You have {} guesses left'.format(n)) else: print('Sorry, you lost. The secret word was: '+secret_word) def get_word(): """ This function returns a secret word that the player is trying to guess in the game. This function initially has a very small list of words that it can select from to make it easier for you to write and debug the main game playing program. In Part II of writing this program, you will re-implement this function to select a word from a much larger list by reading a list of words from the file specified by the constant LEXICON_FILE. index = random.randrange(3) if index == 0: return 'HAPPY' elif index == 1: return 'PYTHON' else: return 'COMPUTER'""" f = open("Lexicon.txt", "r") l=[] for x in f: l.append(x) index=random.randrange(100) return l[index] f.close() def main(): """ To play the game, we first select the secret word for the player to guess and then play the game using that secret word. """ secret_word = get_word() play_game(secret_word) # This provided line is required at the end of a Python file # to call the main() function. if __name__ == "__main__": main()
cbe25e58a699661cba8668b0295a9c7a848e9bb3
chivemind/pythonbiblehomework
/loops101project2.py
864
3.96875
4
# Get sentence from user original = input("Write a sentence to code! ").strip().lower() #split sentence into words words = original.split() #loop through words and convert into pig latin new_words = [] #if word starts with a vowel, add "yay" for word in words: if word[0] in "aeiou": new_word = word +"yay" new_words.append(new_word) #if word starts with consonant, move first to end and add "ay" else: vowel_position = 0 for letter in word: if letter not in "aeiou": vowel_position = vowel_position + 1 else: break cons = word[:vowel_position] the_rest = word[vowel_position:] new_word = the_rest + cons + "ay" new_words.append(new_word) #stick words back together output = " ".join(new_words) #output final string print(output)
2374e05debdb31353c46e9bddca773a02232e7a4
soyoungboy/pythonStudy
/four.py
4,633
3.53125
4
# #!/usr/bin/python # # -*- coding: UTF-8 -*- # # Python程序语言指定任何非0和非空(null)值为true,0 或者 null为false。 # flag = False # name = 'luren' # if name == 'python': # 判断变量否为'python' # flag = True # 条件成立时设置标志为真 # print 'welcome boss' # 并输出欢迎信息 # else: # print name # 条件不成立时输出变量名称 # # !/usr/bin/python # # -*- coding: UTF-8 -*- # # 例2:elif用法 # # num = 5 # if num == 3: # 判断num的值 # print 'boss' # elif num == 2: # print 'user' # elif num == 1: # print 'worker' # elif num < 0: # 值小于零时输出 # print 'error' # elif num == 4: # print "right" # else: # print 'roadman' # 条件均不成立时输出 # #!/usr/bin/python # # -*- coding: UTF-8 -*- # # # 例3:if语句多个条件 # # num = 9 # if num >= 0 and num <= 10: # 判断值是否在0~10之间 # print 'hello' # # num = 10 # if num < 0 or num > 10: # 判断值是否在小于0或大于10 # print 'hello' # else: # print 'undefine' # # num = 8 # # 判断值是否在0~5或者10~15之间 # if (num >= 0 and num <= 5) or (num >= 10 and num <= 15): # print 'hello' # else: # print 'undefine' # # !/usr/bin/python # # -*- coding: UTF-8 -*- # # var = 100 # # if (var == 100): print "变量 var 的值为100" # # print "Good bye!" # #!/usr/bin/python # # count = 0 # while (count < 9): # print 'The count is:', count # count = count + 1 # # print "Good bye!" # # !/usr/bin/python # # -*- coding: UTF-8 -*- # i = 1 # while i < 10: # i += 1 # if i % 2 > 0: # 非双数时跳过输出 # continue # print i # 输出双数2、4、6、8、10 # print "----------------------------------" # i = 1 # while 1: # 循环条件为1必定成立 # print i # 输出1~10 # i += 1 # if i > 10: # 当i大于10时跳出循环 # break # # #!/usr/bin/python # # -*- coding: UTF-8 -*- # # var = 1 # while var == 1 : # 该条件永远为true,循环将无限执行下去 # num = raw_input("Enter a number :") # print "You entered: ", num # # print "Good bye!" # #!/usr/bin/python # # count = 0 # while count < 5: # print count, " is less than 5" # count = count + 1 # else: # print count, " is not less than 5" # #!/usr/bin/python # # flag = 1 # # while (flag): print 'Given flag is really true!' # # print "Good bye!" # # !/usr/bin/python # # -*- coding: UTF-8 -*- # # for letter in 'Python': # 第一个实例 # print '当前字母 :', letter # # fruits = ['banana', 'apple', 'mango'] # for fruit in fruits: # 第二个实例 # print '当前水果 :', fruit # # print "Good bye!" # 通过序列索引迭代 # 内置函数 len() 和 range(),函数 len() 返回列表的长度,即元素的个数。 range返回一个序列的数 # # !/usr/bin/python # # -*- coding: UTF-8 -*- # # fruits = ['banana', 'apple', 'mango'] # i = len(fruits) # l = range(i) # # i相当于size,l相当于position # print i # print l # for index in l: # print '当前水果 :', fruits[index] # # print "Good bye!" # 循环使用 else 语句 # # !/usr/bin/python # # -*- coding: UTF-8 -*- # # for num in range(10, 20): # 迭代 10 到 20 之间的数字 # for i in range(2, num): # 根据因子迭代 # if num % i == 0: # 确定第一个因子 # j = num / i # 计算第二个因子 # print '%d 等于 %d * %d' % (num, i, j) # break # 跳出当前循环 # else: # 循环的 else 部分 # print num, '是一个质数' # !/usr/bin/python # -*- coding: UTF-8 -*- # # i = 2 # while (i < 100): # j = 2 # while (j <= (i / j)): # if not (i % j): break # j = j + 1 # if (j > i / j): print i, " 是素数" # i = i + 1 # # print "Good bye!" # # !/usr/bin/python # # -*- coding: UTF-8 -*- # for letter in 'hello world': # First Example # if letter == 'o': # pass # print "-----------我是分割线-----------" # print 'Current Letter :', letter # # !/usr/bin/python # # var1 = 'Hello World!' # var2 = "Python Runoob" # # print "var1[0]: ", var1[0] # 字符中第一个内容 # print "var2[1:5]: ", var2[1:5] # 从位置1到位置5之间的字符 # # !/usr/bin/python # # -*- coding: UTF-8 -*- # # var1 = 'Hello World!' # # print "更新字符串 :- ", var1[:6] + 'John! I Love You' # 替换第六个位置以后的内容 # # !/usr/bin/python # # print "My name is %s and weight is %d kg!" % ('soyoungboy', 75) # # !/usr/bin/python # hi = '''hi # there''' # hi # print hi # !/usr/bin/python hi = u'Hello\u0020World !' print hi
45454a5eb68caf4713f2b0ed2aab7d8b4d3c1166
quioxe/Trieur-Etre-Vivants
/category.py
1,832
3.65625
4
from sqlite3.dbapi2 import Cursor import database class Category: def __init__(self, name, parent_category=None, id=None) -> None: self.name = name self.parent_category = parent_category def __init__(self, id) -> None: cursor = database.get_cursor() cursor.execute("SELECT * FROM category WHERE id = (?)", (str(id), )) category = cursor.fetchall() if len(category) == 1: self.name = category[0][1] self.id = category[0][0] if(category[0][2]): self.parent_category = Category(category[0][2]) else: self.parent_category = None def save(self): cursor = database.get_cursor() cursor.execute("INSERT INTO category (name, category_id) VALUES (?,?)", (self.name, self.category_id.get_id())) database.conn.commit() @staticmethod def get_categories(): c = database.get_cursor() c.execute("SELECT * FROM category") categories = c.fetchall() return categories @staticmethod def category_listing(): categories = Category.get_categories() for category in categories: category_obj = Category(category[0]) if(category_obj.get_parent_category()): print("Index: " + str(category_obj.get_id()) + ", nume : " + category_obj.get_name() + ", parent : " + category_obj.get_parent_category().get_name()) else: print("Index: " + str(category_obj.get_id()) + ", nume : " + category_obj.get_name() + ", parent : None") def get_name(self): return self.name def get_id(self): return self.id def get_parent_category(self): return self.parent_category
2afdcc56807edf7ac7debe13d55eb4d7f45c645b
danieta/thunderboard
/Desktop/Algdat2/oving2.py
1,337
3.828125
4
#!/usr/bin/python3 from sys import stdin from itertools import repeat def merge(decks): # SKRIV DIN KODE HER mittOrd = "" while(len(decks) != 0 ): minsteVerdi = decks[0][0][0] minsteVerdiIndex = 0 #i vårt tilfelle kan minsteVerdiIndex være 0,1,2,3 eller 4. for i in range(0,len(decks)): if (decks[i][0][0] < minsteVerdi): minsteVerdi = decks[i][0][0] minsteVerdiIndex = i mittOrd += decks[minsteVerdiIndex][0][1] #legger til bokstaven som minsteverdiindex hører sammen med decks[minsteVerdiIndex].pop(0) #popper første element i lista som har den minste verdien. Altså popper minste verdien som er i decks if(len(decks[minsteVerdiIndex]) == 0): #sjekker at lengden på lista som den minste verdien er i, er 0 decks.pop(minsteVerdiIndex) #print(minsteVerdi) #print(mittOrd) #print(len(decks)) #print(decks) #print(decks) return mittOrd def main(): # Read input. decks = [] for line in stdin: (index, csv) = line.strip().split(':') deck = list(zip(map(int, csv.split(',')), repeat(index))) decks.append(deck) # Merge the decks and print result. print(merge(decks)) if __name__ == "__main__": main()
e5a93d3de2bf9f58e15f5f9a48f359f5c1a45b70
a13z/nd256_project3
/problem_7.py
6,522
3.921875
4
# A RouteTrie will store our routes and their associated handlers class RouteTrie: def __init__(self, handler): # Initialize the trie with an root node and a handler, this is the root path or home page node self.root = RouteTrieNode(handler) def insert(self, path, handler): """ Method to insert a RouteTrieNode in the RouteTrie Args: path(string), handler(string): path to add and handler assigned to the path """ node = self.root # if path doesn't start with '/' or handler is empty, we return None if path[0] != '' or handler == '' or len(path) < 2: return None # if path contains 2 elements and they are '' this means path is '/' # so we return the root.handler because this has been already initialised if len(path) == 2 and path[0] == '' and path[1] == '': node.handler = handler return # if path is valid, we iterate it and add it to the RouteTrie for single_path in path[1:]: # we skip extra '/' in the path if they exist if single_path == '': break # we keep traversing the RouteTrie if we are finding part of the path if single_path in node.children: node = node.children[single_path] # if it doesn't exist we create a new Node and add the path else: new_node = RouteTrieNode() node.children[single_path] = new_node node = new_node # We finally add the handler to the path node.handler = handler def find(self, path): """ Method to find a path in a RouteTrie Starting at the root, navigate the Trie to find a match for this path Return the handler for a match, or None for no match Args: path(string): path to find in the RouteTrie """ node = self.root # if path doesn't start with '/' we return None since it is a relative path if path[0] != '' or len(path) < 2: return None # This means that the path is '/' so we return the handler if len(path) == 2 and path[0] == '' and path[1] == '': return node.handler # if path is valid, we iterate the path from the first '/' for single_path in path[1:]: # we skip extra '/' in the path if they exist if single_path == '': break # we keep traversing the RouteTrie if we are finding part of the path if single_path in node.children: node = node.children[single_path] else: # this means that some part of the path is not found so we return None return None # Finally, the node is found so we return the handler return node.handler # A RouteTrieNode will be similar to our autocomplete TrieNode... with one additional element, a handler. class RouteTrieNode: def __init__(self, handler=None): self.handler = handler self.children = {} # The Router class will wrap the Trie and handle class Router: def __init__(self, handler, not_found_handler=None): """ Method to initialise Router class Args: handler(string), not_found_handler(string): handler sets the handler for the root node and not_found_handler sets the default route when a path is not found """ self.not_found_handler = not_found_handler self.trie = RouteTrie(handler) def add_handler(self, path, handler): """ Method to add a handler for a path. Args: path(string), handler(string): add the handler to a path """ path_list = self.split_path(path) self.trie.insert(path_list, handler) def lookup(self, path): """ Method to lookup a path in the RouteTrie. If path is found we return the handler. If not found we return the default not_found_handler which was initialised when we created the TrieRoute The path works with and without the trailing slash. It provides the handler either way if exists I think I covered all bonus points ;) Args: path(string): path to lookup in the RouteTrie """ path_list = self.split_path(path) # find the path in the TrieRoute found = self.trie.find(path_list) # if not found return the default not_found_handler if found is None: return self.not_found_handler return found def split_path(self, path): """ Method to split a path into parts using '/' as a separator Args: path(string): path to split into parts Returns: (list): list of elements created from splitting path with '/' """ return path.split('/') def test_function(test_case, solution): router = Router("root handler", "not found handler") # remove the 'not found handler' if you did not implement this router.add_handler("/home/about", "about handler") # add a route router.add_handler("/home/about/you", "about you handler") # add a route print("Test case", test_case) output = router.lookup(test_case) if output == solution: print("Pass") else: print("Fail") # Here are some test cases and expected outputs you can use to test your implementation # Test case 1 test_case = "/" test_case_solution = 'root handler' test_function(test_case, test_case_solution) # Test case 2 test_case = "/home" test_case_solution = 'not found handler' test_function(test_case, test_case_solution) # Test case 3 test_case = "/home/about" test_case_solution = 'about handler' test_function(test_case, test_case_solution) # Test case 4 test_case = "/home/about/" test_case_solution = 'about handler' test_function(test_case, test_case_solution) # Test case 5 test_case = "/home/about/me" test_case_solution = 'not found handler' test_function(test_case, test_case_solution) # Test case 5 test_case = "/home/////about/me" test_case_solution = 'not found handler' test_function(test_case, test_case_solution) # Test case 5 test_case = "/home/about/you" test_case_solution = 'about you handler' test_function(test_case, test_case_solution) # Test case 6 test_case = "" test_case_solution = 'not found handler' test_function(test_case, test_case_solution)
92572db3c9acc30301d0580bcc8355ec8a4c3c40
AdamSierzan/Python_basics_course_2
/Lesson_1/1.3 Formatting_the_strings_p2.py
591
4.03125
4
#python 2 formatting waluta = "dolar" us = 1 pln = 4.08234915 print("Aktualnie %r %r kosztuje %.2r zł" % (us, waluta, pln)) waluta = "dolar" us = 1 pln = 4.08234915 print("Aktualnie %d %s kosztuje %.2f zł" % (us, waluta, pln)) # in old python version, while formating for: # strings we use: %s # floats: %f # int: %d # any type: %r #python 3 formatting waluta = "dolar" us = 1 pln = 4.08234915 print("Aktualnie {} {} kosztuje {} zł" .format(us, waluta, pln)) print("{3} {1} {2} {0}".format("apple", "grape", "green", "red")) #in new python we use: # {} and .format for any type
58c3f5d0d23fe52ad7cbdaafcd0f7d10ea86c7e7
yogeshvaral/PythonWithFlask
/OppsConceptDemo.py
1,542
3.953125
4
class Computer: def __init__(self, model, ram): self.model = model self.ram = ram def config(self): print("i5,16gb,1TB") print("Model and ram is", self.model, self.ram) comp1 = Computer("AMD", 16) comp2 = Computer("i5", 24) comp1.config() comp2.config() class Person: def __init__(self): self.name = "Yogesh" self.age = 32 def updateAge(self): self.age = 22 def compare(self, other): if self.age == other.age: return True else: return False p1 = Person() p2 = Person() # p1.updateAge() print(p1.name, p1.age) print(p2.name, p2.age) if p1.compare(p2): print("They are same") else: print("They are different") class Car: wheels = 4 # claas level variable in Class Namespace def __init__(self): # Instance level variables in Instance Name space self.mil = 10 self.com = "BMW" c1 = Car() c2 = Car() Car.wheels = 6 print(c1.mil, c1.com, c1.wheels) print(c2.mil, c2.com, c2.wheels) class Student: school = "SIT" def __init__(self, m1, m2, m3): self.m1 = m1 self.m2 = m2 self.m3 = m3 def getAvg(self): return (self.m1+self.m2+self.m3)/3 @classmethod def getschoolinfo(cls): return cls.school @staticmethod def getInfo(): print("This is student class") s1 = Student(12, 13, 14) s2 = Student(23, 45, 56) print(s1.getAvg()) print(s2.getAvg()) print(Student.getschoolinfo()) Student.getInfo()
d3315235bd4fb593a671393c20f9783ed6e4c62b
yogeshvaral/PythonWithFlask
/PolymorphismDuckTyping.py
578
3.53125
4
class Pycharm: def execute(self): print("compiling") print("Running") class Eclipse: def execute(self): print("Checking") print("verifying") print("compiling") print("running") class Laptop: def code(self,ide): ide.execute() ide = Pycharm() ide1 = Eclipse() lap1 = Laptop() lap1.code(ide) lap1.code(ide1) """ This lap1.code will accept and work properly with any type of object until it has the execute method. THIs is called is Duck Typing.Any Bird which has even single feature of duck can be duck"""
b452707e33da8a102d2b964ba93261f4c7003108
MaVericKWareZ/automation
/lesson1.py
2,002
3.703125
4
from datetime import datetime as dt players = {} def get_age_diff(duration_in_s): days = divmod(duration_in_s, 86400) hours = divmod(days[1], 3600) minutes = divmod(hours[1], 60) seconds = divmod(minutes[1], 1) return [days,hours,minutes,seconds] def get_dob_obj(dob_str): return dt.strptime(dob_str,"%d %b %Y") def add_player(name,dob_str): players[name] = get_dob_obj(dob_str) def print_age(dob_str,name): dob_obj = get_dob_obj(dob_str) curr_date = dt.now() if dob_obj > curr_date: print("You haven't been born yet!") else: time_diff_in_s = (curr_date - dob_obj).total_seconds() time_diff_calc = [delta[0] for delta in get_age_diff(time_diff_in_s)] print("Time between dates: {:.0f} days, {:.0f} hours, {:.0f} minutes and {:.0f} seconds".format(*time_diff_calc)) add_player(name,dob_str) def is_younger(name,age_obj,curr_name): return curr_name != name and age_obj > players.get(curr_name) def print_younger_players(curr_name): younger_players = [ name for (name,age_obj) in players.items() if is_younger(name,age_obj,curr_name)] if len(younger_players): print("You are older than {} player(s)".format(str(len(younger_players)))) print("Players younger than you are -",sep=" ") print(*younger_players,sep=" , ") else: print("You are the youngest!") def play(): while True: print("What is your name?") name = input() print("It's great to meet you, " + name) print("Your name has {} letters".format(str(len(name)))) print("Enter your Date of Birth ( Ex. 7 mar 1997 )") dob_str = input() print_age(dob_str,name) if len(players) > 1: print_younger_players(name) print("Press 0 to exit") choice = input() if not int(choice): break else: print(players) print("Hello World") play()
3cffeebd9a0b35519af78d0325f7b58f55334252
mdu74/python_greeting_kata
/test_greeting.py
2,815
3.625
4
import unittest from greeting import Greeting class TestGreeting(unittest.TestCase): def test_Greeter_GivenSingleName_ShouldGreetSingleName(self): singleNames = ["Bob","Mary","Tom"] for eachName in singleNames: # Arrange name = eachName # Act result = Greeting.Greeter(name) # Assert expected = "Hello, " + name self.assertEqual(result, expected) def test_Greeter_GivenNull_ShouldReturnHelloFriend(self): # Arrange name = None # Act result = Greeting.Greeter(name) # Assert expected = "Hello, friend" self.assertEqual(result, expected) def test_Greeter_GivenShoutedNames_ShouldReturnGreetingInAllCaps(self): shoutedNames = ["TOM", "BOB", "MARY", "NKULE"] for eachName in shoutedNames: # Arrange name = eachName # Act result = Greeting.Greeter(name) # Assert expected = "HELLO, " + name self.assertEqual(result, expected) def test_Greeter_GivenShoutedNames_ShouldReturnGreetingInAllCaps(self): shoutedNames = ["TOM", "BOB", "MARY", "NKULE"] for eachName in shoutedNames: # Arrange name = eachName # Act result = Greeting.Greeter(name) # Assert expected = "HELLO, " + name self.assertEqual(result, expected) def test_Greeter_GivenTwoNames_ShouldGreetWithBothNames(self): # Arrange name = ["Tom", "Bob"] # Act result = Greeting.Greeter(name) # Assert expected = "Hello, Tom and Bob" self.assertEqual(result, expected) def test_Greeter_GivenFourNames_ShouldGreetWithAllNames(self): # Arrange names = ["Tom", "Bob", "Nkule", "Lungelo"] # Act result = Greeting.Greeter(names) # Assert expected = "Hello, Tom, Bob, Nkule and Lungelo" self.assertEqual(result, expected) def test_Greeter_GivenAnyNumberOfNames_ShouldGreetWithAllNames(self): # Arrange names = ["Rick", "Morty", "Summer", "Beth", "Jerry", "Chris"] # Act result = Greeting.Greeter(names) # Assert expected = "Hello, Rick, Morty, Summer, Beth, Jerry and Chris" self.assertEqual(result, expected) def test_Greeter_GivenMixOfNormalAndShoutedNames_ShouldGreetWithAllNamesAndShoutAtTheEnd(self): # Arrange names = ["Rick", "Morty", "Summer", "BETH", "Jerry", "Chris"] # Act result = Greeting.Greeter(names) # Assert expected = "Hello, Rick, Morty, Summer, Jerry and Chris. AND BETH" self.assertEqual(result, expected)
b2c24fe1f3d4f3474b70461b608a2c14e9d44e9b
viralsir/python_saket
/if_demo.py
1,045
4.15625
4
''' control structure if syntax : if condition : statement else : statement relational operator operator symbol greater than > less than < equal to == not equal to != greater than or equal to >= less than or equal to <= logical operator operator symbol and and or or not not ''' no1=int(input("Enter No1:")) no2=int(input("Enter No2:")) no3=int(input("Enter No3:")) if no1>0 and no2>0 and no3>0 : if no1>no2 and no1>no3: print(no1," is a maxium no") elif no2>no1 and no2>no3 : print(no2," is a maximum no") else : print(no3," is a maximum no") else : if no1<0: print(no1," is a invalid") elif no2<0: print(no2," is a invalid") else : print(no3," is a invalid") #print("invalid input")
0bdb3507ea776a6b421a6e8dfda6c3e47f2c38bd
viralsir/python_saket
/def_demo3.py
354
4.1875
4
def prime(no): is_prime=True for i in range(2,no): if no % i == 0 : is_prime=False return is_prime def factorial(no): fact=1 for i in range(1,no+1): fact=fact*i return fact # no=int(input("enter No:")) # # if prime(no): # print(no," is a prime no") # else : # print(no," is not a prime no")