blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2fd6bf337c2a5e22e4c8a9ecd158eb55545bd999
Devn913/Rock_Paper_Scissors
/RPS.py
3,091
4.34375
4
import random print('welcome to the Rock Paper Scissors!') print('This game is created by Dev Nirwal') print('Choose how you wanna play: ') print(' Single player or Multiplayer player') game_mode = input(' Type Single / Multi : ').lower() print('Lets get started') print('You will have 3 choices here') print('# # # Rock # # #') print('# # # Paper # # #') print('# # # Scissors # # #') game_continue = 'y' while game_continue == 'y': if(game_mode == 'single'): print('Welcome to the single player mode . Here you will be fighting with computer') randm_no = random.randint(1,3) if(randm_no == 1): computer_input = 'rock' elif(randm_no == 2): computer_input = 'paper' else: computer_input = 'scissors' user_input = input('Input your move Rock / Paper / Scissors : ').lower() if(user_input == computer_input): print('This is a tie. ') print(f'The computer input is {computer_input}') elif(user_input == 'rock'): if(computer_input == 'paper'): print(f'You Lose ! The computer played {computer_input}') else: print(f"You win ! The compuer played {computer_input}") elif(user_input == 'paper'): if(computer_input == 'scissors'): print(f'You Lose ! The computer played {computer_input}') else: print(f'You win ! The compuer played {computer_input}') elif(user_input == 'scissors'): if(computer_input == 'paper'): print(f'You Lose ! The compuer played {computer_input}') else: print(f'You win ! The compuer played {computer_input}') else: print('please try again') elif(game_mode == 'multi'): player1 = input('Enter your Player1 input Rock / Paper / Scissors : ').lower() for i in range(1,20): print(' N o C h e a t i n g ') player2 = input('Enter your Player2 input Rock / Paper / Scissors : ').lower() if(player1 == player2): print('This is a tie ! Both played same move ') elif(player1 == 'rock'): if(player2 == 'scissors'): print('Congratulation ! Player1 wins') elif(player2 == 'paper'): print('Congratulation ! Player2 wins') else: print('Wrong input ! Try again') elif(player1 == 'paper'): if(player2 == 'rock'): print('Congratulation ! Player1 wins') elif(player2 == 'scissors'): print('Congratulation ! Player2 wins') else: print('Wrong Input try again ! ') elif(player1 == 'scissors'): if(player2 == 'paper' ): print('Congratulation ! Player1 wins') elif(player2 == 'rock'): print('Congratulation ! Player2 wins') else: print('Wrong input ! Try again') else: print('Wrong input!') user_input = input('Do you wanna play more? (y/n)').lower() if(user_input == 'n'): break print('Thanks for playing thi game') print('Bye! Have a great time')
e8541ee9b7ff18af145566d977f5ba7cafc09cb9
Aparecida-Silva/Exercicio-pos-greve
/Questão8.py
741
3.890625
4
#Variaveis ListaB = "" verificador = 1 #Lista A só de enfeite ListaA = [] #Progama while(verificador == 1): #Pedir nome do usuario nome=str(input("Digite o nome:")) # Adicionando o nome na lista A(ListaA) ListaA.append(nome) #COntador de palavras no nome palavras = len(nome.split()) #Organização do nome for n in range(0,palavras): #Adicionando o nome iinvertido na lista(ListaB) ListaB = ListaB + nome.split()[palavras -1] palavras = palavras - 1 if (palavras == 0): ListaB = ListaB + ";" else: ListaB = ListaB + "," verificador = int(input("Digite 1 se quiser adicionar mais algum nome, ou 2 para sair e ver o resultado:")) print("(b)",ListaB)
0994fdb75642e6ecd5402c1ca62260802090dfca
dlondonmedina/intro-to-programming-python-code
/exercises/4-1/objects/main.py
1,376
4.1875
4
# "module" refers to code that is imported # copy the phone class into a file called phone.py # create 2 different objects # charge up both their batteries # notice that if you use the battery on one of them its doesn't affect the # current_battery on the other other want # Change the owner name - notice that defining the attribute(prop) outside of the # constructor makes a "static" or shared variable from phone import Phone # import Phone class from phone.py def main(): smart_phone_1 = Phone(2018,"Samsung", "$500", "32MB","8","555-666-7777") smart_phone_2 = Phone(2018,"Apple", "$700", "32MB","8","444-555-666") # charge both phones smart_phone_1.charge_battery(8) smart_phone_2.charge_battery(8) # use some battery # use 4 hours on phone 1 and 2 hours on phone 2 smart_phone_1.use_battery(4) smart_phone_2.use_battery(2) # test the current battery of each are different print("battery life is the same:",smart_phone_1.current_battery == smart_phone_2.current_battery) # show the owner - they are the same print ("owner", smart_phone_1.owner) print ("owner", smart_phone_2.owner) # change the owner on Phone - at the class level not the object # level and see that it changes for both Phone.owner = "dylan" print ("owner", smart_phone_1.owner) print ("owner", smart_phone_2.owner) main()
21fcc097433be88eef53f08037aef57674fa6d88
Goular/PythonModule
/05廖雪峰Python教程/05.函数式编程/02map.py
100
3.546875
4
def f(x): return x * x r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) result = list(r) print(result)
c5e99a6e4e0c0f1aa9e930e3315aacaca682c0cb
igarnett6/CS-1114
/1114 labs/lab9/lab9q3.py
124
4.0625
4
n = int(input("Enter a number n: ")) lst = [] for i in range(1, n+1): add = 2**i lst.append(add) print("List: ",lst)
f36c681465c3a13b8a727b8976e4524ff175fd51
ranamahmud/python-data-structures-subeen
/binary_tree_pre_order.py
236
3.5
4
from binary_tree import * def pre_order(node): print(node) if node.left: pre_order(node.left) if node.right: pre_order(node.right) if __name__ == "__main__": root = create_tree() pre_order(root)
0c6865629b6b390c99dcffbf1b9e25b7b528abd0
NRL-Plasma-Physics-Division/turbopy-training-public
/T03/T03-0/coffeeshop.py
1,974
4.34375
4
class beverage: """ A class representing a basic drink Parameters ---------- drink : str Type of base drink size : str Size of drink Attributes ---------- drink : str Type of base drink size : str Size of drink cost : float Price of drink drinks : dict (str : float) Drink names with corresponding base price sizes : dict (str : float) Drink sizes with corresponding price multiplier """ drinks = {'coffee': 2.5, 'espresso': 1.5, 'black tea': 2.5, 'green tea': 2.75} sizes = {'s': 0.8, 'm': 1, 'l': 1.2} def __init__(self, drink, size): self.drink = drink self.size = size self.cost = self.drinks[drink] * self.sizes[size] class drink_with_toppings(beverage): """ A class representing a drink with toppings Parameters ---------- bev : beverage Type of base beverage additions : list of strings Toppings of new beverage Attributes ---------- additions : list of strings Toppings of new beverage cost : float Price of drink toppings : dict (str : float) Topping names with corresponding price """ toppings = {'2% milk': 0.5, 'soy milk': 0.5, 'almond milk': 0.5, 'ice': 0.25, 'simple syrup': 0.25, 'caramel': 0.5, 'boba': 1, 'espresso shot': 1.5} def __init__(self, bev, additions): super().__init__(bev.drink, bev.size) self.additions = additions self.cost += sum([self.toppings[add] for add in self.additions]) # add all toppings self.cost -= self.toppings[self.additions[0]] # take out the first topping MY_ORDER = drink_with_toppings(beverage('green tea', 's'), ['soy milk', 'ice', 'caramel', 'boba']) print('$' + str(MY_ORDER.cost))
b1ff43b893e687f7b9b65ceae41b6598192cfc54
pawloxx/CodeWars
/is_perfect_square.py
271
4.03125
4
""" is_square (-1) # => false is_square 0 # => true is_square 3 # => false is_square 4 # => true is_square 25 # => true is_square 26 # => false """ from math import sqrt def is_square(n): return int(n) > -1 and sqrt(n) % 1 == 0 print(is_square(1905835656))
8f5bd9e5630a29812d64241464ba6a148a7915d3
nga-27/SecuritiesAnalysisTools
/libs/tools/math_functions.py
11,845
3.5625
4
""" math functions """ from typing import Tuple, Union import pandas as pd import numpy as np from scipy.stats import linregress def lower_low(data: Union[list, pd.DataFrame], start_val: float, start_ind: int) -> list: """Lower Low Looks for a bounce (rise) then lower low Arguments: data {list} -- price data start_val {float} -- a low to find a lower start_ind {int} -- starting index where the low exists Returns: list - [lower_value, respective_index] """ data = list(data) track_ind = start_ind track_val = start_val # 0: first descent or rise; 1: lower low (in progress); 2: rise (lowest low found/not found) bounce_state = 0 lows = [] for price in range(start_ind, len(data)): if (data[price] < start_val) and (bounce_state < 2): track_ind = price track_val = data[price] bounce_state = 1 if (data[price] > track_val) and (bounce_state == 1): bounce_state = 2 if (data[price] < track_val) and (bounce_state > 1): bounce_state = 3 track_ind = price track_val = data[price] if (data[price] > track_val) and (bounce_state == 3): bounce_state = 4 lows.append([track_val, track_ind]) return lows def higher_high(data: Union[list, pd.DataFrame], start_val: float, start_ind: int) -> list: """Higher High Looks for a bounce (drop) then higher high Arguments: data {list} -- price data start_val {float} -- a low to find a lower start_ind {int} -- starting index where the low exists Returns: list - [lower_value, respective_index] """ data = list(data) track_ind = start_ind track_val = start_val # 0: first descent or rise; 1: lower low (in progress); 2: rise (lowest low found/not found) bounce_state = 0 highs = [] for price in range(start_ind, len(data)): if (data[price] > start_val) and (bounce_state < 2): track_ind = price track_val = data[price] bounce_state = 1 if (data[price] < track_val) and (bounce_state == 1): bounce_state = 2 if (data[price] > track_val) and (bounce_state > 1): bounce_state = 3 track_ind = price track_val = data[price] if (data[price] < track_val) and (bounce_state == 3): bounce_state = 4 highs.append([track_val, track_ind]) return highs def bull_bear_th(osc: list, start: int, thresh: float, bull_bear: str = 'bull') -> Union[int, None]: """Bull Bear Thresholding Arguments: osc {list} -- oscillator signal start {int} -- starting index to find the threshold thresh {float} -- threshold for comparison Keyword Arguments: bull_bear {str} -- type, either 'bull' or 'bear' (default: {'bull'}) Returns: int -- index that is above/below threshold """ count = start if bull_bear == 'bull': while count < len(osc): if osc[count] > thresh: return count count += 1 if bull_bear == 'bear': while count < len(osc): if osc[count] < thresh: return count count += 1 return None def beta_comparison(fund: pd.DataFrame, benchmark: pd.DataFrame) -> Tuple[float, float]: """Beta Comparison Arguments: fund {pd.DataFrame} -- fund historical data benchmark {pd.DataFrame} -- a particular benchmark's fund historical data Returns: list -- beta {float}, r-squared {float} """ tot_len = len(fund['Close']) if pd.isna(fund['Close'][len(fund['Close'])-1]): tot_len -= 1 fund_return = [] fund_return.append(0.0) bench_return = [] bench_return.append(0.0) for i in range(1, tot_len): ret = (fund['Close'][i]-fund['Close'][i-1]) / \ fund['Close'][i-1] * 100.0 fund_return.append(ret) ret = (benchmark['Close'][i]-benchmark['Close'] [i-1]) / benchmark['Close'][i-1] * 100.0 bench_return.append(ret) # slope, intercept, r-correlation, p-value, stderr slope, _, r_value, _, _ = linregress(bench_return, fund_return) r_sqd = r_value ** 2 return slope, r_sqd def beta_comparison_list(fund: list, benchmark: list) -> Tuple[float, float]: """Beta Comparison List Like above, but compares entire list versus a benchmark Arguments: fund {list} -- list of the fund to compare benchmark {list} -- list of the benchmark, such as S&P500 Returns: list -- beta, r-squared """ tot_len = len(fund) fund_return = [] fund_return.append(0.0) bench_return = [] bench_return.append(0.0) for i in range(1, tot_len): ret = (fund[i]-fund[i-1]) / fund[i-1] * 100.0 fund_return.append(ret) ret = (benchmark[i]-benchmark[i-1]) / benchmark[i-1] * 100.0 bench_return.append(ret) # slope, intercept, r-correlation, p-value, stderr slope, _, r_value, _, _ = linregress(bench_return, fund_return) r_sqd = r_value ** 2 return slope, r_sqd def risk_comparison(fund: pd.DataFrame, benchmark: pd.DataFrame, treasury: pd.DataFrame, beta: float = None, rsqd: float = None, **kwargs) -> dict: """Risk Comparison Alpha metric, with Sharpe Ratio, Beta, R-Squared, and Standard Deviation Arguments: fund {pd.DataFrame} -- fund dataset benchmark {pd.DataFrame} -- benchmark dataset (does not have to be SP500) treasury {pd.DataFrame} -- 11-week treasury bill dataset Keyword Arguments: beta {float} -- beta figure; will calculate if None (default: {None}) rsqd {float} -- r-squared figure; will calculate if None (default: {None}) Optional Args: print_out {bool} -- prints risk ratios to terminal (default: {False}) sector_data {pd.DataFrame} -- data of related sector (default: {None}) Returns: dict -- alpha data object """ # pylint: disable=too-many-locals,too-many-statements print_out = kwargs.get('print_out', False) sector_data = kwargs.get('sector_data') alpha = {} if beta is None or rsqd is None: beta, rsqd = beta_comparison(fund, benchmark) beta = np.round(beta, 4) rsqd = np.round(rsqd, 4) fund_return, fund_stdev = get_returns(fund) bench_return, bench_stdev = get_returns(benchmark) treas_return = treasury['Close'][-1] alpha_sector = "n/a" beta_sector = "n/a" rsqd_sector = "n/a" sharpe_ratio = "n/a" market_sharpe = "n/a" if sector_data is not None: sector_return, _ = get_returns(sector_data) beta_sector, rsqd_sector = beta_comparison(fund, sector_data) beta_sector = np.round(beta_sector, 4) rsqd_sector = np.round(rsqd_sector, 4) alpha_sector = np.round(fund_return - treas_return - beta_sector * (sector_return - treas_return), 4) alpha_val = np.round(fund_return - treas_return - beta * (bench_return - treas_return), 4) if fund_stdev != 0.0: sharpe_ratio = np.round((fund_return - treas_return) / fund_stdev, 4) if bench_stdev != 0.0: bench_sharpe = np.round((bench_return - treas_return) / bench_stdev, 4) market_sharpe = np.round(sharpe_ratio / bench_sharpe, 4) fund_stdev = np.round(fund_stdev, 4) alpha['alpha'] = {"market": alpha_val} alpha['beta'] = {"market": beta} alpha['r_squared'] = {"market": rsqd} alpha['sharpe'] = sharpe_ratio alpha['market_sharpe'] = market_sharpe alpha['standard_deviation'] = fund_stdev alpha['returns'] = { 'fund': fund_return, 'benchmark': bench_return, 'treasury': treas_return } _, _, fund_interval_std = get_interval_standard_dev(fund) _, _, bench_interval_std = get_interval_standard_dev(benchmark) alpha['standard_dev_ratio'] = np.round(fund_interval_std/bench_interval_std, 4) if sector_data is not None: alpha['returns']["sector"] = sector_return alpha['alpha']["sector"] = alpha_sector alpha['beta']["sector"] = beta_sector alpha['r_squared']["sector"] = rsqd_sector if print_out: print("\r\n") print(f"\r\nAlpha Market:\t\t{alpha_val}") print(f"Alpha Sector:\t\t{alpha_sector}") print(f"Beta Market:\t\t{beta}") print(f"Beta Sector:\t\t{beta_sector}") print(f"R-Squared Market:\t{rsqd}") print(f"R-Squared Sector:\t{rsqd_sector}") print(f"Sharpe Ratio:\t\t{sharpe_ratio}") print(f"Market Sharpe:\t\t{market_sharpe}") print(f"Standard Dev:\t\t{fund_stdev}") print(f"Market Ratio SD:\t{alpha['standard_dev_ratio']}") return alpha def get_returns(data: pd.DataFrame, output: str = 'annual') -> Union[float, float]: """Get Returns Arguments: data {pd.DataFrame} -- fund dataset Keyword Arguments: output {str} -- return for a period (default: {'annual'}) Returns: list -- return, standard deviation """ # pylint: disable=too-many-locals # Determine intervals for returns, start with annual interval = 250 years = int(len(data['Close']) / interval) if years == 0: years = 1 quarters = 4 * years if len(data['Close']) <= interval: interval = 200 annual_returns = 0.0 annual_std = [] for i in range(years): ars = (data['Adj Close'][(i+1) * interval] - data['Adj Close'] [i * interval]) / data['Adj Close'][i * interval] * 100.0 annual_returns += ars annual_std.append(ars) annual_returns /= float(years) annual_returns = (data['Adj Close'][-1] - data['Adj Close'] [-interval]) / data['Adj Close'][-interval] * 100.0 # Determine intervals for returns, next with quarterly q_returns = 0.0 q_std = [] qrs_2 = 0.0 counter = 0 for i in range(quarters): multiple = 62 if i % 2 != 0: multiple = 63 counter += multiple qrs = (data['Adj Close'][counter] - data['Adj Close'] [counter - multiple]) / data['Adj Close'][counter - multiple] * 100.0 q_returns += qrs qrs_2 += qrs if i % 4 == 3: q_std.append(qrs_2) qrs_2 = 0.0 q_returns /= float(quarters) q_returns *= 4.0 q_returns = 0.0 for i in range(4): start = -1 + -1 * int(62.5 * float(i)) subtract = -1 * int(62.5 * float(i + 1)) qrs = (data['Adj Close'][start] - data['Adj Close'] [subtract]) / data['Adj Close'][subtract] * 100.0 q_returns += qrs std_1 = np.std(annual_std) std_2 = np.std(q_std) returns = np.mean([q_returns, annual_returns]) st_devs = np.mean([std_1, std_2]) if output == 'quarterly': returns /= 4.0 return returns, st_devs def get_interval_standard_dev(data: pd.DataFrame, interval: int=250) -> Tuple[float, float, float]: """get_return_standard_dev Mean, Median, Std of return rates from day-to-day Args: data (pd.DataFrame): fund dataset interval (int, optional): trading periods. Defaults to 250. Returns: Tuple[float, float, float]: mean, median, std """ data_slice = data['Adj Close'][-interval:] returns = [0.0] * len(data_slice) for i in range(1, len(data_slice)): returns[i] = (data_slice[i] - data_slice[i-1]) / data_slice[i-1] return np.mean(returns), np.median(returns), np.std(returns)
bf3bbd762d7f12b3e1bf4abe8f455a424662256d
JAYARAJ2014/python
/exceptions2.py
395
3.53125
4
from pprint import pprint try: file = open("app.py") pprint(file.readlines()) age = int(input("Age")) xfactor = 10/age except (ValueError, ZeroDivisionError): print("You didn't enter a valid age") else: print("THere was no errors") finally: file.close() #finally block closes the open file print("Execution continues...") ## Compare this to try-catch-finally in C#
d4857a8303781e1a67dcffc52093ee6f7e77750b
TimmontCd/Proyecto-Peliculas-
/Python Proyecto/Menu.py
3,946
4.125
4
def menu(): opc = 0 Peliculas = {'Tortugas_Ninja':' B'} while opc != 6: print("*" * 10) print(" MENU ") print("*" * 10) print("[1] SUBIR PELICULA") print("[2] MODIFICAR PELICULA") print("[3] ELIMINAR PELICULA") print("[4] BUSCAR CLASIFICACION") print("[5] IMPRIMIR PELICULAS") print("[6] SALIR") try: opc = int(input("Opcion: ")) except ValueError: print("Error en la opcion, RECUERDA SOLO USAR ENTEROS!") print("*" * 10) if opc == 1: try: print("ALTA") AltaPelicula(Peliculas) except: print("Se ha producido un error, use los caracteres correctos.") elif opc == 2: print("CAMBIO ") NombrePelicula = input("Inserte Nombre de la pelicula: ") if NombrePelicula.istitle() == True : CambioPelicula(Peliculas,NombrePelicula) else : print("Volviendo al Menu Principal, NO CARACTERES VALIDOS") print("*" * 10) elif opc == 3: print("BAJA") NombrePelicula = input("Inserte Nombre de la pelicula: ") if NombrePelicula.istitle() == True : BajaPelicula(Peliculas, NombrePelicula) print("*" * 10) else : print("Volviendo al Menu Principal, INSERTE SOLO LETRAS") print("*" * 10) elif opc == 4: print("BUSQUEDA") Busqueda = input("Ingrese Clasificacion a Buscar: ") if Busqueda.istitle() == True : result = Peliculas print( dict(filter(lambda x: x[1] == Busqueda, result.items()))) print("*" * 10) else : print("Volviendo al Menu Principal, INSERTE SOLO LETRAS") print("*" * 10) elif opc == 5: print("IMPRESION DE PELICULAS!!") print(Peliculas) print("") input("Presione Enter para continuar...") elif opc == 6: print("Adios.") def AltaPelicula(Peliculas): try: PeliculaNombre = input("Ingrese Nombre de la Pelicula: ") Clasificacion= input("Inserte Clasificacion: ") if PeliculaNombre.istitle(): Peliculas.update({PeliculaNombre:Clasificacion}) print("") print("Pelicula Guardada de manera CORRECTA!") return Peliculas else: raise Exception except: print("No se guardo el registro, ERROR EN EL FORMATO DEL TITULO") else: print("") print("Pelicula Guardada de manera CORRECTA!") def CambioPelicula(Peliculas,NombrePelicula): try: if NombrePelicula in Peliculas: PeliculaNombre = input("Ingrese Nuevo NOMBRE de la Pelicula: ") Clasificacion= input("Inserte Clasificacion: ") if PeliculaNombre.istitle()==True: Peliculas.update({PeliculaNombre:Clasificacion}) print("") print("Pelicula Modificada de manera CORRECTA!") return Peliculas else: raise Exception else: print("No se encontro la pelicula") return Peliculas except: print("No se guardo el registro, ERROR EN EL FORMATO DEL TITULO") def BajaPelicula(Peliculas, NombrePelicula): if NombrePelicula in Peliculas: Peliculas.pop(NombrePelicula) print("Eliminacion Correcta") return Peliculas else : print("No se encontro la pelicula") return Peliculas if __name__ == "__main__" : menu()
961e6b9b635d11045e8468720ded0f871a2d696b
deyim/python_prac
/mentor_week12.py
1,056
3.609375
4
def searchList(L, x): for i in range(len(L)): if(x == L[i]): return i return -1 def main(): fp_r = open("DataIn_02.txt", "r") fp_w = open("Out_02.txt", "w") for r in fp_r: key = int(r) values = fp_r.readline() i = searchList(values, key) if i != -1: fp_w.write("Key %d is at %d in " % (key, i)) else: fp_w.write("Key %d is not in " % (key)) fp_w.write(values) fp_r.close() fp_w.close() if __name__ == '__main__': main() ''' fp_r = open("DataIn_01.txt", "r") fp_w = open("Out_01.txt", "w") fp_w.write("The square results are\n") num = [] for s in fp_r: for x in s.split(): x = int(x) ; square = x*x num.append(x) fp_w.write("%2d " % square) fp_w.write("\n") fp_w.write("--------------------------------\n") totsum = 0 ; cnt = 0 for number in num: totsum = totsum + number cnt = cnt + 1 fp_w.write("The sum of input data is %d\n" % totsum) fp_w.write("--------------------------------\n") average = float(totsum)/cnt fp_w.write("The average of input data is %.3f\n" % average) fp_r.close() fp_w.close() '''
bb8e9eb19f83e3e4408af6cb5adfa02a74d9cb78
suntong/lang
/lang/Python/StringTemplate.py
816
3.875
4
#!/usr/bin/python3 from string import Template #open the file filein = open( 'StringTemplate.tmpl' ) #read it src = Template( filein.read() ) #document data title = "This is the title" subtitle = "And this is the subtitle" list = ['first', 'second', 'third'] d={ 'title':title, 'subtitle':subtitle, 'list':'\n'.join(list) } #do the substitution result = src.substitute(d) print(result) """ Python technique or simple templating system for plain text output http://stackoverflow.com/questions/6385686/python-technique-or-simple-templating-system-for-plain-text-output Simple solutions to simple problems Use the standard library string template: http://docs.python.org/library/string.html#template-strings Output: $ StringTemplate.py This is the title ... And this is the subtitle ... first second third """
02f7d845e5f6f16a26e850e3db9fd46546b54d0e
timmyjing/python-practice
/hasGivenPath.py
519
3.609375
4
# Given a binary tree t and an integer s, determine whether there is a # root to leaf path in t such that the sum of vertex values equals s. def hasPathWithGivenSum(t, s): if t == None: return s == 0 if t.value == s and not t.left and not t.right: return True left = False right = False if t.left: left = hasPathWithGivenSum(t.left, s - t.value) if t.right: right = hasPathWithGivenSum(t.right, s - t.value) return left or right
e0db18ec8d713e9a259f23ce5d24667b18718bc2
BarbecuePizza/Mypython
/ python基础/getset.py
702
3.625
4
# -*-coding:utf-8 -*- #!/usr/local/bin/python3 class Student(object): """docstring for Stedent""" def __init__(self, name, score): self.__name = name self.__score = score def info(self): print('学生:%s; 分数:%s' % (self.__name, self.__score)) def get_score(self): return self.__score def set_score(self, score): if 0 <= score <= 100: self.__score = score else: print('请输入0到100的数字。') # set用来避免传入无效的参数 stu = Student('xiaoming', 95) print('修改前分数:', stu.get_score()) stu.info() stu.set_score(122) print('修改后分数:', stu.get_score()) stu.info()
c632a8965e24be5fc8376120029ff39a9e4847b5
slfdstrctd/num_methods
/4/main.py
4,671
3.671875
4
print("Приближённое вычисление интеграла по составным квадратурным формулам\nВариант 5\n") # Вес w(x) def w(y): return 1 # Функция f(x) def f(y): global ty if ty == 1: return w(y) * 1 if ty == 2: return w(y) * 2 * y if ty == 3: return w(y) * 4 * (y ** 3) - 2 * y # Max f^(d_+1) для d = 1, 3 def m_(d_): global ty if d_ == 1: if ty == 1: return 0 if ty == 2: return 0 if ty == 3: return 24 * b if d_ == 3: return 0 return 0 # Первообразная f def p_(y): global ty if ty == 1: return y if ty == 2: return y ** 2 if ty == 3: return y ** 4 - y ** 2 # КФ левых прямоугольников def left(): s = 0 k = 0 for j in range(m): s += values[j][1] k += 1 print('count', k) return h * s # КФ правых прямоугольников def right(): s = 0 k = 0 for j in range(1, m + 1): s = s + values[j][1] k += 1 print('count', k) return h * s # КФ средних прямоугольников def mid(): s = 0 k = 0 for j in range(m): s = s + f(values[j][0] + h / 2) k += 1 print('count', k) return h * s # КФ Трапеций def trapeze(): s = 0 k=0 for j in range(1, m): s += values[j][1] k += 1 print('count', k) return h * ((values[0][1] + values[m][1]) / 2 + s) # КФ Симпсона def simpson(): v = [] s_1 = 0 s_2 = 0 for j in range(2 * m + 1): x_ = (a + j * h / 2) v.append((x_, f(x_))) for j in range(1, 2 * m, 2): s_1 = s_1 + v[j][1] for j in range(2, 2 * m - 1, 2): s_2 = s_2 + v[j][1] return (h / 6) * (v[0][1] + 4 * s_1 + 2 * s_2 + v[2 * m][1]) r = 1 while r: print("Введите номер функции:\n" "1) f(x) = 1\n" "2) f(x) = 2x\n" "3) f(x) = 4x^3 - 2x") ty = int(input()) print("Нижний предел интегрирования, A:") a = float(input()) print("Верхний предел интегрирования, B:") b = float(input()) print("Число промежутков деления, m:") m = int(input()) values = [] h = (b - a) / m # длина частичного разбиения # Массив узлов и значений функции в них for i in range(m + 1): xi = (a + i * h) values.append((xi, f(xi))) print('h =', h) print('w(x) =', w(1)) j_ = p_(b) - p_(a) # точный интеграл print('Точное значение интеграла J = F(B) - F(A) =', j_) c = 1 / 2 # const для оценки погрешности d = 1 # точность формулы int_ = left() # вычисленный интеграл print('\nМетод левых прямоугольников, J(h):', int_) print('Фактическая погрешность, |J - J(h)|:', abs(j_ - int_)) err = c * m_(d) * (b - a) * (h ** (d + 1)) print('Теоретическая погрешность:', err) int_ = right() print('\nМетод правых прямоугольников, J(h):', int_) print('Фактическая погрешность, |J - J(h)|:', abs(j_ - int_)) err = c * m_(d) * (b - a) * (h ** (d + 1)) print('Теоретическая погрешность:', err) int_ = mid() c = 1 / 24 print('\nМетод средних прямоугольников, J(h):', int_) print('Фактическая погрешность, |J - J(h)|:', abs(j_ - int_)) err = c * m_(d) * (b - a) * (h ** (d + 1)) print('Теоретическая погрешность:', err) int_ = trapeze() c = 1 / 12 print('\nМетод трапеций, J(h):', int_) print('Фактическая погрешность, |J - J(h)|:', abs(j_ - int_)) err = c * m_(d) * (b - a) * (h ** (d + 1)) print('Теоретическая погрешность:', err) c = 1 / 2880 d = 3 int_ = simpson() print('\nМетод Симпсона, J(h):', int_) print('Фактическая погрешность, |J - J(h)|:', abs(j_ - int_)) err = c * m_(d) * (b - a) * (h ** (d + 1)) print('Теоретическая погрешность:', err) print("Введите 0 для выхода, 1 для продолжения: ") r = int(input())
30410778f4121ca917a3f9eb3bd0b235cbca5800
Eric-Wonbin-Sang/CS110Manager
/2020F_quiz_2_pt_2_submissions/liethan/Quiz 2 Part 2.py
2,746
4.25
4
def main(): start = input("Please enter 1 for mathematical functions, or enter 2 for string operations: ") if start == "1": math = input("Please enter 1 for addition, 2 for subtraction, 3 for multiplication, or 4 for division: ") if math == "1": input1 = float(input("Please enter the first number: ")) input12 = float(input("Please enter the number you would like to add to the first number: ")) add = input1 + input12 print(add, "is the sum of the two numbers entered") elif math == "2": input2 = float(input("Please enter the first number: ")) input22 = float(input("Please enter the number you would like to subtract from the first number: ")) sub = input2 - input22 print(sub, "is the difference of the two numbers entered") elif math == "3": input3 = float(input("Please enter the first number: ")) input32 = float(input("Please enter the number you would like to multiply with the first number: ")) mul = input3 * input32 print(mul, "is the product of the two numbers entered") elif math == "4": input4 = float(input("Please enter the first number: ")) input42 = float(input("Please enter the number you would like to add to the first number: ")) div = input4 / input42 print(div, "is the quotient of the two numbers entered") else: print("That is not a valid input") elif start == "2": inputs = input( "Please enter 1 if you would like to determine the number of vowels in a string, or enter 2 if you would like to encrypt a string: ") if inputs == "1": message = input("Please enter the string you would like to determine the number of vowels in: ") lowermessage = message.lower() count = 0 a = lowermessage.count("a") count = count + a e = lowermessage.count("e") count = count + e i = lowermessage.count("i") count = count + i o = lowermessage.count("o") count = count + o u = lowermessage.count("u") count = count + u print("There are", count, "vowels in your string") elif inputs == "2": message = input("Please enter the string you would like to encrypt: ") print("This is the encrypted message") for i in message: x = ord(i) print("", 2 * x + 3, end="") print() else: print("That is not a valid input") else: print("That is not a valid input") main()
caa0e449793138ededaac5d073d38f9574b57e18
pushker-git/LeetCodeTopInterviewQuestions
/Daily Byte/modeInBST.py
1,066
3.9375
4
Given a binary search tree, return its mode (you may assume the answer is unique). If the tree is empty, return -1. Note: the mode is the most frequently occurring value in the tree. Ex: Given the following tree... 2 / \ 1 2 return 2. Ex: Given the following tree... 7 / \ 4 9 / \ / \ 1 4 8 9 \ 9 return 9. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def findMode(self, root:TreeNode) -> List[int]: if root == None: return [] result = [] dictionary = {} def dfs(root): if root == None: return None if root.val in dictionary: dictionary[root.val] += 1 else: dictionary[root.val] = 1 dfs(root.left) dfs(root.right) dfs(root) maximum = 0 for key, value in dictionary.items(): if maximum < value: maximum = value for key, value in dictionary.items(): if value == maximum: result.append(key) return result
8e57be00bfba1c737dda7f4407126cabd4386627
XyliaYang/Leetcode_Record
/python_version/Interview28.py
990
3.75
4
# @Time : 2020/2/25 17:59 # @Author : Xylia_Yang # @Description : class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: return self.Symmetric(root,root) def Symmetric(self,roo1,root2): if not roo1 and not root2: return True if (roo1 and not root2) or (not roo1 and root2): return False if roo1.val !=root2.val: return False return self.Symmetric(roo1.left,root2.right) and self.Symmetric(roo1.right, root2.left) if __name__=='__main__': root=TreeNode(1) root.left=TreeNode(2) root.right=TreeNode(2) root.left.left=TreeNode(3) root.left.right=TreeNode(4) root.right.left=TreeNode(4) root.right.right=TreeNode(3) solution=Solution() print(solution.isSymmetric(root))
e74ae3c5e1b5c6d1f731e035dc5bf6a15fc14c95
McRules2004/DTCassessment
/Project/question.py
1,359
4.09375
4
""" Joel McKinnon September 2021 Question Class """ # imports import random # class of question, this class will generate the question and all needed variations/answers class Question: def __init__(self, question_num): self.question_num = question_num Units = ["x", "+", "-"] # list of units # generate all random number and unit self.operator = random.choice(Units) self.first_digit = random.randint(0, 10) self.second_digit = random.randint(0, 10) # function to gain the solution to the question def solution(self): # checking which unit if self.operator == "x": return self.first_digit * self.second_digit elif self.operator == "+": return self.first_digit + self.second_digit elif self.operator == "-": return self.first_digit - self.second_digit # function to make sure solution is an int def checks(self, answer): return self.solution() == int(answer) # function to form question as string def to_string(self): return "Question {}: {} {} {} =".format(self.question_num, self.first_digit, self.operator, self.second_digit) # function to form shorter string used in csv file def to_short_string(self): return "{} {} {}".format(self.first_digit, self.operator, self.second_digit)
1ce020a7d394af9462864330c3084b365dbf2e2c
arteum33/homework_lesson_2_Part2
/Homework_Lesson_2_part_2.py
2,860
4
4
#Задачи на циклы и оператор условия------ #---------------------------------------- ''' # Задача 1 # Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована. a = 0 for i in range(5): print(i+1, a, sep='.') ''' ''' # Задача 2 # Пользователь в цикле вводит 10 цифр. Найти количество введеных пользователем цифр 5. i = 0 count = 0 while i < 10: number = input('введите число от 1 до 10: ') number = int(number) if number == 5: count = count + 1 i = i + 1 if i == 10: break print('Количество повторов числа 5: ', count) ''' ''' # Задача 3 # Найти сумму ряда чисел от 1 до 100. Полученный результат вывести на экран. sum = 0 for i in range(1,101): sum += i print(sum) ''' ''' # Задача 4 # Найти произведение ряда чисел от 1 до 10. Полученный результат вывести на экран. multiplication = 1 for i in range(1,10): multiplication *= i print(multiplication) ''' ''' # Задача 5 # Вывести цифры числа на каждой строчке. number = 56229 while number>0: print(number%10) number = number//10 ''' ''' # Задача 6 # Найти сумму цифр числа. sum = 0 number = 56987 while number>0: sum += number % 10 number = number//10 print(sum) ''' ''' # Задача 7 # Найти произведение цифр числа. multiplication = 1 number = 56743 while number>0: multiplication *= number % 10 number = number//10 print(multiplication) ''' ''' # Задача 8 # Дать ответ на вопрос: есть ли среди цифр числа 5? number = input('Введите число: ') number = int(number) while number>0: if number%10 == 5: print('5 есть в составе числа') break number = number//10 else: print('5 нет в составе числа') ''' ''' # Задача 9 # Найти максимальную цифру в числе number = input('Введите число: ') number = int(number) max_num = number%10 number = number//10 while number > 0: if number%10 > max_num: max_num = number%10 number = number//10 print(max_num) ''' ''' # Задача 10 # Найти количество цифр 5 в числе count = 0 number = input('Введите число: ') number = int(number) while number>0: if number%10 == 5: count = count + 1 number = number//10 print('Количество повторов числа 5: ', count) '''
b88a5d2917dd549f2474cdf0e1192daaef005b7d
CodeTemplar99/learnPython
/Exceptions/handling_exceptions.py
927
4.46875
4
# to handle exceptions properly and prevent your program from crashing # put the code to be executed in a try block and # use the except block to print a friendly message for the error try: age = int(input("Age:")) # when a above throws an exception, the code below will not be executed because the control # is now moved to the except block, skipping the code below the error caught # this text below will not print if there's an error in age print("oh really?") except ValueError: # the valueError is type of exception # additional values or arguments can be passed to the except e.g # except ValueError as ex(for exception), error(for errors) print("you didn't enter a valid age") # you can add an else statement ==> this block executes after no exception is caught else: print("no exception caught") # the code below continues after or not catching an error print("execution continues")
0e239323c8a6473c2a9ed1ba4df2d1261ca75234
humbertoperdomo/practices
/python/PythonCrashCourse/PartI/Chapter10/favorite_number_remembered.py
444
3.765625
4
#!/usr/bin/python3 """ Favorite number remembered.""" import json file_name = 'text_files/favorite_number.json' try: with open(file_name) as f_obj: favorite_number = json.load(f_obj) except FileNotFoundError: favorite_number = input("What is your favorite number? ") with open(file_name, 'w') as f_obj: json.dump(favorite_number, f_obj) else: print("I know your favorite number! It's " + favorite_number + ".")
f67c558dd6c3a703ebd03819110321142cdc505c
Ashwathguru/MACHINE-LEARNING---FUNDAMENTALS
/FML_LAB/pythonex.py
19,522
4.40625
4
#add_numbers is a function that takes two numbers and adds them together. def add_numbers(x, y): return x + y add_numbers(1, 2) ------------------------------------- #add_numbers updated to take an optional 3rd parameter. #Using print allows printing of multiple expressions within a single cell. def add_numbers(x,y,z=None): if (z==None): return x+y else: return x+y+z print(add_numbers(1, 2)) print(add_numbers(1, 2, 3)) ------------------------------------- #add_numbers updated to take an optional flag parameter. def add_numbers(x, y, z=None, flag=False): if (flag): print('Flag is true!') if (z==None): return x + y else: return x + y + z print(add_numbers(1, 2, flag=True)) ------------------------------------- #Assign function add_numbers to variable a. def add_numbers(x,y): return x+y a = add_numbers a(1,2) ------------------------------------- #The Python Programming Language: Types and Sequences #Use type to return the object's type. type('This is a string') str type(None) NoneType type(1) int type(1.0) float type(add_numbers) ------------------------------------- #Tuples are an immutable data structure (cannot be altered). x = (1, 'a', 2, 'b') type(x) Lists are a mutable data structure x = [1, 'a', 2, 'b'] type(x) Use append to append an object to a list. x.append(3.3) print(x) This is an example of how to loop through each item in the list. for item in x: print(item) Or using the indexing operator: i=0 while( i != len(x) ): print(x[i]) i = i + 1 Use + to concatenate lists. [1,2] + [3,4] Use * to repeat lists. [1]*3 Use the in operator to check if something is inside a list. 1 in [1, 2, 3] Now let's look at strings. Use bracket notation to slice a string. x = 'This is a string' print(x[0]) #first character print(x[0:1]) #first character, but we have explicitly set the end character print(x[0:2]) #first two characters This will return the last element of the string. x[-1] This will return the slice starting from the 4th element from the end and stopping before the 2nd element from the end. x[-4:-2] This is a slice from the beginning of the string and stopping before the 3rd element. x[:3] And this is a slice starting from the 4th element of the string and going all the way to the end. x[3:] firstname = 'Christopher' lastname = 'Brooks' print(firstname + ' ' + lastname) print(firstname*3) print('Chris' in firstname) split returns a list of all the words in a string, or a list split on a specific character. firstname = 'Christopher Arthur Hansen Brooks'.split(' ')[0] # [0] selects the first element of the list lastname = 'Christopher Arthur Hansen Brooks'.split(' ')[-1] # [-1] selects the last element of the list print(firstname) print(lastname) Make sure you convert objects to strings before concatenating. 'Chris' + 2 Dictionaries associate keys with values. x = {'Christopher Brooks': 'brooksch@umich.edu', 'Bill Gates': 'billg@microsoft.com'} x['Christopher Brooks'] # Retrieve a value by using the indexing operator {'Bill Gates': 'billg@microsoft.com', 'Christopher Brooks': 'brooksch@umich.edu'} x['Kevyn Collins-Thompson'] = None x['Kevyn Collins-Thompson'] {'Bill Gates': 'billg@microsoft.com', 'Kevyn Collins-Thompson': None, 'Christopher Brooks': 'brooksch@umich.edu'} Iterate over all of the keys: for name in x: print(x[name]) Iterate over all of the values: for email in x.values(): print(email) Iterate over all of the items in the list: for name, email in x.items(): print(name) print(email) You can unpack a sequence into different variables: x = ('Christopher', 'Brooks', 'brooksch@umich.edu') fname, lname, email = x fname lname Make sure the number of values you are unpacking matches the number of variables being assigned. x = ('Christopher', 'Brooks', 'brooksch@umich.edu', 'Ann Arbor') fname, lname, email = x The Python Programming Language: More on Strings print('Chris' + 2) print('Chris' + str(2)) Python has a built in method for convenient string formatting. sales_record = { 'price': 3.24, 'num_items': 4, 'person': 'Chris'} sales_statement = '{} bought {} item(s) at a price of {} each for a total of {}' print(sales_statement.format(sales_record['person'], sales_record['num_items'], sales_record['price'], sales_record['num_items']*sales_record['price'])) The Python Programming Language: Dates and Times import datetime as dt import time as tm time returns the current time in seconds since the Epoch. (January 1st, 1970) tm.time() 1534591038.82 Convert the timestamp to datetime. dtnow = dt.datetime.fromtimestamp(tm.time()) dtnow datetime.datetime(2018, 8, 18, 11, 19, 16, 902526) Handy datetime attributes: dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second # get year, month, day, etc.from a datetime (2018, 8, 18, 11, 19, 16) timedelta is a duration expressing the difference between two dates. delta = dt.timedelta(days = 100) # create a timedelta of 100 days delta datetime.timedelta(100) date.today returns the current local date. today = dt.date.today() today - delta # the date 100 days ago datetime.date(2018, 5, 10) today > today-delta # compare dates True The Python Programming Language: Objects and map() An example of a class in python: class Person: department = 'School of Information' #a class variable def set_name(self, new_name): #a method self.name = new_name def set_location(self, new_location): self.location = new_location person = Person() person.set_name('Christopher Brooks') person.set_location('Ann Arbor, MI, USA') print('{} live in {} and works in the department {}'.format(person.name, person.location, person.department)) Christopher Brooks live in Ann Arbor, MI, USA and works in the department School of Information Here's an example of mapping the min function between two lists. store1 = [10.00, 11.00, 12.34, 2.34] store2 = [9.00, 11.10, 12.34, 2.01] cheapest = map(min, store1, store2) cheapest <map at 0x7f7e3005f860> people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero'] def split_title_and_name(person): title = person.split()[0] lastname = person.split()[-1] return '{} {}'.format(title, lastname) list(map(split_title_and_name(), people)) Now let's iterate through the map object to see the values. for item in cheapest: print(item) 9.0 11.0 12.34 2.01 --------------------------------------------------------- The Python Programming Language: Lambda and List Comprehensions Here's an example of lambda that takes in three parameters and adds the first two. my_function = lambda a, b, c : a + b my_function(1, 2, 3) 3 people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero'] def split_title_and_name(person): return person.split()[0] + ' ' + person.split()[-1] #option 1 for person in people: print(split_title_and_name(person) == (lambda x: x.split()[0] + ' ' + x.split()[-1])(person)) #option 2 list(map(split_title_and_name, people)) == list(map(lambda person: person.split()[0] + ' ' + person.split()[-1], people)) Let's iterate from 0 to 9 and return the even numbers my_list = [] for number in range(0, 10): if number % 2 == 0: my_list.append(number) my_list [0, 2, 4, 6, 8] Now the same thing but with list comprehension my_list = [number for number in range(0,1000) if number % 2 == 0] my_list [0, 2, 4, 6, 8] def times_tables(): lst = [] for i in range(10): for j in range (10): lst.append(i*j) return lst times_tables() == [j*i for i in range(10) for j in range(10)] --------------------------------------------------------- The Python Programming Language: Numerical Python (NumPy) import numpy as np Creating Arrays Create a list and convert it to a numpy array mylist = [1, 2, 3] x = np.array(mylist) x array([1, 2, 3]) Or just pass in a list directly y = np.array([4, 5, 6]) y array([4, 5, 6]) Pass in a list of lists to create a multidimensional array. m = np.array([[7, 8, 9], [10, 11, 12]]) m array([[ 7, 8, 9], [10, 11, 12]]) Use the shape method to find the dimensions of the array. (rows, columns) m.shape (2, 3) arange returns evenly spaced values within a given interval. n = np.arange(0, 30, 2) # start at 0 count up by 2, stop before 30 n array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]) reshape returns an array with the same data with a new shape. n = n.reshape(3, 5) # reshape array to be 3x5 n array([[ 0, 2, 4, 6, 8], [10, 12, 14, 16, 18], [20, 22, 24, 26, 28]]) linspace returns evenly spaced numbers over a specified interval. o = np.linspace(0, 4, 9) # return 9 evenly spaced values from 0 to 4 o array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. ]) resize changes the shape and size of array in-place. o.resize(3, 3) o array([[ 0. , 0.5, 1. ], [ 1.5, 2. , 2.5], [ 3. , 3.5, 4. ]]) ones returns a new array of given shape and type, filled with ones. np.ones((3, 2)) array([[ 1., 1.], [ 1., 1.], [ 1., 1.]]) zeros returns a new array of given shape and type, filled with zeros. np.zeros((2, 3)) array([[ 0., 0., 0.], [ 0., 0., 0.]]) eye returns a 2-D array with ones on the diagonal and zeros elsewhere. np.eye(3) array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) diag extracts a diagonal or constructs a diagonal array. np.diag(y) np.diag(x) array([[1, 0, 0], [0, 2, 0], [0, 0, 3]]) Create an array using repeating list (or see np.tile) np.array([1, 2, 3] * 3) array([1, 2, 3, 1, 2, 3, 1, 2, 3]) Repeat elements of an array using repeat. np.repeat([1, 2, 3], 3) array([1, 1, 1, 2, 2, 2, 3, 3, 3]) Combining Arrays p = np.ones([2, 3], int) p array([[1, 1, 1], [1, 1, 1]]) Use vstack to stack arrays in sequence vertically (row wise). np.vstack([p, 2*p]) array([[1, 1, 1], [1, 1, 1], [2, 2, 2], [2, 2, 2]]) np.vstack([p, 2*p, 3*p]) array([[1, 1, 1], [1, 1, 1], [2, 2, 2], [2, 2, 2], [3, 3, 3], [3, 3, 3]]) Use hstack to stack arrays in sequence horizontally (column wise) np.hstack([p, 2*p]) array([[1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2]]) np.hstack([p, 2*p, 3*p]) array([[1, 1, 1, 2, 2, 2, 3, 3, 3], [1, 1, 1, 2, 2, 2, 3, 3, 3]]) Operations Use +, -, *, / and ** to perform element wise addition, subtraction, multiplication, division and power. print(x + y) # elementwise addition [1 2 3] + [4 5 6] = [5 7 9] print(x - y) # elementwise subtraction [1 2 3] - [4 5 6] = [-3 -3 -3] print(x * y) # elementwise multiplication [1 2 3] * [4 5 6] = [4 10 18] print(x / y) # elementwise divison [1 2 3] / [4 5 6] = [0.25 0.4 0.5] print(x**2) # elementwise power [1 2 3] ^2 = [1 4 9] Dot Product: x.dot(y) # dot product 1*4 + 2*5 + 3*6 z = np.array([y, y**2]) z array([[ 4, 5, 6], [16, 25, 36]]) print(len(z)) # number of rows of array 2 Let's look at transposing arrays. Transposing permutes the dimensions of the array. z = np.array([y, y**2]) z array([[ 4, 5, 6], [16, 25, 36]]) The shape of array z is (2,3) before transposing. z.shape (2, 3) Use .T to get the transpose. z.T array([[ 4, 16], [ 5, 25], [ 6, 36]]) The number of rows has swapped with the number of columns. z.T.shape (3, 2) Use .dtype to see the data type of the elements in the array. z.dtype dtype('int64') Use .astype to cast to a specific type. z = z.astype('f') z.dtype dtype('float32') Math Functions Numpy has many built in math functions that can be performed on arrays. a = np.array([-4, -2, 1, 3, 5]) a.sum() 3 a.max() 5 a.min() -4 a.mean() 0.60 a.std() 3.26 argmax and argmin return the index of the maximum and minimum values in the array. a.argmax() 4 a.argmin() 0 Indexing / Slicing s = np.arange(5)**2 s array([ 0, 1, 4, 9, 16]) Use bracket notation to get the value at a specific index. Remember that indexing starts at 0. s[0], s[4], s[-1] (0, 16, 16) Use : to indicate a range. array[start:stop] Leaving start or stop empty will default to the beginning/end of the array. s[1:5] s = np.arange(13)**2 s array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144]) s[0], s[4], s[-1] (0, 16, 144) s[1:5] array([ 1, 4, 9, 16]) Use negatives to count from the back. s[-4:] array([ 81, 100, 121, 144]) A second : can be used to indicate step-size. array[start:stop:stepsize] Here we are starting 5th element from the end, and counting backwards by 2 until the beginning of the array is reached. s[-5::-2] array([64, 36, 16, 4, 0]) Let's look at a multidimensional array. r = np.arange(36) r.resize((6, 6)) r array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35]]) Use bracket notation to slice: array[row, column] r[2, 2] 14 And use : to select a range of rows or columns r[3, 3:6] array([21, 22, 23]) Here we are selecting all the rows up to (and not including) row 2, and all the columns up to (and not including) the last column. r[:2, :-1] array([[ 0, 1, 2, 3, 4], [ 6, 7, 8, 9, 10]]) This is a slice of the last row, and only every other element. r[-1, ::2] array([30, 32, 34]) We can also perform conditional indexing. Here we are selecting values from the array that are greater than 30. (Also see np.where) r[r > 30] array([31, 32, 33, 34, 35]) Here we are assigning all values in the array that are greater than 30 to the value of 30. r[r > 30] = 30 r array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29], [30, 30, 30, 30, 30, 30]]) Copying Data Be careful with copying and modifying arrays in NumPy! r2 is a slice of r r2 = r[:3,:3] r2 array([[ 0, 1, 2], [ 6, 7, 8], [12, 13, 14]]) Set this slice's values to zero ([:] selects the entire array) r2[:] = 0 r2 array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) r has also been changed! r array([[ 0, 0, 0, 3, 4, 5], [ 0, 0, 0, 9, 10, 11], [ 0, 0, 0, 15, 16, 17], [18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29], [30, 30, 30, 30, 30, 30]]) To avoid this, use r.copy to create a copy that will not affect the original array r_copy = r.copy() r_copy array([[ 0, 0, 0, 3, 4, 5], [ 0, 0, 0, 9, 10, 11], [ 0, 0, 0, 15, 16, 17], [18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29], [30, 30, 30, 30, 30, 30]]) Now when r_copy is modified, r will not be changed. r_copy[:] = 10 print(r_copy, '\n') print(r) [[10 10 10 10 10 10] [10 10 10 10 10 10] [10 10 10 10 10 10] [10 10 10 10 10 10] [10 10 10 10 10 10] [10 10 10 10 10 10]] [[ 0 0 0 3 4 5] [ 0 0 0 9 10 11] [ 0 0 0 15 16 17] [18 19 20 21 22 23] [24 25 26 27 28 29] [30 30 30 30 30 30]] Iterating Over Arrays Let's create a new 4 by 3 array of random numbers 0-9. test = np.random.randint(0, 10, (4,3)) test array([[5, 1, 7], [0, 1, 9], [9, 3, 7], [1, 6, 6]]) array([[4, 7, 9], [0, 9, 0], [6, 7, 0], [5, 4, 3]]) Iterate by row: for row in test: print(row) [4 7 9] [0 9 0] [6 7 0] [5 4 3] Iterate by index: for i in range(len(test)): print(test[i]) [4 7 9] [0 9 0] [6 7 0] [5 4 3] Iterate by row and index: for i, row in enumerate(test): print('row', i, 'is', row) row 0 is [4 7 9] row 1 is [0 9 0] row 2 is [6 7 0] row 3 is [5 4 3] Use zip to iterate over multiple iterables. test2 = test**2 test2 array([[16, 49, 81], [ 0, 81, 0], [36, 49, 0], [25, 16, 9]]) for i, j in zip(test, test2): print(i,'+',j,'=',i+j) 4 7 9] + [16 49 81] = [20 56 90] [0 9 0] + [ 0 81 0] = [ 0 90 0] [6 7 0] + [36 49 0] = [42 56 0] [5 4 3] + [25 16 9] = [30 20 12] ____________________________________ import pandas as pd pd.Series? animals = ['Tiger', 'Bear', 'Moose'] pd.Series(animals) numbers = [1, 2, 3] pd.Series(numbers) animals = ['Tiger', 'Bear', None] pd.Series(animals) numbers = [1, 2, None] pd.Series(numbers) import numpy as np np.nan == None np.nan == np.nan np.isnan(np.nan) sports = {'Archery': 'Bhutan', 'Golf': 'Scotland', 'Sumo': 'Japan', 'Taekwondo': 'South Korea'} s = pd.Series(sports) s s.index s = pd.Series(['Tiger', 'Bear', 'Moose'], index=['India', 'America', 'Canada']) s sports = {'Archery': 'Bhutan', 'Golf': 'Scotland', 'Sumo': 'Japan', 'Taekwondo': 'South Korea'} s = pd.Series(sports, index=['Golf', 'Sumo', 'Hockey']) s ------------------------------ Querying a Series: sports = {'Archery': 'Bhutan', 'Golf': 'Scotland', 'Sumo': 'Japan', 'Taekwondo': 'South Korea'} s = pd.Series(sports) s s.iloc[3] s.loc['Golf'] s[3] s['Golf'] sports = {99: 'Bhutan', 100: 'Scotland', 101: 'Japan', 102: 'South Korea'} s = pd.Series(sports) s[0] #This won't call s.iloc[0] as one might expect, it generates an error instead s = pd.Series([100.00, 120.00, 101.00, 3.00]) s total = 0 for item in s: total+=item print(total) import numpy as np total = np.sum(s) print(total) s = pd.Series(np.random.randint(0,1000,10000)) s.head() len(s) %%timeit -n 100 summary = 0 for item in s: summary+=item %%timeit -n 100 summary = np.sum(s) s+=2 #adds two to each item in s using broadcasting s.head() for label, value in s.iteritems(): s.set_value(label, value+2) s.head() %%timeit -n 10 s = pd.Series(np.random.randint(0,1000,10000)) for label, value in s.iteritems(): s.loc[label]= value+2 %%timeit -n 10 s = pd.Series(np.random.randint(0,1000,10000)) s+=2 s = pd.Series([1, 2, 3]) s.loc['Animal'] = 'Bears' s original_sports = pd.Series({'Archery': 'Bhutan', 'Golf': 'Scotland', 'Sumo': 'Japan', 'Taekwondo': 'South Korea'}) cricket_loving_countries = pd.Series(['Australia', 'Barbados', 'Pakistan', 'England'], index=['Cricket', 'Cricket', 'Cricket', 'Cricket']) all_countries = original_sports.append(cricket_loving_countries) original_sports cricket_loving_countries all_countries all_countries.loc['Cricket'] ----------------------------- python-code-for students.txt Displaying python-code-for students.txt.
778f3eae949fd05001d7497407193f20ceb50609
sumanes4u/Anaconda-Projects
/All-Classes_DotPY_Modified_Sublime/Class-2-datatypes-Sep13.py
2,562
4.1875
4
# coding: utf-8 # In[1]: x = 'Hello' # In[2]: print(x) # This print the value of the x as it gets stored # print(x) # This prints the value in a suitable format. # In[3]: num = 121 name = 'Sam' # In[5]: print('My number is:{one}, and my name is: {two}'.format(one=num,two=name)) # In[9]: print('My number is:{}, and my name is: {}'.format(num,name)) # In[10]: # List # In[11]: [1,2,3] # int # In[12]: ['hi',1,2,3] # int + string # In[13]: my_list = ['a','b','c'] # In[14]: print(my_list.append('d')) # In[15]: print(my_list) # In[16]: print(my_list.pop()) # In[17]: print(my_list) # In[18]: x = my_list.pop() # In[19]: print(x) # In[20]: l1 = [1,2,3] # In[26]: l2 = ['a','my basket','c'] # In[24]: l3 = l1 + l2 # In[25]: print(l3) # In[27]: print(my_list[0]) # In[28]: print(my_list[1]) # In[29]: #my_list[2] --> IndexError: list index out of range # In[33]: my_list = ['a','b','c','d','e','f'] # In[35]: print(my_list[1:3]) # In[37]: print(my_list[:4]) # In[40]: print(my_list[2:-1]) # In[41]: # Dictionaries # In[42]: d = {'key1':'value1','key2':'value2'} # In[44]: print(d['key1']) # In[45]: print(d.keys()) # In[46]: print(d.values()) # In[47]: print(d.items()) # In[48]: print(my_list[0]) # In[49]: my_list[0]='z' # In[50]: print(my_list[0]) # In[53]: d['key3']='hello' # In[54]: print(d) # In[55]: # Booleans # In[56]: True # In[57]: False # In[58]: # Comparision Operator # In[59]: print(1 > 2) # In[60]: print(1 < 2) # In[61]: print(1 >= 1) # In[62]: print(1 <=4) # In[63]: print(1 == 1) # In[64]: print('hi' == 'hi') # In[65]: print('hi' == 'Hi') # In[66]: # Logical operator # In[67]: print(( 1 > 2) and ( 2 < 3)) # In[68]: print(( 1 > 2) or ( 2 < 3)) # In[69]: print(( 1 > 2) | ( 2 < 3)) # In[70]: print(( 1 == 2) or (2 == 3) or (4 == 4)) # In[71]: # List # Dictionaries # Tuples # Sets # In[73]: #Tuples # In[74]: t = (1,2,3) # In[75]: print(t) # In[76]: #t[0] = 4 ---> TypeError: 'tuple' object does not support item assignment # In[77]: # Sets - removes duplicate # In[78]: {1,2,2,3,3,4,4,5,5} # In[79]: list = ['ravi','raj','ravi','priya','priya'] # In[80]: another_list = set(list) # In[81]: print(another_list) # In[82]: another_list_set={1,2,2,3,3,} # In[83]: print(another_list_set) # In[90]: print(list[len(list)-1]) # In[89]: list = ['ravi','raj','ravi','priya2'] # In[91]: print(type(d)) # In[ ]: #as # In[ ]: # In[ ]:
4dead7197da8a1086349c96fdb9894fdd331f465
Bschuster3434/Euler_Problems
/p8.py
2,638
3.671875
4
import urllib2 website = "http://projecteuler.net/problem=8" def return_greatest_product(website): source = urllib2.urlopen(website) list = source.readlines() full_list_string = ''.join(list) string_start = "<p style='font-family:courier new;font-size:10pt;text-align:center;'>" string_end = "</p>" start_loc = full_list_string.find(string_start) #Finds the location in string where first unique identifier exists half_list_string = full_list_string[start_loc + len(string_start):] #Takes full string and shortens it to the beginning end_loc = half_list_string.find(string_end) #Finds end location in new string list_string = half_list_string[:end_loc] #Cuts down to just the relevant string number_string = grab_number_list(list_string) #Output is single string with 1000 digits digit_list = parse_number_to_length(number_string) #Output is list of strings with 5 digits each non_zero_digit_list = remove_zero_case(digit_list) #Output is same list as digit_list, minus the zero cases product_digit_list = add_product(non_zero_digit_list) #Output is same list as non_zero_digit_list, with each entry having an appended product largest_product = find_larget_product(product_digit_list) return largest_product def grab_number_list(string): # Grabs the raw numbers from the string and formats them as one number number_list = [] parse = "<br />" while string.find(parse) != -1: next_end_loc = string.find(parse) number_list.append(string[1:next_end_loc]) next_start_loc = next_end_loc + len(parse) string = string[next_start_loc:] final_number = ''.join(number_list) return final_number def parse_number_to_length(number_string): digit_list = [] length = 5 while len(number_string) >= 5: digit_list.append(number_string[0:length]) number_string = number_string[1:] return digit_list def remove_zero_case(digit_list): #Remove all strings where product equals 0 non_zero_digit_list = [] for i in digit_list: find_zero = i.find('0') if find_zero == -1: non_zero_digit_list.append(i) return non_zero_digit_list def add_product(digit_list): #turns number into a two place list and adds product into the '1' list place dig_pro_list = [] for i in digit_list: product = 1 product = int(i[0]) * int(i[1]) * int(i[2]) * int(i[3]) * int(i[4]) dig_pro_list.append([i, product]) return dig_pro_list def find_larget_product(product_list): largest_product_pair = ['', 0] for i in product_list: if i[1] > largest_product_pair[1]: largest_product_pair = i return largest_product_pair print return_greatest_product(website)
cb96023ef71998d1c1073ef0d319240d750646c9
nataliewyq/GSS-homework
/0703hw1.py
494
4.1875
4
print('enter your score:') score=int(input()) if score >=0 and score<=100: print('score valid') if score>=91 and score <=100: print('your letter grade is A') if score>=81 and score<=90: print ('your letter grade is B') if score>=71 and score<=80: print('your letter grade is C') if score>=61 and score<=70: print('your letter grade is D') if score<=60 and score>=0: print('your letter grade is F') else: print('score invalid')
e5c9db6b67aa1ab3211716a535b253b1265d09b8
lpyqyc/Python-100-Days
/Day01-15/code/Day01/hello.py
967
4.53125
5
""" 第一个Python程序 - hello, world! 向伟大的Dennis M. Ritchie先生致敬 Version: 0.1 Author: 骆昊 Date: 2018-02-26 请将该文件命名为hello.py 使用Windows的小伙伴可以在命令行提示下通过下面的命令运行该程序 python hello.py 对于使用Linux或macOS的小伙伴可以打开终端并键入下面的命令来运行程序 python3 hello.py """ print('hello, world!') # print("你好,世界!") print('你好', '世界') print('hello', 'world', sep=', ', end='!') print('goodbye, world', end='!\n') import turtle turtle.pensize(4) turtle.pencolor('red') turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.mainloop() import turtle import time # 同时设置pencolor=color1, fillcolor=color2 turtle.color("red", "yellow") turtle.begin_fill() for _ in range(50): turtle.forward(200) turtle.left(170) turtle.end_fill() turtle.mainloop()
037248ddbf07dd5a0dfc13b6bcb08342fa139604
RaghavGoyal/Raghav-root
/python/code/src/DataStructures/Tree/Binary/Main.py
1,053
4.3125
4
""" Demo for Binary Search Tree """ from BinarySearchTree import BinarySearchTree if __name__ == '__main__': bst = BinarySearchTree() bst.insert(10) print(f'Root Data: {bst.root.data}') print(f'Root.left: {bst.root.left}') print(f'Root.right: {bst.root.right}') bst.insert(5) bst.insert(20) print('Inserted 5 and 20') print(f'Root Data: {bst.root.data}') print(f'Root.left.data: {bst.root.left.data}') print(f'Root.right.data: {bst.root.right.data}') print(f'Search for 10 {bst.search(10)}') print(f'Search for 5 {bst.search(5)}') print(f'Search for 20 {bst.search(20)}') print(f'Search for 15 {bst.search(15)}') bst.insert(3) bst.insert(7) bst.insert(15) bst.insert(17) print("Inorder Traversal:") bst.inOrderTraverse() print("pre-order Traversal:") bst.preOrderTraverse() print("post-order Traversal:") bst.postOrderTraverse() print(f'height of tree is: {bst.height()}') print(f'getting nodes at depth 3: {bst.getNodesAtDepth(2)}')
c30f5b6b642a2d45ff26bfe9f010953d891f245b
diesarrollador/CRUD-MySQL
/insertar.py
938
3.53125
4
import mysql.connector # creando la coneccion a la base de datos mydb = mysql.connector.connect( host = "localhost", user = "root", password = "", database = "clientes" ) # gestiona las operaciones de la base de datos def insertar(): try: mycursor = mydb.cursor() cedula_cliente = input("Ingrese la cédula: ") nombre_cliente = input("Ingrese el nombre: ") correo_cliente = input("Ingrese el correo: ") provincia_cliente = input("Ingrese la provincia: ") sql = """ INSERT INTO datos (cedula, nombre, correo, provincia) VALUES('{}', '{}', '{}', '{}') """.format(cedula_cliente, nombre_cliente, correo_cliente, provincia_cliente) mycursor.execute(sql) mydb.commit() #mycursor.close() #mydb.close() print('\nDatos insertados correctamente!\n') except ImportError(): print("Algo ha ido mal")
658112caa4819c814840951fbb7f2b4eb4a34535
ThaiSonNguyenTl/NguyenThaiSon-fundamental-c4e24
/session1/homework1/or_even_better.py
104
3.734375
4
from turtle import* shape("turtle") speed(0) for i in range(100): circle(100) left(9) mainloop()
c6b9c06700952a2a13cf2e320da8a6917bcba520
harshagl2002/COVID_CLI
/Country_CovidGraph.py
1,507
3.625
4
import requests import json import datetime import matplotlib.pyplot as plt from datetime import timedelta def country_graph(): url = "https://covid-193.p.rapidapi.com/history" date_string = '2020-04-01' date = datetime.datetime.strptime(date_string, '%Y-%m-%d').date() today = datetime.date.today() yesterday = today - datetime.timedelta(days=1) country = input("Enter the country you would like to search for: ") case_list = [] date_list = [] while date <= yesterday: querystring = {"country":country,"day":date} headers = { 'x-rapidapi-key': "574d25f133msh5c58c65e8a4c944p1e6b8fjsnee1da55d91cd", 'x-rapidapi-host': "covid-193.p.rapidapi.com" } response = requests.request("GET", url, headers=headers, params=querystring) data = response.text parsed = json.loads(data) if parsed["results"] == 0: date += timedelta(days=1) continue else: response_dict = parsed["response"][0] cases_dict = response_dict["cases"] if cases_dict["new"] is None: date += timedelta(days=1) continue else: case_list.append(int(cases_dict["new"])) date_list.append(response_dict["day"]) #print(response_dict["day"]) date += timedelta(days=1) plt.plot(date_list, case_list) plt.xlabel("Date") plt.ylabel("Cases") plt.title("Covid-19 graph") plt.show()
1e9d421f4fe2bdd66f8ead4364cb636727df4967
msonderegger/PolyglotDB
/polyglotdb/io/parsers/speaker.py
1,904
3.703125
4
import os class SpeakerParser(object): def parse_path(self, path): raise (NotImplementedError) class FilenameSpeakerParser(SpeakerParser): """ Class for parsing a speaker name from a path that gets a specified number of characters from either the left of the right of the base file name. Parameters ---------- number_of_characters : int Number of characters to include in the speaker designation orientation : str Whether to pull characters from the left or right of the base file name, defaults to 'left' """ def __init__(self, number_of_characters, orientation='left'): self.number_of_characters = number_of_characters self.orientation = orientation def parse_path(self, path): """ Parses a file path and returns a speaker name Parameters ---------- path : str File path Returns ------- str Substring of path that is the speaker name """ name = os.path.basename(path) name, ext = os.path.splitext(name) if self.orientation == 'left': return name[:self.number_of_characters] else: return name[-1 * self.number_of_characters:] class DirectorySpeakerParser(SpeakerParser): """ Class for parsing a speaker name from a path that gets the directory immediately containing the file and uses its name as the speaker name """ def __init__(self): pass def parse_path(self, path): """ Parses a file path and returns a speaker name Parameters ---------- path : str File path Returns ------- str Directory that is the name of the speaker """ name = os.path.dirname(path) name = os.path.basename(name) return name
a67e149c2a7d7eeca08e13b3e2ecedb32a5ba731
ashutosh1906/DistributedCyberMirror
/Dijkstra.py
7,559
3.875
4
import heapq def Dijkstra_algorithm_unweighted(source, adjacent_matrix): '''Find the shortest path to all nodes from the source node Return the output structured as dictionary where the keys are ids of the nodes and the value is the shortest distance''' # print("Neighbour Node %s"%(adjacent_matrix[source])) all_reachable_shortest_nodes = {source:0} reachable_nodes = {} explored_node = {} min_priority_queue = [] for node_id in adjacent_matrix[source]: if node_id not in reachable_nodes: reachable_nodes[node_id] = [1,node_id] heapq.heappush(min_priority_queue,reachable_nodes[node_id]) ############################################### Dijkstra Starts from here ####################################### explored_node[source] = 1 while(len(min_priority_queue)>0): current_node = heapq.heappop(min_priority_queue) node_id = current_node[1] node_value = current_node[0] explored_node[node_id] = 1 all_reachable_shortest_nodes[node_id] = node_value # print("Current Node :%s Edge %s Neighbour %s" % (node_id, node_value, adjacent_matrix[node_id])) try: for adjacent_node in adjacent_matrix[node_id]: if adjacent_node in explored_node: continue if adjacent_node not in reachable_nodes: reachable_nodes[adjacent_node] = [node_value+1,adjacent_node] heapq.heappush(min_priority_queue,reachable_nodes[adjacent_node]) else: if node_value+1 < reachable_nodes[adjacent_node][0]: reachable_nodes[adjacent_node][0] = node_value+1 heapq.heapify(min_priority_queue) except: print("Error ---> Current Node :%s Edge %s" % (node_id, node_value)) # print("Dijkstra's Output for Source: %s --> %s"%(source,all_reachable_shortest_nodes)) return all_reachable_shortest_nodes def Dijkstra_algorithm_unweighted_pair(source,target,adjacent_matrix,max_distance = 100000): '''Find the shortest distance between a source and a destination''' '''Maximum distance is treated as the optiional argument which if given as the parameter, will ignore any path with length greater than the max_distance''' all_reachable_shortest_nodes = {} reachable_nodes = {} explored_node = {} min_priority_queue = [] pair_distance = -1 if source==target: return 0 #################################### Source and target is same, soo length=0 for node_id in adjacent_matrix[source]: if node_id==target: return 1 ############ target is the neighbour of source if node_id not in reachable_nodes: reachable_nodes[node_id] = [1, node_id] heapq.heappush(min_priority_queue, reachable_nodes[node_id]) ############################################### Dijkstra Starts from here ####################################### explored_node[source] = 1 while (len(min_priority_queue) > 0): current_node = heapq.heappop(min_priority_queue) node_id = current_node[1] node_value = current_node[0] if node_value == max_distance: return -1 ################### No path between source and destination is short than the max distance explored_node[node_id] = 1 all_reachable_shortest_nodes[node_id] = node_value # print("Current Node :%s Edge %s Neighbour %s" % (node_id, node_value, adjacent_matrix[node_id])) try: for adjacent_node in adjacent_matrix[node_id]: if adjacent_node==target: pair_distance = node_value+1 ############################ Got the target return pair_distance if adjacent_node in explored_node: continue if adjacent_node not in reachable_nodes: reachable_nodes[adjacent_node] = [node_value + 1, adjacent_node] heapq.heappush(min_priority_queue, reachable_nodes[adjacent_node]) else: if node_value + 1 < reachable_nodes[adjacent_node][0]: reachable_nodes[adjacent_node][0] = node_value + 1 heapq.heapify(min_priority_queue) except: print("Error ---> Current Node :%s Edge %s" % (node_id, node_value)) return -1 def shortest_route(source,target,adjacent_matrix,max_distance = 100000): '''Find the shortest distance between a source and a destination''' '''Get the shortest path from the source to destinations''' '''Considering the path has equal weights''' reachable_nodes = {} explored_node = {} min_priority_queue = [] parent_node = {} pair_distance = -1 if source==target: return [target] #################################### Source and target is same, soo length=0 # print('%s:%s' % (source, adjacent_matrix[source])) for node_id in adjacent_matrix[source]: if node_id==target: parent_node[node_id] = source return return_path(source,target,parent_node) ############ target is the neighbour of source if node_id not in reachable_nodes: reachable_nodes[node_id] = [1, node_id] parent_node[node_id] = source heapq.heappush(min_priority_queue, reachable_nodes[node_id]) ############################################### Dijkstra Starts from here ####################################### explored_node[source] = 1 while (len(min_priority_queue) > 0): current_node = heapq.heappop(min_priority_queue) # print('Current Nodes %s'%(current_node)) node_id = current_node[1] node_value = current_node[0] if node_value == max_distance: return None ################### No path between source and destination is short than the max distance explored_node[node_id] = 1 # print("Current Node :%s Edge %s Neighbour %s" % (node_id, node_value, adjacent_matrix[node_id])) try: # print('Node %s --> %s'%(node_id,adjacent_matrix[node_id])) for adjacent_node in adjacent_matrix[node_id]: if adjacent_node==target: parent_node[adjacent_node] = node_id return return_path(source,target,parent_node) if adjacent_node in explored_node: continue if adjacent_node not in reachable_nodes: reachable_nodes[adjacent_node] = [node_value + 1, adjacent_node] heapq.heappush(min_priority_queue, reachable_nodes[adjacent_node]) parent_node[adjacent_node] = node_id else: if node_value + 1 < reachable_nodes[adjacent_node][0]: reachable_nodes[adjacent_node][0] = node_value + 1 heapq.heapify(min_priority_queue) parent_node[adjacent_node] = node_id except: print("Error ---> Current Node :%s Edge %s" % (node_id, node_value)) return None def return_path(source,target,parent_node): # print("******** (%s,%s) and Parents : %s ****"%(source,target,parent_node)) path = [target] while(True): if path[-1] not in parent_node: return None parent = parent_node[path[-1]] path.append(parent) if parent == source: return path[::-1]
7bbe66d7ec2da4e7bb5cef550a01dc1d50a0e4cc
MrHamdulay/csc3-capstone
/examples/data/Assignment_4/edwmoe001/piglatin.py
1,822
3.828125
4
VOWELS = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U") def consonant_check(a): first = a.lower() if first in ('a', 'e', 'i', 'o', 'u'): return False else: return True def conv_consonant_start(word): if len(word)>=2 and consonant_check(word[1]) == True: if len(word)>=3 and consonant_check(word[2]) == True: if len(word)>=4 and consonant_check(word[3]) == True: pig_latin_word = word[4:] + "a" + word[0:4] + "ay" else: pig_latin_word = word[3:] + "a" + word[0:3] + "ay" else: pig_latin_word = word[2:]+ "a" + word[0:2] + "ay" else: pig_latin_word = word[1:]+ "a" + word[0] + "ay" return pig_latin_word def conv_vowel_start(word): pig_latin_word = word + "way" return pig_latin_word def toPigLatin(s): engl_words = s.split(" ") pig_latin_words = [] for i in engl_words: first_letter = i[0] vowel = False if first_letter in VOWELS: vowel = True if vowel == True: pig_latin_words.append(conv_vowel_start(i)) else: pig_latin_words.append(conv_consonant_start(i)) new = " ".join(pig_latin_words) return new def toEnglish(s): pigl_words = s.split(" ") eng_words = [] for i in pigl_words: three_last = i[-3:-1] if three_last == "wa": eng_words.append(vowel(i)) else: eng_words.append(cons(i)) neweng = " ".join(eng_words) return neweng def vowel(word): word = word[:(len(word)-3)] return word def cons(word): word = word[:(len(word)-2)] #if len(word)>2 and consonant_check(word[-2]) == True: a = word.rfind("a") last = word[a+1:] word = word[0:a] engword = last + word #else: #last = word[-1] #word = word[0:len(word)] #engword = last + word return engword
adbd48685f7a2c5366adfa59744cda9e52263f71
Rochan2001/python_stuff
/python_projects/print_matrix_spiral.py
1,254
4
4
class Spiral: def __init__(self, matrix): self.matrix = matrix def print_spiral(self, i, j, r, c): # If i or j lies outside the matrix if i >= r or j >= c: return # Print First Row for index in range(i, c): print(self.matrix[i][index], end=" ") #Print Last Column for index in range(i+1, r): print(self.matrix[index][c-1], end=" ") # Print Last Row, if Last and # First Row are not same if ((i-1) != r): for index in range(c-1, i, -1): print(self.matrix[c-1][index-1], end=" ") #Print First Column, if Last and #First Column are not same if ((j-1) != c): for index in range(r-1, j+1, -1): print(self.matrix[index-1][j], end=" ") return Spiral.print_spiral(self, i+1, j+1, r-1, c-1) print("Enter the dimensions of a square matrix(m x n) :") r,c = list(map(int,input().split())) try: if r == c: matrix = [[int(x) for x in input().split()] for i in range(c)] s_matrix = Spiral(matrix) s_matrix.print_spiral(0,0,r,c) else: raise Exception("Dimensions do not match!") except Exception as e: print(e)
3a82a3d4a10c73c8bf67eb6e065444ae7b590397
yacinekedidi/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
501
4.03125
4
#!/usr/bin/python3 """module text_indentation. """ def text_indentation(text): """ function text_indentation """ if type(text) is not str: raise TypeError("text must be a string") i = 0 text = text.strip() while i < len(text): print(text[i], end="") if text[i] == "\n" or text[i] in "?.:": print("\n") i += 1 while i < len(text) and text[i] == " ": i += 1 continue i += 1
c1bb73c746d32812f283a5523f131415733b081b
AntonSergeqich/GeekHttps
/ls4_dz2.py
750
4.28125
4
# Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента. # Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор. from random import randint my_list = [] for i in range(10): my_list.append(randint(1, 300)) result_list = [el for el in my_list[1:] if el > my_list[my_list.index(el) - 1]] print(f"Оригинальный список - {my_list}") print(f"Результативный список - {result_list}")
f1ca2e1dee1086447a00fc099592d32fc2b5985e
EleazarLopezOsuna/COMPI2-PROYECTO1
/Modelos/Objeto.py
1,434
3.6875
4
class Objeto(): # Constructor de la clase objeto, funciona como multi constructor ya que se hace una verificacion # del tipo de dato que le estamos enviando; Puede ser cadena o un Objeto def __init__(self, *args): if isinstance(args[0], str): self.parametros = {} self.arreglo = [] self.tipo = None self.nombreTipo = "" self.nombre = args[0] elif isinstance(args[0], Objeto): self.nombre = args[0].nombre self.nombreTipo = args[0].nombreTipo self.parametros = {} for key in args[0].parametros: self.parametros[key] = args[0].parametros[key] self.tipo = args[0].tipo if not args[0].arreglo: self.arreglo = args[0].arreglo # Busca el nombre de un parametro dentro del objeto # {Objeto: Encontro, None: No encontro} def buscar(self, nombre): if nombre in self.parametros: return self.parametros[nombre] return None # Busca por nombre y modifica un parametro dentro del objeto # {True: Encontro y modifico, False: No encontro} def modificar(self, nombre, simbolo): if nombre in self.parametros: viejo = self.parametros[nombre] if viejo == simbolo.tipo: self.parametros[nombre] = simbolo return True return False
6cca993ad5317df22f412fe9f660088ba6c6c641
jvano74/advent_of_code
/2020/day_11_test.py
9,284
4.3125
4
from collections import defaultdict from typing import NamedTuple class Pt(NamedTuple): x: int y: int class Puzzle: """ --- Day 11: Seating System --- Your plane lands with plenty of time to spare. The final leg of your journey is a ferry that goes directly to the tropical island where you can finally start your vacation. As you reach the waiting area to board the ferry, you realize you're so early, nobody else has even arrived yet! By modeling the process people use to choose (or abandon) their seat in the waiting area, you're pretty sure you can predict the best place to sit. You make a quick map of the seat layout (your puzzle input). The seat layout fits neatly on a grid. Each position is either floor (.), an empty seat (L), or an occupied seat (#). For example, the initial seat layout might look like this: L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL Now, you just need to model the people who will be arriving shortly. Fortunately, people are entirely predictable and always follow a simple set of rules. All decisions are based on the number of occupied seats adjacent to a given seat (one of the eight positions immediately up, down, left, right, or diagonal from the seat). The following rules are applied to every seat simultaneously: - If a seat is empty (L) and there are no occupied seats adjacent to it, the seat becomes occupied. - If a seat is occupied (#) and four or more seats adjacent to it are also occupied, the seat becomes empty. - Otherwise, the seat's state does not change. Floor (.) never changes; seats don't move, and nobody sits on the floor. After one round of these rules, every seat in the example layout becomes occupied: #.##.##.## #######.## #.#.#..#.. ####.##.## #.##.##.## #.#####.## ..#.#..... ########## #.######.# #.#####.## After a second round, the seats with four or more occupied adjacent seats become empty again: #.LL.L#.## #LLLLLL.L# L.L.L..L.. #LLL.LL.L# #.LL.LL.LL #.LLLL#.## ..L.L..... #LLLLLLLL# #.LLLLLL.L #.#LLLL.## This process continues for three more rounds: #.##.L#.## #L###LL.L# L.#.#..#.. #L##.##.L# #.##.LL.LL #.###L#.## ..#.#..... #L######L# #.LL###L.L #.#L###.## #.#L.L#.## #LLL#LL.L# L.L.L..#.. #LLL.##.L# #.LL.LL.LL #.LL#L#.## ..L.L..... #L#LLLL#L# #.LLLLLL.L #.#L#L#.## #.#L.L#.## #LLL#LL.L# L.#.L..#.. #L##.##.L# #.#L.LL.LL #.#L#L#.## ..L.L..... #L#L##L#L# #.LLLLLL.L #.#L#L#.## At this point, something interesting happens: the chaos stabilizes and further applications of these rules cause no seats to change state! Once people stop moving around, you count 37 occupied seats. Simulate your seating area by applying the seating rules repeatedly until no seats change state. How many seats end up occupied? --- Part Two --- As soon as people start to arrive, you realize your mistake. People don't just care about adjacent seats - they care about the first seat they can see in each of those eight directions! Now, instead of considering just the eight immediately adjacent seats, consider the first seat in each of those eight directions. For example, the empty seat below would see eight occupied seats: .......#. ...#..... .#....... ......... ..#L....# ....#.... ......... #........ ...#..... The leftmost empty seat below would only see one empty seat, but cannot see any of the occupied ones: ............. .L.L.#.#.#.#. ............. The empty seat below would see no occupied seats: .##.##. #.#.#.# ##...## ...L... ##...## #.#.#.# .##.##. Also, people seem to be more tolerant than you expected: it now takes five or more visible occupied seats for an occupied seat to become empty (rather than four or more from the previous rules). The other rules still apply: empty seats that see no occupied seats become occupied, seats matching no rule don't change, and floor never changes. Given the same starting layout as above, these new rules cause the seating area to shift around as follows: L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL #.##.##.## #######.## #.#.#..#.. ####.##.## #.##.##.## #.#####.## ..#.#..... ########## #.######.# #.#####.## #.LL.LL.L# #LLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLL# #.LLLLLL.L #.LLLLL.L# #.L#.##.L# #L#####.LL L.#.#..#.. ##L#.##.## #.##.#L.## #.#####.#L ..#.#..... LLL####LL# #.L#####.L #.L####.L# #.L#.L#.L# #LLLLLL.LL L.L.L..#.. ##LL.LL.L# L.LL.LL.L# #.LLLLL.LL ..L.L..... LLLLLLLLL# #.LLLLL#.L #.L#LL#.L# #.L#.L#.L# #LLLLLL.LL L.L.L..#.. ##L#.#L.L# L.L#.#L.L# #.L####.LL ..#.#..... LLL###LLL# #.LLLLL#.L #.L#LL#.L# #.L#.L#.L# #LLLLLL.LL L.L.L..#.. ##L#.#L.L# L.L#.LL.L# #.LLLL#.LL ..#.L..... LLL###LLL# #.LLLLL#.L #.L#LL#.L# Again, at this point, people stop shifting around and the seating area reaches equilibrium. Once this occurs, you count 26 occupied seats. Given the new visibility method and the rule change for occupied seats becoming empty, once equilibrium is reached, how many seats end up occupied? """ pass SAMPLE = [ 'L.LL.LL.LL', 'LLLLLLL.LL', 'L.L.L..L..', 'LLLL.LL.LL', 'L.LL.LL.LL', 'L.LLLLL.LL', '..L.L.....', 'LLLLLLLLLL', 'L.LLLLLL.L', 'L.LLLLL.LL'] with open('day_11_input.txt') as fp: INPUT = [ln.strip() for ln in fp] class Board: DELTAS = [Pt(0, 1), Pt(1, 1), Pt(1, 0), Pt(1, -1), Pt(0, -1), Pt(-1, -1), Pt(-1, 0), Pt(-1, 1)] def __init__(self, layout, v=0): self.grid = {} self.generations = 0 self.max_y = len(layout) self.max_x = len(layout[0]) self.v = v for y, row in enumerate(layout): for x, pos in enumerate(row): self.grid[Pt(x, y)] = pos def next_state(self, x, y): if self.grid[Pt(x, y)] == '.': return '.' occupied_neighbors = 0 for d in self.DELTAS: pt_to_check = Pt(x + d.x, y + d.y) if pt_to_check in self.grid and self.grid[pt_to_check] == '#': occupied_neighbors += 1 if self.grid[Pt(x, y)] == 'L' and occupied_neighbors == 0: return '#' elif self.grid[Pt(x, y)] == '#' and occupied_neighbors >= 4: return 'L' return self.grid[Pt(x, y)] def find_neighbor_in_direction(self, x, y, d): for dist in range(1, max(self.max_x, self.max_y)): pt = Pt(x + dist * d.x, y + dist * d.y) if pt not in self.grid: return '.' if self.grid[pt] == '#': return '#' if self.grid[pt] == 'L': return 'L' def next_state_v2(self, x, y): if self.grid[Pt(x, y)] == '.': return '.' occupied_neighbors = 0 for d in self.DELTAS: pt_to_check = self.find_neighbor_in_direction(x, y, d) if pt_to_check == '#': occupied_neighbors += 1 if self.grid[Pt(x, y)] == 'L' and occupied_neighbors == 0: return '#' elif self.grid[Pt(x, y)] == '#' and occupied_neighbors >= 5: return 'L' return self.grid[Pt(x, y)] def tick(self): self.generations += 1 if self.v == 0: new_grid = {k: self.next_state(k.x, k.y) for k in self.grid} else: new_grid = {k: self.next_state_v2(k.x, k.y) for k in self.grid} # self.print_grid(new_grid) if new_grid != self.grid: self.grid = new_grid return 1 return 0 def run(self): while self.tick() == 1: pass def print_grid(self, next_grid=None): if next_grid is None: next_grid = {} print('\n\n') for y in range(self.max_y): row = [] for x in range(self.max_x): row.append(self.grid[Pt(x, y)]) if len(next_grid) > 0: row.append(next_grid[Pt(x, y)]) row.append('+') print(''.join(row)) def test_sample(): sample = Board(SAMPLE) sample.run() assert sum([v == '#' for k, v in sample.grid.items()]) == 37 sample2 = Board(SAMPLE, 1) sample2.run() assert sum([v == '#' for k, v in sample2.grid.items()]) == 26 def test_input(): sample = Board(INPUT) sample.run() assert sum([v == '#' for k, v in sample.grid.items()]) == 2243 sample2 = Board(INPUT, 1) sample2.run() assert sum([v == '#' for k, v in sample2.grid.items()]) == 2027
066872bc7eeb81328ad8bc545bc90731730d5302
yanolab/python-functionals
/functionals.py
2,626
3.796875
4
# -*- coding: utf-8 -*- from string import letters, digits from random import choice from itertools import islice, count, tee, takewhile, imap def randstrings(strs, limit=None): """ generate random strings by given string. """ return (choice(strs) for x in countup(stop=limit)) def randalphanumerics(limit=None): """ generate random alphabet or numeric. """ return randstrings(letters + digits, limit) def take(seq, num): """ take items from sequence """ return islice(seq, 0, num) def takeright(seq, num): """ selects last n elements. """ length = len(seq) return islice(seq, length - num, None) def mkstring(seq, sep=''): """ this is another way to make sring join iterbles. """ return sep.join(seq) def countup(stop=None): """ countup for stop. if stop is None, countup to infinity. """ return (x for x in take(count(), stop)) def head(seq): """ select first element. """ return next(take(seq, 1)) def tail(seq): """ selects all elements except the first. """ return islice(seq, 1, None) def swap(x, y, pred=lambda x,y: true): """ swap args, if pred is true. """ return (y, x) if pred(x,y) else (x, y) def zipwithindex(seq, start=0): """ zip with indexing. """ return ((i, x) for i, x in enumerate(seq, start)) def splitat(seq, index, step=0): """ splits this list into two at a given position. """ seq1, seq2 = tee(seq) return islice(seq1, 0, index), islice(seq2, index + step, None) def sliding(seq, size, step=1): """ Groups elements in fixed size blocks by passing a 'sliding window' over them (as opposed to partitioning them, as is done in grouped. """ def _(_seq, _size, _step): seq1, seq2 = splitat(_seq, _size, _step-_size) yield list(seq1) for seq3 in sliding(seq2, size, step): yield seq3 return takewhile(lambda x: x != [], _(seq, size, step)) def slidingwithpadding(seq, size, step=1, padding=''): def _(lst): if len(lst) != size: return lst + [padding]*(size-len(lst)) else: return lst return imap(_, sliding('abcdefg', size, step)) def reduceright(func, seq): """ applies a binary operator to all elements of this list, going right to left. """ return reduce(func, reversed(seq)) def reversemap(func, seq): """ builds a new collection by applying a function to all elements of this list and collecting the results in reversed order. """ return imap(func, reversed(seq))
b77aa4d261eb4d0c618addd7e21116cff4eb93ed
mccdaq/daqhats
/examples/python/mcc118/ifttt/ifttt_log.py
3,146
3.59375
4
#!/usr/bin/env python """ MCC 118 example program Read channels 0 and 1 every 5 minutes and send an IFTTT event for logging to a Google sheets spreadsheet. This uses the IFTTT Webhooks channel for inputs. You create your own event and enter the name here for event_name (we used voltage_data for the name), then choose an activity to occur when the event happens. We used the Google Sheets activity and selected "add a row to a spreadsheet", then set it up to log the time and voltages (Value0 and Value1). 1. Sign in to your account at [https://ifttt.com](https://ifttt.com), select "My Applets", and click the "New Applet" button. 2. Click "this" then search for Webhooks. Click the Webhooks icon when found. 3. On the "Choose trigger" screen, click "Receive a web request". 4. On the "Complete trigger fields" screen, enter an event name ("voltage_data" for this example) and click the "Create trigger" button. 5. Click "that", then search for "Google Sheets" on the "Choose action service" screen and select the "Google Sheets" icon when found. 6. On the "Choose action" screen, select "Add row to spreadsheet". 7. On the "Complete action fields" screen, enter a spreadsheet name, modify the "Formatted row" field so it contains "{{OccurredAt}} ||| {{Value1}} ||| {{Value2}}" (without quotes). Change the Google Drive folder path if desired, then click the "Create action" button. 8. Review the summary statement, then click the **Finish** button. Enter your key from IFTTT Webhooks documentation for the variable "key". You can find this key by: 1. At IFTTT.com go to My Applets, then click the Services heading. 2. Enter Webhooks in the Filter services field, then click on Webhooks. 3. Click on Documentation. Your key will be listed at the top; copy that key and paste it inside the quotes below, replacing <my_key>. """ from __future__ import print_function import time import sys import daqhats as hats import requests # IFTTT values EVENT_NAME = "voltage_data" KEY = "<my_key>" def send_trigger(event, value1="", value2="", value3=""): """ Send the IFTTT trigger. """ report = {} report['value1'] = str(value1) report['value2'] = str(value2) report['value3'] = str(value3) requests.post("https://maker.ifttt.com/trigger/" + event + "/with/key/" + KEY, data=report) def main(): """ Main function """ log_period = 5*60 if KEY == "<my_key>": print("The default key must be changed to the user's personal IFTTT " "Webhooks key before using this example.") sys.exit() # Find the first MCC 118 mylist = hats.hat_list(filter_by_id=hats.HatIDs.MCC_118) if not mylist: print("No MCC 118 boards found") sys.exit() board = hats.mcc118(mylist[0].address) while True: # read the voltages value_0 = board.a_in_read(0) value_1 = board.a_in_read(1) send_trigger(EVENT_NAME, "{:.3f}".format(value_0), "{:.3f}".format(value_1)) print("Sent data {0:.3f}, {1:.3f}.".format(value_0, value_1)) time.sleep(log_period) if __name__ == '__main__': main()
69f1c30d5959b3c70f91e5323cfe84ab2067e5aa
umfundii/learning-robot-swarm-controllers
/source/controllers/controllers_task2.py
9,290
4.21875
4
from utils import utils class ManualController: """ Using the sensing of the robots, decide which robots are the first and the last and start sending a communication message containing a value that is incremented by each robot that received it. Each robot can receive two messages, if the count received from the right is higher than the one from the left, then the agent is in the first half, otherwise it is in the second. When the robot is sure about is position (it is able to understand on which side of the row it is, compared to the mid of the line) then the robot can turn on the top led using different colours depending if it is positioned in the first or second half of the row. :param name: name of the controller used (in this case manual) :param goal: task to perform (in this case colour) :param N: number of thymios in the simulation :param kwargs: other arguments """ def __init__(self, name, goal, N, net_input, **kwargs): super().__init__(**kwargs) self.name = name self.goal = goal self.N = N self.net_input = net_input def perform_control(self, state, dt): """ :param state: object containing the agent information :param dt: control step duration :return colour, communication: the colour and the message to communicate """ if state.index == 0: colour = 1 message = 1 elif state.index == self.N - 1: colour = 0 message = 1 else: communication = utils.get_received_communication(state, goal=self.goal) # if no communication is received yet, do not send any message and colour the top led randomly if communication == [0, 0]: colour = 2 message = 0 # if some communication is received... else: # if the number of robots is odd if self.N % 2 == 1: # if no communication is received from left... if communication[0] == 0: if communication[1] > self.N // 2: message = communication[1] - 1 colour = 1 elif communication[1] == self.N // 2: message = communication[1] + 1 colour = 1 else: message = communication[1] + 1 colour = 0 # if no communication is received from right... elif communication[1] == 0: if communication[0] > self.N // 2: message = communication[0] - 1 colour = 0 elif communication[0] == self.N // 2: message = communication[0] + 1 colour = 1 else: message = communication[0] + 1 colour = 1 # if the communication is received from both sides... else: if communication[0] > communication[1]: message = communication[1] + 1 colour = 0 else: message = communication[0] + 1 colour = 1 # if the number of robots is even elif self.N % 2 == 0: # if no communication is received from left... if communication[0] == 0: if communication[1] > self.N // 2: # WARNING # message = communication[1] or communication[1] - 1 message = communication[1] colour = 1 else: message = communication[1] + 1 colour = 0 # if no communication is received from right... elif communication[1] == 0: if communication[0] < self.N // 2: message = communication[0] + 1 colour = 1 else: # WARNING # message = communication[0] or communication[0] - 1 message = communication[0] colour = 0 # if the communication is received from both sides... else: if communication[0] > communication[1]: message = communication[1] + 1 colour = 0 elif communication[0] < communication[1]: message = communication[0] + 1 colour = 1 else: message = communication[0] colour = 0 return colour, int(message) class OmniscientController: """ The robots can turn on and colour the top led also following an optimal “omniscient” controller. In this case, based on the position of the robots in the line, the omniscient control colour the robots in the first half with a colour and the others with another. :param name: name of the controller used (in this case omniscient) :param goal: task to perform (in this case colour) :param N: number of agents in the simulation :param net_input: input of the network (between: prox_values, prox_comm and all_sensors) :param kwargs: other arguments """ def __init__(self, name, goal, N, net_input, **kwargs): super().__init__(**kwargs) self.name = name self.goal = goal self.N = N self.net_input = net_input def perform_control(self, state, dt): """ Do not move the robots but just colour the robots belonging to the first half with a certain colour and the other half with a different colour. :param state: object containing the agent information :param dt: control step duration :return colour, communication: the colour and the message to communicate """ return state.goal_colour, 0 class LearnedController: """ The robots can be moved following a controller learned by a neural network. :param name: name of the controller used (in this case omniscient) :param goal: task to perform (in this case distribute) :param N: number of agents in the simulation :param net: network to be used by the controller :param net_input: input of the network (between: prox_values, prox_comm and all_sensors) :param communication: states if the communication is used by the network :param kwargs: other arguments """ def __init__(self, name, goal, N, net, net_input, communication, **kwargs): super().__init__(**kwargs) self.name = name self.goal = goal self.N = N self.net = net if self.net is None: raise ValueError("Value for net not provided") self.communication = communication self.net_controller = net.controller(thymio=self.N) self.net_input = net_input def perform_control(self, state, dt): """ Extract the input sensing from the list of (7 or 14) proximity sensor readings, one for each sensor. The first 5 entries are from frontal sensors ordered from left to right. The last two entries are from rear sensors ordered from left to right. In case of all sensors the first 7 values refers to ``prox_values`` and the following 7 to ``prox_comm``. Each value is normalised dividing it by 1000, that is the mean value of the sensors. The obtained sensing is passed as input to the net and obtain the speed and the eventual communication to be transmitted. .. note:: Keep still the robots at the ends of the line and send for them alway 0 as message. :param state: object containing the agent information :param dt: control step duration :return speed, communication: the velocity and the message to communicate """ if hasattr(state, 'sim') and state.sim: colour, comm = self.net_controller(state.prox_values, state.messages.tolist(), state.index) t_comm = comm[state.index] return colour, t_comm else: sensing = utils.get_input_sensing(self.net_input, state) communication = utils.get_received_communication(state) colour, comm = self.net_controller(sensing, communication, state.index) if colour > 0.5: colour = 1 else: colour = 0 t_comm = int(comm[state.index] * (2 ** 10)) if state.index == 0: return 1, 0 elif state.index == self.N - 1: return 0, 0 else: return colour, t_comm
b6bc4fdad48a21a679055fa4d6a55344ccc44052
btrif/Python_dev_repo
/Algorithms/Tonelli - Shanks.py
4,293
4.03125
4
# Created by Bogdan Trif on 16-05-2018 , 5:08 PM. # https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm # The Tonelli–Shanks algorithm (referred to by Shanks as the RESSOL algorithm) # is used in modular arithmetic to solve for r in a congruence of the form r^2 ≡ n (mod p), # where p is a prime: that is, to find a square root of n modulo p. def legendre_symbol(a, p): """ Legendre symbol Define if a is a quadratic residue modulo odd prime http://en.wikipedia.org/wiki/Legendre_symbol """ ls = pow(a, (p - 1)//2, p) if ls == p - 1: return -1 return ls def prime_mod_sqrt(a, p): """ Square root modulo prime number Solve the equation x^2 = a mod p and return list of x solution http://en.wikipedia.org/wiki/Tonelli-Shanks_algorithm """ a %= p # Simple case if a == 0: return [0] if p == 2: return [a] # Check solution existence on odd prime if legendre_symbol(a, p) != 1: return [] # Simple case if p % 4 == 3: x = pow(a, (p + 1)//4, p) return [x, p-x] # Factor p-1 on the form q * 2^s (with Q odd) q, s = p - 1, 0 while q % 2 == 0: s += 1 q //= 2 # Select a z which is a quadratic non resudue modulo p z = 1 while legendre_symbol(z, p) != -1: z += 1 c = pow(z, q, p) # Search for a solution x = pow(a, (q + 1)//2, p) t = pow(a, q, p) m = s while t != 1: # Find the lowest i such that t^(2^i) = 1 i, e = 0, 2 for i in range(1, m): if pow(t, e, p) == 1: break e *= 2 # Update next value to iterate b = pow(c, 2**(m - i - 1), p) x = (x * b) % p t = (t * b * b) % p c = (b * b) % p m = i return [x, p-x] prime_mod_sqrt(12, 13), legendre_symbol(12,13) ################ VARIANT II ############ def modular_sqrt(a, p): """ Find a quadratic residue (mod p) of 'a'. p must be an odd prime. Solve the congruence of the form: x^2 = a (mod p) And returns x. Note that p - x is also a root. 0 is returned is no square root exists for these a and p. The Tonelli-Shanks algorithm is used (except for some simple cases in which the solution is known from an identity). This algorithm runs in polynomial time (unless the generalized Riemann hypothesis is false). """ # Simple cases # if legendre_symbol(a, p) != 1: return 0 elif a == 0: return 0 elif p == 2: return n elif p % 4 == 3: return pow(a, (p + 1) // 4, p) # Partition p-1 to s * 2^e for an odd s (i.e. # reduce all the powers of 2 from p-1) # s = p - 1 e = 0 while s % 2 == 0: s /= 2 e += 1 # Find some 'n' with a legendre symbol n|p = -1. # Shouldn't take long. # n = 2 while legendre_symbol(n, p) != -1: n += 1 # Here be dragons! # Read the paper "Square roots from 1; 24, 51, # 10 to Dan Shanks" by Ezra Brown for more # information # # x is a guess of the square root that gets better # with each iteration. # b is the "fudge factor" - by how much we're off # with the guess. The invariant x^2 = ab (mod p) # is maintained throughout the loop. # g is used for successive powers of n to update # both a and b # r is the exponent - decreases with each update # x = pow(a, (s + 1) // 2, p) b = pow(a, s, p) g = pow(n, s, p) r = e while True: t = b m = 0 for m in range(r): if t == 1: break t = pow(t, 2, p) if m == 0: return x gs = pow(g, 2 ** (r - m - 1), p) g = (gs * gs) % p x = (x * gs) % p b = (b * g) % p r = m def legendre_symbol(a, p): """ Compute the Legendre symbol a|p using Euler's criterion. p is a prime, a is relatively prime to p (if p divides a, then a|p = 0) Returns 1 if a has a square root modulo p, -1 otherwise. """ ls = pow(a, (p - 1) // 2, p) return -1 if ls == p - 1 else ls
731e233d78a85e9b2237d5ea83984571246e4ff9
KacperKubara/USAIS_Workshops
/Other/grid_search.py
1,941
3.5625
4
"""Grid Search Example based on the Random Forest Regression""" import numpy as np import pandas as pd import matplotlib.pyplot as plt # Read Data from sklearn.datasets import load_boston dataset = load_boston() #Loading Sklearn internal dataset # Choose which features to use x = dataset["data"][:, [7, 9]] # using DIS and TAX features y = dataset["target"] # output value # Split data into train and test dataset from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x[:,:], y, test_size = 0.2, random_state = 42) # Data Preprocessing from sklearn.preprocessing import StandardScaler sc_x = StandardScaler() x_train = sc_x.fit_transform(x_train) # Scaling the data x_test = sc_x.transform(x_test) # Train Model with the Grid Search from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import GridSearchCV """ You can take any parameters to sweep through as long as they're available in the specific model""" parameters = {'n_estimators': [5, 10, 50, 75, 100], 'min_samples_split': [2, 3, 4, 5], 'min_samples_leaf': [1, 2, 3, 4, 5]} random_forest = GridSearchCV( estimator = RandomForestRegressor(), param_grid = parameters, cv = 5) # Train the model random_forest.fit(x_train, y_train) best_parameters = random_forest.best_params_ # Predict the model y_pred = random_forest.predict(x_test) # Measure Accuracy from sklearn.metrics import mean_squared_error acc = mean_squared_error(y_test, y_pred) # Visualise Results from mpl_toolkits.mplot3d import axes3d fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_xlabel('DIS values') ax.set_ylabel('TAX values') ax.set_zlabel('House Price(1k$)') x_test = sc_x.inverse_transform(x_test) ax.scatter(x_test[:,0], x_test[:,1], y_test, color = 'r') ax.scatter(x_test[:,0], x_test[:,1], y_pred, color = 'b') plt.show()
34d54b4a8459a5fa6ab23943968d07a213e03415
gurramdeepika/python_programming
/PycharmProjects/no1/Fourth_Day/Fibnocci.py
357
3.515625
4
class fibnum: def __init__(self): self.f1 = 0 self.f2 = 1 def __next__(self): self.f1,self.f2,olff2 = self.f1+self.f2,self.f1,self.f2 return olff2 def __iter__(self): return self def main(): f = fibnum() for i in f: print(i) if i > 20: break if __name__ == '__main__': main()
0baae320e7a2056a09fd1d024920a60c42078ecb
lokeshV89/pythonPrac
/numpy/1numpy.py
344
3.859375
4
import numpy as np # single dimentional array a = np.array([1,2,3]) # multi dimentional array b = np.array([(1,2,3),(4,5,6)]) print(a) print(b) # create a array of 1000 number d = np.arange(1000) print(d) print(d.itemsize) # to get a tupple having array dimensions print(a.shape) print(b.shape) # to reshap a array c = b.reshape(3,2) print(c)
c2e4fefcd02e71824d17291a0d6033c72de51c25
Toma-L/NLP
/NLP.py
13,094
3.796875
4
#Natural Language Processing with Python #1.1==================== import nltk #nltk.download() #download book from nltk.book import * text1 text2 text1.concordance("monstrous") text2.concordance("affection") text1.similar("monstrous") text2.similar("monstrous") text2.common_contexts(["monstrous", "very"]) text4.dispersion_plot(["citizens", "democracy", "freedom", "duties", "America"]) text3.generate() #not working any more len(text3) sorted(set(text3)) #sorted: from ,./ to abc, from A to Z, from a to z len(set(text3)) #2789 unique symbols and words from __future__ import division text3.count("smote") 100 * text4.count("a") / len(text4) #1.46% of text4 is "a" text5.count("lol") #704 text5.count("lol") / len(text5) * 100 #1.56% of text5 is "lol" def lexical_diversity(text): return len(text) / len(set(text)) def percentage(count, total): return 100 * count / total lexical_diversity(text3) lexical_diversity(text5) percentage(4, 5) percentage(text4.count('a'), len(text4)) #1.2==================== sent1 = ["Call", "me", "Ishmael", "."] sent1 lexical_diversity(sent1) ex1 = ["Monty", "Python", "and", "the", "Holy", "Grail"] sorted(set(ex1)) len(set(ex1)) ex1.count("Monty") ["Monty", "Python"] + ["and", "the", "Holy", "Grail"] sent4 + sent1 sent1.append("Some") #add one item to sent1 len(sent1) sent1 text4[173] #call number 173 word of text4 text4.index("awaken") text5[16715:16735] text6[1600:1625] #actually 1600~1624 sent = ["word1", "word2", "word3", "word4", "word5", "word6", "word7", "word8", "word9", "word10"] sent[0] sent[9] sent[10] #Error but not Syntax Error sent[5:8] sent[5] sent[7] sent[:3] #0~2 text2[141525:] sent[0] = "First" sent[9] = "Last" sent sent1 = ["Call", "me", "Ishmael", "."] my_sent = ["Bravely", "bold", "Sir", "Robin", ",", "rode", "forth", "from", "Camelot", "."] noun_phrase = my_sent[1:4] noun_phrase wOrDs = sorted(noun_phrase) wOrDs not = "Camelot" #Error vocab = set(text1) vocab_size = len(vocab) vocab_size name = "Monty" name[0] name[:4] name * 2 name + "!" " ".join(["Monty", "Python"]) "Monty Python".split() #1.3==================== saying = ["After", "all", "is", "said", "and", "done", "more", "is", "said", "than", "done"] tokens = set(saying) tokens = sorted(tokens) tokens[-2:] #count from backward fdist1 = FreqDist(text1) fdist1 vocabulary1 = list(fdist1.keys()) vocabulary1[:50] #Freq top 50 words fdist1['whale'] fdist2 = FreqDist(text2) fdist2 vocabulary2 = list(fdist2.keys()) vocabulary2[:50] fdist1.plot(50, cumulative = True) fdist2.plot(50, cumulative = True) fdist1.hapaxes() #words only appear once V = set(text1) long_words = [w for w in V if len(w) > 15] #long words sorted(long_words) vocab = set(text1) long_words = [word for word in vocab if len(word) > 15] sorted(long_words) fdist5 = FreqDist(text5) sorted([w for w in set(text5) if len(w) > 7 and fdist5[w] > 7]) #nchar > 7 and freq > 7 list(bigrams(['more', 'is', 'said', 'than', 'done'])) #bigrams() isn't working! WHY text4.collocations() text8.collocations() [len(w) for w in text1] fdist = FreqDist([len(w) for w in text1]) fdist fdist.keys() fdist.items() fdist.max() fdist[3] fdist.freq(3) fdist['monstrous'] fdist.N() fdist.tabulate() fdist.plot() fdist.max() fdist.plot(cumulative = True) fdist1 < fdist2 #1.4==================== sent7 [w for w in sent7 if len(w) < 4] [w for w in sent7 if len(w) <= 4] [w for w in sent7 if len(w) == 4] [w for w in sent7 if len(w) != 4] sent7[0].startswith("P") sent7[0].endswith("t") "e" in sent7[0] sent7[0].islower() sent7[0].isupper() sent7[0].isalpha() sent7[0].isalnum() sent7[3].isdigit() sent7[0].istitle() sorted([w for w in set(text1) if w.endswith('ableness')]) sorted([term for term in set(text4) if 'gnt' in term]) sorted([item for item in set(text6) if item.istitle()]) sorted([item for item in set(sent7) if item.isdigit()]) sorted([w for w in set(text7) if '-' in w and 'index' in w]) sorted([wd for wd in set(text3) if wd.istitle() and len(wd) > 10]) sorted([t for t in set(text2) if 'cie' in t or 'cei' in t]) [len(w) for w in text1] [w.upper() for w in text1] len(text1) len(set(text1)) len(set([word.lower() for word in text1])) #eliminate the difference between upper & lower len(set([word.lower() for word in text1 if word.isalpha()])) #only alpha left word = 'cat' if len(word) < 5: print ('word length is less than 5') if len(word) >=5: print ('word length is greater than or equal to 5') for word in ['Call', 'me', 'Ishmael', '.']: print (word) sent1 = ['Call', 'me', 'Ishmael', '.'] for xyzzy in sent1: if xyzzy.endswith('l'): print (xyzzy) for token in sent1: if token.islower(): print (token, 'is a lowercase word') elif token.istitle(): print (token, 'is a titlecase word') else: print (token, 'is punctuation') tricky = sorted([w for w in set(text2) if 'cie' in w or 'cei' in w]) for word in tricky: print (word), #2.1==================== import nltk nltk.corpus.gutenberg.fileids() emma = nltk.corpus.gutenberg.words('austen-emma.txt') len(emma) emma = nltk.Text(nltk.corpus.gutenberg.words('austen-emma.txt')) emma.concordance('surprize') #another way to do this from nltk.corpus import gutenberg gutenberg.fileids() emma = gutenberg.words('austen-emma.txt') for fileid in gutenberg.fileids(): num_chars = len(gutenberg.raw(fileid)) num_words = len(gutenberg.words(fileid)) num_sents = len(gutenberg.sents(fileid)) num_vocab = len(set([w.lower() for w in gutenberg.words(fileid)])) print (int(num_chars/num_words), int(num_words/num_sents)) #avg word & sentence length and the diversity of words macbeth_sentences = gutenberg.sents('shakespeare-macbeth.txt') macbeth_sentences #load sentences of Macbeth macbeth_sentences[1037] longest_len = max([len(s) for s in macbeth_sentences]) [s for s in macbeth_sentences if len(s) == longest_len] #find longest sentence from nltk.corpus import webtext for fileid in webtext.fileids(): print (fileid, webtext.raw(fileid)[:65], '...') from nltk.corpus import nps_chat chatroom = nps_chat.posts('10-19-20s_706posts.xml') chatroom[123] from nltk.corpus import brown brown.categories() brown.words(categories = 'news') brown.words(fileids = ['cg22']) from nltk.corpus import brown news_text = brown.words(categories = 'news') fdist = nltk.FreqDist([w.lower() for w in news_text]) modals = ['can', 'could', 'may', 'might', 'must', 'will'] for m in modals: print (m + ':', fdist[m],) cfd = nltk.ConditionalFreqDist( (genre, word) for genre in brown.categories() for word in brown.words(categories = genre)) genres = ['news', 'religion', 'hobbies', 'science_fiction', 'romance', 'humor'] modals = ['can', 'could', 'may', 'might', 'must', 'will'] cfd.tabulate(conditions = genres, samples = modals) from nltk.corpus import reuters reuters.fileids() reuters.categories() reuters.categories('training/9865') reuters.categories(['training/9865', 'training/9880']) reuters.fileids('barley') reuters.fileids(['barley', 'corn']) reuters.words('training/9865')[:14] reuters.words(['training/9865', 'training/9880']) reuters.words(categories = 'barley') reuters.words(categories = ['barley', 'corn']) from nltk.corpus import inaugural inaugural.fileids() [fileid[:4] for fileid in inaugural.fileids()] cfd = nltk.ConditionalFreqDist( (target, fileid[:4]) for fileid in inaugural.fileids() for w in inaugural.words(fileid) for target in ['america', 'citizen'] if w.lower().startswith(target)) cfd.plot() nltk.corpus.cess_esp.words() nltk.corpus.floresta.words() #Error nltk.corpus.indian.words('hindi.pos') nltk.corpus.udhr.fileids() nltk.corpus.udhr.words('Javanese-Latin1')[11:] from nltk.corpus import udhr languages = ['Chickasaw', 'English', 'German_Deutsch', 'Greenlandic_Inuktikut', 'Hungarian_Magyar', 'Ibibio_Efik'] cfd = nltk.ConditionalFreqDist( (lang, len(word)) for lang in languages for word in udhr.words(lang + '-Latin1')) cfd.plot(cumulative = True) raw = gutenberg.raw("burgess-busterbrown.txt") raw[1:20] words = gutenberg.words("burgess-busterbrown.txt") words[1:20] sents = gutenberg.sents("burgess-busterbrown.txt") sents[1:20] from nltk.corpus import PlaintextCorpusReader corpus_root = '' #yourown file wordlists = PlaintextCorpusReader(corpus_root, '.*') wlrdlists.fileids() wordlists.words('connectives') from nltk.corpus import BracketParseCorpusReader corpus_root = r"" file_pattern = r".*/wsj_.*\.mrg" ptb = BracketParseCorpusReader(corpus_root, file_pattern) ptb.fileids() len(ptb.sents()) ptb.sents(fileids = '20/wsj_2013.mrg')[19] #2.2==================== text = ['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', ...] pairs = [('news', 'The'), ('news', 'Fulton'), ('news', 'County'), ...] import nltk from nltk.corpus import brown cfd = nltk.ConditionalFreqDist( (genre, word) for genre in brown.categories() for word in brown.words(categories = genre)) genre_word = [(genre, word) for genre in ['news', 'romance'] for word in brown.words(categories = genre)] len(genre_word) genre_word[:4] genre_word[-4:] cfd = nltk.ConditionalFreqDist(genre_word) cfd cfd.conditions() cfd['news'] cfd['romance'] list(cfd['romance']) cfd['romance']['could'] from nltk.corpus import inaugural cfd = nltk.ConditionalFreqDist( (target, fileid[:4]) for fileid in inaugural.fileids() for w in inaugural.words(fileid) for target in ['america', 'citizen'] if w.lower().startswith(target)) from nltk.corpus import udhr languages = ['Chickasaw', 'English', 'German_Deutsch', 'Greenlandic_Inuktikut', 'Hungarian_Magyar', 'Ibibio_Efik'] cfd = nltk.ConditionalFreqDist( (lang, len(word)) for lang in languages for word in udhr.words(lang + '-Latin1')) cfd cfd.tabulate(conditions = ['English', 'German_Deutsch'], samples = range(10), cumulative = True) #showyourwork / p.58 genre_word = [(genre, word) for genre in ['news', 'romance'] for word in brown.words(categories = genre)] cfd = nltk.ConditionalFreqDist(genre_word) days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] cfd.tabulate(samples = days) sent = ['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven', 'and', 'the', 'earth', '.'] nltk.bigrams(sent) #doesn't work def generate_model(cfdist, word, num = 15): for i in range(num): print (word), word = cfdist[word].max() text = nltk.corpus.genesis.words('english-kjv.txt') bigrams = nltk.bigrams(text) cfd = nltk.ConditionalFreqDist(bigrams) print (cfd['living']) generate_model(cfd, 'living') #2.3==================== from __future__ import division def lexical_diversity(my_text_data): word_count = len(my_text_data) vocab_size = len(set(my_text_data)) diversity_score = word_count / vocab_size return diversity_score def plural(word): if word.endswith('y'): return word[:-1] + 'ies' elif word[-1] in 'sx' or word[-2:] in ['sh', 'ch']: return word + 'es' elif word.endswith('an'): return word[:-2] + 'en' else: return word + 's' plural('fairy') plural('woman') plural('wish') plural('fan') #incorrect #2.4==================== def unusual_words(text): text_vocab = set(w.lower() for w in text if w.isalpha()) english_vocab = set(w.lower() for w in nltk.corpus.words.words()) unusual = text_vocab.difference(english_vocab) return sorted(unusual) unusual_words(nltk.corpus.gutenberg.words('austen-sense.txt')) unusual_words(nltk.corpus.nps_chat.words()) from nltk.corpus import stopwords stopwords.words('english') def content_fraction(text): stopwords = nltk.corpus.stopwords.words('english') content = [w for w in text if w.lower() not in stopwords] return len(content) / len(text) content_fraction(nltk.corpus.reuters.words()) puzzle_letters = nltk.FreqDist('egivrvonl') obligatory = 'r' wordlist = nltk.corpus.words.words() [w for w in wordlist if len(w) >= 6 and obligatory in w and nltk.FreqDist(w) <= puzzle_letters] names = nltk.corpus.names names.fileids() male_names = names.words('male.txt') female_names = names.words('female.txt') [w for w in male_names if w in female_names] cfd = nltk.ConditionalFreqDist( (fileid, name[-1]) for fileid in names.fileids() for name in names.words(fileid)) cfd.plot() entries = nltk.corpus.cmudict.entries() len(entries) for entry in entries[39943:39951]: print (entry) for word, pron in entries: if len(pron) == 3: ph1, ph2, ph3 = pron if ph1 == 'P' and ph3 == 'T': print (word, ph2,) syllable = ['N', 'IHO', 'K', 'S'] [word for word, pron in entries if pron[-4:] == syllable] [w for w, pron in entries if pron[-1] == 'M' and w[-1] == 'n'] sorted(set(w[:2] for w, pron in entries if pron[0] == 'N' and w[0] != 'n'))
f0d63914bb07dc9927df4be3cd6dfc0fb181ccb3
eduardogomezvidela/Summer-Intro
/10 Lists/Excersises/23.py
493
3.921875
4
#5 char word counter list = ['no','umm', 'crazy', 4, 'banana', 'scuba', 'apple', 1, 'nope', 'bloke'] #4 5 letter words five_letters = 0 counter = 0 for word in list: counter = 0 if (type(word)) == int: #In case of ints in list x = 0 else: #Counts 5 letter words for letter in word: counter = counter +1 if counter == 5: five_letters = five_letters + 1 print(five_letters)
f1633d2b7fd2fe05e157b9b4f8c62b6ea852b0b8
hayuzi/py-first
/base/function.py
6,186
4.125
4
# 函数 def funcFirst(): print('hello world') # python 函数的参数传递: # 不可变类型:类似 c++ 的值传递,如 整数、字符串、元组。如fun(a),传递的只是a的值,没有影响a对象本身。 # 比如在 fun(a)内部修改 a 的值,只是修改另一个复制的对象,不会影响 a 本身。 # 可变类型:类似 c++ 的引用传递,如 列表,字典。如 fun(la),则是将 la 真正的传过去,修改后fun外部的la也会受影响 # 关键字参数 # 关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值。 # 使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值。 # 以下实例在函数 printme() 调用时使用参数名 def printinfo(name, age=20): # "打印任何传入的字符串" print("名字: ", name) print("年龄: ", age) return # 调用printinfo函数 printinfo(age=50, name="test name") printinfo("test name", 100) printinfo("test name") printinfo(name="test name") # 不定长参数 # 你可能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数,和上述 2 种参数不同,声明时不会命名。 # 加了星号 * 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数。 # 格式如下 # def functionname([formal_args,] *var_args_tuple ): # "函数_文档字符串" # function_suite # return [expression] # 打印任何传入的参数 def printinfomulti(arg1, *vartuple): print("输出: ") print(arg1) print(vartuple) printinfomulti(1, 2, 3, 4, 5) # 还有一种就是参数带两个星号 **基本语法如下: # 加了两个星号 ** 的参数会以字典的形式导入。 # def functionname([formal_args,] **var_args_dict ): # "函数_文档字符串" # function_suite # return [expression] # 声明函数时,参数中星号 * 可以单独出现,如果单独出现星号 * 后的参数必须用关键字传入。例如: def f(a, b, *, c): return a+b+c f(1, 2, c=3) # 匿名函数 # python 使用 lambda 来创建匿名函数。 # lambda 只是一个表达式,函数体比 def 简单很多。 # lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。 # lambda 函数拥有自己的命名空间,且不能访问自己参数列表之外或全局命名空间里的参数。 # 虽然lambda函数看起来只能写一行,却不等同于C或C++的内联函数,后者的目的是调用小函数时不占用栈内存从而增加运行效率。 # lambda 函数的语法只包含一个语句,如下: # lambda [arg1 [,arg2,.....argn]]:expression def sum(arg1, arg2): return arg1 + arg2 # 调用sum函数 print("相加后的值为 : ", sum(10, 20)) print("相加后的值为 : ", sum(20, 20)) # return语句 # return [表达式] 语句用于退出函数,选择性地向调用方返回一个表达式。不带参数值的return语句返回None。 def sumB(arg1, arg2): # 返回2个参数的和." total = arg1 + arg2 print("函数内 : ", total) return total # 调用sum函数 total = sumB(10, 20) print("函数外 : ", total) # 变量作用域 # Python 中,程序的变量并不是在哪个位置都可以访问的,访问权限决定于这个变量是在哪里赋值的。 # 变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称。Python的作用域一共有4种,分别是: # L (Local) 局部作用域 # E (Enclosing) 闭包函数外的函数中 # G (Global) 全局作用域 # B (Built-in) 内置作用域(内置函数所在模块的范围) # 以 L –> E –> G –>B 的规则查找,即:在局部找不到,便会去局部外的局部找(例如闭包),再找不到就会去全局找,再者去内置中找。 g_count = 0 # 全局作用域 def outer(): o_count = 1 # 闭包函数外的函数中 print(o_count) def inner(): i_count = 2 # 局部作用域 print(i_count) inner() # 内置作用域是通过一个名为 builtin 的标准模块来实现的,但是这个变量名自身并没有放入内置作用域内,所以必须导入这个文件才能够使用它。 # 在Python3.0中,可以使用以下的代码来查看到底预定义了哪些变量: # >>> import builtins # >>> dir(builtins) # Python 中只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域, # 其它的代码块(如 if/elif/else/、try/except、for/while等)是不会引入新的作用域的, # 也就是说这些语句内定义的变量,外部也可以访问. # 全局变量和局部变量 # 定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。 # 局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。 # 调用函数时,所有在函数内声明的变量名称都将被加入到作用域中。 total = 0 # 这是一个全局变量 # 可写函数说明 def sumC(arg1, arg2): # 返回2个参数的和." total = arg1 + arg2 # total在这里是局部变量. print("函数内是局部变量 : ", total) return total # 调用sum函数 sumC(1, 2) print("函数外是全局变量 : ", total) # 以上实例输出结果: # 函数内是局部变量 : 3 # 函数外是全局变量 : 0 # global 和 nonlocal关键字 # 当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal关键字了。 # 以下实例修改全局变量 num: num = 1 def fun1(): global num # 需要使用 global 关键字声明 print(num) num = 123 print(num) fun1() print(num) # 如果要修改嵌套作用域(enclosing 作用域,外层非全局作用域)中的变量则需要 nonlocal 关键字了,如下实例: def outerfunc(): num = 10 def innerfunc(): nonlocal num # nonlocal关键字声明 num = 100 print(num) innerfunc() print(num) outerfunc()
ad998f0cc40ecdb4d0cc8255be9f67f0ff530beb
userddssilva/Exemplos-introducao-a-programacao
/condicional.py
137
3.890625
4
idade = float (input ( "informe uma idade: ")) if idade >= 18: print ("voce ja pode beber") else: print(" voce nao pode beber")
a504d5468361efaabf472ef887e885f4bf3d4444
Nonac/Python_practise
/Xs and Os Referee.py
1,206
3.734375
4
def checkio(game_result): a = "" for i in game_result: a = a + i if a[0] == a[1] and a[0] == a[2] and a[0] != ".":return a[0] elif a[0] == a[3] and a[0] == a[6] and a[0] != ".":return a[0] elif a[0] == a[4] and a[0] == a[8] and a[0] != ".":return a[0] elif a[1] == a[4] and a[1] == a[7] and a[1] != ".":return a[1] elif a[2] == a[5] and a[2] == a[8] and a[2] != ".":return a[2] elif a[2] == a[4] and a[2] == a[6] and a[2] != ".": return a[2] elif a[3] == a[4] and a[3] == a[5] and a[3] != ".": return a[3] elif a[6] == a[7] and a[6] == a[8] and a[6] != ".": return a[6] else:return "D" if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert checkio([ "X.O", "XX.", "XOO"]) == "X", "Xs wins" assert checkio([ "OO.", "XOX", "XOX"]) == "O", "Os wins" assert checkio([ "OOX", "XXO", "OXX"]) == "D", "Draw" assert checkio([ "O.X", "XX.", "XOO"]) == "X", "Xs wins again" print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
7627698addfefc711f0d24b0e13a961cc932dbff
hyolin97/bigdata_web
/python/실습3.py
357
3.515625
4
pu=int(input("숫자를 입력하시오:")) if pu>10: if pu%2==0: print("%d는 10보다 큰 짝수입니다."%pu) else: print("%d는 10보다 큰 홀수입니다."%pu) else: if pu%2==0: print("%d는 10보다 작은 짝수입니다."%pu) else: print("%d는 10보다 작은 홀수입니다."%pu)
5dc708d1a573ad42ff14a73aa04eecb86a66d782
Mnoori198/week_4
/main_store/coupon_calculations.py
607
3.609375
4
def calculate_price(price, cash_coupen, percent_coupen): shipping_vp_to_ten = 5.95 shipping_ten_to_thrity = 7.95 shipping = 0 tax = 0.06 price_after_cash_coupen = price - cash_coupen price_after_percent_coupen = price_after_cash_coupen - (price_after_cash_coupen* percent_coupen) price_with_tax = price_after_percent_coupen + (price_after_percent_coupen* tax) if price_after_percent_coupen < 10: total_prince = price_with_tax + shipping_vp_to_ten print(total_prince) return total_prince if __name__ == '__main__': calculate_price(6, 5, 12)
aafc25c9b625d5793f83033dfc5c717acfa0f1db
aidardarmesh/leetcode
/Problems/200. Number of Islands.py
1,093
3.53125
4
from typing import * class Solution: def numIslands(self, grid: List[List[str]]) -> int: ''' Strategy is to "draw" lands in water ''' if not grid: return 0 N = len(grid) M = len(grid[0]) islands = 0 for i in range(N): for j in range(M): if grid[i][j] == '1': grid[i][j] = '0' islands += 1 queue = [(i,j)] while queue: x,y = queue.pop() for ni, nj in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]: if 0 <= ni < N and 0 <= nj < M: if grid[ni][nj] == '1': grid[ni][nj] = '0' queue.append((ni,nj)) return islands s = Solution() islands = s.numIslands([["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]) print(islands)
d8566277f2f88b1b63ce4463a3c8e7adea2b9913
Alextter/lesson4-year2
/lesson4_4.py
115
3.640625
4
a = int(input("Storona")) r = int(input("RadiusK")) if r == (a/2): print("mojno") else: print("net")
cb1eafcd6285b415a2545685aef67a9f1d6a1379
conradstorz/Palindrome
/Palindrome_python2.py
2,912
4.125
4
#! /usr/bin/env python #python 2 """ A simple module for testing the isPalindrome(string) code. """ import string def isPalindrome_Jaysen(s): s = s.upper() s = s.translate( string.maketrans("", ""), string.punctuation + string.whitespace) return s == s[::-1] def isPalindrome_Storz(s): upcase = s.upper() newString = ''.join(e for e in upcase if e.isalnum()) # I found this example on stackoverflow.com # it iterates through each element of the now uppercase string and only keeps letters and numbers return newString == newString[::-1] def isPalindrome_PhillipAdkins(s): return s == s[::-1] # import string # already imported above def isPalindrome_Dmitry(s): s = s.upper() s = ''.join(e for e in s if e.isalnum()) length = len(s) half = (length / 2) if (length % 2 == 0): return s[:half - 1] == s[:half:-1] else: return s[:half] + s[half + 1] == s[:half:-1] + s[half + 1] def runTests(): """ setup some test sentences and run them against isPalindrome(string) """ sentenceList = [ "Sore was I ere I saw Eros.", "This is not a Palindrome!", "A man, a plan, a canal -- Panama", "Never a foot too far, even.", "Euston saw I was not Sue.", "Live on evasions? No, I save no evil.", "Red Roses run no risk, sir, on nurses order.", "Salisbury moor, sir, is roomy. Rub Silas.", '''Marge, let's "went." I await news telegram.''', "A new order began, a more Roman age bred Rowena.", "I, man, am regal; a German am I.", "Tracy, no panic in a pony-cart.", "Egad! Loretta has Adams as mad as a hatter. Old age!", "Eve, mad Adam, Eve!", "Resume so pacific a pose, muser.", "Marge let a moody baby doom a telegram.", "Tenet C is a basis, a basic tenet.", '''Nella's simple hymn: "I attain my help, Miss Allen."''', "Straw? No, too stupid a fad. I put soot on warts.", "Sir, I demand, I am a maid named Iris.", "Lay a wallaby baby ball away, Al.", "Tessa's in Italy, Latin is asset.", "Noel sees Leon.", ] print() print("Start of Proposal by Conrad Storz...") for candidate in sentenceList: print(" " + str(isPalindrome_Storz(candidate)) + "[" + candidate + "] {is a palindrome} ") print() print("Start of Proposal by Jaysen...") for candidate in sentenceList: print(" " + str(isPalindrome_Jaysen(candidate)) + "[" + candidate + "] {is a palindrome} ") print() print("Start of Proposal by Phillip Adkins...") for candidate in sentenceList: print(" " + str(isPalindrome_PhillipAdkins(candidate)) + "[" + candidate + "] {is a palindrome} ") print() print("Start of Proposal by Dmitry Kreslavskiy...") for candidate in sentenceList: print(" " + str(isPalindrome_Dmitry(candidate)) + "[" + candidate + "] {is a palindrome} ") # # boilerplate for running built-in test suite when this module is run at the commandline. if __name__ == "__main__": print("Starting tests....") runTests()
006ef29a90b0d540f1c8bba0ef31e7c8289f5dfd
Hezel254/python_projects
/meal.py
233
3.515625
4
username='hez' password=1234 def log(): user=input('Enter name: ') pass_=int(input('Enter password: ')) if user==username and pass_==password: print('Welcome') else: print('Access Denied') log()
c13a3700c4791a9393d7f25a8b226a27f335f4f3
Sebastian-CQ/Introduction-to-Algorithm
/Data_Structure_And_Algorithm/_6_UnorderedList.py
3,536
3.8125
4
class Node: def __init__(self, initial): self.data = initial self.next = None def getData(self): return self.data def getNext(self): return self.next def setData(self, newData): self.data = newData def setNext(self, newNext): self.next = newNext class UnorderedList: def __init__(self): self.head = None def isEmpty(self): return self.head is None def add(self, item): temp = Node(item) temp.setNext(self.head) self.head = temp def size(self): size = 0 current = self.head while current is not None: size += 1 current = current.getNext() return size def search(self, target): search = False current = self.head while current is not None and not search: if current.getData() == target: search = True else: current = current.getNext() return search def remove(self, item): if self.search(item): current = self.head while True: if current.getNext().getData() == item: current.setNext(current.getNext().getNext()) break current = current.getNext() def traversal(self): traversal_list = [] current = self.head while current is not None: traversal_list.append(current.getData()) current = current.getNext() return traversal_list class OrderedList: def __init__(self): self.head = None def isEmpty(self): return self.head is None def size(self): size = 0 current = self.head while current is not None: size += 1 current = current.getNext() return size def search(self, item): current = self.head found = False stop = False while current is not None and not found and not stop: if current.getData() == item: found = True else: if current.getData() > item: stop = True else: current = current.getNext() return found def add(self, item): current = self.head node = Node(item) previous = None stop = False while current is not None and not stop: if current.getData() > item: stop = True else: previous = current current = current.getNext() if previous is None: node.setNext(self.head) self.head = node else: node.setNext(current) previous.setNext(node) def remove(self, item): if not self.search(item): return current = self.head previous = None while current.getData() != item: previous = current current = current.getNext() previous.setNext(current.getNext()) def traverlsal(self): traverl_List = [] current = self.head while current is not None: traverl_List.append(current.getData()) current = current.getNext() return traverl_List o_list = OrderedList() o_list.add(1) print(o_list.traverlsal()) o_list.add(5) o_list.add(10) o_list.add(15) print(o_list.traverlsal()) o_list.remove(10) print(o_list.traverlsal())
3f1b790ce48502e601ab104f777c1be12f5150e4
DataBranner/recurse_center_mentoring_11139
/db_setup.py
1,358
4.125
4
import sqlite3 def connect_db(): """Connects to or creates a db and returns a cursor""" conn = sqlite3.connect('word_problems.db') return conn.cursor() def make_table(c, table_name, columns): tables = c.execute('''SELECT name FROM sqlite_master WHERE type='table' AND name=?;''', (table_name,)) tables = tables.fetchall() if not tables: c.execute('CREATE TABLE {} {}'.format(table_name, columns)) else: print "Table name already exists" def delete_table(c, table_name): tables = c.execute('''SELECT name FROM sqlite_master WHERE type='table' AND name=?;''', (table_name,)) tables = tables.fetchall() if tables: c.execute('DROP TABLE {}'.format(table_name)) def fill_table(c, file_name): """Reads .tsv file, populates db table where columns 1 & 4 are int""" with open(file_name, 'rU') as f: for record in f.read().split('\n')[1:]: if record: record = record.split('\t') record[0] = float(record[0]) record[3] = float(record[3]) c.execute('''INSERT INTO problems VALUES (?,?,?,?,?,?,?,?,?)''', record) def print_table(c, table_name): for row in c.execute('SELECT * FROM {}'.format(table_name)): print row
b6fd4fc85a1033d0e5dc7c7f69813cd9a0672f83
writecrow/text_processing
/final_file_standardization/final_file_standardization.py
2,253
3.8125
4
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- # DESCRIPTION: Given a directory with text files passed as argument # to the script, the folder directory is copied copying over # all text files. File names are cleaned (_checked and _deidentified) are # removed from file and folder names. And all lines breaks are replaced with # notepad readable line breaks (\r\n) # # Usage example: # python final_file_standardization.py --directory=../../../Fall\ 2017/deidentified/ # python final_file_standardization.py --directory=deidentified_files/Spring\ 2018/ # python final_file_standardization.py --directory=../../../MACAWS/deidentified_files/ import argparse import os import re import sys # Define the way we retrieve arguments sent to the script. parser = argparse.ArgumentParser(description='Copy folder structure') parser.add_argument('--directory', action="store", dest='dir', default='') args = parser.parse_args() def clean_file(filename, overwrite=False): if '.txt' in filename: clean_filename = re.sub(r'\.\.[\\\/]', r'', filename) clean_filename = re.sub(r'(\s)?_checked|_deidentified', '', clean_filename, flags=re.IGNORECASE) # remove extra folders clean_filename = re.sub(r'(.+[\\\/])+(Fall|Spring|Summer|Winter)', '\g<2>', clean_filename) output_dir = 'final_version' output_filename = os.path.join(output_dir, clean_filename) output_directory = os.path.dirname(output_filename) if not os.path.exists(output_directory): os.makedirs(output_directory) original_file = open(filename, 'r') original_contents = original_file.read() print("Preparing final version of file: " + output_filename) clean_contents = re.sub(r'(\r+)?\n', '\r\n', original_contents) output_file = open(output_filename, 'w') output_file.write(clean_contents) original_file.close() output_file.close() def clean_all_files(directory, overwrite=False): for dirpath, dirnames, files in os.walk(directory): for name in files: clean_file(os.path.join(dirpath, name), overwrite) if args.dir: clean_all_files(args.dir) else: print('You need to supply a valid directory with textfiles')
ab95d535646c25a184601c6f11772b250a3b0d87
NastyaZotkina/STP
/lab21.py
486
4.25
4
weight,height=map(float,input().split()) def bmi(weight: float, height: float) -> float: return weight/(height/100)**2 def print_bmi(bmi: float): if(bmi<18.5): print("Underweight") elif(bmi>=18.5 and bmi<25.0): print("Normal") elif(bmi>=25.0 and bmi<30.0): print("Overweight") elif(bmi>=30.0): print("Obesity") else: print("введены некорректные данные") print_bmi(bmi(weight,height))
1b0d899cbc067e91601f1fb9e9cf262cbb29f757
CharlesECruz/PythonCICC
/Introduction/Labs/Alone/Lab6/Lab6.py
808
4.03125
4
""" Primes, GCD, LCM """ import math def is_prime(num): """ Check if n is prime """ if num <= 1: return False for i in range(2,int(math.sqrt(num))+1): if num% i == 0: return False return True def gcd(a, b): """ GCD of a and b """ if b == 0: return a else: return gcd(b,a % b) def lcm(a, b): """ LCM of a and b """ if a>b: maximum = a else: maximum = b while True: if maximum % a ==0 and maximum % b ==0: return maximum else: maximum += 1 def generate_primes(n): """ Generating a list of primes :return: a list of primes from 2 to n """ a = [] for i in range(0,n + 1): if is_prime(i): a.append(i) return a
d341d01aae35873c8401acf139d4faedd6d92728
shashankgaur/machine-learning
/HW1/Problem 1/problem1.py
3,099
3.671875
4
#!/usr/bin/python #author: Shashank Gaur, FEUP, UP201309443 #Course: Machine Learning HomeWork1 # Explaination pending for the whole file by Shashank Gaur #The file loads the training data, calculates the mean, convolution and then decides where to plot other data. import scipy.io #from sklearn import svm import numpy import math import cmath from scipy.io import loadmat, savemat import matplotlib.pyplot as plt var = loadmat('trainingset.mat') X1 = var['X1'] X2 = var['X2'] X3 = var['X3'] XX = var['XX'] meanX1 = numpy.asmatrix(numpy.mean(X1, axis=0)) meanX3 = numpy.asmatrix(numpy.mean(X3, axis=0)) meanX2 = numpy.asmatrix(numpy.mean(X2, axis=0)) covX1 = numpy.cov(X1.T) covX2 = numpy.cov(X2.T) covX3 = numpy.cov(X3.T) print meanX1, meanX2, meanX3, covX1, covX2, covX3 detcovX1 = numpy.linalg.det(covX1) detcovX2 = numpy.linalg.det(covX2) detcovX3 = numpy.linalg.det(covX3) RowXX = XX.shape[0] ColXX = XX.shape[1] #plt.plot(X1[:,0], X1[:,1], 'ro',X2[:,0], X2[:,1], 'bo', X3[:,0], X3[:,1], 'yo') #Plot of decision boundaries x_min, x_max = X1[:, 0].min() - 1, X1[:, 0].max() + 1 y_min, y_max = X1[:, 1].min() - 1, X1[:, 1].max() + 1 xx, yy = numpy.meshgrid(numpy.arange(x_min, x_max, .02), numpy.arange(y_min, y_max, .02)) meu1 = 0.4922*(xx**2)+0.4924*(yy**2)-0.0131*xx*yy-4.8463*xx-5.8193*yy+29.5086 #meu12 = 0.0012*(xx**2)-0.0041*(yy**2)-0.0088*xx*yy-2.9078*xx-7.7995*yy+25.6031 #meu1 = meu1.reshape(xx.shape) plt.contourf(xx, yy, meu1)#, cmap=plt.cm.Paired) x_min, x_max = X2[:, 0].min() - 1, X2[:, 0].max() + 1 y_min, y_max = X2[:, 1].min() - 1, X2[:, 1].max() + 1 xx, yy = numpy.meshgrid(numpy.arange(x_min, x_max, .02), numpy.arange(y_min, y_max, .02)) meu2 = 0.4910*(xx**2)+0.4965*(yy**2)-0.0043*xx*yy-1.9385*xx-1.9802*yy+3.9055 #meu2 = meu2.reshape(xx.shape) plt.contourf(xx, yy, meu2)#, cmap=plt.cm.Paired) x_min, x_max = X3[:, 0].min() - 1, X3[:, 0].max() + 1 y_min, y_max = X3[:, 1].min() - 1, X3[:, 1].max() + 1 xx, yy = numpy.meshgrid(numpy.arange(x_min, x_max, .02), numpy.arange(y_min, y_max, .02)) meu3 = 0.5259*(xx**2)+1.0234*(yy**2)-1.0433*xx*yy-6.2616*xx-12.3001*yy+36.9585 #meu3 = meu3.reshape(xx.shape) plt.contourf(xx, yy, meu3)#, cmap=plt.cm.Paired ) #Plot of the X1,X2,X3 plt.scatter(X1[:,0], X1[:,1], c='red', marker='o') plt.scatter(X2[:,0], X2[:,1], c='blue', marker='o') plt.scatter(X3[:,0], X3[:,1], c='yellow', marker='o') #Taking decision for XX observations for x in range(0, RowXX): R1 = math.log(1/math.sqrt(detcovX1))-0.5*((XX[x,:]-meanX1)*numpy.linalg.inv(covX1)*((XX[x,:]-meanX1).transpose())) R2 = math.log(1/math.sqrt(detcovX2))-0.5*((XX[x,:]-meanX2)*numpy.linalg.inv(covX2)*((XX[x,:]-meanX2).transpose())) R3 = math.log(1/math.sqrt(detcovX3))-0.5*((XX[x,:]-meanX3)*numpy.linalg.inv(covX3)*((XX[x,:]-meanX3).transpose())) if (R1>R2 and R1>R3): plt.plot(XX[x,0], XX[x,1], 'ks', mew=2, ms=6) elif (R2>R3 and R2>R1): plt.plot(XX[x,0], XX[x,1], 'k^', mew=2, ms=6) elif (R3>R2 and R3>R1): plt.plot(XX[x,0], XX[x,1], 'k+', mew=2, ms=10) plt.show()
8ce559a2ddbe734f5cc0ad6c1d52252e1cd08419
Svegge/GB_2021_06_py_foundations
/02_homeworks/01/task_01.py
568
4.15625
4
''' 1. Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран. ''' FIRST_VAR = 1 SECOND_VAR = 2 print(FIRST_VAR, SECOND_VAR) third_var = int(input('Please enter number:\n>>> ')) fourth_var = input('Please enter any string:\n>>> ') fith_var = input('Please enter any string again:\n>>> ') print(third_var, fourth_var, fith_var)
775997871756527391fcb1a6516ab7b4a51bbe71
Eezzeldin/HackerRankChallnges
/Ceasar_Cipher/Ceasar_Cipher_test.py
1,464
3.765625
4
''' Original alphabet: abcdefghijklmnopqrstuvwxyz Alphabet rotated +3: defghijklmnopqrstuvwxyzabc ''' cipher = {} n = 3 #abcdefghijklmnopqrstuvwxyz letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q", "R","S","T","U","V","W","X","Y","Z"] #print (len (letters)) letters_2 = [letters [letters.index(i) + n] for i in letters [:-n]] #print (letters_2) letters_3 = [letters [i] for i in range (len (letters [-n:]))] #print (letters_3) letters_4 = letters_2 + letters_3 #print (letters_4) for i,j in zip (letters, letters_4): cipher [i] = j #print (cipher) # encoded = "" # word = "abcdefghij-klmnopq-rstuvwxyz" # for w in word : # if w.upper() in letters: # print (cipher [w.upper()]) # # if w.islower (): # encoded = encoded + cipher [w.upper()].lower() # else: # encoded = encoded + cipher [w.upper()] # else: # encoded = encoded + w # print (encoded) def cipher_word (word): encoded = "" #word = "abcdefghij-klmnopq-rstuvwxyz" for w in word : if w.upper() in letters: #print (cipher [w.upper()]) if w.islower (): encoded = encoded + cipher [w.upper()].lower() else: encoded = encoded + cipher [w.upper()] else: encoded = encoded + w return encoded test_word_1 = "abcdefghij-klmnopq-rstuvwxyz" test_word_2 = "There's-a-starman-in-the-sky" print (cipher_word (test_word_1)) print (cipher_word (test_word_2))
e13492435f33b44107bb96297764283953b0a72c
flerchy/codestyle-core
/ml_quality/datasets/shit/inverse.py
1,395
4.25
4
def slow_inverse(f, delta=1/128.): """Given a function y = f(x) that is a monotonically increasing function on non-negatve numbers, return the function x = f_1(y) that is an approximate inverse, picking the closest value to the inverse, within delta.""" def f_1(y): x = 0 while f(x) < y: x += delta # Now x is too big, x-delta is too small; pick the closest to y return x if (f(x)-y < y-f(x-delta)) else x-delta return f_1 def inverse(f, delta = 1/128.): """Given a function y = f(x) that is a monotonically increasing function on non-negatve numbers, return the function x = f_1(y) that is an approximate inverse, picking the closest value to the inverse, within delta.""" def f_1(y): x = delta while f(x) < y: x = x*2 # Now x is too big, x-delta is too small; pick the closest to y l = x/2 r = x return bin_search(l, r, f, y, delta) return f_1 def bin_search(l, r, f, y, delta): m = (l+r)/2 if f(m) >= y and f(m-delta) <= y: return m if (f(m)-y < y-f(m-delta)) else m-delta if f(m) < y: return bin_search(m, r, f, y, delta) else: return bin_search(l, m, f, y, delta) def square(x): return x*x sqrt = slow_inverse(square) print sqrt(1000000000) sqrt1 = inverse(square) print sqrt1(1000000000)
af321a1091219842d1f1308f2c4a2d1923024485
Samtrak/HomeWork1
/OOP/Account.py
1,141
3.578125
4
class Account: def __init__(self, id ,name, balance = 0): self.id = id self.name = name self.balance = balance def __str__(self): return "Account [" + "id=" + str(self.id)+","+"name="+self.name + "," +"balance="+ str(self.balance)+"]" def getID(self): return self.id def getName(self): return self.name def getBalance(self): return self.balance def credit(self, amount): if amount >= 0: self.balance += amount return self.balance def debit(self, amount): if self.balance - amount >= 0: self.balance = self.balance - amount else: print("amount exceeded") return self.balance def transferTo(self, another, amount): if self.balance >= amount: self.balance -= amount another.credit(amount) else: print("amount exceeded") return self.balance a= Account("5","Hasan") b = Account("7","Bek",2000) print(a.credit(700)) print(a.debit(400)) print(a.transferTo(b, 100)) Asan = Account(5, "Asan", 0) print(Asan)
38173fd27e45fa9205aa07a66b1d4e106d93c154
RideGreg/LintCode
/Python/1465-order-of-tasks.py
1,921
3.765625
4
# Time O(nlogn) # Space O(1) # There are n different tasks, the execution time of tasks are t[], and the # probability of success are p[]. When a task is completed or all tasks fail, # the operation ends. Tasks can be performed in a different order, and it is # expected that in different order the time to stop the action is generally different. # # Please answer in what order to perform the task (task index is 1-based) # in order to make the duration of the action the shortest time? If the expected # end time of the two task sequences is the same, the lexicographic minimum # order of tasks is returned. # 1 <= n <= 50, 1 <= ti <= 10, 0 <= pi <= 1 # Example 1: Given n=1, t=[1], p=[1.0], return [1]. # Explanation:The shortest expected action end time is 1.0*1+(1.0-1.0)*1=1.0 # Example 2: # Given n=2, t=[1,2], p=[0.3, 0.7], return [2,1]. # Explanation: # The expected action end time for [2, 1] is # 0.7 * 2 + (1.0-0.7)*0.3*(2+1) + (1.0-0.7)*(1.0-0.3)*(2+1)=2.3 # task 2 success task 2 fail + 1 succ task 2 and 1 fail # p2 * t2 + (1-p2) * (t1 + t2) = (t1+t2) - p2t1 = (t1+t2)/p1p2 - t1/p1 # The expected action end time for [1, 2] is # 0.3 * 1 + (1.0-0.3)*0.7*(1+2) + (1.0-0.3)*(1.0-0.7)*(1+2)=2.4 # task 1 success task 1 fail + 2 succ task 1 and 2 fail # p1 * t1 + (1-p1) * (t1 + t2) = (t1+t2) - p1t2 = (t1+t2)/p1p2 - t2/p2 # solution: 拿 time/probability = ratio, ratio 小的排在前面 # 题目要求是求出一个期望时间最短。ratio越小,说明这个任务完成的概率越高或者时间越少, # 这就是我们想要找的那一个最具有效率的task。 class Solution(object): def getOrder(self, n, t, p): return sorted(list(range(1, n+1)), key=lambda x: t[x-1]/p[x-1]) print(Solution().getOrder(1, [1], [1.0])) # [1] print(Solution().getOrder(2, [1, 2], [0.3, 0.7])) # [2, 1] print(Solution().getOrder(2, [1, 2], [0.3, 0.6])) # [1, 2] same ratio
b72ea63b66637c0e73fb9b0332d5753bf5930f83
JinshanJia/leetcode-python
/+Longest Palindromic Substring.py
1,697
3.75
4
__author__ = 'Jia' # Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, # and there exists one unique longest palindromic substring. class Solution: # @return a string def longestPalindrome_DP(self, s): #isP[i][j] means s[j:i + 1] is palindrome isP = [[False for j in range(len(s))] for j in range(len(s))] for i in range(len(s) - 1): isP[i][i] = True isP[i + 1][i] = True if s[i] == s[i + 1] else False isP[len(s) - 1][len(s) - 1] = True for i in range(2, len(s)): for j in range(i - 2, -1, -1): if isP[i - 1][j + 1] and s[i] == s[j]: isP[i][j] = True list = [0, -1] for i in range(len(s)): for j in range(i + 1): if isP[i][j] and i - j > list[1] - list[0]: list = [j, i] return s[list[0]:list[1] + 1] def longestPalindrome(self, s): result = "" for i in range(len(s) - 1): temp1 = self.expandFromCenter(s, i, i) if len(result) < len(temp1): result = temp1 temp2 = self.expandFromCenter(s, i, i + 1) if len(result) < len(temp2): result = temp2 temp1 = self.expandFromCenter(s, len(s) - 1, len(s) - 1) if len(result) < len(temp1): result = temp1 return result def expandFromCenter(self, s, l, r): while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1 r += 1 return s[l + 1:r] s = Solution() string = "aabbb" print string print s.longestPalindrome(string)
f5b58167a84be4e8b68c0848aad676b2fa4046ba
blam4521/ConvertTgaToPng
/Checkes_Dir/check_dir.py
705
3.609375
4
"Check the directory if it exists." # Built-in imports import os import sys import os.path import shutil def check_name(img_dir): """Check if the directory exists. Args: img_dir (str): name of the file directory. """ src_small = img_dir + ' ' #src_large = img_dir + ' ' try: if not os.path.exists(src_small): # if os.path.exists(src_small): print(img_dir) except: print 'There folders named textures_small' if __name__ == '__main__': f = open(' ', 'r') for line in f: img_dir = line.rstrip('\n') #print 'dealing with this director ', img_dir check_name(img_dir) print('...done')
5776ffb7a7b0edea9c32dff12675382526741791
Taraslut/git_tarin
/lesson_19/initila.py
344
3.515625
4
def addition_action(fn): def inner(var): print("Before foo call") rez = fn(var) print("After foo call") return rez return inner @addition_action def double(x): print("In double") return x * 2 print(double("Hello")) # print(addition_action(double)("Hello")) # double = addition_action(double)
c7306fae1ae63f5143fc3af8636daf1ed47fd086
jsebastianrincon/curso_python
/Fundamentos/metodos_privados.py
825
3.828125
4
# Crear metodos privados en clases class Persona: def __init__(self, nombre, primer_ape, segundo_ape): # No privado self.nombre = nombre # Protegido self._primer_ape = primer_ape # Privado self.__segundo_ape = segundo_ape def metodo_publico(self): self.__metodo_privado() # Metodos Privados def __metodo_privado(self): print(self.nombre) print(self._primer_ape) print(self.__segundo_ape) def get_segundo_ape(self): return self.__segundo_ape def set_segundo_ape(self, segundo_ape): self.__segundo_ape = segundo_ape p1 = Persona("Juan", "Rincon", "Calderon") # p1.__metodo_privado() p1.metodo_publico() print(p1.nombre) print(p1._primer_ape) # print(p1.__segundo_ape()) print(p1.get_segundo_ape())
3d7be1ce3f34a58bec65e79fa7c12520b9c33dd8
cowboybebophan/LeetCode
/Solutions/~1019. Next Greater Node In Linked List.py
548
3.53125
4
# similar to 503 and 739 class Solution: def nextLargerNodes(self, head): res, stack = [], [] # Be carefule here, do Not initialize like this: res = stack = [] # because res and stack points to the same reference and they will change together as [] changes. while head: while stack and stack[-1][1] < head.val: res[stack.pop()[0]] = head.val stack.append([len(res), head.val]) res.append(0) head = head.next return res
8ffa50a65d7d5cb027ab8e3f6df94ab76e5f900a
VinceVi83/RemoteControlNAO
/NAO/MoveHeadNAO.py
4,187
3.546875
4
# coding=utf-8 __author__ = 'Vincent' from threading import Thread import time class MoveHeadNAO(Thread): """ * Gere le pilotage de la tête du NAO :param motion: Objet permettant de contrôler la tête du NAO :type motion: ALMotion """ def __init__(self, motion): Thread.__init__(self) # Initialisation self.cmd = 1 self.flag = False self.init = True self.angleHead = 0 self.angleHeady = 0 self.sleep = 0.2 self.lasty = 0 # Valeur Max et Min de HeadPitch et de HeadYaw en radian self.XMAX = 117 / 360.0 * 3 * 3.44 self.XMIN = (( - 117) / 360.0) * 3.0 * 3.44 self.YMAX = 18 / 360.0 * 2 * 3.44 self.YMIN = -25 / 360.0 * 2 * 3.44 # Determination des pas a chaque incrementation self.mvx = (self.XMAX - self.YMIN) / 20.0 self.mvy = (self.YMAX - self.YMIN) / 5.0 self.names = "Head" self.initial = True self.targetAngles = 1.0 self.maxSpeedFraction = 0.2 # Using 20% of maximum joint speed self.motion = motion def setX(self, value): """ * A method who add or reduce the coordinate of the NAO at HeadYaw depend of the value. """ print(value) self.cmd = int(value) if value == '0' or value == '2': self.x = True self.initial = False print('Je control la tete') else: self.x = False def setY(self, value): """ * A method who add or reduce the coordinate of the NAO at HeadPitch depend of the value. """ if value == 1 and ((self.angleHeady + self.mvy) < self.YMAX): self.angleHeady += self.mvy print("bas") if value == 0 and ((self.angleHeady + self.mvy) > self.YMIN): self.angleHeady -= self.mvy print("haut") def manageX(self): """ * A method who manage the coordinate of the movement of the NAO at HeadYaw. * At first control increment the coordinate of head when it is controlled. * When the head is not controlled, the head return to initial position. """ if self.x: # Le client controle la tête # Tourne la tête à gauche if self.cmd == 0 and ((self.angleHead + self.mvx * 1.0 ) < self.XMAX): self.angleHead += self.mvx * 1.0 # Tourne la tête à droite if self.cmd == 2 and ((self.angleHead + self.mvx * -1.0 ) > self.XMIN): self.angleHead += self.mvx * -1.0 self.initial = False print("down") return # La tête du NAO est dans sa position initiale if 0.5 > self.angleHead > -0.5: # self.motion.setAngles("HeadYaw", 0, 0.8) self.initial = True return # La ẗête retourne à sa position initiale if self.angleHead > 0: toto = self.angleHead + self.mvx * -1.0 self.angleHead = toto return # La ẗête retourne à sa position initiale if self.angleHead < 0: toto = self.angleHead + self.mvx * 1.0 self.angleHead = toto return def run(self): """ * Run the thread to control the head depending of self.angleHeady """ self.flag = True while self.flag: if self.initial: # Tete non contrôlé sur l'axe X if self.lasty != self.angleHeady: # self.motion.setAngles("HeadPitch", self.angleHeady, 0.2) print("vertical") time.sleep(self.sleep) else: # print('sleep') time.sleep(self.sleep) else: # Tete contrôlé sur les axes X et Y self.manageX() print(self.angleHead) # motion.setAngles("Head",[self.angleHead, self.angleHeady], 0.2) time.sleep(self.sleep) print(self.cmd) def stop(self): self.flag = False
49b07b3989ea17e5760451626a54f15fc084e190
nileshnegi/hackerrank-python
/day009/ex54.py
1,054
3.765625
4
""" Piling Up! The first line contains a single integer ```T```, the number of test cases. For each test case, there are 2 lines. The first line of each test case contains ```n```, the number of cubes. The second line contains ```n``` space separated integers, denoting the sideLengths of each cube in that order. """ from collections import deque if __name__ == "__main__": for _ in range(int(input())): N = int(input()) d = deque(map(int, input().split())) stack = [] if d[0] <= d[-1]: stack.append(d.pop()) else: stack.append(d.popleft()) for i in range(1, N): if d[0] >= d[-1]: if d[0] > stack[-1]: print("No") break else: stack.append(d.popleft()) else: if d[-1] > stack[-1]: print("No") break else: stack.append(d.pop()) else: print("Yes")
bc789c8b12d94337d28ee6318cd2669b6ff37733
Jack7510/python_algorithm
/simple_sort.py
2,864
4.4375
4
# author: Jack Lee # samples of Python # sort algorithm with Python # Simple Sort: Bubble, Insertion # from random import randrange # # func: gen_rand_list(numbers of random ) # desc: generate random number of list with bubble sort algorithm # para: number - how many numbers of random will be generated # def gen_rand_list( number ): a = [] # null list for i in range( number ): a.append( randrange(number * 2) ) # range will be 0 to 2 * number return a # # func: bubble_sort( list ) # desc: sort a list in ascend # algorithm desc, https://en.wikipedia.org/wiki/Bubble_sort # para: list - the list will be sorted # def bubble_sort( l ): n = len( l ) if n < 2 : return for i in range( n ): for j in range( i + 1, n ): # compare L[i] with L[i+1] ... n-1 if l[i] > l[j]: # if i > j, swap them l[i], l[j] = l[j], l[i] return # # func: shell_sort( list ) # desc: generate random number of list with Shell algorithm # para: number - how many numbers of random will be generated # def shell_sort( L ): return L # # func: insertion_sort( list ) # desc: generate random number of list with Insertion algorithm # desc: https://en.wikipedia.org/wiki/Insertion_sort # para: number - how many numbers of random will be generated # def insertion_sort_v1( L ): n = len( L ) if n < 2 : return L for i in range( 1, n ) : j = i while j > 0 and L[j - 1] > L[ j ] : L[j - 1], L[ j ] = L[j], L[j - 1] # swap j = j - 1 return L # # v2: more efficient, do not # def insertion_sort( L ): # check the parameter n = len( L ) if n < 2 : return L for i in range( 1, n ) : x = L[ i ] j = i - 1 while j >= 0 and L[ j ] > x: L[ j + 1 ] = L[ j ] # move L[j] to upper position j = j - 1 L[ j + 1 ] = x return L # # func: insertion_sort_R( list, numbers ) # desc: generate random number of list with Insertion algorithm in Recursvie way # desc: https://en.wikipedia.org/wiki/Insertion_sort # para: L - the list to be sorted # numbers - how many numbers of random will be generated # def insertion_sort_R( L, numbers ): # check the parameter if numbers < 2 : return L insertion_sort_R( L, numbers - 1 ) # place L[numbers - 1] in the left sorted array/list x = L[ numbers - 1 ] i = numbers - 2 while i >= 0 and L[ i ] > x : L[i + 1] = L[ i ] i = i - 1 L[ i + 1 ] = x return L # # func: merge_sort( list, numbers ) # desc: generate random number of list with merge algorithm # desc: https://en.wikipedia.org/wiki/Merge_sort # para: L - the list to be sorted # numbers - how many numbers of random will be generated # # test program if __name__ == '__main__': n = eval(input("input numbers of rand you want to generate:")) l = gen_rand_list(n) print(l) #bubble_sort( l ) #insertion_sort( l ) insertion_sort_R( l, l.count() ) print(l)
37357d0a3b15d068b02b6412018f6c08e2df9c95
ZouCheng321/myPythonCode
/csc1002/Assignment#4/VocabularyGUIStep1(to students).py
1,474
3.796875
4
def PressShowMeaning(): print('PressShownMeaning') def PressNextWord(): print('PressNextWord') from tkinter import * root=Tk() root.geometry('500x600+150+200') root.title('My first GUI') wordLabel0=Label(root,text='Word:',height=2) wordLabel0.grid(row=0,column=0) wordLabel1=Label(root,width=30,text='abash',height=2) wordLabel1.grid(row=0,column=1) meaningLabel0=Label(root,text='Meaning:',height=3) meaningLabel0.grid(row=1,column=0) meaningLabel1=Label(root, text='To lose self-confidence, to confuse, put to shame',height=3) meaningLabel1.grid(row=1,column=1) sampleLabel0=Label(root,text='Sample:',height=3) sampleLabel0.grid(row=2,column=0) sampleLabel1=Label(root,text='abashed before the assembled dignitaries',height=3) sampleLabel1.grid(row=2,column=1) synLabel0=Label(root,text='Synonyms:',height=8) synLabel0.grid(row=3,column=0) synLabel1=Label(root,text='fluster\ndisconcert\ndiscomfit\ndiscompose',height=8) synLabel1.grid(row=3,column=1) antLabel0=Label(root,text='Antonyms:',height=8) antLabel0.grid(row=4,column=0) antLabel1=Label(root,text='self-possessed',height=8) antLabel1.grid(row=4,column=1) showMeaningButton=Button(root, text="Show meaning...", command=PressShowMeaning) showMeaningButton.grid(row=5,column=0) nextWordButton=Button(root, text="Next word", command=PressNextWord) nextWordButton.grid(row=5,column=1) root.mainloop() ''' height=2,3,3,8,8 root.mainloop() '''
0877c6cb13dbc6514b981e28caf85472262a4b53
tgreenhalgh/Intro-Python
/src/day-1-toy/fileio.py
462
4.28125
4
# Use open to open file "foo.txt" for reading f = open('foo.txt', 'r') # Print all the lines in the file for line in f: print(line, end='') print("\n") # Close the file f.close() # Use open to open file "bar.txt" for writing f = open('foo.txt', "a") # Use the write() method to write three lines to the file f.write('If you do, sir, I am for you: I serve as good a man as you.\n') f.write('No better.\n') f.write('Well, sir.\n') # Close the file f.close()
2643e967a4879875efd26271fa1a0e59a216e083
Ghanshyam-Coder/Positive-Number-List
/Positive number list.py
545
4.09375
4
#!/usr/bin/env python # coding: utf-8 # In[5]: #Python Program to print Positive Number in a List def positive_number(NumList): for j in range(Number): if(NumList[j] >= 0): print(NumList[j],end=' ') NumList=[] Number = int(input("Please Enter the Total Number of List Element:")) for i in range(1,Number+1): value = int(input("Please enter the value of %d Element:" %i)) NumList.append(value) print("\nPositive Number in thisList are;") positive_number(NumList) # In[ ]: # In[ ]:
94bc60f74782f8910131aaaba10efdf4736e66ab
AdamZhouSE/pythonHomework
/Code/CodeRecords/2450/60837/242782.py
402
3.578125
4
def exist(nums,target): start=-1 end=-1 num=0 for i in range(len(nums)): if nums[i]==target: if num==0: start=i end=i num+=1 else: end=i res=[] res.append(start) res.append(end) return res nums=list(map(int,input().split(','))) target=int(input()) print(exist(nums,target))
f8a5502f2b0a3eb3e83bab07a25fc80aeed3e311
HWYWL/python-examples
/面向对象/Cat.py
431
3.578125
4
class Cat: def __init__(self, cat_name): print("创建对象,数据初始化。。。") self.name = cat_name def eat(self): print("%s 爱吃鱼" % self.name) def drink(self): print("%s 喝水" % self.name) # 对象创建 cat = Cat("Tomcat") # 对象方法调用 cat.eat() cat.drink() # 对象创建 lazy_cat = Cat("大懒猫") # 对象方法调用 lazy_cat.eat() lazy_cat.drink()
3b3e5828cb47f9ea88b0bca054ac982ac902df30
ninaReb/ExerciciosPy
/primeiro_desafio.py
924
4.03125
4
# ***Primeiro desafio*** # Você recebe uma lista de 300 números ordenados por ordem crescente. # Sua tarefa é achar um número aleatório informado pelo usuário da # maneira mais eficiente possível. #digitar os números do array. ex: 1,2,3,4 # def get_array(): # text = input("digite os numeros") # my_array = text.split(',') # my_array = [int(i) for i in my_array] # print (my_array) # return my_array # class Primeiro_desafio(): def __init__(self, array): self.my_array = array self.number = int(input("digite o numero")) self.find_number() def find_number(self): number = self.number if number in self.my_array: position = self.my_array.index(number) print("O número {} está na posição [{}] da lista".format(number, position)) else: print("O número não foi encontrado na lista")
0ba6d2e2e7ed0f576b8855950bc095e086317dc9
ANTZ314/raspi
/python/file_R_W/write1.py
1,076
3.828125
4
# -*- coding: utf-8 -*- """ Python 2.7 (virtual env) If file doesn't exist, file is created If exists, opens existing file reads & prints contents Appends 10 new lines """ import sys def main(): exists = 0 # append after printing contents try: # Skip if file doesn't exist file = open('test.txt', 'r') # Open to read file print file.read() # Print the contents file.close() # Close the file except: exists = 1 # Don't append twice if file exists file= open("test.txt","a+") # Create/open file then Append data for i in range(10): # file.write("This is line %d\r\n" % (i+1)) # file.close() # Exit the opened file if exists == 0: # append after printing contents file= open("test.txt","a+") # Create/open file then Append data for i in range(10): # file.write("This is line2 %d\r\n" % (i+1)) # file.close() # Exit the opened file else: # print "\nFile Didn't exist..." # notification if __name__ == "__main__": main()
1bc2315ebf763fe1c8147a2cce7d0a8e49a3b6b2
mwsmales/project_alien_invasion
/ship.py
2,092
3.78125
4
import pygame from pygame.sprite import Sprite class Ship(Sprite): def __init__(self, ai_settings, screen): """Initialise the ship and its starting position""" super(Ship, self).__init__() self.screen = screen self.ai_settings = ai_settings # load and resize the ship image, then get its rect (rectangular dimensions) self.image = pygame.image.load(ai_settings.ship_image) self.image = pygame.transform.smoothscale(self.image, (ai_settings.ship_width, ai_settings.ship_height)) self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() # start each new ship at the bottom centre of the screen self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom # Store a decimal value for the ship's centre self.center = float(self.rect.centerx) # set movement flags self.moving_right = False self.moving_left = False def blitme(self): """Draw the ship at its current locations.""" self.screen.blit(self.image, self.rect) def update(self): """Update the ship's position based on the movement flag""" # firstly update the ship's centre value (not the rect) # also prevent ship going off the edge of the screen if self.moving_right == True and self.rect.right < self.screen_rect.right: self.center += self.ai_settings.ship_speed_factor if self.moving_left == True and self.rect.left > self.screen_rect.left: self.center -= self.ai_settings.ship_speed_factor # then update the ship's rect from self.centre self.rect.centerx = self.center def center_ship(self): """Recentre the ship in the middle of the screen""" # Stop the ship moving if it was already self.moving_right = False self.moving_left = False #update ship's centre self.center = self.screen_rect.centerx # update the ship's rect from self.centre self.rect.centerx = self.center
ee2f727de4e49c7446a1137ef339efda5f5cba5b
Mercy1231/CMPUT-396
/rushhour.py
15,794
3.828125
4
""" CMPUT 396 Assignment 3 Created by Andrea Whittaker 1386927 And Mercy Woldmariam 1413892 --- RUSH HOUR --- The Objective: slide the red car through the exit to freedom! To Play: slide the blocking cars and trucks in their lanes (up and down, left and right) until the path is clear for the red car to escape """ from sys import exit import random from random import shuffle blocking_vehicles = ['B','C','E','F','G','H','I','J','K','L','M','N','O','P','Q'] # the game has 15 blocking cars and trucks wall = '#' space = '.' exit = '!' red = 'R' # this is your red car directions = ['w', 'a', 's', 'd'] # up, left, down, right side_len = 8 selected_vehicle = red class Board: # read the puzzle from a file def __init__(self, infile): self.lines = [] self.original = [] for line in infile: self.lines.append(line.strip('\n')) for i in range(side_len): assert(self.lines[0][i] == wall and self.lines[side_len-1][i] == wall) # make sure top and bottom walls are solid assert(self.lines[3][side_len-1] == exit) # make sure there is an exit at the right spot for line in self.lines: assert(line[0] == wall and (line[7] == wall or exit)) # make sure left and right walls are solid infile.close() self.original = self.lines[:] return def resetBoard(self): self.lines = self.original[:] return # print the current state to stdout in a more readable format def prettyPrint(self): for line in self.lines: for x in line: print(x,' ',end='') # add spaces for readability print('') print('') return # match vehicles with their legal moves and size def organizeVehicles(self): self.vehicles = {} self.vehicles[red] = (0, 2) # add the direction that red can go to the dictionary for i in range(side_len): for j in range(side_len): letter = self.lines[i][j] if letter in blocking_vehicles and letter not in self.vehicles: if self.lines[i][j+1] == letter: # vehicle is horizontal if self.lines[i][j+2] == letter: self.vehicles[letter] = (0, 3) # 0 for moving left or right, 3 for size 3 else: self.vehicles[letter] = (0, 2) # 0 for moving left or right, 2 for size 2 else: # if it isn't horizontal, it must be vertical if self.lines[i+2][j] == letter: self.vehicles[letter] = (1, 3) # 1 for moving up or down, 3 for size 3 else: self.vehicles[letter] = (1, 2) # 1 for moving up or down,, 2 for size 2 return # move the selected vehicle in a legal direction # returns 0 if changing vehicles (won't print the board again), def chooseMove(self, move): bump = False result = 0 if move not in directions: # if the user selected a new vehicle, change it and return move = move.upper() if move not in self.vehicles and move != red: # vehicle does not exist print("that vehicle does not exist!") else: global selected_vehicle selected_vehicle = move print("changed vehicle to " + selected_vehicle + ".") return 0, bump # make sure that the move does not run into a wall or another vehicle if move == 'w': if self.vehicles[selected_vehicle][0] != 1: print("stay in your lane!") return 0, bump for i in range(side_len-1, -1, -1): # travel through the lines from bottom left to top right for j in range(side_len): if self.lines[i][j] == selected_vehicle: size = self.vehicles[selected_vehicle][1] if self.lines[i-size][j] != space and self.lines[i-size][j] != exit: # the spot above it is not an empty space #print("* bump *") bump = True return 0, bump result = self.moveVehicle(i, j, i-size, j) # sends the index of the bottom character and the space return result, bump # make sure that the move does not run into a wall or another vehicle elif move == 's': if self.vehicles[selected_vehicle][0] != 1: print("stay in your lane!") return 0, bump for i in range(side_len): # travel through the lines from top left to bottom right for j in range(side_len): if self.lines[i][j] == selected_vehicle: size = self.vehicles[selected_vehicle][1] if self.lines[i+size][j] != space and self.lines[i+size][j] != exit: # the spot below it is not an empty space #print("* bump *") bump = True return 0, bump result = self.moveVehicle(i, j, i+size, j) # sends the index of the top character and the space return result, bump # make sure that the move does not run into a wall or another vehicle elif move == 'a': if self.vehicles[selected_vehicle][0] != 0: print("stay in your lane!") return 0, bump for i in range(side_len): # travel through the lines from top right to bottom left for j in range(side_len-1, -1, -1): if self.lines[i][j] == selected_vehicle: size = self.vehicles[selected_vehicle][1] if self.lines[i][j-size] != space and self.lines[i][j-size] != exit: # the spot to the left is not an empty space #print("* bump *") bump = True return 0, bump result = self.moveVehicle(i, j, i, j-size) # sends the index of the right character and the space return result, bump # make sure that the move does not run into a wall or another vehicle else: # move == 'd' if self.vehicles[selected_vehicle][0] != 0: print("stay in your lane!") return 0, bump for i in range(side_len): # travel through the lines from top left to bottom right for j in range(side_len): if self.lines[i][j] == selected_vehicle: size = self.vehicles[selected_vehicle][1] if self.lines[i][j+size] != space and self.lines[i][j+size] != exit: # the spot to the right is not an empty space #print("* bump *") bump = True return 0, bump result = self.moveVehicle(i, j, i, j+size) # sends the index of the left character and the space return result, bump def bfs(self, board): current_board = self.lines[:] original_board = self.lines[:] winning_state = False queue = [] moves = "" past_moves = "" vehicle_to_make_move = "" past_order_of_vehicles = "" seen_states = [] queue.append((current_board, moves, vehicle_to_make_move)) while winning_state == False: #pick first item in queue current_state = queue.pop(0) boardC = current_state[0][:] moves = "" vehicle_to_make_move = "" past_order_of_vehicles = "" past_moves = "" seen_states.append(boardC[:]) for previous_move in current_state[1]: moves += previous_move past_moves += previous_move for previous_vehicle in current_state[2]: vehicle_to_make_move += previous_vehicle past_order_of_vehicles += previous_vehicle #check to see if its a winning state if boardC[3][7] == 'R': winning_state = True makeMove = "Vehicle " + vehicle_to_make_move[0] + " should move " + moves[0] return makeMove else: #not a winning state, begin bfs v =[] for key in self.vehicles: v.append(key) shuffle(v) for vehicle in v: global selected_vehicle selected_vehicle = vehicle if self.vehicles[vehicle][0] == 0: #possible_movesRLR1 = ["a", "d"] possible_movesRLR2 = ["d", "a"] shuffle(possible_movesRLR2) for move in possible_movesRLR2: result, bump = board.chooseMove(move) moves += move vehicle_to_make_move += vehicle if self.lines[3][7] == 'R': winning_state = True self.lines = original_board[:] makeMove = "Vehicle " + vehicle_to_make_move[0] + " should move " + moves[0] return makeMove board_after_move = self.lines[:] #if the new state did not result in bumping into the way or we have not seen it before, we will add it to the queue if bump == False and self.lines[:] not in seen_states: queue.append((board_after_move, moves, vehicle_to_make_move)) #print(queue) moves = past_moves vehicle_to_make_move = past_order_of_vehicles self.lines = boardC[:] else: #self.vehicles[vehicle][0] == 1 possible_movesRUD2 = ["s", "w"] shuffle(possible_movesRUD2) #if self.vehicles[vehicle][0] == 1: for move in possible_movesRUD2: result, bump = board.chooseMove(move) moves += move vehicle_to_make_move += vehicle if self.lines[3][7] == 'R': winning_state = True self.lines = original_board[:] makeMove = "Vehicle " + vehicle_to_make_move[0] + " should move " + moves[0] return makeMove board_after_move = self.lines[:] #if the new state did not result in bumping into the way or we have not seen it before, we will add it to the queue if bump == False and self.lines[:] not in seen_states: queue.append((board_after_move, moves, vehicle_to_make_move)) moves = past_moves vehicle_to_make_move = past_order_of_vehicles self.lines = boardC[:] self.lines = original_board[:] makeMove = "Vehicle " + vehicle_to_make_move[0] + " should move " + moves[0] return makeMove def moveVehicle(self, i, j, x, y): # exchange space with end of vehicle if blocking vehicle # if you have reached the goal, return success if self.lines[x][y] == exit: self.lines[i] = self.lines[i][0:j] + space + self.lines[i][j+1:] self.lines[x] = self.lines[x][0:y] + red + self.lines[x][y+1:] return 2 else: self.lines[i] = self.lines[i][0:j] + space + self.lines[i][j+1:] self.lines[x] = self.lines[x][0:y] + selected_vehicle + self.lines[x][y+1:] return 1 return result def printHello(): print("-"*10 + " RUSH HOUR " + "-"*10, end='\n\n') print("The Objective: slide the red car R R through the exit ! to freedom!", end='\n\n') print("To Play: slide the blocking cars and trucks in their lanes") print("(up and down, left and right) until the path is clear for") print("the red car to escape.", end='\n\n') print("Enter the letter of the car you wish to move, then move") print("it up and down or left and right with the w, a, s, d keys.") print("Type \"reset\" to reset the board.") print("Type \"help\" tp get what your next move should be.") print("Enter \"0\" to quit the game.", end="\n\n") print("-"*31, end='\n\n') def main(): print(" ") try: filename = input("Enter the name of the puzzle: ") infile = open(filename,'r') except IOError: raise SystemExit("File name does not exist.") board = Board(infile) board.organizeVehicles() printHello() board.prettyPrint() result = -1 bump = "" # while the goal has not been reached, get input from the user, # make a move, and print the current state. while result != 2: move = input() if move == "0": print("Goodbye!") print("-"*31, end='\n\n') raise SystemExit() elif move == "help": next_move = board.bfs(board) print("Here is your next move: " + next_move) elif move == "reset": board.resetBoard() print("The board has been reset.") else: result, bump = board.chooseMove(move) if bump: print("* bump *") if result != 0: board.prettyPrint() print("Congratulations, you escaped rush hour! Thanks for playing.") print("-"*31, end='\n\n') main()
88ba4393b835759a46cc69b45aeaac347e564e6a
jerrylance/LeetCode
/819.Most Common Word/819.Most Common Word.py
1,336
3.625
4
# LeetCode Solution # Zeyu Liu # 2019.5.29 # 819.Most Common Word from typing import List # method 1 dic, replace(),常规 class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: count = 0 dic = {} for c in "!?',;.": paragraph = paragraph.replace(c, " ") for i in paragraph.lower().split(): if i not in banned: if i not in dic: dic[i] = 1 else: dic[i] += 1 if dic[i] > count: count = dic[i] res = i return res # transfer method solve = Solution() print(solve.mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"])) # method 2 set(),方法1优化 class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: count = 0 for c in "!?',;.": paragraph = paragraph.replace(c, " ") paragraph = paragraph.lower().split() for i in set(paragraph): if i not in banned: count1 = paragraph.count(i) if count1 > count: count = count1 res = i return res # transfer method solve = Solution() print(solve.mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"]))
071731d701260c2d72d7f894e7f4930c33c3f7f0
luchen-z/pdsnd_github
/bikeshare_project/project_bikeshare.py
13,570
4.4375
4
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!') # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs while True: try: cities = ['chicago', 'new york city', 'washington'] city = input("Would you like to see data for Chicago, New York, or Washington? Please enter: ").lower() if city == 'new york': city += ' city' break elif city in cities: break else: print('It seems the spelling of the city is not correct...Please re-enter the city name.') except: # other error situations e.g. none stings being input; but not sure which type(s) of errors should be specified here print('It seems like an invalid input...Please re-enter the city.') # get user input for month (all, january, february, ... , june) # get user input for day of week (all, monday, tuesday, ... sunday) months = ['january', 'february', 'march', 'april', 'may', 'june'] days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] while True: choice = input("Would you like to filter by month, day, both, or neither (no filter)? Please enter your choice: ").lower() if choice == 'month' or choice == 'by month': while True: month = input("Which month - January, February, March, April, May, or June? Please enter: ").lower() day = 'all' if month in months: break else: print('The input is not valid. Please input the correct month.') break elif choice == 'day' or choice == 'by day': while True: day = input("Which day - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday? Please enter: ").lower() month = 'all' if day in days: break else: print('The input is not valid. Please input the correct day name.') break elif choice == 'both' or choice == 'by both': while True: month = input("Which month - January, February, March, April, May, or June? Please enter: ").lower() day = input("Which day - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday? Please enter: ").lower() if (month in months) and (day in days): break else: print('It seems at least one of the inputs is not valid. Please input the correct month and/or day name.') break elif choice == 'neither' or choice == 'no filter': month = 'all' day = 'all' break else: print('The input is not valid. Please make sure the choice input is in correct format.') print('-'*40) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ months = ['january', 'february', 'march', 'april', 'may', 'june'] days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] df = pd.read_csv(CITY_DATA[city]) df['Start Time'] = pd.to_datetime(df['Start Time']) # convert the Start Time column to datetime df['month'] = df['Start Time'].dt.month # extract month from start time to create a new column df['day_of_week'] = df['Start Time'].dt.day_name() # extract day from start time to create a new column if month in months and day == 'all': # filter the df only by month if applicable month = convert_to_int(months, month) df = df.loc[df['month'] == month] if month == 'all' and day in days : # filter the df only by day of week if applicable df = df.loc[df['day_of_week'] == day.title()] if month in months and day in days: # use the index of the months list to get the corresponding month's int month = convert_to_int(months, month) df = df.loc[df['month'] == month] # first filter the df by month df = df.loc[df['day_of_week'] == day.title()] # then filter the df by day of week return df # no filter applied def convert_to_int(months, month): month = months.index(month) + 1 return month def frequency_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() if df['month'].nunique() != 1 and df['day_of_week'].nunique() != 1: # user choose no filter most_common_month = df['month'].value_counts().idxmax() # display the most common month months = ['January', 'February', 'March', 'April', 'May', 'June'] most_common_month = months[int(most_common_month) - 1] # convert the index of month back to month name print("\nThe most common month is {}.".format(most_common_month)) most_common_day = df['day_of_week'].value_counts().idxmax() # display the most common day of week print("\nThe most common day of week is {}.".format(most_common_day)) df['hour'] = df['Start Time'].dt.hour most_common_start_hour = df['hour'].value_counts().idxmax() # display the most common start hour print("\nThe most common start hour is {}.".format(most_common_start_hour)) if df['month'].nunique() == 1 and df['day_of_week'].nunique() != 1: # user choose to filter by month months = ['January', 'February', 'March', 'April', 'May', 'June'] month = months[int(df['month'].iloc[0]) - 1] # convert the index of month back to month name most_common_day = df['day_of_week'].value_counts().idxmax() # display the most common day of week print("\nThe most common day of week in {0} is {1}.".format(month, most_common_day)) df['hour'] = df['Start Time'].dt.hour most_common_start_hour = df['hour'].value_counts().idxmax() # display the most common start hour print("\nThe most common start hour in {0} is {1}.".format(month, most_common_start_hour)) if df['day_of_week'].nunique() == 1 and df['month'].nunique() != 1: # user choose to filter by day of week day = str(df['day_of_week'].iloc[0]).title() most_common_month = df['month'].value_counts().idxmax() # display the most common month months = ['January', 'February', 'March', 'April', 'May', 'June'] most_common_month = months[int(most_common_month) - 1] # convert the index of month back to month name print("\nThe most common month on day of {0} is {1}.".format(day, most_common_month)) df['hour'] = df['Start Time'].dt.hour most_common_start_hour = df['hour'].value_counts().idxmax() # display the most common start hour print("\nThe most common start hour on day of {0} is {1}.".format(day, most_common_start_hour)) if df['month'].nunique() == 1 and df['day_of_week'].nunique() == 1: # user choose to filter by both month and day months = ['January', 'February', 'March', 'April', 'May', 'June'] month = months[int(df['month'].iloc[0]) - 1] # convert the index of month back to month name day = str(df['day_of_week'].iloc[0]).title() df['hour'] = df['Start Time'].dt.hour most_common_start_hour = df['hour'].value_counts().idxmax() # display the most common start hour print("\nThe most common start hour on {0} in {1} is {2}.".format(day, month, most_common_start_hour)) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # display most commonly used start station most_common_start_station = df['Start Station'].value_counts().idxmax() print("\nThe most commonly used start station is {}.".format(most_common_start_station)) # display most commonly used end station most_common_end_station = df['End Station'].value_counts().idxmax() # display the most common start station print("\nThe most commonly used end station is {}.".format(most_common_start_station)) # display most frequent combination of start station and end station trip df['Route'] = df['Start Station'] + ' to ' + df['End Station'] most_common_route = df['Route'].value_counts().idxmax() print("\nThe most frequent route is from {}.".format(most_common_route)) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() # display total travel time total_trip_duration = df['Trip Duration'].sum() print("\nThe total travel time is {}.".format(total_trip_duration)) # display mean travel time mean_trip_duration = df['Trip Duration'].mean() print("\nThe mean travel time is {}.".format(mean_trip_duration)) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() # Display counts of user types user_types = df['User Type'].value_counts() print("\nThe distribution of user types is:\n{}".format(user_types)) # Display counts of gender if 'Gender' in df: genders_count = df['Gender'].value_counts() print("\nThe distribution of user gender is:\n{}".format(genders_count)) else: print("\nThere is no available information regarding users' gender in this city.") # Display earliest, most recent, and most common year of birth if 'Birth Year' in df: earlist_birth_year = int(df['Birth Year'].min()) most_recent_birth_year = int(df['Birth Year'].max()) most_common_birth_yaer = int(df['Birth Year'].value_counts().idxmax()) print("\nThe earlist year of birth among the users is {}.".format(earlist_birth_year)) print("\nThe most recent year of birth among the users is {}.".format(most_recent_birth_year)) print("\nThe most common year of birth among the users is {}.".format(most_common_birth_yaer)) else: print("\nThere is no available information regarding users' year of birth in this city.") print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def get_raw_data(df): """Prompt the user whether they would like to see the raw data. Print out 5 rows of the data (ascending indices, accumulative) for each 'yes' attempt until a 'no' input or the last row.""" row_number = 0 while True: attempt = input("\nWould you like to check the raw data? Enter 'yes' or 'no'.\n").lower() if attempt in ['yes', 'y', 'no', 'n']: while (attempt == 'yes' or attempt == 'y') and row_number < df.shape[0]: # number of total rows if row_number < df.shape[0] - 4: df_output = df.iloc[row_number: row_number+5] row_number += 5 print(df_output) while True: attempt = input("\nWould you like to continue checking the raw data? Enter 'yes' or 'no'.\n").lower() if attempt in ['yes', 'y', 'no', 'n']: break else: print("\nThe input is not valid. Please re-enter 'yes' or 'no'.\n") else: df_output = df.iloc[row_number:] row_number += 5 print(df_output) print("\nWe have reached the last row of the raw data.\n") if attempt == 'no' or attempt == 'n' or row_number >= df.shape[0]: print("\nThe check on raw data is finishing... Thank you.\n") break else: print("\nThe input is not valid. Please enter 'yes' or 'no'.\n") print('-'*40) def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) frequency_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
b5b41b91f229aa0c23246d2585ad58da1b17a6a0
speciallan/algorithm
/leetcode/problem231/problem231.py
757
3.75
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Speciallan class Solution(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ if n <= 0: return False if n == 1: return True # yushu = n % 10 # # if yushu not in [2, 4, 6, 8]: # return False bi_num = bin(n)[2:] if bi_num[0] == '1': i = 1 while i <= len(bi_num) - 1: if bi_num[i] == '0': i += 1 else: return False return True if __name__ == "__main__": n = 4 solution = Solution() result = solution.isPowerOfTwo(n) print(result)
0bc9f19f70076857a77efe690a7f54085ac50345
mocchacino/latihan_python
/PembagianTanpaOperator.py
221
3.578125
4
# membuat fungsi pembagian tanpa menggunakan div atau '/' # menghasilkan integer def pembagian(a,b): hasil = -1 while a >= 0: a = a - b hasil += 1 print(hasil) pembagian(9,3)
f52f07b7cb868e9805bbc3d1156bcd91ea62a347
bhattaraijay05/prg
/multiple_of_any_number.py
260
3.984375
4
multiple_number=int(input("Whose multiple ")) multiple_upto=int(input("upto where ")) for multiple_upto in range(1,multiple_upto+1): multiple=multiple_number*multiple_upto print(str(multiple_number) + " * " + str(multiple_upto) + " = " + str(multiple))
a7bd81aee9907933e878b4d26868d5f6ba071f1a
Beardocracy/holberton-system_engineering-devops
/0x16-api_advanced/100-count.py
1,903
3.546875
4
#!/usr/bin/python3 ''' This module contains the count function ''' import re import requests def count_words(subreddit, word_list, hot_list=[], print_flag=0): ''' Prints the number of occurrences for a list of keywords in a subs hotlist ''' url = "https://www.reddit.com/r/{}/hot.json".format(subreddit) headers = {'User-agent': 'tbearden'} items = len(hot_list) if items == 0: params = {'limit': 100} else: last_listing = hot_list[items - 1] last_fullname = "{}_{}".format(last_listing['kind'], last_listing['data']['id']) params = {'after': last_fullname, 'limit': 100} r = requests.get(url, headers=headers, params=params) if r.status_code != 200: return None data = r.json() children = [] if 'data' in data.keys() and 'children' in data['data'].keys(): children = data['data']['children'] if len(children) == 0: titles = [listing['data']['title'] for listing in hot_list] print_matches(titles, word_list) else: for child in children: hot_list.append(child) print_flag += 1 count_words(subreddit, word_list, hot_list, print_flag) def print_matches(titles, word_list): ''' Prints out the keyword match rankings ''' ''' word_list = set([x.lower() for x in word_list]) ''' kw_count = {} for kw in word_list: kw_count[kw] = 0 for title in titles: for kw in word_list: expr = "(?i)(?<!\S){}(?!\S)".format(kw) matches = re.findall(r'{}'.format(expr), title.lower(), re.I) kw_count[kw] += len(matches) kw_count = {k: v for k, v in kw_count.items() if v > 0} for kw in sorted(kw_count, reverse=True, key=lambda kw: kw_count[kw]): if kw_count[kw] > 0: print("{}: {}".format(kw, kw_count[kw]))
5e087948839dbdbf36330e9f9491bf96960cae6c
nov3mb3r/DidierStevensSuite
/sortcanon.py
5,225
3.65625
4
#!/usr/bin/env python __description__ = 'Sort with canonicalization function' __author__ = 'Didier Stevens' __version__ = '0.0.2' __date__ = '2022/07/17' """ Source code put in public domain by Didier Stevens, no Copyright https://DidierStevens.com Use at your own risk History: 2015/07/07: start 2015/07/08: added output option 2022/06/19: update for Python 3 2022/07/17: 0.0.2 added email Todo: """ import optparse import glob import sys import collections import textwrap dLibrary = { 'domain': "lambda x: '.'.join(x.split('.')[::-1])", 'length': "lambda x: len(x)", 'ipv4': "lambda x: [int(n) for n in x.split('.')]", 'email': "lambda x: '.'.join(x.split('@', 1)[1].split('.')[::-1]) + '@' + x.split('@', 1)[0]" } def PrintManual(): manual = r''' Manual: sortcanon is a tool to sort the content of text files according to some canonicalization function. The tool takes input from stdin or one or more text files provided as argument. All lines from the different input files are put together and sorted. If no option is used to select a particular type of sorting, then normal alphabetical sorting is applied. Use option -o to write the output to the given file, in stead of stdout. Use option -r to reverse the sort order. Use option -u to produce a list of unique lines: remove all doubles before sorting. Option -c can be used to select a particular type of sorting. For the moment, 2 options are provided: domain: interpret the content of the text files as domain names, and sort them first by TLD, then domain, then subdomain, and so on ... length: sort the lines by line length. The longest lines will be printed out last. ipv4: sort IPv4 addresses. You can also provide your own Python lambda function to canonicalize each line for sorting. Remark that this involves the use of the Python eval function: do only use this with trusted input. ''' for line in manual.split('\n'): print(textwrap.fill(line, 79)) def File2Strings(filename): try: f = open(filename, 'r') except: return None try: return list(map(lambda line:line.rstrip('\n'), f.readlines())) except: return None finally: f.close() def ProcessAt(argument): if argument.startswith('@'): strings = File2Strings(argument[1:]) if strings == None: raise Exception('Error reading %s' % argument) else: return strings else: return [argument] def ExpandFilenameArguments(filenames): return list(collections.OrderedDict.fromkeys(sum(map(glob.glob, sum(map(ProcessAt, filenames), [])), []))) class cOutput(): def __init__(self, filename=None): self.filename = filename if self.filename and self.filename != '': self.f = open(self.filename, 'w') else: self.f = None def Line(self, line): if self.f: self.f.write(line + '\n') else: print(line) def Close(self): if self.f: self.f.close() self.f = None def SortCanon(args, options): global dLibrary lines = [] for file in args: if file == '': fIn = sys.stdin else: fIn = open(file, 'r') for line in [line.strip('\n') for line in fIn.readlines()]: lines.append(line) if file != '': fIn.close() if options.canonicalize == '': Canonicalize = lambda x: x elif options.canonicalize in dLibrary: Canonicalize = eval(dLibrary[options.canonicalize]) else: Canonicalize = eval(options.canonicalize) if options.unique: lines = list(set(lines)) oOutput = cOutput(options.output) for line in sorted(lines, key=Canonicalize, reverse=options.reverse): oOutput.Line(line) oOutput.Close() def Main(): global dLibrary moredesc = ''' Arguments: @file: process each file listed in the text file specified wildcards are supported Valid Canonicalization function names: ''' for key in sorted(dLibrary.keys()): moredesc += ' %s: %s\n' % (key, dLibrary[key]) moredesc += ''' Source code put in the public domain by Didier Stevens, no Copyright Use at your own risk https://DidierStevens.com''' oParser = optparse.OptionParser(usage='usage: %prog [options] [files]\n' + __description__ + moredesc, version='%prog ' + __version__) oParser.add_option('-m', '--man', action='store_true', default=False, help='Print manual') oParser.add_option('-c', '--canonicalize', default='', help='Canonicalization function') oParser.add_option('-r', '--reverse', action='store_true', default=False, help='Reverse sort') oParser.add_option('-u', '--unique', action='store_true', default=False, help='Make unique list') oParser.add_option('-o', '--output', default='', help='Output file') (options, args) = oParser.parse_args() if options.man: oParser.print_help() PrintManual() return if len(args) == 0: SortCanon([''], options) else: SortCanon(ExpandFilenameArguments(args), options) if __name__ == '__main__': Main()
343ae2be3ca6f112dec9cb1ac646c1187b5c5513
Sidney-kang/Unit5-03
/lowest_value_array.py
724
4.4375
4
# Created by : Sidney Kang # Created on : 13 Nov. 2017 # Created for : ICS3UR # Daily Assignment - Unit5-03 # This program def find_lowest_value(arrays = []): value_number_in_array = 0 for value in arrays: if value_number_in_array == 0: value_number_in_array = value else: if value_number_in_array > value: value_number_in_array = value else: value_number_in_array = value_number_in_array return value_number_in_array array = [5,4,7,9,3,6] find_lowest_value(array) min_value = find_lowest_value(array) print("The min value of the array is: " + str(min_value))
35cfc68d3bbea3b1a42b6a5d20def9d4cb98d66b
snlnrush/python-alg-and-data
/les_2_task_4.py
477
3.90625
4
""" 4. Найти сумму n элементов следующего ряда чисел: 1, -0.5, 0.25, -0.125,… Количество элементов (n) вводится с клавиатуры. """ def s_element(n, s=0, b=1): if n == 0: return s s += b n -= 1 b /= 2 return s_element(n, s, b) amount = int(input('Enter number:')) if amount == 0: print(f'Sum of numbers: 0') else: print(f'Sum of numbers: {s_element(amount)}')
3d098db289ab06c07a42a429cb8ecc4da39ece42
scriptographers/CS228-Assignment-1
/src/mastermind-harness.py
2,966
3.78125
4
# !/usr/bin/python3 # sample harness; your code should play against this code without # any modification in this code. For any issues in this code # please report asap. # your code lives in this file; we will import it import mastermind # We expect the following three functions in your code # their usage will explain their interface. # # mastermind.initialize(n,k) # # mastermind.get_second_player_move() # # mastermind.put_first_player_response( red, white ) # we randomly choose number of colors and length of sequence import random n = random.randint(8, 12) k = random.randint(3, 7) # two modes of testing # play with self or play with a human # play_self = True code = [] # pick a code in autoplay if play_self: for i in range(k): code.append(random.randint(0, n - 1)) # calculate response in auto play def get_auto_response(move): l = random.randint(1, 10) if (l < 6): move = [0] * k print("incorrect") assert(len(move) == k) reds = 0 for i in range(k): if move[i] == code[i]: reds += 1 matched_idxs = [] whites_and_reds = 0 for i in range(k): c = move[i] for j in range(k): if j in matched_idxs: continue if c == code[j]: whites_and_reds += 1 matched_idxs.append(j) break print("found a move:") print(move) print("Enter red count: " + str(reds)) print("Enter white count: " + str(whites_and_reds - reds)) return reds, whites_and_reds - reds def get_human_response(): red = int(input("Enter red count: ")) white = int(input("Enter white count: ")) if white + red > k: raise Exception("bad input!") return red, white def play_game(): if play_self: print("Chosen code:") print(code) # ~~~~ API CALL: We tell your code our choice of n and k # n is the number of colors # k is the size of the sequence # mastermind.initialize(n, k) guess_list = [] response_list = [] red = 0 while red < k: # ~~~~ API CALL: we collect your move # Your response should be of a list of k numbers. Ex. [ 2, 4, 4, 5] # The numbers indicate the colors # move = mastermind.get_second_player_move() guess_list.append(move) if play_self: red, white = get_auto_response(move) else: print("found a move:") print(move) red, white = get_human_response() # ~~~~ API CALL: we collect your guesses # We send you reds and white responses # red : number of correct colors in correct positions # white: number of correct colors in wrong positions # mastermind.put_first_player_response(red, white) print("Game solved in " + str(len(guess_list)) + " moves for n = " + str(n) + " and k = " + str(k) + "!") play_game()
4c0c873866cc2367199759556938fb0de05b055e
shiannn/LeetCodePython
/linklist/LeetCode 78 [Subsets]OneBranch.py
1,053
3.65625
4
class Solution(object): def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if nums is None: return [] res = [[]] self.dfs(sorted(nums), 0, [], res) return res def dfs(self, nums, index, path, res): for i in range(index, len(nums)): print(path + [nums[i]]) res.append(path + [nums[i]]) path.append(nums[i]) self.dfs(nums, i+1, path, res) path.pop() def subsets2(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() result = [[]] for x in nums: with_x = [] for s in result: with_x.append(s + [x]) print('x',x,'with_x',with_x) result = result + with_x return result if __name__ == '__main__': sol = Solution() nums = [1,2,3] #sol.subsets(nums) sol.subsets2(nums)
bd647fc6841613b0f0e733174d37a24680fe1999
azam6301732985/test
/Prediction Using Supervised ML.py
4,591
4.125
4
#!/usr/bin/env python # coding: utf-8 # # AUTHOR :- M.A.AZAM # # TASK 1 :-Prediction Using Supervised Ml GRIP @ THE SPARKS FOUNDATION # Linear Regression with Python Scikit Learn # In this section we will see how the Python Scikit-Learn library for machine learning can be used to implement regression functions. We will start with simple linear regression involving two variables. # # Simple Linear Regression # In this regression task we will predict the percentage of marks that a student is expected to score based upon the number of hours they studied. This is a simple linear regression task as it involves just two variables. # In[3]: # Importing all the libraries required in this notebook from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import numpy as np import pandas as pd import matplotlib.pyplot as plt # ## Step-1: Reading Data from Remote link # In[6]: # Reading data from remote link url = "http://bit.ly/w-data" s_data = pd.read_csv(url) print("Data imported successfully") s_data.head(10) # Let's plot our data points on 2-D graph to eyeball our dataset and see if we can manually find any relationship between the data. We can create the plot with the following script: # # Step-2: Visualization the Input Data # In[7]: # Plotting the distribution of scores s_data.plot(x='Hours', y='Scores', style='o') plt.title('Hours vs Percentage') plt.xlabel('Hours Studied') plt.ylabel('Percentage Score') plt.show() # ### From the graph above, we can clearly see that there is a positive linear relation between the number of hours studied and percentage of score. # # Step-3: Preparing the Data # ##The next step is to divide the data into "attributes" (inputs) and "labels" (outputs). # In[8]: X = s_data.iloc[:, :-1].values y = s_data.iloc[:, 1].values # # Step-4: Splitting the data in to Training and Test sets. # ##Now that we have our attributes and labels, the next step is to split this data into training and test sets. We'll do this by using Scikit-Learn's built-in train_test_split() method: # # In[9]: from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) # # Training the Algorithm # We have split our data into training and testing sets, and now is finally the time to train our algorithm. # In[10]: from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) print("Training complete.") # # Step-5: Plotting the line of Regression # In[11]: # Plotting the regression line line = regressor.coef_*X+regressor.intercept_ # Plotting for the test data plt.scatter(X, y) plt.plot(X, line); plt.show() # # Step-6 Making Predictions # Now that we have trained our algorithm, it's time to make some predictions. # In[12]: print(X_test) # Testing data - In Hours y_pred = regressor.predict(X_test) # Predicting the scores # # Step-7: Comparing Actual vs Predicted Values # # In[13]: # Comparing Actual vs Predicted df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred}) df # In[15]: #Estimating the Train and Test print('train values:',regressor.score(X_train,y_train)) print('test values:',regressor.score(X_test,y_test)) # In[19]: #Plotting the line Graph to depict the difference between Actual and Predicted Values df.plot(kind='line',figsize=(8,6)) plt.grid(which='major',linewidth='0.5',color='orange') plt.grid(which='major',linewidth='0.5',color='blue') plt.show() # In[24]: # testing with this data hours = 9.25 test=np.array([hours]) test=test.reshape(-1,1) own_pred = regressor.predict(test) print("No of Hours = {}".format(hours)) print("Predicted Score = {}".format(own_pred[0])) # # Step-8: Model Evaluation # The final step is to evaluate the performance of algorithm. This step is particularly important to compare how well different algorithms perform on a particular dataset.Here, we have chosen the Mean Absolute Error,Mean Squared Error,Root Mean Squared Error and R2 # In[26]: from sklearn import metrics print('Mean Absolute Error(MAE):', metrics.mean_absolute_error(y_test, y_pred)) print('Mean Squared Error(MSE):', metrics.mean_squared_error(y_test, y_pred)) print('Root Mean Squared Error(RMSE):', np.sqrt(metrics.mean_squared_error(y_test, y_pred))) print('R2:',metrics.r2_score(y_test,y_pred)) # # Conclusion # # # R2 gives the score of model fit ,here R2 is actually a middle score for this model. # # Thank you.
802cf41dbad7ea163cf2ba69c3c5048936379d52
skshabeera/dictionary
/saral10.py
495
3.921875
4
# dict = {'Alex': ['subj1', 'subj2', 'subj3'], 'David': ['subj1', 'subj2']} # ctr = sum(map(len, dict.values())) # print(ctr) dict = { 'Alex': ['subj1', 'subj2', 'subj3'], 'David': ['subj1', 'subj2']} total=0 for value in dict: value_list=dict[value] count=len(value_list) total=total+count print(total) # dict={"siri":20,"anusha":21,"shabeera":23} # total=0 # for value in dict: # value_list=dict[value] # count=dict.len() # toatal=total+count # print(total)
d8734960bcddeeb471adc5f6142d3cd481306c01
benzheren/python-playground
/project-euler/p019.py
861
3.921875
4
''' You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? ''' days_in_a_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) start = 366 # jan 1st 1901 is 366 num = 0; for i in xrange(1901, 2001): for j in xrange(12): if j == 1 and not i % 4: start += (days_in_a_month[j] + 1) else: start += days_in_a_month[j] if not start % 7: num += 1 print num