blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b74d570c12404a0204c7b7eb6bb29280a46446c1
bluestar31/dinhthanhlong-fundamental-c4e13
/Session 2/fizzbuzz.py
226
4.09375
4
n = int(input("Enter a number: ")) for i in range(n): if i % 2 == 0: if i % 3 == 0: print("FizzBuzz") else: print("Fizz") else: if i % 3 == 0: print("Buzz")
0b22ccf7c3442f0b8cb8b489e3bdf133c3fbf274
kgardouh/machine-learning-data-sante
/parser-clean.py
499
3.640625
4
import re def find_str(s, char): index = 0 if char in s: c = char[0] for ch in s: if ch == c: if s[index:index+len(char)] == char: return index index += 1 return -1 with open('example.txt', 'r') as f: #open the file contents = f.readlines() #put the lines to a variable (list). #print(contents) #contents = map(lambda s: s.strip(), contents) for x in contents: print(x)
148b005ebcaff7002c7f1c6b461761b0a6e708f2
bomendez/bomendez.github.io
/Hangman/test_hangman.py
1,565
3.5
4
from hangman import (is_letter, in_word, already_guessed, insert_letters, add_to_guessed, game_over, end_string) def test_end_string(): assert(end_string("APPLE") == "_____") assert(end_string("OBVIOUS") == "_______") assert(end_string("XYLOPHONE") == "_________") def test_game_over(): assert(game_over("APPLE", "APPLE") is True) assert(game_over("OBVIOUS", "OBVIOUS") is True) assert(game_over("XYLOPHONE", "XYLOPHONE") is True) assert(game_over("APPLE", "_____") is False) assert(game_over("APPLE", "APPL_") is False) def test_add_to_guessed(): assert(add_to_guessed("A", "") == "A") assert(add_to_guessed("A", "E") == "EA") assert(add_to_guessed("A", "PEIA") == "PEIAA") assert(add_to_guessed("APPLE", "") == "APPLE") def test_insert_letters(): assert(insert_letters("APPLE", "A") == "A____") assert(insert_letters("APPLE", "AP") == "APP__") assert(insert_letters("APPLE", "APPLE") == "APPLE") assert(insert_letters("APPLE", "AL") == "A__L_") def test_already_guessed(): assert(already_guessed("A", "A") is True) assert(already_guessed("A", "APP") is True) assert(already_guessed("AP", "APPLE") is True) assert(already_guessed("A", "PAL") is True) def test_in_word(): assert(in_word("APPLE", "APPLE") is True) assert(in_word("OBVIOUS", "OBVIOUS") is True) assert(in_word("APPL", "APPLE") is True) assert(in_word("I", "APPLE") is False) def test_is_letter(): assert(is_letter("A") is True) assert(is_letter("AB") is False)
1d0d08f1f18d35ae3f93ad4d86863a58e915a41b
JerryHDev/Functional-Programming
/Chapter 5/5_4.py
294
3.671875
4
#Jerry Huang #Period 4 def main(): phrase = input("Enter a phrase: ") myList = phrase.split(" ") listLength = len(myList) x = 0 for i in range(listLength): f_word = myList[x] f_letter = f_word[0].upper() print(f_letter, end="") x = x + 1 main()
e1359df8232d2dde0560891b526ec0cb34d2fc1a
hasan55-krmz/Portfolio-Manegement
/portfolio_management_modul.py
8,578
3.640625
4
########################################################### # Libraries ########################################################### import pandas as pd import numpy as np import pandas_datareader as pdr from datetime import datetime import seaborn as sns import matplotlib.pyplot as plt ########################################################### # Functions ########################################################### # Take Stock Data From Yahoo def get_stock(stock_code, start_date=[2019,1,1], end_date=[2019,12,31]): """This function gets the stock data within the desired date range from Yahoo Finance. The data includes High, Low, Open, Close, Volume, Adj Close prices. It returns a DataFrame :param stock_code: It is a string. The code of the stock on Yahoo Fınace, For example for Amazon; "AMZN" :param start_date: It is a List. The starting date of data. For example ; [2019,1,1]. [2019,1,1] by default :param end_date: It is a List. The end date of data. For example ; [2019,12,31]. [2019,12,31] by default :return: returns the all data (opened, closed, volume, adj close etc) of stock """ stock=pdr.get_data_yahoo(symbols=stock_code, start=datetime(start_date[0],start_date[1],start_date[2],), end=datetime(end_date[0],end_date[1],end_date[2],)) return stock # Creat a portfolio with wanted stocks def creat_portfolio(stock_list,start_date,end_date,price_type="Adj Close"): """ Creats porfolio within the desired stocks and date range from Yahoo Finance, Gets the Stocks' price and puts on DataFrame, Price type can be adjusted. For examaple it can be open, closed, adjusted close, high ect. :param stock_list: It is a list or array. Is has toks code which will be included in portfolio. For example ["AAPL","AMZN","T"] :param start_date: It is a List. The starting date of data. For example ; [2019,1,1]. :param end_date: It is a List. The end date of data. For example ; [2019,12,31]. :param price_type: which price type is the target price ( "Open", "Close", "Adj Close"). "Adj Close" by default :return: A DataFrame. Retuns the portfolio dataframe """ portfolio = pd.DataFrame() for stock in stock_list: portfolio[stock] = pdr.get_data_yahoo(symbols=stock, start=datetime(start_date[0],start_date[1],start_date[2]), end=datetime(end_date[0],end_date[1],end_date[2],))[price_type] return portfolio # Visualize the Portfolio or Stock Data def plot_pf_price(portfolio): """It is plot the price of all stocks in portfolio :param portfolio: Portfolio DataFrame that include stock prices :return: Plot the daily price of all stocks """ fig, ax=plt.subplots(figsize=(15,6)) for stock in portfolio.columns: ax.plot(portfolio.loc[:,stock],label=stock); ax.legend(fontsize="x-large") plt.show() # Calculate the portfolio return with wanted wegihts def return_portf(portfolio, weight): """It calculates the daily return of portfolio with desired weights. :param portfolio: Portfolio DataFrame that include stock prices :param weight: array or list, desired weights :return: A pandas series. Daily returns of portfolio """ return_daily=portfolio.pct_change() portfolio_returns = return_daily.mul(weight, axis=1).sum(axis=1) return portfolio_returns # Calculate portfolio volatility def portf_vol(portfolio, weight,st_exch_day=252): """ It calucltes portfolio volatility by covariance matrix and weights :param portfolio:It is a DataFrame, Portfolio DataFrame that include stock prices :param weight: A numpy array or list. Portfolio weight set :param st_exch_day: An integer or float. Is is stock excahnge days in a year. :return: An integer. Portfolio volatility """ #cov_matrix_annual=(portfolio.pct_change().apply(lambda x: np.log(1+x))).cov()*st_exch_day cov_matrix_annual=(portfolio.pct_change()).cov()*st_exch_day portfolio_volatility=np.sqrt(np.dot(weight.T, np.dot(cov_matrix_annual, weight))) return portfolio_volatility # Creat random portrfolio weight sets with wanted range def creat_random_portf(portfolio,size=5000): """It creats up to size diffirent weight sets for each stocks in a dataframe. :param portfolio:It is a DataFrame, Portfolio DataFrame that include stock prices :param size: An integer. Number of Diffirent Potfolio sets :return: A DataFrame. Is include size diffirent portfolio weight sets """ RandomPortfolio = pd.DataFrame() for i in range(size): weight = np.random.random(portfolio.shape[1]) weight /= np.sum(weight) RandomPortfolio.loc[i,portfolio.columns+"_weight"] = weight return RandomPortfolio # Create Random Portfolio, Calculate the portfolio metrics and sharp Ratio and plot efficent frontier def markowitz_portfolio(portfolio, risk_free=0, size=5000, plot=False,stc_days=252): """ Creats a random portfolio weight sets and calculates Markowitz porfolio metrics and save on DataFrame. :param portfolio:It is a DataFrame, Portfolio DataFrame that include stock prices :param risk_free: An integer or float. Risk-free rate on stock market :param plot: A boolen. İf True, then plots some portfolio cum price and Markowitz Random portfolio return-volatility scatter plot :return: Return two data frame, first Random Portfolio Dataframe, second is weight-returns sets Dataframe """ portfolio_return = portfolio.pct_change() col = portfolio.columns RandomPortfolio = pd.DataFrame() for i in range(size): weight = np.random.random(portfolio.shape[1]) weight /= np.sum(weight) RandomPortfolio.loc[i, col] = weight RandomPortfolio["Return"] = np.dot(RandomPortfolio.loc[:, col], portfolio_return.mean()*stc_days) RandomPortfolio["Volatility"] = RandomPortfolio.apply(lambda x: portf_vol(portfolio, x[0:portfolio.shape[1]]), axis=1) RandomPortfolio['Sharpe'] = (RandomPortfolio["Return"] - risk_free) / RandomPortfolio["Volatility"] numstock = portfolio.shape[1] e_w = np.repeat(1 / numstock, numstock) msr_w = np.array(RandomPortfolio.sort_values(by="Sharpe", ascending=False).iloc[0:1, 0:numstock]) gmv_w = np.array(RandomPortfolio.sort_values(by="Volatility").iloc[0:1, 0:numstock]) port_returns = portfolio.pct_change() port_returns["Return_EW"] = port_returns.loc[:, col].mul(e_w, axis=1).sum(axis=1) port_returns["Return_MSR"] = port_returns.loc[:, col].mul(msr_w, axis=1).sum(axis=1) port_returns["Return_GMV"] = port_returns.loc[:, col].mul(gmv_w, axis=1).sum(axis=1) weight_set=pd.DataFrame() weight_set.loc["msr_w", col] = msr_w weight_set.loc["gmv_w", col] = gmv_w weight_set.loc["e_w", col] = e_w weight_set["Return"] = np.dot(weight_set.loc[:, col], portfolio_return.mean() * stc_days) weight_set["Volatility"] = weight_set.apply(lambda x: portf_vol(portfolio, x[0:portfolio.shape[1]]), axis=1) weight_set['Sharpe'] = (weight_set["Return"] - risk_free) / weight_set["Volatility"] if plot: ((1 + port_returns[["Return_EW", "Return_MSR", "Return_GMV"]]).cumprod() - 1).plot() plt.ylabel("Cumilative Return") plt.show() sns.scatterplot(x="Volatility", y="Return", data=RandomPortfolio) sns.scatterplot(x="Volatility", y="Return", data=RandomPortfolio.sort_values(by="Sharpe", ascending=False).iloc[0:1], color="red", marker="*", s=500) sns.scatterplot(x="Volatility", y="Return", data=RandomPortfolio.sort_values(by="Volatility").iloc[0:1], color="orange", marker="*", s=500) plt.show() return RandomPortfolio, weight_set # Plotting Corelation Heatmap def corr_mat(portfolio): """ :param portfolio: portfolio dataframe :return: plot Corelation matrix heatmap """ corr_matrix=portfolio.pct_change().corr() plt.subplots(figsize=(8,6)) sns.heatmap(corr_matrix, annot=True,cmap="PiYG");
a4139cdd4c99903b152351442e09296fa76baafb
murakumo512/aaaa
/4.py
130
3.921875
4
count = 0 while (count < 5): print(count, "kurang dari 5") count = count + 2 else: print(count, "tidak kurang dari 5")
44bbbea0525dcc460e0891ed1434ddefd53b1d76
elenaborisova/Python-Fundamentals
/04. Data Types and Variables - Exercise/09_snowballs.py
667
3.75
4
snowballs_count = int(input()) max_snowball_value = 0 max_snowball_snow = 0 max_snowball_time = 0 max_snowball_quality = 0 for snowball in range(snowballs_count): snowball_snow = int(input()) snowball_time = int(input()) snowball_quality = int(input()) snowball_value = (snowball_snow / snowball_time) ** snowball_quality if snowball_value > max_snowball_value: max_snowball_value = snowball_value max_snowball_snow = snowball_snow max_snowball_time = snowball_time max_snowball_quality = snowball_quality print(f"{max_snowball_snow} : {max_snowball_time} = {int(max_snowball_value)} ({max_snowball_quality})")
0564e4da936a14f7ca3e8eb5e202dc066f8f5a4c
RamshackleJohnny/todo-manager
/manager.py
2,514
3.890625
4
from item import Item class Manager(object): def __init__(self): pass def menu(self): print("Do you want to add something, mark something as done, remove something, or check your list?") option = input("> ") option = option.lower() print(option) if option == 'add': Manager.add('') elif option == 'check': print("These things are on your list") Manager.view('') Manager.menu('') elif option == 'remove': inpot = open('todos.txt','r').readlines() print('These are your options, which do you want to remove? (Write the line number)') Manager.view('') theline = input("> ") theline = int(theline) with open('todos.txt','w') as output: for thedo, line in enumerate(inpot): if thedo != theline - 1: output.write(line) print('Your list now contains the following') Manager.view('') Manager.menu('') elif option == 'mark': inpot = open('todos.txt','r').readlines() print("These things are on your list") Manager.view('') print('Which do you want to mark as complete? (Write the line number)') theline = input("> ") theline = int(theline) with open('todos.txt','w') as output: for thedo, line in enumerate(inpot): if thedo != theline - 1: output.write(line) elif thedo == theline -1: line = line.replace('Completed?: False', 'Completed?: True') output.write(line) print('Your list now contains the following') Manager.view('') Manager.menu('') else: print("Sorry, I have no idea what you're talking about.") Manager.menu('') def view(self): file = open('todos.txt') print (file.read()) def add(self): print("What do you want to add to your list?") task = input("> ") print("Is it done already?") done = input("> ") done = done.lower() if done =='yes': done = True elif done == 'no': done = False print('Your list now contains the following') Item.compile('', done, task) Manager.view('') Manager.menu('')
5bb860225a4dc13b02dd76f6835d80cdb779337c
Yuchen1995-0315/review
/01-python基础/code/day17/demo02.py
1,188
3.96875
4
""" """ list01 = [4, 54, "65", 75, 8, "9", "b"] # 需求1:找出所有偶数 def find01(): for item in list01: if type(item) == int and item % 2 == 0: yield item # 需求2:找出所有字符串 def find02(): for item in list01: if type(item) == str: yield item # 需求3:找出所有大于10的整数 def find03(): for item in list01: if type(item) == int and item > 10: yield item # "封装" : 拆分变化点 # "变化的" def condition01(item): return type(item) == int and item % 2 == 0 def condition02(item): return type(item) == str def condition03(item): return type(item) == int and item > 10 """ # "继承":抽象变化点 --> 统一变化 --> 隔离变化 # "不变的" -----> 万能查找 def find(func_condition): for item in list01: # if condition01(item): if func_condition(item): yield item # “多态”:调用父,执行子。 # 不变的 + 变化的 for item in find(condition03): print(item) """ from common.iterable_tools import IterableHelper for item in IterableHelper.find_all(list01,condition01): print(item)
5bec81dc028d8e5507cd9a31d701e7e24a04c49c
ronaksvyas/spojSol
/nextPalindrome.py
569
3.578125
4
def main(): t = int(raw_input()) for i in xrange(t): n = long(raw_input()) getNextPalindrome(n) def getNextPalindrome(n): ns = list(str(n)) if(isPalindrome("".join(ns))): print "".join(ns) return if(len(ns) == 1): print 11 return else: i = 0 j = len(ns) - 1 for i in xrange(len(ns)/2): ns[len(ns)-i-1] = ns[i] while(isPalindrome("".join(ns)) == False): ns = list(str(long("".join(ns))+1)) print "".join(ns) def isPalindrome(n): n = str(n) if(n[::-1] == n): return True else: return False if __name__ == '__main__': main()
81941e65ab7693369888526da8f62e4b13fe6fbf
NevineMGouda/Data-Sructures-And-Algorithms
/Assignment 1/birthday_present.py
4,927
3.546875
4
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- ''' Assignment 1: Birthday Present Team Number: 60 Student Names: Mona Mohamed Elamin, Nevine Gouda ''' import unittest def birthday_present(P, n, t): ''' Sig: int[0..n-1], int, int --> Boolean Pre: P is a list of non-negative integers and t >= 0 Post: True if and only if a subset exists with summation equals t Example: P = [2, 32, 234, 35, 12332, 1, 7, 56] birthday_present(P, len(P), 299) = True birthday_present(P, len(P), 11) = False ''' # Initialize the dynamic programming matrix, A # Type: Boolean[0..n][0..t] try: #Variant: i, j #Invariant: A[i-1][j-1] the previous calculated element in never change A = [[None for i in range(t + 1)] for j in range(n + 1)] for j in range(1, (t + 1)): #Variant: j #Invariant: A[1..n-1][0..t-1] all elements in A not row 0, never change A[0][j] = False for i in range(0, (n + 1)): #Variant: i #Invariant: A[0..n-1][1..t-1] all elements in A not column 0, never change. A[i][0] = True for i in range(1, (n + 1)): #Variant: i #Invariant: none for j in range(1, (t + 1)): #Variant: j #Invariant: A[0..i-1][0..j-1] all element in A previously calculated never change. if P[i - 1] > j: A[i][j] = A[i - 1][j] else: A[i][j] = A[i - 1][j - P[i - 1]] or A[i - 1][j] return A[n][t] except IndexError: print "IndexError: Insert a list of positive integers only" return False def birthday_present_subset(P, n, t): ''' Sig: int[0..n-1], int, int --> int[0..m] Pre: P is a list of non-negative integers and t >= 0 Post: list of a subset with a summation equals t and is empty if no subset exists Example: P = [2, 32, 234, 35, 12332, 1, 7, 56] birthday_present_subset(P, len(P), 299) = [56, 7, 234, 2] birthday_present_subset(P, len(P), 11) = [] ''' try: A = [[None for i in range(t + 1)] for j in range(n + 1)] P_subset = [] count = t for j in range(1, (t + 1)): #Variant: j #Invariant: A[1..n-1][0..t-1] all elements in A not in row 0, never change. A[0][j] = False for i in range(0, (n + 1)): #Variant: i #Invariant: A[0..n-1][1..t-1] all elements in A not column 0, never change. A[i][0] = True for i in range(1, (n + 1)): #Variant: i #Invariant: none for j in range(1, (t + 1)): #Variant: j #Invariant: A[0..i-1][0..j-1] all elements in A previously calculated never change. if P[i - 1] > j: A[i][j] = A[i - 1][j] else: A[i][j] = A[i - 1][j - P[i - 1]] or A[i - 1][j] if A[n][t] is True: i = n j = t while count != 0: #Variant: i #Invariant: P_subset previously appended elements never change. if i < 0: break if A[i][j] is True and A[i - 1][j] is False: P_subset.append(P[i - 1]) count = count - P[i - 1] j = j - P[i - 1] i = i - 1 else: i = i - 1 return P_subset except IndexError: print "IndexError: Insert a list of positive integers only" return [] class BirthdayPresentTest(unittest.TestCase): """Test Suite for birthday present problem Any method named "test_something" will be run when this file is executed. Use the sanity check as a template for adding your own tests if you wish. (You may delete this class from your submitted solution.) """ def test_sat_sanity(self): """Sanity Test for birthday_present() This is a simple sanity check; passing is not a guarantee of correctness. """ P = [2, 32, 234, 35, 12332, 1, 7, 56] n = len(P) t = 11 self.assertFalse(birthday_present(P, n, t)) def test_sol_sanity(self): """Sanity Test for birthday_present_subset() This is a simple sanity check; passing is not a guarantee of correctness. """ P = [2, 32, 234, 35, 12332, 1, 7, 56] n = len(P) t = 299 self.assertTrue(birthday_present(P, n, t)) self.assertItemsEqual(birthday_present_subset(P, n, t), [56, 7, 234, 2]) if __name__ == '__main__': unittest.main()
df5f11fc1d712ffc86328f81de8c9fb71143069e
Xay001/Bubble_Sort_Algorithm
/Sort1.1.py
488
3.75
4
sayilar = [] i = 0 j = 0 s = 0 uzunluk = int(input("How long your number array :")) uz = uzunluk while(i < uzunluk): sayilar.append(int(input("Enter numbers : "))) i = i + 1 while(j < uzunluk): s = 0 while(s < uz-1): if(sayilar[s] > sayilar[s+1]): alternatif_sayi = sayilar[s] sayilar[s] = sayilar[s+1] sayilar[s+1] = alternatif_sayi s = s + 1 j = j + 1 print(sayilar)
728894aff472e7d503312fead422cbbfa5a4bb47
MadanParth786/Sightseeing-Advisor-Application
/Sightseeing Advisor App.py
19,528
3.703125
4
#!/usr/bin/env python # coding: utf-8 # In[2]: import tkinter from tkinter import * from tkinter import messagebox # In[3]: val =" " #global variable A = 0 #to store Value in A operator = " " #global variable # In[4]: def Delhi(): import random def randomSolution(tsp): cities = list(range(len(tsp))) solution = [] for i in range (len(tsp)): randomCity = cities[random.randint(0,len(cities)-1)] solution.append(randomCity) cities.remove(randomCity) return solution def routeLen(tsp,solution): routelen =0 for i in range(len(solution)): routelen += tsp[solution[i-1]] [solution[i]] return routelen def getneibours(solution): neibours =[] length =[] for i in range (len(solution)): for j in range (i+1,len(solution)): neibour = solution.copy() neibour[i] = solution[j] neibour[j] =solution[i] neibours.append(neibour) return neibours def getsoln(tsp,neibours): bestlen =routeLen(tsp,neibours[0]) bestsoln = neibours[0] for neibour in neibours: currentroutelen =routeLen(tsp,neibour) if currentroutelen <bestlen: bestlen = currentroutelen bestsoln =neibour return bestsoln,bestlen def hillclimbing(tsp): print("****Welcome To Delhi****") print("Top 5 places for Sightseeging in a day are:[0->Red Fort,1->Qutub Minar,2->Humayun Tomb,3->India Gate,4->Jama Masjid ]") print("Current Optimal(Random) Solution: ") currentsoln = randomSolution(tsp) print(currentsoln) currentroutelen =routeLen(tsp,currentsoln) print("Total Distance:") print(currentroutelen) neibour =getneibours(currentsoln) print("All possible Ways for Sightseeing are: ") print(neibour) bestsolution ,bestsolutionlen = getsoln(tsp,neibour) while bestsolutionlen <currentroutelen: currentsoln = bestsolution currentroutelen = bestsolutionlen bestsolution ,bestsolutionlen = getsoln(tsp,neibour) print("Best Optimal Order for Sightseeing is:") return currentsoln,currentroutelen def main(): Data = [ [0,18,8,7,1], [18,0,13,11,6], [8,13,0,3,9], [7,11,3,0,6], [1,6,9,6,0] ] print(hillclimbing(Data)) print("***Hope you will Enjoy alot***") if __name__ == "__main__": main() def Jaipur(): import random def randomSolution(tsp): cities = list(range(len(tsp))) solution = [] for i in range (len(tsp)): randomCity = cities[random.randint(0,len(cities)-1)] solution.append(randomCity) cities.remove(randomCity) return solution def routeLen(tsp,solution): routelen =0 for i in range(len(solution)): routelen += tsp[solution[i-1]] [solution[i]] return routelen def getneibours(solution): neibours =[] length =[] for i in range (len(solution)): for j in range (i+1,len(solution)): neibour = solution.copy() neibour[i] = solution[j] neibour[j] =solution[i] neibours.append(neibour) return neibours def getsoln(tsp,neibours): bestlen =routeLen(tsp,neibours[0]) bestsoln = neibours[0] for neibour in neibours: currentroutelen =routeLen(tsp,neibour) if currentroutelen <bestlen: bestlen = currentroutelen bestsoln =neibour return bestsoln,bestlen def hillclimbing(tsp): print("****Welcome To Jaipur****") print("Top 5 places for Sightseeging in a day are:[0->Amber Fort,1->Nahargarh Fort,2->Hawa Mahal,3->Jal Mahal,4->Jantar Mantar ]") print("Current Optimal(Random) Solution: ") currentsoln = randomSolution(tsp) print(currentsoln) currentroutelen =routeLen(tsp,currentsoln) print("Total Distance:") print(currentroutelen) neibour =getneibours(currentsoln) print("All possible Ways for Sightseeing are: ") print(neibour) bestsolution ,bestsolutionlen = getsoln(tsp,neibour) while bestsolutionlen <currentroutelen: currentsoln = bestsolution currentroutelen = bestsolutionlen bestsolution ,bestsolutionlen = getsoln(tsp,neibour) print("Best Optimal Order for Sightseeing is:") return currentsoln,currentroutelen def main(): Data = [ [0,10,8,3,9], [10,0,14,10,14], [8,14,0,5,2], [3,10,5,0,4], [9,14,2,4,0] ] print(hillclimbing(Data)) print("***Hope you will Enjoy alot***") if __name__ == "__main__": main() def Agra(): import random def randomSolution(tsp): cities = list(range(len(tsp))) solution = [] for i in range (len(tsp)): randomCity = cities[random.randint(0,len(cities)-1)] solution.append(randomCity) cities.remove(randomCity) return solution def routeLen(tsp,solution): routelen =0 for i in range(len(solution)): routelen += tsp[solution[i-1]] [solution[i]] return routelen def getneibours(solution): neibours =[] length =[] for i in range (len(solution)): for j in range (i+1,len(solution)): neibour = solution.copy() neibour[i] = solution[j] neibour[j] =solution[i] neibours.append(neibour) return neibours def getsoln(tsp,neibours): bestlen =routeLen(tsp,neibours[0]) bestsoln = neibours[0] for neibour in neibours: currentroutelen =routeLen(tsp,neibour) if currentroutelen <bestlen: bestlen = currentroutelen bestsoln =neibour return bestsoln,bestlen def hillclimbing(tsp): print("****Welcome To Agra****") print("Top 5 places for Sightseeging in a day are:[0->Agra Fort,1->Taj Mahal,2->Fatehpur Sikari,3->Akbar Tomb,4->Moti Masjid ]") print("Current Optimal(Random) Solution: ") currentsoln = randomSolution(tsp) print(currentsoln) currentroutelen =routeLen(tsp,currentsoln) print("Total Distance:") print(currentroutelen) neibour =getneibours(currentsoln) print("All possible Ways for Sightseeing are: ") print(neibour) bestsolution ,bestsolutionlen = getsoln(tsp,neibour) while bestsolutionlen <currentroutelen: currentsoln = bestsolution currentroutelen = bestsolutionlen bestsolution ,bestsolutionlen = getsoln(tsp,neibour) print("Best Optimal Order for Sightseeing is:") return currentsoln,currentroutelen def main(): Data = [ [0,2,37,14,1], [2,0,41,16,4], [37,41,0,36,38], [14,16,36,0,11], [1,4,38,11,0] ] print(hillclimbing(Data)) print("***Hope you will Enjoy alot***") if __name__ == "__main__": main() def Amritsar(): import random def randomSolution(tsp): cities = list(range(len(tsp))) solution = [] for i in range (len(tsp)): randomCity = cities[random.randint(0,len(cities)-1)] solution.append(randomCity) cities.remove(randomCity) return solution def routeLen(tsp,solution): routelen =0 for i in range(len(solution)): routelen += tsp[solution[i-1]] [solution[i]] return routelen def getneibours(solution): neibours =[] length =[] for i in range (len(solution)): for j in range (i+1,len(solution)): neibour = solution.copy() neibour[i] = solution[j] neibour[j] =solution[i] neibours.append(neibour) return neibours def getsoln(tsp,neibours): bestlen =routeLen(tsp,neibours[0]) bestsoln = neibours[0] for neibour in neibours: currentroutelen =routeLen(tsp,neibour) if currentroutelen <bestlen: bestlen = currentroutelen bestsoln =neibour return bestsoln,bestlen def hillclimbing(tsp): print("****Welcome To Amritsar****") print("Top 5 places for Sightseeging in a day are:[0->Golden Temple,1->Wagah Border,2->Partition Museum,3->Jallianwala Bagh,4->Baba Atal Tower ]") print("Current Optimal(Random) Solution: ") currentsoln = randomSolution(tsp) print(currentsoln) currentroutelen =routeLen(tsp,currentsoln) print("Total Distance:") print(currentroutelen) neibour =getneibours(currentsoln) print("All possible Ways for Sightseeing are: ") print(neibour) bestsolution ,bestsolutionlen = getsoln(tsp,neibour) while bestsolutionlen <currentroutelen: currentsoln = bestsolution currentroutelen = bestsolutionlen bestsolution ,bestsolutionlen = getsoln(tsp,neibour) print("Best Optimal Order for Sightseeing is:") return currentsoln,currentroutelen def main(): Data = [ [0,35,1,1,1], [35,0,30,29,28], [1,30,0,2,1], [1,29,2,0,1], [1,28,1,1,0] ] print(hillclimbing(Data)) print("***Hope you will Enjoy alot***") if __name__ == "__main__": main() def Chandigarh(): import random def randomSolution(tsp): cities = list(range(len(tsp))) solution = [] for i in range (len(tsp)): randomCity = cities[random.randint(0,len(cities)-1)] solution.append(randomCity) cities.remove(randomCity) return solution def routeLen(tsp,solution): routelen =0 for i in range(len(solution)): routelen += tsp[solution[i-1]] [solution[i]] return routelen def getneibours(solution): neibours =[] length =[] for i in range (len(solution)): for j in range (i+1,len(solution)): neibour = solution.copy() neibour[i] = solution[j] neibour[j] =solution[i] neibours.append(neibour) return neibours def getsoln(tsp,neibours): bestlen =routeLen(tsp,neibours[0]) bestsoln = neibours[0] for neibour in neibours: currentroutelen =routeLen(tsp,neibour) if currentroutelen <bestlen: bestlen = currentroutelen bestsoln =neibour return bestsoln,bestlen def hillclimbing(tsp): print("****Welcome To Chandigarh****") print("Top 5 places for Sightseeging in a day are:[0->Rose garden,1->Rock Garden,2->Sukhna Lake ,3->Fun City,4->Chandigarh Museum ]") print("Current Optimal(Random) Solution: ") currentsoln = randomSolution(tsp) print(currentsoln) currentroutelen =routeLen(tsp,currentsoln) print("Total Distance:") print(currentroutelen) neibour =getneibours(currentsoln) print("All possible Ways for Sightseeing are: ") print(neibour) bestsolution ,bestsolutionlen = getsoln(tsp,neibour) while bestsolutionlen <currentroutelen: currentsoln = bestsolution currentroutelen = bestsolutionlen bestsolution ,bestsolutionlen = getsoln(tsp,neibour) print("Best Optimal Order for Sightseeing is:") return currentsoln,currentroutelen def main(): Data =[ [0,5,6,8,3], [5,0,6,8,2], [6,6,0,7,3], [8,8,7,0,7], [3,2,3,7,0] ] print(hillclimbing(Data)) print("***Hope you will Enjoy alot***") if __name__ == "__main__": main() def Ahemadabad(): import random def randomSolution(tsp): cities = list(range(len(tsp))) solution = [] for i in range (len(tsp)): randomCity = cities[random.randint(0,len(cities)-1)] solution.append(randomCity) cities.remove(randomCity) return solution def routeLen(tsp,solution): routelen =0 for i in range(len(solution)): routelen += tsp[solution[i-1]] [solution[i]] return routelen def getneibours(solution): neibours =[] length =[] for i in range (len(solution)): for j in range (i+1,len(solution)): neibour = solution.copy() neibour[i] = solution[j] neibour[j] =solution[i] neibours.append(neibour) return neibours def getsoln(tsp,neibours): bestlen =routeLen(tsp,neibours[0]) bestsoln = neibours[0] for neibour in neibours: currentroutelen =routeLen(tsp,neibour) if currentroutelen <bestlen: bestlen = currentroutelen bestsoln =neibour return bestsoln,bestlen def hillclimbing(tsp): print("****Welcome To Ahembdabad****") print("Top 5 places for Sightseeging in a day are:[0->Sabarmati Ashram,1->Bhadra Fort,2->Sarkhej Roza,3->Vastrapur Lake,4->Kankaria Lake ]") print("Current Optimal(Random) Solution: ") currentsoln = randomSolution(tsp) print(currentsoln) currentroutelen =routeLen(tsp,currentsoln) print("Total Distance:") print(currentroutelen) neibour =getneibours(currentsoln) print("All possible Ways for Sightseeing are: ") print(neibour) bestsolution ,bestsolutionlen = getsoln(tsp,neibour) while bestsolutionlen <currentroutelen: currentsoln = bestsolution currentroutelen = bestsolutionlen bestsolution ,bestsolutionlen = getsoln(tsp,neibour) print("Best Optimal Order for Sightseeing is:") return currentsoln,currentroutelen def main(): Data =[ [0,9,13,8,9], [9,0,10,7,4], [13,10,0,8,12], [8,7,8,0,10], [9,4,12,10,0] ] print(hillclimbing(Data)) print("***Hope you will Enjoy alot***") if __name__ == "__main__": main() # In[5]: #root:Create Window: (***FIRST PART OF CODE***) root =tkinter.Tk() root.title("Sightseeing-Advisor") #creating menu rows: menurow0=Frame(root,bg="#000000") menurow0.pack(expand=True,fill="both",) menurow1=Frame(root,) menurow1.pack(expand=True, fill="both",) menurow2=Frame(root,) menurow2.pack(expand=True,fill="both",) menurow3=Frame(root,) menurow3.pack(expand=True,fill="both",) menurow4=Frame(root,) menurow4.pack(expand=True,fill="both",) menurow5=Frame(root,) menurow5.pack(expand=True,fill="both",) #creating menu titles:(***SECOND PART OF CODE***) menutitle0=Button( menurow0, text = "Welcome to Sightseeing Advisor", font = ("Algerian", 24), relief = GROOVE, border = 1, ) menutitle0.pack(expand=True,fill="both",) menutitle1=Button( menurow1, text = "City : Delhi", font = ("verdana", 22), relief = GROOVE, border = 2, bg = "#ffffff", command = Delhi, #command is used to execute function ) menutitle1.pack(side=LEFT,expand=True,fill="both",) menutitle1=Button( menurow1, text = "City : Jaipur", font = ("verdana", 22), relief = GROOVE, border = 2, command = Jaipur, #command is used to execute function ) menutitle1.pack(side=LEFT,expand=True,fill="both",) menutitle2=Button( menurow2, text = " City : Agra", font = ("verdana", 22), relief = GROOVE, border = 2, command = Agra, #command is used to execute respective function. ) menutitle2.pack(side=LEFT,expand=True,fill="both",) menutitle3=Button( menurow2, text = "City : Amritsar", font = ("verdana", 22), relief = GROOVE, border = 2, bg = "#ffffff", command = Amritsar, ) menutitle3.pack(side=LEFT,expand=True,fill="both",) menutitle4=Button( menurow3, text = " City : Chandigarh", font = ("verdana", 22), relief = GROOVE, border = 2, bg = "#ffffff", command = Chandigarh, ) menutitle4.pack(side=LEFT,expand=True,fill="both",) menutitle5=Button( menurow3, text = "City : Ahemedabad", font = ("verdana", 22), relief = GROOVE, border = 2, command = Ahemadabad, ) menutitle5.pack(side=LEFT,expand=True,fill="both",) menutitle5=Button( menurow4, text = " ******Explore Your Way With Full Convenience******", font = ("Castelar", 20), relief = GROOVE, bg = "#ffffff", border = 0, ) menutitle5.pack(side=RIGHT,expand=True,fill="both",) menutitle6=Button( menurow5, text = "(APP-DEVELOPER:PRIYA MITTAL,PARTH MADAN)", font = ("verdana", 10), relief = GROOVE, border = 1, ) menutitle6.pack(side=RIGHT,expand=True,fill="both",) root.mainloop() # In[ ]: # In[ ]:
cdeac857109edbb57d854c91406e334a5b266925
RoslinErla/AllAssignments
/assignments/lists/add_to_list.py
694
4.375
4
#Write a program that keeps asking the user for new values to be added to a list # until the user enters 'exit' ('exit' should NOT be added to the list). # After that, the program creates a new list with 3 copies of every value in the initial list. # Finally, the program prints out all of the values in the new list. def stop(final_list): the_final_list = final_list * 3 for char in the_final_list: print(char) def main(): the_list = [] input_str = input("Enter value to be added to list: ") while input_str != "exit": the_list.append(input_str) input_str = input("Enter value to be added to list: ") else: stop(the_list) main()
48b55e7375d8038d430949cff632ef5e40b5ae93
barvilenski/daily-kata
/Python/string_incrementer.py
765
4.25
4
""" Name: String incrementer Level: 5kyu Description: Your job is to write a function which increments a string, to create a new string. If the string already ends with a number, the number should be incremented by 1. If the string does not end with a number the number 1 should be appended to the new string. Examples: foo -> foo1 foobar23 -> foobar24 foo0042 -> foo0043 foo9 -> foo10 foo099 -> foo100 Attention: If the number has leading zeros the amount of digits should be considered. """ import re def increment_string(strng): match = re.search(r'\d+$', strng) if match: st = re.sub('\d+$', '', strng) num = match.group(0) num = str(int(num) + 1).zfill(len(num)) strng = st + num else: strng += '1' return strng
786fabf64790a2755c95268526e051a6e084d66b
KocUniversity/comp100-2021f-ps0-yhamid21
/main.py
160
3.5
4
import numpy x = float(input("Enter number x: ")) y = float(input("Enter number y: ")) z = x ** y print("x**y",z) print("log(x) =",numpy.log2(x)) print("77916")
9c6915456c8f5386ec0402705f1e331787c509bb
NikitaSemenovV/Python-introduction
/slide2.py
1,029
3.734375
4
def fib(n): arr = [1, 1] for i in range(3, n + 1): tmp = sum(arr) arr = [arr[1], tmp] return arr[1] def fib3(n): arr = [1, 1, 1] for i in range(4, n + 1): tmp = sum(arr) arr = [arr[1], arr[2], tmp] return arr[2] def squares(n): return [i ** 2 for i in range(1,n+1,2)] if __name__ == '__main__': ### # for 1 print("for 1") print(fib(7)) # for 2 print("for 2") print(fib3(7)) # for 3 print("for 3") print(squares(7)) # for 4 print("for 4") a=10 b = 21 s = sum(range(a, b)) m = 1 for i in range(a, b): m *= i print("{:d} {:d}".format(s, m)) # for 5 print("for 5") a = 10 b = 20 print([i for i in range(a+1,b) if i % 2 == 0]) print([i for i in range(a+1,b) if i % 2 == 1]) # for 6 print("for 6") arr = [1, -1, 2, -2, 3, -3, 4, 5] print([i for i in arr if i > 0]) print([i for i in arr if i < 0])
321fc1e5d5cabcaa2f5b756e1e339edd83e41a4e
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/2_9.py
2,751
4.15625
4
Python program to convert Base 4 system to binary number Given a base 4 number N, the task is to write a python program to print its binary equivalent. **Conversion Table:** ![](https://media.geeksforgeeks.org/wp- content/uploads/20200128113422/Table33.png) **Examples:** > **Input :** N=11002233 > > > > > > > > **Output :** 101000010101111 > > **Explanation :** From that conversion table we changed 1 to 01, 2 to 10 ,3 > to 11 ,0 to 00. > > **Input:** N=321321 > > **Output:** 111001111001 **Approach:** * Take an empty string say **resultstr.** * We convert the decimal **number to string.** * Traverse the string and convert each character to integer * If the integer is **1 or 0** then before converting to binary add ‘0’ to **resultstr** (Because we cannot have 01,00 in integers) * Now convert this **integer to binary string** and **concatenate the resultant binary string** **** to **resultstr.** * Convert **resultstr** to integer(which removes leading zeros). * Return **resultstr.** Below is the implementation of above approach. ## Python3 __ __ __ __ __ __ __ # function which converts decimal to binary def decToBin(num): # Using default binary conversion functions binary = bin(num) # removing first two character as the # result is always in the form 0bXXXXXXX # by taking characters after index 2 binary = binary[2:] return binary # function to convert base4 to bianry def convert(num): # Taking a empty string resultstr = "" # converting number to string numstring = str(num) # Traversing string for i in numstring: # converting this character to integer i = int(i) # if i is 1 or 0 then add '0' to result # string if(i == 1 or i == 0): resultstr = resultstr+'0' # passing this integer to get converted to # binary binary = decToBin(i) # print(binary) # Concatenating this binary string to result # string resultstr = resultstr+binary # Converting resultstr to integer resultstr = int(resultstr) # Return result string return resultstr # Driver code Number = 11002233 # Passing this number to convert function print(convert(Number)) --- __ __ **Output:** 101000010101111 Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
7d6d642095b3e4a7d7b59f1f80bffd6fa3e5c866
lordbeerus0505/xero
/lib/yellowant_command_center/unix_epoch_time.py
310
3.671875
4
import datetime import calendar def convert_to_epoch(date): #date format=MM/DD/YYYY day=int(date[3:5]) month=int(date[0:2]) year=int(date[6:10]) time=datetime.datetime(year,month,day,0,0) time=calendar.timegm(time.timetuple()) return time #print(convert_to_epoch("04/01/2012"))
0291913d9ba3adb5fd713abf20e0b18b0ebcf0fb
KistVictor/exercicios
/exercicios de python/Mundo Python/026.py
271
3.90625
4
frase = input('Digite uma frase: ').lower().strip() print('sua frase possui', frase.count('a'), 'a letra "a"') print('ela aparece, pela primeira vez, na {}° casa'.format(frase.find('a')+1)) print('ela aparece, pela última vez, na {}° casa'.format(frase.rfind('a')+1))
beb3f59c450bd01f1c430746d2e0786877a954a1
Krina666/CST8279_302
/Final302_changqi_Li/Final302_changqi_Li/6.py
804
3.78125
4
gradeDict = {} f = open("final302.csv", "r") while True: line = f.readline() if line == "": break if line.find(" "): pass elif line.find(","): line = line.split(",") #line[0]+line[1] is the concatenation of names, line[5] and line[6] are decimal and letter grades respectively. gradeDict[line[0]+line[1]] = [line[5], line[6]] count = True while count: name = input("please enter the full name of a student without space(i.e. MariaInce) or q to quit:") if name == "q": exit() try: print("The student is: ", name, "; decimal grade is: ", gradeDict[name][0], "; Alphabetical Final grade is: ", gradeDict[name][1]) count = False except KeyError: print("The student is not in the dictionary") f.close()
a985d1439e1f07522b6d141260b8e299278e045b
Kritika05802/DataStructures
/area of circle.py
235
4.21875
4
#!/usr/bin/env python # coding: utf-8 # In[3]: radius = float(input("Enter the radius of the circle: ")) area = 3.14 * (radius) * (radius) print("The area of the circle with radius "+ str(radius) +" is " + str(area)) # In[ ]:
bd6da79fd6732103f3c0b8410f8dfc3ad860cca7
calebjcourtney/adventofcode_2019
/day06/solve.py
974
3.71875
4
import networkx as nx def part_one(input_data): graph_part_one = nx.DiGraph() graph_part_one.add_edges_from(input_data) orbit_count = sum([get_pred_sum(node, graph_part_one) for node in graph_part_one.nodes]) return orbit_count def get_pred_sum(node, graph_part_one): predecessors = list(graph_part_one.predecessors(node)) predecessors_sum = len(predecessors) # recursion actually worked on this problem! return sum([predecessors_sum + get_pred_sum(pred, graph_part_one) for pred in predecessors]) def part_two(input_data): graph_part_two = nx.Graph() graph_part_two.add_edges_from(input_data) path = nx.shortest_path(graph_part_two, 'YOU', 'SAN') return len(path[2:-1]) if __name__ == '__main__': DATA = [[record.split(')')[0], record.split(')')[1]] for record in open('input.txt', 'r').read().split('\n')] print(f"part one solution: {part_one(DATA)}") print(f"part two solution: {part_two(DATA)}")
0d4950fcfb89d01d64575cad02fff950d9a8304e
msanden/contact-list
/run.py
2,897
4.25
4
#!/usr/bin/env python3.6 from contact import Contact def create_contact(fname,lname,phone,email): new_contact = Contact(fname,lname,phone,email) return new_contact def save_contacts(contact): contact.save_contact() def del_contact(contact): contact.delete_contact() def find_contact(number): return Contact.find_by_number(number) def check_existing_contacts(number): return Contact.contact_exists(number) def display_contacts(): return Contact.display_contacts() def copy_clipboard(number): return Contact.copy_email(number) def main(): print('Welcome to your contact list. Enter your name.') userName = input(); print(f"What would you like to do today {userName}?") print('\n') while True: print("""Use this short codes to proceed: cc - create contact, dc - display contacts fc - find a contact ex - exit""") shortCode = input().lower() if shortCode == 'cc': print('New Contact') print('-'*10) print('First Name') fName = input(); print('Last Name') lName = input(); print('Phone Number') phoneNum = input(); print('Email Address') emailAdd = input(); # create and save new contact. save_contacts(create_contact(fName,lName,phoneNum,emailAdd)) print('\n') print(f"New contact {fName} {lName} created") print('\n') elif shortCode == 'dc': if display_contacts(): print("Here is a list of all your contacts") print('\n') for contact in display_contacts(): print(f"""{contact.firstName} {contact.lastName} {contact.phoneNumber} {contact.email}""") print('\n') else: print('\n') print("You don't have any saved contacts.") print('\n') elif shortCode == 'fc': print("Enter the phone number you want to find.") searchNumber = input() if check_existing_contacts(searchNumber): searchContact = find_contact(searchNumber) print(f"Name:{searchContact.firstName} {searchContact.lastName}") print('-'*20) print(f"Phone number:{searchContact.phoneNumber}" ) print(f"Email Address:{searchContact.email}" ) else: print('Contact does not exist. Check the phone number again.') # Task: implement the remaining behaviors : 1. Deleting a contact. 2. Copying a contact email. elif shortCode == 'ex': print('Goodbye!') break else: print("I didn't understand your input. Check you shortcode.") if __name__ == '__main__': main()
d307b4cc643aaedda1bf32b618ff7722ccd0523a
sainihimanshu1999/Data-Structures
/Practice - DS-New/deletemiddle.py
513
3.828125
4
def deleteMid(head): ''' head: head of given linkedList return: head of resultant llist ''' m = middle(head) prev = head curr = head while curr!=None and curr.data!=m: prev = curr curr = curr.next prev.next = curr.next curr = None return head #code here def middle(head): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow.data
48b542d564750b8d38af12e213098ae207b12f00
yzl232/code_training
/mianJing111111/Google/trie/You have a dictionary which is an array of words and array of strings. Write two functions 1. Prepare the array of strings to be searched in the dictionary 2. Check if the string contains all valid words or not..py
1,304
4.15625
4
# encoding=utf-8 ''' You have a dictionary which is an array of words and array of strings. Write two functions 1. Prepare the array of strings to be searched in the dictionary 2. Check if the string contains all valid words or not. 用trie 1 。 make a trie 2 。 trie contains。 1。 这里每个string都自己做一个trie。 2. 每个word都在trie里边。 就是True ''' # F家 #面试者说面试官暗示它用trie... _end = '_end_' class Trie: def __init__(self): self.root = {} def makeTrie(self, words): root = self.root for word in words: self.insert(word) return root def insert(self, word): #这两个函数用的多 cur = self.root for ch in word: if ch not in cur: cur[ch] = {} cur = cur[ch] cur[_end] = _end #end的value可以用来存储东西。。。 def inTrie(self, trie, word): branch = self.retrieveBranch(trie, word) if branch and _end in branch: return True return False def retrieveBranch(self, trie, word):#这两个函数用的多 curDict = trie; result = [] for l in word: if l in curDict: curDict = curDict[l] else: return None return curDict
93451461153185b3134e5a8c62314c70969f0bfc
kashikakhatri08/Python_Poc
/python_poc/python_list_program/list_element_search.py
918
3.890625
4
def user_input(): element = int(input("Enter element you want to search: ")) return element def naive_method(element): list_container = [1,2,3,4,5] for i in range(len(list_container)): if element == list_container[i]: return True def in_method(element): list_container = [1, 2, 3, 4, 5] if element in list_container: return True def main(): list_container = [1, 2, 3, 4, 5] print(list_container) element = user_input() naive_reply = naive_method(element) if naive_reply: print("{} is persent in {}".format(element, list_container)) else: print("{} is not persent in {}".format(element, list_container)) in_reply = in_method(element) if in_reply: print("{} is persent in {}".format(element, list_container)) else: print("{} is not persent in {}".format(element, list_container)) main()
f2e616b3eb26cb190912e9d2a3c4980c478ce584
elu3/Python
/zagadka4cichonia2.py
4,123
3.515625
4
from math import * from string import * def wstaw(tekst, nowe, pozycja): return tekst[:pozycja] + nowe + tekst[pozycja:] def zamien_jeden_znak(text,indeks_znaku, znak): nowy = text[:indeks_znaku] + znak + text[(indeks_znaku+1):] return nowy def znajdz_indeks_nastepnego_miejsca_do_wstawienia_nawiasu_w_dol(wyrazenie, indeks_startowy):#M8 if (indeks_startowy==0): return 0 j = indeks_startowy minieto_prawe = 0 minieto_lewe = 0 operator_odwiedzony = 0; odwiedzone_wyrazenie_nawias = 0 while (j>=0): if ((wyrazenie[j] == ")")or(wyrazenie[j] == "(")): if (wyrazenie[j] == ")"): minieto_prawe = minieto_prawe + 1 if (wyrazenie[j] == "("): minieto_lewe = minieto_lewe + 1 if((minieto_prawe == minieto_lewe)): odwiedzone_wyrazenie_nawias = odwiedzone_wyrazenie_nawias + 1 operator_odwiedzony = 0 if ((wyrazenie[j] == "+")or(wyrazenie[j] == "-")or(wyrazenie[j] == "*")): operator_odwiedzony = operator_odwiedzony+1 if (((minieto_prawe==0)and(minieto_lewe==0))and(operator_odwiedzony >= 2)and(odwiedzone_wyrazenie_nawias==0)): return j; if ((operator_odwiedzony >= 2) and (minieto_prawe == minieto_lewe)and(odwiedzone_wyrazenie_nawias>=1)): if(j!=0): if((wyrazenie[j-1]!="(")and(wyrazenie[j-1]!=")")): return j j=j-1 return 0 def zbuduj_formulke(nawiasy, operatory, liczby):#M6 wyrazenie = "" Nliczb = len(liczby) Nop = Nliczb-1 wyrazenie ="(" + nawiasy[:] i = 0 while (i<Nliczb): if (i == 0): wyrazenie = wyrazenie.replace("(",str(liczby[i]),1) else: wyrazenie = wyrazenie.replace("(",operatory[i-1]+str(liczby[i]),1) i = i+1 i = 0 while (i<len(wyrazenie)): if (wyrazenie[i]==")"): j = i - 1 nastepny_nawias = -1 minieto_prawe = 0 minieto_lewe = 0 while (j>=0): if ((wyrazenie[j] == "+")or(wyrazenie[j] == "-")or(wyrazenie[j] == "*")or(wyrazenie[i]==")")or(wyrazenie[i]=="(")): nastepny_nawias = znajdz_indeks_nastepnego_miejsca_do_wstawienia_nawiasu_w_dol(wyrazenie, j)#M7 if (nastepny_nawias != 0): wyrazenie = wstaw(wyrazenie,"(",nastepny_nawias+1) else: wyrazenie = wstaw(wyrazenie,"(",nastepny_nawias) i=i+1 break j = j-1 i = i+1 return wyrazenie ilosc_kombinacji = 0 ilosc_rozwiazan = 0 def licz_wyrazenie(y,liczby,operatory,nawiasy,level_op,naw_pozycja,naw_otwarty,naw_zamkniety): Nliczb = len(liczby) Nop = Nliczb - 1 global ilosc_kombinacji global ilosc_rozwiazan if(level_op==1): if (naw_zamkniety==Nop): # "()(())", "+-*" , [1,2,3,4] #M5 wyrazenie = zbuduj_formulke(nawiasy, operatory, liczby) wynik = eval(wyrazenie) if(wynik==y): ilosc_rozwiazan = ilosc_rozwiazan + 1 #M9 ilosc_kombinacji=ilosc_kombinacji+1 return 0 else: if (naw_otwarty>naw_zamkniety): nawiasy = zamien_jeden_znak(nawiasy,naw_pozycja, ")") licz_wyrazenie(y,liczby,operatory,nawiasy,level_op,naw_pozycja+1,naw_otwarty,naw_zamkniety+1) if (naw_otwarty<Nop): nawiasy = zamien_jeden_znak(nawiasy,naw_pozycja, "(") licz_wyrazenie(y,liczby,operatory,nawiasy,level_op,naw_pozycja+1,naw_otwarty+1,naw_zamkniety) else: #M4 operatory_nowe_plus = operatory + "+" licz_wyrazenie(y,liczby,operatory_nowe_plus,nawiasy,level_op-1,naw_pozycja,naw_otwarty,naw_zamkniety) operatory_nowe_minus = operatory + "-" licz_wyrazenie(y,liczby,operatory_nowe_minus,nawiasy,level_op-1,naw_pozycja,naw_otwarty,naw_zamkniety) operatory_nowe_mnoz = operatory + "*" licz_wyrazenie(y,liczby,operatory_nowe_mnoz,nawiasy,level_op-1,naw_pozycja,naw_otwarty,naw_zamkniety) return 0 def zagadka(liczby,y): Nliczb = len(liczby) Nop = Nliczb - 1 nawiasy = "" global ilosc_kombinacji global ilosc_rozwiazan for x in range(0,2*Nop): nawiasy = nawiasy + " " operatory = "" print("Znalezione rozwiazania zagadki dla liczb " + str(liczby)+" = " + str(y) + " to: ") licz_wyrazenie(y,liczby,operatory,nawiasy,Nliczb,0,0,0) #M2 print("Przeszukano do tego celu "+str(ilosc_kombinacji)+" kombinacji, znaleziono "+str(ilosc_rozwiazan)+" rozwiazan") ilosc_kombinacji=0 ilosc_rozwiazan =0 print(" ") return 0 zagadka([1,2,3,4],0) #M1
eeea48990dde4cc9268d1c30543e72eb1655fb51
NorCalVictoria/assess-2-hb-OO
/assessment.py
2,897
4.8125
5
""" Part 1: Discussion 1. What are the three main design advantages that object orientation can provide? Explain each concept. close to --- Easier debugging --- Reuse of code (inheritance) --- Flexibility --- data lives close to it's functionality : you don't need to know info a method uses: Easy to make different interchangeable types of animals . 2. What is a class? --- All code iplemented using a special construct 3. What is a method? --- a function that takes a class instance as it's first parameter 4. What is an instance in object orientation? --- an object that was built from a class 5. How is a class attribute different than an instance attribute? --- Class attributes are owned by the class itself . instance attributes belong to the instance and are unique Give an example of when you might use each. --- Class attributes when you have many objects that share the same traits --- instance attribute when you want to override the parent class """ # Part 2: Road Class # ############################################################################# # Create your Road class here class Road: def __init__(self, num_lanes, speed_limit): self.num_lanes = 2 self.speed_limit = 25 # Instantiate Road objects here road_1 = Road () road_1.num_lanes = 2 road_1.speed_limit = 25 road_2 = Road() road_2.num_lanes = 4 road_2.num_lanes = 60 #print(road_2.numlanes) #print(road_1.speed_limit) # Part 3: Update Password # ############################################################################# class User(object): """A user object.""" def __init__(self, username, password): self.username = username self.password = password # write the update_password method here def update_password(self,username,password): if self.password == password: self.password = new_password else: print('Invalid password') # Part 4: Build a Library # ############################################################################# class Book(object): """A Book object.""" def __init__(self, title, author): self.title = title self.author = author # Create your Library class here class Library(self, title, author): def __init__() books = [] # :'-( # Part 5: Rectangles # ############################################################################# class Rectangle(object): """A rectangle object.""" def __init__(self, length, width): self.length = float(length) self.width = float(width) def calculate_area(self): """Return the rectangle's area (length * width).""" return self.length * self.width # Create the Square class here class Square(object): def __init__(self,x): self.x = x self.y = x
e19a697898e3a79540a6bde4c19907325088981e
awerar/AI-Draughts
/Bot.py
6,181
3.59375
4
import time from cmath import inf from typing import List from Piece import Piece from Position import Position from Board import Board class BestBot: def make_move(self, board: Board) -> List[type(Position)]: start_time = time.time() best_move = [] for depth in range(1, 100): best_move = self.get_best_move(board, depth) if time.time() >= start_time + 1: break return best_move def get_best_move(self, board: Board, depth): best_score = -inf best_move = [] for move in self.get_possible_moves(board): new_board = board.make_move(move) new_score = -self.evaluate_board(new_board, depth - 1, -inf, inf, False) if new_score > best_score or best_score == -inf: best_move = move best_score = new_score return best_move def evaluate_board(self, board: Board, rec_left, best, worst, my_turn): if rec_left <= 0: return self.get_board_score(board) moves = self.get_possible_moves(board) new_boards = [] for move in moves: #print(board.__str__()) #for p in move: # print(p.__str__(), end=" ") #print() new_board = board.make_move(move) #print(new_board.revert().__str__()) new_boards.append(new_board) new_boards = sorted(new_boards, key=lambda b: -self.get_board_score(b)) best_score = inf if not my_turn else -inf for new_board in new_boards: new_score = -self.evaluate_board(new_board, rec_left - 1, best, worst, not my_turn) if my_turn: best = max(best, new_score) if new_score >= worst: return new_score best_score = max(best_score, new_score) else: worst = min(worst, new_score) if new_score > best: return new_score best_score = min(best_score, new_score) return best_score def get_board_score(self, board: Board): if board.white_lost(): return -inf score = 0.0 score += len(board.whites) * 2 score -= len(board.blacks) * 2 for p in board.blacks: if p.king: score -= 5 for p in board.whites: if p.king: score += 6 else: for xd in [-1, 1]: cap_pos = p.position().add(-1, xd) if not board.on_board(cap_pos) or not board.isEmpty(cap_pos): score += 0.75 return score def get_possible_moves(self, board: Board): moves = [] for piece in board.whites: man_func = self.get_moves_man if not board.capture_possible() else self.get_captures_man king_func = self.get_moves_king if not board.capture_possible() else self.get_captures_king move_func = king_func if piece.king else man_func moves.extend(move_func(piece.position(), board)) return moves def get_moves_king(self, pos: Position, board: Board): for xd in [-1, 1]: for yd in [-1, 1]: for i in range(1, 10): new_pos = pos.add(yd * i, xd * i) if board.on_board(new_pos) and board.isEmpty(new_pos): yield [pos, new_pos] else: break def get_moves_man(self, pos: Position, board: Board): for xd in [-1, 1]: new_pos = pos.add(1, xd) if board.on_board(new_pos) and board.isEmpty(new_pos): yield [pos, new_pos] def get_captures_king(self, pos: Position, board: Board, banned_dx=0, banned_dy=0, first=True): for xd in [-1, 1]: for yd in [-1, 1]: if (xd == banned_dx and yd == banned_dy) or (-xd == banned_dx and -yd == banned_dy): continue for i in range(1, 10): new_pos = pos.add(yd * i, xd * i) if not board.on_board(new_pos): break if board.isBlack(new_pos): after_kill_pos = new_pos.add(yd, xd) if board.on_board(after_kill_pos) and board.isEmpty(after_kill_pos): yield [pos, after_kill_pos] for k in range(1, 10): slide_pos = after_kill_pos.add(yd * k, xd * k) if not board.on_board(slide_pos) or not board.isEmpty(slide_pos): break yield [pos, slide_pos] new_board = board.make_single_move(pos, after_kill_pos, True, first) tails = self.get_captures_king(after_kill_pos, new_board, xd, yd, False) for tail in tails: move = [pos] move.extend(tail) yield move if not board.isEmpty(new_pos): break def get_captures_man(self, pos: Position, board: Board, first=True): for yd in [-1, 1]: if yd == -1 and first: continue for xd in [-1, 1]: kill_pos = pos.add(yd, xd) if not board.on_board(kill_pos) or not board.isBlack(kill_pos): continue after_kill_pos = kill_pos.add(yd, xd) if not board.on_board(after_kill_pos) or not board.isEmpty(after_kill_pos): continue yield [pos, after_kill_pos] new_board = board.make_single_move(pos, after_kill_pos, True, first) tails = self.get_captures_man(after_kill_pos, new_board, False) for tail in tails: move = [pos] move.extend(tail) yield move
c5421c1a0a437377c3f6506d5e2f6a9ba71e53f9
santhosh-kumar/AlgorithmsAndDataStructures
/python/test/unit/problems/binary_tree/test_check_array_is_preorder_bst.py
1,088
3.71875
4
""" Unit Test for convert_sorted_array_to_bst """ from unittest import TestCase from problems.binary_tree.check_array_is_preorder_bst import CheckArrayIsPreOrderBST class TestCheckArrayIsPreOrderBST(TestCase): """ Unit test for CheckArrayIsPreOrderBST """ def test_solve(self): """Test solve Args: self: TestCheckArrayIsPreOrderBST Returns: None Raises: None """ # Given input_list = [5, 3, 2, 4, 7, 6, 8] array_preorder_bst_problem = CheckArrayIsPreOrderBST(input_list) # When self.assertTrue(array_preorder_bst_problem.solve()) def test_solve_invalid(self): """Test solve (invalid) Args: self: TestCheckArrayIsPreOrderBST Returns: None Raises: None """ # Given input_list = [5, 6, 2, 4, 7, 6, 8] array_preorder_bst_problem = CheckArrayIsPreOrderBST(input_list) # When self.assertFalse(array_preorder_bst_problem.solve())
d7018067dba35584a7714b1455625bcb9551b818
SuryaNMenon/Python
/Dictionaries/maxValue.py
276
4.1875
4
userdict = {} for iter in range(int(input("Enter the number of key value pairs: "))): userdict[input("Enter a key: ")] = input("Enter a value: ") print(userdict) maxvalue = max(userdict.values()) for k,v in userdict.items(): if v == maxvalue: print("Max value is", v)
d1b153523fd7a6a17f47d19e7377558253944bb5
crp3/python-practice
/algorithms/byte-by-byte/zero_matrix.py
1,234
3.859375
4
def zero_matrix(matrix): zero_first_column = False zero_first_row = False for i, row in enumerate(matrix): for j, item in enumerate(row): if item: matrix[0][j] = True matrix[i][0] = True if i == 0: zero_first_row = True if j == 0: zero_first_column = True for i, row in enumerate(matrix): if row[0] and i != 0: zero_row(matrix, i) for j, item in enumerate(matrix[0]): if item and j != 0: zero_column(matrix, j) if zero_first_column: zero_column(matrix, 0) if zero_first_row: zero_row(matrix, 0) def zero_column(matrix, column): for i in range(len(matrix)): matrix[i][column] = True def zero_row(matrix, row): for i in range(len(matrix[row])): matrix[row][i] = True sample_matrix = [ [True, False, False], [False, False, False], [False, False, False] ] second_matrix = [ [False, False, False], [False, True, False], [False, False, True] ] def print_matrix(matrix): for row in matrix: print(row) if __name__ == '__main__': zero_matrix(second_matrix) print_matrix(second_matrix)
05cc96906224cfdfd4bc169098a643850f604436
kontai/python
/條件控制語句/for/search.py
161
3.71875
4
items=["aaa",111,(4,5),2.01] tests=[(4,5),3.14] for key in tests: if key in items: print(key,"was found") else: print(key,"not found!")
4fdde698686bf135c708a27d6a0c3220420d1a08
fcunhaneto-test/pyalgorithms
/trees_udemy/binarytree.py
914
3.90625
4
#!/home/francisco/.pyvenv/mypython3/bin/python3 # -*- coding: utf-8 -*- class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self): self.root = None def insert(self, value, node): if not self.root: self.root = Node(value) return else: node = Node(value) current = self.root def walk(self, node=None, flag=True): if not node and flag: node = self.root if node: flag = False self.walk(node.left, flag) print(node.value) self.walk(node.right, flag) if __name__ == '__main__': bt = BinaryTree() bt.insert(11) bt.insert(2) bt.insert(14) bt.insert(1) bt.insert(7) bt.insert(15) bt.insert(5) bt.insert(8) bt.walk()
04b6a28fd65d08117ca6a15d0e502afedfb9231b
njones777/school_programs
/point.py
1,298
4.1875
4
import math # the 2D point class class Point: #class constructor with default values set at 0 def __init__(self, x=0, y=0): self.x = float(x) self.y = float(y) #acessor @property def x(self): return self._x #mutator @x.setter def x(self, value): self._x = value #acessor @property def y(self): return self._y #mutator @y.setter def y(self, value): self._y = value #class method to calculate midpoint def midpt(set1, set2): #get necessary point data for calculations x1, x2 = set1.x, set2.x y1, y2 = set1.y, set2.y #algorithm for the midpoint coordinates midpointX, midpointY = (((x1 + x2) / 2), ((y1 + y2) / 2)) #creating new Point object to in order for new object to use further distance method new_obj = Point(midpointX, midpointY) return new_obj #class method to calculate distance between two points def dist(set1, set2): #get necessary point data for calculations x1, x2 = set1.x, set2.x y1, y2 = set1.y, set2.y #algorithm for distance between two points partx = ((x2-x1)**2) party = ((y2-y1)**2) to_be_squared = partx + party distance = math.sqrt(to_be_squared) return distance #magic function to dictate how the object will be printed out def __str__(self): return(" ({},{})".format(self.x, self.y))
e67f5fcf171e240db968a82cfea7b892f7765bea
luogao/python-learning
/py_parameter.py
3,436
4.0625
4
##函数的参数 #位置参数 def power(x,n=2): #默认为计算平方 s = 1 while n>0: n = n-1 s = s * x return s print(power(3,3)) print(power(5)) ### 定义默认参数要牢记一点:默认参数必须指向不变对象! def add_end(L=None): if L is None: L = [] L.append('END') return L print(add_end()) def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum print(calc(1, 2, 3)) nums = [1, 2, 3] print(calc(*nums)) ##*nums表示把nums这个list的所有元素作为可变参数传进去 def person(name, age, **kw): print('name:', name, 'age:', age, 'other:', kw) person('Bob', 35, city='Beijing') extra = {'city': 'Beijing', 'job': 'Engineer'} person('Jack', 24, **extra) ##**extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数,kw将获得一个dict,注意kw获得的dict是extra的一份拷贝,对kw的改动不会影响到函数外的extra def person1(name, age, **kw): if 'city' in kw: # 有city参数 pass if 'job' in kw: # 有job参数 pass print('name:', name, 'age:', age, 'other:', kw) person('Jack', 24, city='Beijing', addr='Chaoyang', zipcode=123456) def person2(name, age, *, city='Beijing', job): print(name, age, city, job) person2('Jack', 24, job='Engineer') def product(*args): if not args == (): result = 1 for n in args: result = result * n return result else: raise TypeError('none args gievn') # 测试 print('product(5) =', product(5)) print('product(5, 6) =', product(5, 6)) print('product(5, 6, 7) =', product(5, 6, 7)) print('product(5, 6, 7, 9) =', product(5, 6, 7, 9)) if product(5) != 5: print('测试失败!') elif product(5, 6) != 30: print('测试失败!') elif product(5, 6, 7) != 210: print('测试失败!') elif product(5, 6, 7, 9) != 1890: print('测试失败!') else: try: product() print('测试失败!') except TypeError: print('测试成功!') ####################################################################################################### # 小结 # Python的函数具有非常灵活的参数形态,既可以实现简单的调用,又可以传入非常复杂的参数。 # # 默认参数一定要用不可变对象,如果是可变对象,程序运行时会有逻辑错误! # # 要注意定义可变参数和关键字参数的语法: # # *args是可变参数,args接收的是一个tuple; # # **kw是关键字参数,kw接收的是一个dict。 # # 以及调用函数时如何传入可变参数和关键字参数的语法: # # 可变参数既可以直接传入:func(1, 2, 3),又可以先组装list或tuple,再通过*args传入:func(*(1, 2, 3)); # # 关键字参数既可以直接传入:func(a=1, b=2),又可以先组装dict,再通过**kw传入:func(**{'a': 1, 'b': 2})。 # # 使用*args和**kw是Python的习惯写法,当然也可以用其他参数名,但最好使用习惯用法。 # # 命名的关键字参数是为了限制调用者可以传入的参数名,同时可以提供默认值。 # # 定义命名的关键字参数在没有可变参数的情况下不要忘了写分隔符*,否则定义的将是位置参数。 #######################################################################################################
123e40b4251007a3419f4b2a266534993efbb22f
ZCW-Data1dot2/python-12-Anujangalapalli
/viva_comprehensions.py
867
3.578125
4
from typing import List, Dict, Set, Callable import enum class Parity(enum.Enum): ODD = 0 EVEN = 1 def gen_list(start: int, stop: int, parity: Parity) -> list: """ Generate a list :param start: :param stop: :param parity: :return: """ if parity == Parity.EVEN: return [val for val in range(start, stop) if val % 2 == 0] else: return [val for val in range(start, stop) if val % 2 != 0] def gen_dict(start: int, stop: int, strategy: Callable) -> Dict: """ Generate a dictionary :param start: :param stop: :param strategy: :return: """ return {i: strategy(i) for i in range(start, stop)} def gen_set(val_in: str) -> Set: """ Generate a set :param val_in: :return: """ return set(char for char in val_in.swapcase() if char.isupper())
f59305c3ca4b09b7306a571e25f4a83e4383d861
IanFroning/metropolis-ising-model
/Metropolis.py
2,096
3.96875
4
""" File: Metropolis.py Metropolis algorithm outlined by Hjorth-Jensen in "Computational Physics" 1. Compute energy of initial state 2. Flip a spin at random 3. Compute energy of new state 4. Accept change if energy is lowered 5. If energy is increased, calculate Boltzman factor 6. Compare BF with ranndom number; if the random number is lower, accept the change 7. Repeat for all latice sites 8. Update expectation value of magnetization 9. Divide by number of cycles and number of spins All energies are expressed in units of J Programmer: Ian Froning (froning.10@osu.edu) """ import random import math from Hamiltonian import Hamiltonian def metropolis( hamiltonian, kt, cycles ): """ runs the Metropolis algorithm on a given hamiltonian at a given temperature, for a given number of cycles """ magnetizationSum = hamiltonian.getMagnetization() for i in range(1, cycles): for j in range(1, hamiltonian.getLength()): # 1. Compute energy of initial state oldEnergy = hamiltonian.getEnergy() # 2. Flip a spin at random spinToFlip = random.randint(0, hamiltonian.getLength()-1) hamiltonian.flipSpin( spinToFlip ) # 3. Compute energy of new state newEnergy = hamiltonian.getEnergy() # 4. Accept change if energy is lowered # 5. If energy is increased, calculate Boltzman factor # 6. Compare BF with ranndom number; if the random number is # lower, accept the change if newEnergy > oldEnergy: boltzmanFactor = math.exp( -(newEnergy - oldEnergy) / kt ) if boltzmanFactor < random.uniform(0, 1): hamiltonian.flipSpin( spinToFlip ) # 7. Repeat for all latice sites # 8. Update expectation value of magnetization magnetizationSum += hamiltonian.getMagnetization() # 9. Divide by number of cycles magnetization = float( magnetizationSum ) / cycles / hamiltonian.getLength() return magnetization
8ee7a856f08d854cea0d6c0702988783180f7466
muhammad-masood-ur-rehman/Skillrack
/Python Programs/two-policemen-catching-a-thief.py
1,256
4.15625
4
Two Policemen Catching a Thief Policeman1 and Policeman2 along with a thief are standing on X-axis. The integral value of their location on the X-axis is passed as the input. Both the policemen run at the same speed and they start running at the same time to catch the thief. · The program must print Police1 if Policeman1 will catch the thief first. · The program must print Police2 if Policeman2 will catch the thief first. · The program must print Both if Policeman1 and Policeman2 will reach the thief at the same time. Input Format: The first line will contain the value of N which represents the number of test cases to be passed as the input. Next N lines will contain the integral location of Policeman1, Policeman2 and the thief each separated by a space. Output Format: The first line will contain one of the following values - Police1, Police2, Both Constraints: 1 <= N <= 20 Example Input/Output 1: Input: 3 1 2 3 1 3 2 2 1 3 Output: Police2 Both Police1 Example Input/Output 2: Input: 2 -2 2 0 10 5 -1 Output: Both Police2 n=int(input()) for i in range(n): a,b,c=[int(j)for j in input().split()] if abs(a-c)==abs(b-c): print("Both") elif abs(a-c)<abs(b-c): print("Police1") else: print("Police2")
d2936efa49713b66d319425e7b1f8621f70eda3d
mollycaffery10/pythonschool
/Final Project Draft.py
8,092
3.640625
4
import winsound import urllib import webbrowser startQuestion = input('Would you like to learn about France? y/n') true = 'y' if startQuestion == true: print("OK!") winsound.PlaySound('Für Elise (Piano version) (1).wav', winsound.SND_FILENAME|winsound.SND_ASYNC ) historyQuestion = input("Would you like to hear a breif history about the French Revolution? y/n") true = 'y' if historyQuestion == true: print("_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _") print ("It all began in the year 1789, when the Revolution overthrew the monarchy") print("--------------------------------------------------------------------------") print(" _ ") print(" | | ") print(" _ __ ___ ___ _ __ __ _ _ __ ___| |__ _ _") print("| '_ ` _ \ / _ \| '_ \ / _` | '__/ __| '_ \| | | |") print("| | | | | | (_) | | | | (_| | | | (__| | | | |_| |") print("|_| |_| |_|\___/|_| |_|\__,_|_| \___|_| |_|\__, |") print(" __/ |") print(" |___/ ") historyQuestion2 = input("Continue? y/n") if historyQuestion2 == 'y': print("Then the country began to face violent periods of political turmoil") print(" \ ___/________") print(" ___ ) , @ / \ \"") print(" @___, \ / @__\ /\ @___/ \@/") print(" /\__, | /\_, \/ / /\__/ |") print(" / \ / @\ / \ ( / \ / / \ ") print("_/__|___/___/_______________/__|____\_____________/__/__________|__\__") print("and then Napoleon took over as the new leader of France...") print(" ________") print(" / \'") print(" __/ (o)\_") print(" / ______\\ \'") print(" |____/__ __\____|") print(" [ --~~-- ]") print(" |( L )| ") print(" ___----\ __ /----_") print(" / | < \____/ > | \'") print(" / | < \--/ > | \'") print(" |||||| \ \/ / ||||||") print(" | \ / o |") print(" | | \/ === | |") print(" | | |o ||| | |") print(" | \______| +#* | |") print(" | |o | | Napoleon Bonaparte, (1769-1821).") print(" \ | / /") print(" |\__________|o / /") print(" | | / /") continueQuestion = input("Would you like to play an interactive version of the history of the French Revolution? y/n") if continueQuestion == 'y': name = input("what is your name?") joinQuestion = input(name + ", there is a secret group trying to overthrow the monarchy. Do you want to join in?!! y/n") if joinQuestion == 'y': print("One day as " + name + " is walking there is a violent protest that erupts in the town square!") violentRevolt = input("Join in the violent protest or flee and go back home? y for join/ n for flee") if violentRevolt == 'n': print("You flee back home to saftey") print(" []___") print(" / /\'") print("/____/__\'") print("|[][]||||") print("|____ |_|") print(" ") writeQuestion = input(name + " you get the oppertunity to write an article to be published anonymously in favor of the revolt, will you do it? y/n ") if writeQuestion == 'y': print("(\ ") print("\'\ ") print(" \'\ __________ ") print(" / '| ()_________)") print(" \ '/ \ ~~~~~~ \'") print(" \ \ ~~~~~~ \'") print(" ==). \__________\'") print(" (__) ()__________)") print("Congratulations! " + name + " you have helped fund the revolt") print("Now the monarchy has been overthrown!") print("╔═══╗─────────────╔╗───╔╗───╔╗") print("║╔═╗║────────────╔╝╚╗──║║──╔╝╚╗") print("║║─╚╬══╦═╗╔══╦═╦═╩╗╔╬╗╔╣║╔═╩╗╔╬╦══╦═╗╔══╗") print("║║─╔╣╔╗║╔╗╣╔╗║╔╣╔╗║║║║║║║║╔╗║║╠╣╔╗║╔╗╣══╣") print("║╚═╝║╚╝║║║║╚╝║║║╔╗║╚╣╚╝║╚╣╔╗║╚╣║╚╝║║║╠══║") print("╚═══╩══╩╝╚╩═╗╠╝╚╝╚╩═╩══╩═╩╝╚╩═╩╩══╩╝╚╩══╝") print("──────────╔═╝║") webpageQuestion = input(name + "would you like to visit France?! y/n") if webpageQuestion == 'y': webbrowser.open('https://www.france.com/') else: print("You have been arrested for being apart of the violent revolt!") print("┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼") print("███▀▀▀██┼███▀▀▀███┼███▀█▄█▀███┼██▀▀▀") print("██┼┼┼┼██┼██┼┼┼┼┼██┼██┼┼┼█┼┼┼██┼██┼┼┼") print("██┼┼┼▄▄▄┼██▄▄▄▄▄██┼██┼┼┼▀┼┼┼██┼██▀▀▀") print("██┼┼┼┼██┼██┼┼┼┼┼██┼██┼┼┼┼┼┼┼██┼██┼┼┼") print("███▄▄▄██┼██┼┼┼┼┼██┼██┼┼┼┼┼┼┼██┼██▄▄▄") print("┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼") print("███▀▀▀███┼▀███┼┼██▀┼██▀▀▀┼██▀▀▀▀██▄┼") print("██┼┼┼┼┼██┼┼┼██┼┼██┼┼██┼┼┼┼██┼┼┼┼┼██┼") print("██┼┼┼┼┼██┼┼┼██┼┼██┼┼██▀▀▀┼██▄▄▄▄▄▀▀┼") print("██┼┼┼┼┼██┼┼┼██┼┼█▀┼┼██┼┼┼┼██┼┼┼┼┼██┼") print("███▄▄▄███┼┼┼─▀█▀┼┼─┼██▄▄▄┼██┼┼┼┼┼██▄") else: print("You should :(") quit()
5f7b088cb80169166031d06807ffb01c77105411
developer73/cglife
/cglife/input.py
476
3.734375
4
def read_from_file(filename): """ Reads text file <filename> and returns it's content. content of the file: test 123 abc 456 end output: ['test 123\n', 'abc 456\n', 'end\n'] """ f = open(filename, 'r') lines = f.readlines() f.close() return lines def get_data(path="data/rectangle.txt"): m = read_from_file(path) # remove new line characters m = [item.rstrip('\n') for item in m] return m
9b415bee3e176464c403e8fedc7519ccbfbf9258
geo-wurth/URI
/Python/1051 - Imposto de Renda.py
667
4.03125
4
x = float(input()) if (x <= 2000): print("Isento") elif (2000 < x <= 3000): x = x - 2000 imposto = x * 0.08 print("R$ %.2f"%imposto) elif (3000 < x <= 4500): x = x - 2000 imposto = 999.99 * 0.08 x = x - 999.99 imposto = imposto + (x * 0.18) print("R$ %.2f"%imposto) elif (3000 < x <= 4500): x = x - 2000 imposto = 999.99 * 0.08 x = x - 999.99 imposto = imposto + (x * 0.18) print("R$ %.2f"%imposto) else: x = x - 2000 imposto = 1000 * 0.08 x = x - 1000 imposto = imposto + (1500 * 0.18) x = x - 1500 imposto = imposto + (x * 0.28) print("R$ %.2f"%imposto)
f35f444d47e078374dc8237ffce3308cba09b9ef
AlexeevAlexey/ProgiSPBD
/Laba3/Lessons 3.py
261
3.609375
4
a =[int(i) for i in input("введите числа через пробел ").split()] n=int(input("В какую степень вы хотите возвести числа? ")) for i in range(len(a)): a[i]=a[i]**n print("Ваши числа-",a)
0ec6d9d750e511a75c2eb69da0089c8035341f8b
brothenhaeusler/connect_four
/src/four_wins_functions_functional.py
10,551
4.15625
4
#! /usr/local/opt/python/bin/python3.8 import numpy as np import random import re def create_board(rows, columns): board = np.zeros((rows,columns),dtype=np.int8) return board def one_to_zero_indexing(number): return number-1 # does_column_has_space checks whether a stone can still be inserted in certain column (columns fill up) def does_column_has_space(board, current_player_input_column): # user indexing to 0-indexing of matrices selected_column=one_to_zero_indexing(current_player_input_column) selected_column_array = board[:,selected_column] #np.any works on bool arrays if np.any(selected_column_array == 0): return True else: return False # essentially gives back the transformed 2D board (with the inserted value) in the form of a 1D array. # functional! Unfortunately not KISS def give_recursively_back_one_d_array_with_one_replaced_number(board, one_d_array, current_row, current_column, rows, columns, insert_row_0_indexed, insert_column_0_indexed, to_be_inserted): # fundamental decision: what gets inserted into the new _to be array new_one_d_array? if current_column == insert_column_0_indexed and current_row == insert_row_0_indexed: #push on a new number new_one_d_array=np.append(one_d_array, to_be_inserted) else: #push on a new number new_one_d_array=np.append(one_d_array, board[current_row][current_column]) # walking one step further through the board now.. # walked till the end of the row? if current_column + 1 == columns: # are you at the lower end of the matrix? - then you can't walk any further if current_row +1 == rows: return new_one_d_array else: #only set the new variables in calling the new function. Because: functional # go one row down (rows are in the first dimension) return give_recursively_back_one_d_array_with_one_replaced_number(board, new_one_d_array, current_row+1, 0, rows, columns, insert_row_0_indexed, insert_column_0_indexed, to_be_inserted) else: #only set the new variables in calling the new function. Because: functional # just walk down the board one column further return give_recursively_back_one_d_array_with_one_replaced_number(board, new_one_d_array, current_row, current_column + 1, rows, columns, insert_row_0_indexed, insert_column_0_indexed, to_be_inserted) # Preparation and postpreparation function for give_recursively_back_one_d_array_with_one_replaced_number(..) # functional! # essentially returns a new 2D board with to_be_inserted at the right place for the (old board and the indexes and the to_be_inserted) def give_back_new_board_with_one_replaced_number(board, insert_row_0_indexed, insert_column_0_indexed, to_be_inserted): rows=board.shape[0] columns=board.shape[1] # trick: 2D to 1D in order to get functional one_d_array=np.zeros(0, dtype=np.int8) # we need to call the recursive function with the walking variable current_column (instantiated with 0) # as well as a one_d_array --- a 1D data structure that allows push and pop (in contrast to 2D data structures) new_one_d_array=give_recursively_back_one_d_array_with_one_replaced_number(board, one_d_array, 0, 0, rows, columns, insert_row_0_indexed, insert_column_0_indexed, to_be_inserted) return new_one_d_array.reshape(board.shape[0], board.shape[1]) # 3 values are possible on the board / matrix: # 0 - nothing played here yet # 1 - Player 1 has set a stone here # 2 - Player 2 has set a stone here def insert_stone(board, current_player_input_column, current_player): # user indexing to 0-indexing of matrices selected_column_zero_indexed=one_to_zero_indexing(current_player_input_column) #slice out the column array selected_column_array = board[:,selected_column_zero_indexed] #find empty slot empty_slot_zero_indexed = np.max(np.where(selected_column_array == 0)) # functional! - analogue to board[empty_slot_zero_indexed][selected_column_zero_indexed]=current_player # I tend to say: this is not KISS! return give_back_new_board_with_one_replaced_number(board, empty_slot_zero_indexed, selected_column_zero_indexed, current_player) #recursion without using mutable variables: def check_whether_game_definitely_undecided(board_slice): #extract all zeros from the first row if board_slice.ndim == 2: zero_array= list(filter(lambda x : x ==0, board_slice[0])) #last slice returns a 1D array elif board_slice.ndim == 1: zero_array= list(filter(lambda x : x ==0, board_slice)) if len(zero_array) == 0: #exit condition for recursion - the board has fully been walked through if len(board_slice[:,1]) == 1: print('board is definitely undecided') return True else: #recursion with a smaller board return check_whether_game_definitely_undecided(board_slice[1:,:]) else: # board has still some 'unplayed' spots return False def are_there_consecutive_four_in_a_line(line): if len(line) >3: #are the first 4 entries the same? and if they are: are they entries of either player 1 or player 2? player_1=1 player_2=2 if line[0] == line[1] and line[1] == line[2] and line[2] == line[3] \ and (line[0] == player_1 or line[0] == player_2): #Congrat messages print() print('------------------------------') if line[0] == player_1: print('Player 1 wins, congrats :)') else: print('Player 2 wins, congrats :)') print('------------------------------') return True else: return are_there_consecutive_four_in_a_line(line[1:]) else: return False # functional! -> recursion def are_there_consecutive_four_horizontally(board_slice): if board_slice.shape[0] > 0: line= list(board_slice[0]) if are_there_consecutive_four_in_a_line(line): return True else: return are_there_consecutive_four_horizontally(board_slice[1:]) else: return False # functional def are_there_consecutive_four_vertically(board): #reuse code: transpose matrix and use the _horizontally function: return are_there_consecutive_four_horizontally(np.transpose(board)) def recursive_diagonal_upper_left_to_lower_right_line_checker(board,i): #abortion, if the diagonal plane is just empty if board.diagonal(i).shape[0]==0: return False else: if are_there_consecutive_four_in_a_line(board.diagonal(i)): return True else: return recursive_diagonal_upper_left_to_lower_right_line_checker(board,i+1) def are_there_four_diagonal_upper_left_to_lower_right(board): # starting point is negative, because we want to s start_int_recursive_line_checker= - len(board[:,0]) + 1 return recursive_diagonal_upper_left_to_lower_right_line_checker(board,start_int_recursive_line_checker) def are_there_four_diagonal_lower_left_to_upper_right(board): #mirroring the board at the horizontal, middle axis, one can use the # are_there_four_diagonal_upper_left_to_lower_right - function # (please visualize it graphically for you) return are_there_four_diagonal_upper_left_to_lower_right(np.flip(board,axis=0)) def is_game_over(board): return are_there_four_diagonal_upper_left_to_lower_right(board) \ or are_there_four_diagonal_lower_left_to_upper_right(board) \ or are_there_consecutive_four_horizontally(board) \ or are_there_consecutive_four_vertically(board) \ or check_whether_game_definitely_undecided(board) def is_current_player_input_legitimate(current_player_input, number_of_columns): #check length, only one character permitted if(len(current_player_input) > 1): return False #check regex: a number between 1 and number_of_columns elif re.match(r'[1-7]', current_player_input): return True else: return False # This is a recursive function that checks whether the game is over and runs a new round of the game if the game is not yet over # Otherwise it prints the winning board def recursive_new_round(board,current_player): if not is_game_over(board): number_of_columns = board.shape[1] print() print("Player", current_player, "\'s turn!") print(board) print("Select a column between", 1, 'and', number_of_columns, " ") #prompt the player to insert column number current_player_input=input("Input: ") if is_current_player_input_legitimate(current_player_input, number_of_columns): #input is legitimate, we interpret it as the intended column of the current player current_player_input_column=int(current_player_input) if does_column_has_space(board, current_player_input_column): new_board=insert_stone(board, current_player_input_column, current_player) # change the current_player if current_player==1: new_current_player=2 else: new_current_player=1 recursive_new_round(new_board,new_current_player) else: print("Column is already full! - Try again inserting into another column!") recursive_new_round(board,current_player) else: print("Input hasn\'t been properly recognized. Try again!") recursive_new_round(board,current_player) else: print("Winning board:") print(board) def execute_game(): # set the board parameters like in the original game with 7 columns and 6 rows number_of_rows=6 number_of_columns=7 #create new board board = create_board(number_of_rows,number_of_columns) #randomly choose the first player to start. There's player 1 and player 2. current_player=random.randint(1, 2) print("Welcome to the game \'Connect Four\'") print("----------------------------------------------------") print("Empty positions on the board are depicted as 0") print("Player 1 positions on the board are depicted as 1") print("Player 2 positions on the board are depicted as 2") print("Have fun!") print() recursive_new_round(board,current_player)
89d827ea5d3898f30ceea668a741c4b943805f0a
cuiboautotest/learnpython3
/16_class/基础/4_添加类属性.py
591
4.15625
4
class Flower(object): height=20#类属性, def __init__(self, name, color,height):#括号里的是实例属性 self.name = name self.color = color # self返回的是类对象本身 self.height = height #实例属性 print(self) print(Flower.height)#类属性是直接绑定在类上的,所以,访问类属性不需要创建实例,就可以直接访问: f=Flower('玫瑰','红色',10) print(f.height)#实例属性优先级高于类属性,所以输出结果是10 del f.height#删除 print(f.height)#删除实例属性自动调用类属性
fed2a10aab2a30d744289836b372ce9599fc4a7b
mkosmala/mtbforecast
/summarize_weather.py
1,513
3.546875
4
#!/usr/bin/env python import sys import csv import pandas # -*- coding: utf-8 -*- """ Created on Thu Jan 11 19:16:06 2018 @author: mkosmala """ if len(sys.argv) < 3 : print ("format: summarize_weather.py <input file> <output file>") exit(1) infilename = sys.argv[1] outfilename = sys.argv[2] # get a weather vector for each date weather = {} with open(infilename,'r') as infile: ireader = csv.reader(infile) # header head = next(ireader) # rows for row in ireader: wdate = row[5] rawdata = row[6:] # convert to numeric data = [] for d in rawdata: try: x = float(d) data.append(x) except: data.append(None) if wdate not in weather: weather[wdate] = [] weather[wdate].append(data) # calculate averages for each date averages = [] for wdate in weather: # list of lists - convert to pandas dataframe ldata = weather[wdate] # calculate average over each column and save to averages mdata = pandas.DataFrame(ldata) means = mdata.mean(axis=0, skipna=True) averages.append([wdate] + means.tolist()) # output with open(outfilename,'w') as outfile: owriter = csv.writer(outfile) # header owriter.writerow(['date'] + head[6:]) # data owriter.writerows(sorted(averages))
e5f5b0492324a16dc393d29a03e620423e278a16
AbdiVicenciodelmoral/linear_regression
/linear_regression.py
3,484
3.6875
4
import numpy as np class LinearRegression_OLS: def __init__(self): self.mean_x = None self.mean_y = None self.var = 0 self.covar = 0 self.m = 0 self.b = 0 self.data_length = None def fit(self,x_Vals,y_Vals): # We need to get the mean of all the x # and y values, respectively. # mean = (sum of all values)/(number of values) self.mean_x = np.mean(x_Vals) self.mean_y = np.mean(y_Vals) # and now need to calculate the variance and covariance # variance = (sum of all x values - mean of x all values)^2)/(number of values) # covariance = (sum of all x values - mean of x all values) (sum of all y values - mean of y all values))/(number of values) # in order to sum all the values of x we need to iterate through # the column containing x. self.data_length = len(x_Vals) for i in range(len(x_Vals)): self.var += (x_Vals[i]-self.mean_x)**2 self.covar += (x_Vals[i]-self.mean_x)*(y_Vals[i]-self.mean_y) # Now we need to estimate the coefficients for the # approximation y = mean of y - m * mean of x self.m = self.covar/self.var self.b = self.mean_y - self.m * self.mean_x return self.m,self.b def predict(self,x,m,b): return np.dot(x,m) + b #Root Mean Square Error (RMSE) is the standard deviation #of the residuals (prediction errors). Residuals are a #measure of how far from the regression line data points #are; RMSE is a measure of how spread out these residuals #are. In other words, it tells you how concentrated the #data is around the line of best fit. def mean_squared_error(self,y, y_pred): return np.mean((y - y_pred)**2) def root_mean_squared_error(self, test_x, test_y): mse = 0 for i in range(self.data_length): pred_y = self.b + self.m* test_x[i] mse += (test_y[i] - pred_y) ** 2 rmse = np.sqrt(mse/self.data_length) return rmse # SST = Total sum of squares # SSR = Total sum of squares of residuals # R² score can measure the accuracy of the linear model # R² = SSR/SST def R_score(self,test_x,test_y): ss = 0 sr = 0 for i in range(self.data_length) : pred_y = self.b + self.m * test_x[i] sr += (test_y[i] - pred_y) **2 ss += (test_y[i] - self.mean_y) ** 2 score = 1 - (sr/ss) class LinearRegression_Gradient_Descent: def __init__(self, learning_rate, n_iters): self.lr = learning_rate self.epochs = n_iters self.m = None self.b = 0 data_length = 0 #Gradient Descent def fit(self, x_Vals, y_Vals): rows, cols = x_Vals.shape self.m = np.zeros(cols) data_length = len(x_Vals) for _ in range(self.epochs): pred_y = np.dot(x_Vals,self.m) + self.b Deriv_m = (-2/data_length) * np.dot(x_Vals.T,(y_Vals - pred_y)) Deriv_b = (-2/data_length) * np.sum( y_Vals - pred_y) self.m = self.m - (self.lr * Deriv_m) self.b = self.b - (self.lr * Deriv_b) return self.m,self.b def mean_squared_error(self,y, y_pred): return np.mean((y - y_pred)**2) def predict(self,x): return np.dot(x,self.m) + self.b
ca76a2fccf6fb982ef0d168e06a5c9f1dffa847f
Ethanpho2002/Classwork
/Python IF statements.py
418
4.0625
4
Question 34 code: a=int(input("Please enter a number:")) if(a%2==0): print("That is an even number") else: print("That is an odd number") Question 35 code: Question 36 code: letter=input("Please enter a letter:") if(letter=='a' or 'e' or 'i' or 'o' or 'u'): print("This is a definitive vowel.") elif(letter=='y'): print("This can be either a vowel or constonant.") Question 37 code:
4bff1518bdeb585ef1b4f65113a8c86ae005605c
kzlamaniec/Python-Beginnings-2018
/02 - 11mandat.py
369
3.65625
4
limit = int(input('Podaj limit prędkości (km/h): ')) speed = int(input('Podaj prędkość pojazdu (km/h): ')) if speed > limit: n = speed - limit # liczba przekroczonej prędkości if n <= 10: money = 5 * n print('Wysokość mandatu (zł): ', money) else: money = 50 + (n-10)*15 print('Wysokość mandatu (zł): ', money)
5e960595973c842dd620517fc84e99d88437ec71
ashushekar/python-advance-samples
/linkedin/2.mergelinkedlist.py
1,761
4.0625
4
class Node: def __init__(self, dataval=None): self.dataval = dataval self.nextval = None class SLinkedList: def __init__(self): self.headval = None def listprint(self): printval = self.headval while printval is not None: print(printval.dataval, end='-->') printval = printval.nextval def insertAtbeginning(self, new_element): newnode = Node(new_element) newnode.nextval = self.headval self.headval = newnode # def insertatEnd(self, new_element): # new_node = Node(new_element) # traverse = self.headval # if traverse is None: # return new_node # while traverse.nextval: # traverse = traverse.nextval # traverse.nextval = new_node # # def insertatMiddle(self, middlenode, new_element): # new_node = Node(new_element) # traverse = self.headval # if traverse is None: # return new_node # temp = middlenode.nextval # middlenode.nextval = new_node # new_node.nextval = temp list1 = SLinkedList() list1.headval = Node('Monday') e2 = Node('Tuesday') e3 = Node('Wednesday') list1.headval.nextval = e2 e2.nextval = e3 print("\n\nTraversing a Linked List:") list1.listprint() print("\n\nInserting at the Beginning of the Linked List:") list1.insertAtbeginning('Sunday') list1.listprint() list2 = SLinkedList() list2.headval = Node('January') list2.insertAtbeginning('February') list2.listprint() # print("\n\nInserting at the End of the Linked List:") # list1.insertatEnd('Thursday') # list1.listprint() # # print("\n\nInserting in between two Data Nodes: ") # list1.insertatMiddle(e2, 'between') # list1.listprint()
0685e903b9dae8e8ce3596376ce5e315c8a444fe
LogonDev/Intro_to_the_Math_of_intelligence
/gradientDescent.py
1,964
3.59375
4
from numpy import * ''' Computes the error for a linear graph y = mx + b m = gradient b = y-intercept N = number of points Error for individual point(x,y) = (y - (mx+b))^2 Error for all points = 1/N * Sum(Error for individual points) ''' def computeError(b, m, points): totalError = 0 #For each point for i in range(0, len(points)): x = points[i, 0] y = points[i, 1] totalError += (y - (m * x + b)) ** 2 return totalError / float(len(points)) ''' Calculates the partial derivative with respect to m m = gradient b = y-intercept N = number of points individual point caclulation(x,y) = -x(y - (mx + b)) derivative = 2/N * sum(individual point calculation) ''' def computePartialDerivativeM(b, m, points): N = float(len(points)) derivativeM = 0 #For each point for i in range(0, len(points)): x = points[i, 0] y = points[i, 1] derivativeM += (x * (y - (m * x + b) )) return (-2/N) * derivativeM ''' Calculates the partial derivative with respect to m m = gradient b = y-intercept N = number of points individual point caclulation(x,y) = -(y-(mx+b)) derivative = 2/N * sum(individual point calculation) ''' def computePartialDerivativeB(b, m, points): N = float(len(points)) derivativeB = 0 #For each point for i in range(0, len(points)): x = points[i, 0] y = points[i, 1] derivativeB += (y - (m * x + b)) return (-2/N) * derivativeB if __name__ == '__main__': points = genfromtxt("blood.csv", delimiter=",", skip_header=1) learningRate = 0.0001 #The learning rate numberOfIterations = 1000 #The number of iterations b = 0 #initial value for b m = 0 #initial value for m for i in range(1000): #Update our values of b and m b = b - (learningRate * computePartialDerivativeB(b, m, points)) m = m - (learningRate * computePartialDerivativeM(b, m, points)) #Print out a summary print("y = " + format(m, '.2f') + "x + " + format(b, '.2f')) print("Error = " + str(computeError(b, m, points)))
71fb5ab35539839f8d8810bbd26003f5ba605ee2
hcmMichaelTu/python
/lesson12/turtle_escape.py
328
3.828125
4
import turtle as t import random t.shape("turtle") d = 20 actions = {"L": 180, "R": 0, "U": 90, "D": 270} while (abs(t.xcor()) < t.window_width()/2 and abs(t.ycor()) < t.window_height()/2): direction = random.choice("LRUD") t.setheading(actions[direction]) t.forward(d) print("Congratulations!")
de20c92ae722b36548ad06a278bd0a94ed503175
duongthebach/duongthebach-fundamental-c4e21
/session3/homework/sheep_2.py
202
3.671875
4
sizes = [5, 7, 300, 90, 24, 50, 75] print("Hello, my name is bach and these are my ship sizes: ") print(sizes) bigsize = max(sizes) print("Now my biggest sheep has size", bigsize, "let's shear it")
dc1e2a92d50b64deba10df918367e0f09ae74055
hmkthor/Algorithms
/tree.py
2,572
3.984375
4
# 트리 구조에서 사용할 노드에 대한 자료형 class Node: def __init__(self, data): self.data = data self.left = None self.right = None def init_tree(): global root new_node = Node("A") root = new_node new_node = Node("B") root.left = new_node new_node = Node("C") root.right = new_node new_node_1 = Node("D") new_node_2 = Node("E") node = root.left # refer to address node.left = new_node_1 node.right = new_node_2 new_node_1 = Node("F") new_node_2 = Node("G") node = root.right node.left = new_node_1 node.right = new_node_2 # 전위순회 알고리즘 (Pre-Order Traverse) # 가운데 노드를 먼저 방문하고 그 다음에는 왼쪽 노드를 방문하고 그리고 나서 오른쪽 노드를 방문하는 방법 def preorder_traverse(node): if node==None: return print(node.data, end = ' -> ') preorder_traverse(node.left) preorder_traverse(node.right) # 중위순회 알고리즘 (In-Order Traverse) # 왼쪽 자식 노드를 방문하고 그 다음 부모 노드를 방문한 후 다시 오른쪽 자식 노드를 방문 def inorder_traverse(node): if node==None: return inorder_traverse(node.left) print(node.data, end = ' -> ') inorder_traverse(node.right) # 후위순회 알고리즘 (Post-Order Traverse) # 왼쪽 자식 노드를 방문하고 다음에 오른쪽 자식 노드를 방문한 후에 마지막으로 부모 노드를 방문하는 알고리즘 def postorder_traverse(node): if node==None: return postorder_traverse(node.left) postorder_traverse(node.right) print(node.data, end = ' -> ') # 단계순회 알고리즘 (Level-Order Traverse) # 루트 노드부터 단계 순서대로 왼쪽부터 오른쪽으로 방문하는 순회 알고리즘 # 단계 순회 알고리즘의 경우 스택을 사용하기는 어렵고, 큐를 사용하는게 바람직하다. levelq = [] def levelorder_traverse(node): global levelq levelq.append(node) while len(levelq) != 0: # visit visit_node = levelq.pop(0) print(visit_node.data, end = ' -> ') # put child node if visit_node.left != None: levelq.append(visit_node.left) if visit_node.right != None: levelq.append(visit_node.right) # 실행결과 if __name__=='__main__': init_tree() print("전위순회(Preorder-traverse)") preorder_traverse(root) print("중위순회(Inorder-traverse)") inorder_traverse(root) print("후위순회(Postorder-traverse)") postorder_traverse(root) print("단계 순위 순회 알고리즘(Levelorder-Traverse)") levelorder_traverse(root)
5829dd89e8d794f4efcf6f2902024cbfc1d4abec
ziyeZzz/python
/LeetCode/204_计算质数.py
476
3.953125
4
# coding:utf-8 ''' 统计所有小于非负整数 n 的质数的数量。 示例: 输入: 10 输出: 4 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 ''' def countPrimes(n): primes = [1 for i in range(n)]# prime is 1 count = 0 for i in range(2,n): if primes[i]: for j in range(i+i,n,i): primes[j] = 0 count += 1 return count if __name__=='__main__': n = 10 print(countPrimes(n))
2fb15fce329c1cb2e61c34c6c6dae282f187d41c
nerutia/leetcode_new
/155.最小栈.py
825
3.75
4
# # @lc app=leetcode.cn id=155 lang=python3 # # [155] 最小栈 # # @lc code=start class MinStack: def __init__(self): """ initialize your data structure here. """ self.st = [] self.rank = [] # 始终存此次push后的最小值,一路存。 def push(self, val: int) -> None: self.st.append(val) v = self.rank[-1] if self.rank else float("inf") self.rank.append(min(v, val)) def pop(self) -> None: self.rank.pop() return self.st.pop() def top(self) -> int: return self.st[-1] def getMin(self) -> int: return self.rank[-1] # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(val) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin() # @lc code=end
ed92cfa01117d34907b2b4640e827409769b3e56
honestlywhocares/artificial-intellegence
/rotation.py
449
3.609375
4
import numpy as np import matplotlib.pyplot as plt import test as t def point_rotation(point,angle,p_r): x = point[0] y = point[1] xn = (x-p_r[0])*np.cos(np.radians(angle)) - (y-p_r[1])*np.sin(np.radians(angle))+p_r[0] yn = (x-p_r[0])*np.sin(np.radians(angle)) + (y-p_r[1])*np.cos(np.radians(angle))+p_r[1] return([xn,yn]) def rotate(angle,points,p_r): l = [] for i in points: l.append(point_rotation(i,angle,p_r)) return(l)
9b8d43e98f0f3883cbd1624608eec560042afd67
namankumar818/python-lab
/armstrong_number.py
202
3.625
4
a = input("enter the number") ln = len(a) s = 0 i = 0 while i<ln: s += int(a[i])**ln i += 1 if int(a) == s: print('number is armstrong') else: print('not armstrong')
c76847a276dfbbf566367b1e40accf413298ced6
Hoyo-yu/Learning
/python/learns/day04-迭代器和生成器/generator.py
575
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author:Mario # 生成器:只有调用时才会生成相应的数据,只记录当前位置,只有一个__next__()方法,省内存 # 列表生成式:[i*2 for i in range(1000)] def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return "done" for i in fib(6): print(i) # while True: # try: # x = next(f) # print(x) # f.__next__()=next(f) # except StopIteration as e: # print("Generator return value", e.value) # break
6d07024b2b71129298a5bf21e8e05dfc7c54afeb
monkeydunkey/interviewCakeProblems
/reverseWordsInStr.py
535
3.6875
4
def reverseWord(st, stInd, stpInd): for i in range(0, (stpInd - stInd)//2 + 1): st[stInd + i], st[stpInd - i] = st[stpInd - i], st[stInd + i] def reverseStrWords(st): stli = list(st) stInd = 0 for i, c_ in enumerate(stli): if c_ == '.': #we found a word end reverseWord(stli, stInd, i-1) stInd = i + 1 reverseWord(stli, stInd, len(stli) - 1) return ''.join(stli) test = input() for i in range(test): st = raw_input() print(reverseStrWords(st))
ac64880c3fe729dbd1333156a8df64097a0ed946
krzjoa/udemy
/text/word_encoder.py
3,000
3.53125
4
# Krzysztof Joachimiak 2017 # sciquence: Time series & sequences in Python # # Word Encoder # Author: Krzysztof Joachimiak # # License: MIT from collections import OrderedDict import numpy as np from operator import add class WordEncoder(object): ''' Class used for for transforming text data into word indices ''' def __init__(self): self.words = OrderedDict([('START', 0), ('END', 1)]) def __getitem__(self, item): if isinstance(item, int): return self.words.keys()[item] elif isinstance(item, str): return self.words[item] def fit(self, X, y=None): ''' Fit WordEncoder object Parameters ---------- X: list of list of str or str List containing list of strings or raw text input Returns ------- self: object Returns self ''' self.partial_fit(X) return self def partial_fit(self, X, y=None): ''' Partially fit WordEncoder to the given word set Parameters ---------- X: list of list of str or str List containing list of strings or raw text input Returns ------- self: object Returns self ''' unique = np.unique(reduce(add, X)) current_index = len(self.words) update = [(word, current_index + idx) for idx, word in enumerate(unique) if word not in self.words] self.words.update(update) return self def fit_transform(self, X, y=None): ''' Fit WordEncoder and transform list of tokenized sentences (or raw text) into lists of indices Parameters ---------- X: list of list of str or str List containing list of strings or raw text input Returns ------- indices: list of list of int Nested list containing word indices ''' return self.fit(X).transform(X) def transform(self, X, y=None): ''' Transform list of tokenized sentences (or raw text) into lists of indices Parameters ---------- X: list of list of str or str List containing list of strings or raw text input Returns ------- indices: list of list of int Nested list containing word indices ''' return [[self.words['START']] + [self.words[word]for word in sentence] +[self.words['END']] for sentence in X] def inverse_transform(self, X): '''' Transform list of indices into list of words Parameters ---------- X: list of list of str or str List containing list of strings or raw text input Returns ------- indices: list of list of int Nested list containing word indices ''' return [[self.words.keys()[idx] for idx in sentence] for sentence in X]
679cff0eedb437c1ab887c78b6e055a321c72034
Hrishikesh-3459/leetCode
/prob_876.py
588
3.828125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def middleNode(self, head: ListNode) -> ListNode: le = 0 cur = head while True: if (cur.next == None): le += 1 break le += 1 cur = cur.next pos = le // 2 cur = head while True: if (pos == 0): return cur pos -= 1 cur = cur.next
f7228058fbed517f7f7ded1ca67dac2fb2ad605c
alreis/Learning_Python
/exemundo2/exe47.py
193
3.71875
4
for c in range(1, 50+1, 1): print('.', end='') if c % 2 == 0: print(c, end=' ') print('\n') for c in range(2, 50+1, 2): print('.', end='') print(c, end=' ')
31f58b4ef152561e1997ef6387258471d431b953
bgarrisn/python_fundamentals
/02_basic_datatypes/2_strings/02_08_occurrence.py
362
4.09375
4
''' Write a script that takes a string of words and a letter from the user. Find the index of first occurrence of the letter in the string. For example: String input: hello world Letter input: o Result: 4 ''' userwords=input("type the words hello world: ") userletter=input("pick a letter in the words above: ") result=userwords.find(userletter) print(result)
9317d254bb503fae6776e1278ad67e887a07fb28
gabriellaec/desoft-analise-exercicios
/backup/user_169/ch140_2020_04_01_19_31_11_312946.py
414
3.609375
4
lista=[2,4,6,8] def faixa_notas(lista): i=0 lista2=[] while i<len(lista): if lista[i]<5: lista2.append(len(lista[i]<5)) if lista[i]>=5 and lista[i]<=7: lista2.append(len(lista[i]>=5 and lista[i]<=7)) if lista[i]>7: lista2.append(len(lista[i]>7)) i+=1
df079e4cdbfa1a169af9101a28c49bea408cce2d
jonag-code/python
/dictionary_play.py
308
3.890625
4
#D = {'a':1, 'b': 2, 'c':3 } D = dict(a=1, b=2, c=3) for k in D.keys(): print(k, '->', D[k]) print("\n") for ke in D: print(ke, '->', D[ke]) print("\n") for key in D: print('{} -> {}' .format( key, D[key] )) print("\n") for (key, value) in D.items(): print("%s -> %s " %( key, value ))
72aef059a0a7ada01a2e2146e90e4dba875debdb
chang0959/BaekJoon-Algorithm
/입출력과 사칙연산/2588_곱셈.py
291
3.921875
4
# %% num=int(input()) num1=int(input()) third=num1%10 second=int(num1%100/10) first=int(num1/100) print(num*third) #num1%10:마지막 자리 print(num*second) #int(num1%100/10): 두번째 자리 print(num*first) #int(num1/100): 첫번째자리 print(num*third+num*second*10+num*first*100)
de295b0bcb14d7fb07d26609a6a5f7b1f5960c9b
Aasthaengg/IBMdataset
/Python_codes/p02256/s178779192.py
281
3.59375
4
#Greatest Common Diveser def gcd(x, y): if x >= y: x = x % y if x == 0: return y return gcd(x, y) else: y = y % x if y == 0: return x return gcd(x, y) x, y = map(int, input().split()) print(gcd(x, y))
3dd53cc49dadaf8de9cd760be921ce0e5dfd9389
mdelafuen/Week6
/Week6InClass.py
679
3.921875
4
def main(): age = int(input("How old are you? ")) statement = input("Say something") if age <16 or "floglegroopp" > statement: print("you are young enough to be silly") else: print("oh no you are so old!") #main() def little_sister(): number_of_times = 0 say_it = "Yeet it now" what_you_said = "" while number_of_times <10 and say_it.lower() != what_you_said.lower(): what_you_said = input("Say it Comp151 Student") number_of_times += 1 what_you_said = what_you_said[:12] if number_of_times < 10: print("Hooray you said it") else: print("Aww you are so boring") little_sister()
d6a80e7008470685c535bf91a5907788dab8137a
nilankh/LeetCodeProblems
/Recursion/PrintFactorialWithRecursion.py
781
4.0625
4
#PRINTKE CASE PEHLE HMKO APNA KAAM KRNA HOTA H FIR RECURSION SE(RECURSION SE) #normal ''' def fact(n): if n == 0: return 1 smallOutput = fact(n-1) return n * smallOutput print(fact(5))''' #Another Method ''' def fact(n): if n == 0: return 1 smallOutput = fact(n-1) output = n * smallOutput print(output) return output fact(5)''' #Hack method ''' def factHelper(n): if n == 0: return 1 smallOutput = factHelper(n-1) output = n * smallOutput return output def fact(n): output = factHelper(n) print(output) fact(5)''' #without returning just prinitng def printFact(n,ans): if n == 0: print(ans) return ans = ans * n printFact(n-1,ans) printFact(5,1)
148e1e02951b43771de15775c5ae8c5fc57e66e2
emma0212/GameDesign2021
/HangmanLW.py
4,061
3.703125
4
#Emma Hoffman #06/21/2021 #Creating a hangman version of game: #Using images in list, use fonts, and render them from typing import Text import pygame, math, random, sys, time, os pygame.init() os.system('cls') #create our screen or window WIDTH=800 HEIGHT=500 screen = pygame.display.set_mode((WIDTH,HEIGHT)) pygame.display.set_caption("Hangman") # Define Colors WHITE=[255,255,255] BLACK=[0,0,0] gameWords= ['python','java','trackpad','computer','keyboard','geeks','laptop','headphones','charger','mouse','software','hardware'] images = [] for i in range(7): image= pygame.image.load("Images/hangman"+str(i)+".png") images.append(image) # screen.blit(images[i],(80,100)) # pygame.display.update() # pygame.time.delay(500) #Set up fonts TitleFont = pygame.font.SysFont("comicsans", 70) WordFont = pygame.font.SysFont("comicsans", 50) LetterFont = pygame.font.SysFont("comicsans",40) #Define letters for rectangular buttons A=65 Wbox=30 dist=10 letters=[]#an array of arrays [[x, y, ltr, boolean]] startx= round((WIDTH - (Wbox + dist)*13) /2) #int function round starty= 350 #load the letters into our double array for i in range(26): x=startx+dist*2+((Wbox + dist)*(i%13)) y=starty+((i//13)*(dist + Wbox * 2)) letters.append([x,y,chr(A+i), True]) print(letters) # function to update game and screen def updateScreen(turns,displayWord): screen.fill(WHITE) title=TitleFont.render("Hangman", 1, BLACK) centerTitle=WIDTH/2-title.get_width()/2 #gets the width of my screen/2 - width ofour text /2 screen.blit(title, (centerTitle,20)) screen.blit(images[turns],(100,100)) textW=WordFont.render(displayWord, 1, BLACK) screen.blit(textW,(300, 150)) for letter in letters: x,y,ltr, see= letter if see: rect=pygame.Rect(x-Wbox/2,y-Wbox/2,Wbox,Wbox) pygame.draw.rect(screen, BLACK, rect, width = 1) text=LetterFont.render(ltr,1,BLACK) screen.blit(text,(x-text.get_width()/2,y-text.get_height()/2)) pygame.display.update() def updateWord(word, guesses): # function with a parameter to update word displayWord = "" for char in word: if char in guesses: displayWord += char+" " else: displayWord += "_ " return displayWord play_again = "Y" while play_again == "Y" or play_again == "y": print("Welcome to Hangman") print("Start guessing") def dis_message(message): screen.fill(WHITE) text = TitleFont.render(message,1,BLACK) screen.blit(text, (200, 200)) pygame.display.update() pygame.time.delay(2000) dis_message("Please choose letter you wish to use") def main(): word=random.choice(gameWords).upper() print(word) guesses=[] turns=0 # find better way to create turns check=True while check: for event in pygame.event.get(): if event.type == pygame.QUIT: check=False if event.type== pygame.MOUSEBUTTONDOWN: mx,my=pygame.mouse.get_pos() for letter in letters: x,y,ltr,see = letter if see: rect=pygame.Rect(x-Wbox/2,y-Wbox/2,Wbox,Wbox) if rect.collidepoint(mx,my): letter[3]=False guesses.append(ltr) if ltr not in word: turns +=1 #always have a way to close your screen displayWord= updateWord(word, guesses) updateScreen(turns,displayWord) win=True for letter in word: if letter not in guesses: win=False break if win: dis_message("You Win!!!") print("Play Again? (y/n)") break if turns == 6: dis_message("You lose") play_again = input("Play again? (Y/N)") break pygame.quit() sys.exit()
f1c029591ce7203007a44b730961b1834d5c2a35
orestv/python-for-qa
/3-python-intermediate/examples/re_example.py
427
3.78125
4
import re text = ''' Posting Date: June 25, 2008 [EBook #11] Release Date: March, 1994 [Last updated: December 20, 2011] Language: English ''' numbers_regexp = re.compile('\d+') print(re.findall(numbers_regexp, text)) # ['25', '2008', '11', '1994', '20', '2011'] language_regexp = re.compile('language: (\w+)', re.IGNORECASE) match = re.search(language_regexp, text) if match: print(match.group(1)) # English
26fd08f7b1cbc7f302fcbbe1aa671686c96f0a10
naltoma/python_intro
/report/tic_tac_toe.py
3,464
4.75
5
"""Example code for Tic-tac-toe 3x3 board was described as a list with 9 sequential items. Each item in the list shows as follows. - 'e': empty - 'o': circle - 'x': cross For example, board = ['e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e'] shows that all cells have empty state. The index of board[] begins from upper-left to lower-right. For example, board = ['e', 'o', 'e', 'e', 'o', 'x', 'e', 'e', 'e'] describes the state of following. 'e'|'o'|'e' ---+---+--- 'e'|'o'|'x' ---+---+--- 'e'|'e'|'e' Example: This module has a test_play(), which executes 1. prepare an empty board, 2. play one hand with `o' randomly, 2. play one hand with `c' randomly. case 1: % python > import tic_tac_toe > tic_tac_toe.test_play() case 2: % python > from tic_tac_toe import * > test_play() case 3: % python tic_tac_toe.py """ import random def init_board(): """Return the empty board. Args: None Returns: list: the empty board with 9 items. >>> board = init_board() >>> print(board) ['e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e'] """ board = [] index = 0 while (index <= 9): board.append('e') index += 1 return board def print_board(board): """Print the board with 3x3. Args: board (list): the list with 9 items. Returns: None (only print the board to sys.stdout (standard output) >>> board = init_board() >>> print_board(board) eee eee eee --- """ count = 0 for state in board: count += 1 if count % 3 == 0: print('{0}'.format(state)) else: print('{0}'.format(state), end='') print('---') def gather_empty_cells(board): """Gather empty cells on the board. Args: board (list): the list with 9 items. Returns: list: the index list of empty state on the board. >>> board = ['o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'e'] >>> empty_list = gather_empty_cells(board) >>> len(empty_list) == 1 True >>> empty_list[0] == 8 True """ empty_list = [] index = 0 for state in board: if state == 'e': empty_list.append(index) index += 1 return empty_list def point_random(board, player): """Play one step randomly. Args: board (list): the list with 9 items. player (str): 'o' for circle player, 'x' for cross player Returns: #####board (list): the point one step randomly with the player. point (int): the pointed index on the board Note: This function DOESN'T check the validity of turn. You can play oneside-game. >>> board = init_board() >>> index = point_random(board, 'o') >>> board[index] == 'o' True """ empty_list = gather_empty_cells(board) point = random.randint(0, len(empty_list)-1) board[empty_list[point]] = player return empty_list[point] def test_play(): board = init_board() print('# board was initialized.') print_board(board) index = point_random(board, 'o') print("# user 'o' pointed to board[{0}]".format(index)) print_board(board) index = point_random(board, 'x') print("# user 'x' pointed to board[{0}]".format(index)) print_board(board) if __name__ == '__main__': test_play()
5543ebb3b49233de027b260f4162c3a1f9319f9c
verdatestudo/Codewars
/codewars_paperboy.py
1,832
3.6875
4
''' Codewars - PaperBoy http://www.codewars.com/kata/paperboy 2016-Mar-26 Python 2.7 Chris Description: You and your best friend Stripes have just landed your first high school jobs! You'll be delivering newspapers to your neighbourhood on weekends. For your services you'll be charging a set price depending on the quantity of the newspaper bundles. The cost of deliveries is: $3.85 for 40 newspapers $1.93 for 20 $0.97 for 10 $0.49 for 5 $0.10 for 1 Stripes is taking care of the footwork doing door-to-door drops and your job is to take care of the finances. What you'll be doing is providing the cheapest possible quotes for your services. Write a function that's passed an integer representing the amount of newspapers and returns the cheapest price. The returned number must be rounded to two decimal places. ''' def cheapest_quote(num_newspapers): count = -1 for item in delivery_cost: # divmod returns (division, modulo) if divmod(num_newspapers, item[0])[0] != 0: count += 1 if num_newspapers == 0 or count == 0: return round(num_newspapers * delivery_cost[0][1], 2) div, mod = divmod(num_newspapers, delivery_cost[count][0]) return round((div * delivery_cost[count][1]) + cheapest_quote(mod), 2) delivery_cost = [[1, 0.1], [5, 0.49], [10, 0.97], [20, 1.93], [40, 3.85]] def test_cases(): print cheapest_quote(1), 0.10 print cheapest_quote(5), 0.49 print cheapest_quote(10), 0.97 print cheapest_quote(20), 1.93 print cheapest_quote(40), 3.85 print cheapest_quote(41), 3.95 print cheapest_quote(80), 7.70 print cheapest_quote(26), 2.52 print cheapest_quote(0), 0.0 print cheapest_quote(499), 48.06 print cheapest_quote(52968) test_cases()
d93b7732e86fc680e9e0eedb25f37e1e8ee10a99
MachineLearnWithRosh/Data-Structure-and-Algorithms
/Dynamic Programming/4-MaximumSubArray_kadanesAlgo.py
596
3.8125
4
def max_sum_subarray(arr): c_sum = 0 curr_maxValue = arr[0] st, end, poi = 0, 0 ,0 for i in range(0, len(arr)): c_sum = c_sum + arr[i] if c_sum > curr_maxValue: curr_maxValue = c_sum st = poi end = i if c_sum<0: c_sum = 0 poi = i+1 print("Maximum sum Subarray is",curr_maxValue) print("Start Index of window is",st) print("End Index of window is",end) array = [4,-3,-2,2,3,1,-2,-3,6,-6,-4,2,1] max_sum_subarray(array)
a1c3911b74706e44a1a7bb69324194cf74ac5a67
khrystyna21/Python
/lesson7/7.3.py
594
4.0625
4
def make_operation(operator, *args): if operator == '+': return_value = 0 for num in args: return_value += num return return_value elif operator == '-': return_value = args[0] for num in args[1:]: return_value = return_value - num return return_value elif operator == '*': return_value = 1 for num in args: return_value = num * return_value return return_value print(make_operation('+', 7, 7, 2)) print(make_operation('-', 5, 5, -10, -20)) print(make_operation('*', 7, 6))
fafb61cff6256896c850cd738ec16f4c6209143c
AtarioGitHub/Sub-task-8.1-and-8.2
/subtask1.py
339
4
4
import math n = input('Enter your number which we will call n = ') print('n = ',n) DecimalNumberofN = float(n) # We use float so that we can also use a decimal value TheSquareRootofThatNumber = math.sqrt(DecimalNumberofN) xyz = int(TheSquareRootofThatNumber) # Let xyz be an integer value q=pow(xyz,2) print('q = ', q)
0e44fb0621442be8656542aac4a2a033a2127c0b
SafonovMikhail/python_000577
/000000stepikProgBasKirFed/Stepik000000ProgBasKirFedсh01p05st04TASK04_20210205_math.py
443
4.09375
4
''' На вход программе подается натуральное двухзначное число. Напишите программу, которая выводит сначала количество десятков в этом числе, затем количество единиц Sample Input 1: 58 Sample Output 1: 5 8 Sample Input 2: 37 Sample Output 2: 3 7 ''' n1 = int(input()) print(n1 // 10, n1 % 10, sep='\n')
81223401b3701d786c5b89ab75e5eaf1b0d95a02
pmazgaj/SerialApp
/modules/random_data_generator.py
837
3.734375
4
""" Create random data for an application, in similar pattern to serial data """ import random __author__ = "Przemek" class RandomDataHandler: def __init__(self): ... def get_random_num_in_range(self, range_of_data: list) -> float: """get random float number in given range, for 3 decimal places """ number = random.uniform(range_of_data[0], range_of_data[1]) return round(number, 3) def create_random_data(self, tuple_with_ranges: list) -> list: """creates random data for an application""" while True: return [self.get_random_num_in_range(range_num) for range_num in tuple_with_ranges] a = RandomDataHandler() for x in range(0, 1000): a.create_random_data([(0, 22), (3, 14), [99, 228]]) print(a.create_random_data([(0, 22), (3, 14), [99, 228]]))
3e7efd801d979c496845b0ebfc06571700de54db
ceon97/Leetcode
/Happy_Number.py
703
3.796875
4
"A happy number is a number defined by the following process:" "Starting with any positive integer, replace the number by the sum of the squares of its digits." "Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1." "Those numbers for which this process ends in 1 are happy." "Return true if n is a happy number, and false if not." class Solution(object): def isHappy(self, n): k=set() while n!=1: c=0 for i in str(n): c=c+(int(i)**2) n=c if n in k: return False else: k.add(n) return True
f2f8d0414aa5cba4a1dfea2de56604c6eccfc3cf
Mariogallo/Projetos-Python-Digital-Innovation-One
/app_python/aula5.py
2,328
3.890625
4
lista = [12, 10, 7, 5] lista_animal = ['cachorro', 'gato', 'elefante', 'lobo', 'arara'] lista_animal[0] = 'macaco' print(lista_animal) tupla = (1, 10, 12, 14) print(len(tupla)) print(len(lista_animal)) tupla_animal = tuple(lista_animal) print(type(tupla_animal)) print(tupla_animal) lista_numerica = list(tupla) print(type(lista_numerica)) print(lista_numerica) lista_numerica[0] = 100 print(lista_numerica) # tupla = (1, 10, 12, 14) # tupla[0] = 12 # tupla = (1, 10, 12, 14) # print(tupla) # lista.sort() # lista_animal.sort() # print(lista) # print(lista_animal) # lista_animal.reverse() # print(lista_animal) # lista = [1, 3, 7, 5] # lista_animal = ['cachorro', 'gato', 'elefante'] # # print(lista_animal[1]) # nova_lista = lista_animal * 3 # print(nova_lista) # if 'lobo' in lista_animal: # print('Existe um lobo na lista') # else: # print('Não existe um lobo na lista. Será incluido.') # lista_animal.append('lobo') # print(lista_animal) # lista_animal.remove('elefante') # print(lista_animal) # lista_animal.pop() # print(lista_animal) # # lista_animal.pop(0) # print(lista_animal) # # lista_animal.pop(1) # print(lista_animal) # lista = [1, 3, 7, 5] # lista_animal = ['cachorro', 'gato', 'elefante'] # # print(lista_animal[1]) # # if 'lobo' in lista_animal: # print('Existe um lobo na lista') # else: # print('Não existe um lobo na lista') # if 'gato' in lista_animal: # print('Existe um gato na lista') # else: # print('Não existe um gato na lista') # lista = [1, 3, 7, 5] # lista_animal = ['cachorro', 'gato', 'elefante'] # # print(lista_animal[1]) # print(min(lista_animal)) # print(max(lista_animal)) # lista = [1, 3, 7, 5] # lista_animal = ['cachorro', 'gato', 'elefante'] # print(lista_animal[1]) # # print(max(lista)) # print(min(lista)) # lista = [1, 3, 5, 7, 'gato'] # lista_animal = ['cachorro', 'gato', 'elefante'] # print(lista_animal[1]) # # print(sum(lista)) # soma = 0 # for x in lista: # print(x) # soma += x # print(soma) # for x in lista_animal: # print(x) # lista = [1, 3, 5, 7, 'gato'] # lista_animal = ['cachorro', 'gato', 'elefante'] # print(lista) # lista = [1, 3, 5, 7] # lista_animal = ['cachorro', 'gato', 'elefante'] # print(type(lista)) # lista = [1, 3, 5, 7] # lista_animal = ['cachorro', 'gato', 'elefante'] # print(lista)
8a10d28f47c4bc5e0b92a6fb64d84293e2cc8c82
codingyen/CodeAlone
/Python/0058_length_of_last_word.py
474
3.9375
4
# Starting from the back! Do the reverse! # reversed() # Time: O(n) # Space: O(1) class Solution: def lengthOfLastWord(self, s): if not s: return 0 length = 0 for i in reversed(s): if i == " ": if length: break else: length += 1 return length if __name__ == "__main__": s = "Hello World " t = Solution() print(t.lengthOfLastWord(s))
5c434fe23a2e4c13346f9038a43cec44a121d5d8
laisOmena/Recursao-em-Python
/lista3/quest03.py
182
4.03125
4
def cont(text): if len(text) == 0: return 0 else: return len(text.split(x)) - 1 text = "estrutura de dados" x = input("Digite uma letra: ") print(cont(text))
f3c870562bc8857182ec3927b3f888531024449d
EvgeniyOrlov/KrakenRepo
/Lesson3/Lesson3_3.py
252
3.796875
4
def my_func(n1, n2, n3): return (n1 + n2 + n3) - min(n1, n2, n3) num1, num2, num3 = int(input('Введите число: ')), int(input('Введите число: ')), int(input('Введите число: ')) print(my_func(num1, num2, num3))
2f64bd70891b6fee82f6ff591114518bfaf0e989
molliegoforth818/py-functions
/chickenmonkey.py
212
3.734375
4
def chicken_monkey(): for num in range(0, 101): if num%5==0: print("chicken") elif num%7==0: print('monkey') else: print(num) chicken_monkey()
15b1e28d2989bf7e6f278461182c475148de28e7
marianinakraemer/aulas_python_UERJ
/pendulo_functions_eduardoV.py
883
3.671875
4
""" Funções importantes do pêndulo duplo: posição x e y de cada massa, energia cinética, potencial e total Autor: Eduardo da Costa Valadão - eduardovaladao98@gmail.com """ import numpy as np def pendulum_x1(theta1, l1, i): x1 = l1*np.sin(theta1[i]) return x1 def pendulum_y1(theta1, l1, i): y1 = - l1*np.cos(theta1[i]) return y1 def pendulum_x2(theta2, l2, x1, i): x2 = x1[i] + l2*np.sin(theta2[i]) return x2 def pendulum_y2(theta2, l2, y1, i): y2 = y1[i] - l2*np.cos(theta2[i]) return y2 def energia_cinetica(theta1, theta2, alfa1, alfa2, m1, m2, l1, l2, i): k = 0.5*m1*(l1**2)*(alfa1[i]**2) + 0.5*m2*((l1**2)*(alfa1[i]**2) + (l2**2)*(alfa2[i]**2) + 2*l1*l2*alfa1[i]*alfa2[i]*np.cos(theta1[i] - theta2[i])) return k def energia_potencial(theta1, theta2, m1, m2, l1, l2, g, i): u = -(m1 + m2)*g*l1*np.cos(theta1[i]) - m2*g*l2*np.cos(theta2[i]) return u
80d2a6f1f709659a4f5e020b4a8cabcd83d67c0e
Asko24/pp1-pythonprojects
/02/39.py
144
3.5625
4
fib = 50 n1 = 0 n2 = 1 liczba = 0 while liczba < fib: print(n1,end=' , ') n3 = n1 + n2 n1 = n2 n2 = n3 liczba += 1
e31bc08c4c97d98b1b0f42d0a0384336565ab0d9
attiakihal/MazeSolver
/search/a_star_manhattan.py
2,965
3.609375
4
import heapq import math from common.nodes import Node def a_star_manhattan(maze, start, end): # Create start and end nodes start = Node(None, start) end = Node(None, end) # Create fringe fringe = [] heapq.heapify(fringe) visited = list() # Add start node heapq.heappush(fringe, start) # Add difficulty metrics max_fringe = 0 nodes_exp = 0 while len(fringe) > 0: # Update Max Fringe if len(fringe) > max_fringe: max_fringe = len(fringe) # Update Nodes Expanded nodes_exp = nodes_exp + 1 current = heapq.heappop(fringe) visited.append(current) # Found the end node if current == end: path = [] while current is not None: path.append(current.position) current = current.parent # Reverse the path and return path = path[::-1] return {"path": path, "path_len": len(path), "max_fringe": max_fringe, "nodes_exp": nodes_exp} # Get neighbors neighbors = [] for x_change, y_change in [(1, 0), (-1, 0), (0, 1), (0, -1)]: # Calculate position of neighbor x_new, y_new = ( current.position[0] + x_change, current.position[1] + y_change) # Make sure neighbor is inside maze if x_new > (len(maze) - 1) or x_new < 0 or y_new > (len(maze) - 1) or y_new < 0: continue # Make sure neighbor is walkable if maze[x_new][y_new] != 1: continue # Create new node and append to neighbors new_node = Node(current, (x_new, y_new)) neighbors.append(new_node) # Loop through neighbors for neighbor in neighbors: # Check to make sure neighbor has not already been visited if neighbor in visited: continue # Increase cost by one neighbor.cost = current.cost + 1 # Calculate heuristic neighbor.heuristic = abs( neighbor.position[0] - current.position[0]) + abs(neighbor.position[1] - current.position[1]) # Calculate total cost neighbor.total_cost = neighbor.cost + neighbor.heuristic # Check if neighbor is already in the fringe and take the smallest value shortest_path_to_neighbor = True for node in fringe: # If a path to the neighbor is already in the fringe if neighbor == node: # If the path to this node is longer than one already in the fringe if neighbor.total_cost >= node.total_cost: shortest_path_to_neighbor = False if shortest_path_to_neighbor: heapq.heappush(fringe, neighbor) return {"path": [], "path_len": 0, "max_fringe": 0, "nodes_exp": 0}
9b22e7bc69b261d6865af0169bb3d269d6ea5404
ZammadGill/python-practice-tasks
/task3.py
373
4.21875
4
""" With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary """ def generateDictionary(n): dictionary = {} for x in range(1, n + 1): dictionary[x] = x * x print(dictionary) generateDictionary(8)
5cedd1cff591c08ceff27f3abbe88210b659cc27
Bruck1701/CodingInterview
/generalAlgorithms/birthday.py
430
3.59375
4
def birthday(s, d, m): if len(s)==1 and m==1 and s[0]== d: return m count = 0 for i in range(0,len(s)-m+1): soma = 0 ct = 0 while ct<m: soma += s[i+ct] ct+=1 if soma == d: count+=1 print("Count: ",count) print(count) return count lstr = "2 5 1 3 4 4 3 5 1 1 2 1 4 1 3 3 4 2 1" birthday([int(x) for x in lstr.split()],18,7) lstr = "1 2 1 3 2" birthday([int(x) for x in lstr.split()],3,2)
d9fe4e576fee9d7a335bd38230367d1e798d6e49
jauvariah/RandomCode
/Puzzles/UBSQuestion.py
604
3.671875
4
#The number 1978 is such a number that if you add the first 2 sets of numbers, you'll will get the middle 2 sets of numbers. So in 1978, 19+78=97; so the question is write a formula that can find numbers that satisfy these conditions. #From Business Insider: http://www.businessinsider.com/heres-the-answer-to-that-impossible-quant-interview-question-2011-9 resultList = [] for i in range (1000, 9999): iString = str(i) firstSet = int(iString[:2]) secondSet = int(iString[-2:]) middleSet = int(iString[2:3]) if firstSet + secondSet == middleSet: resultList.append(i) print resultList
2297487a5f669be36b6be2cbbaf46c8f606adddb
msm17b019/Project
/Mini_Project/dance_form_gui.py
1,759
3.78125
4
from tkinter import* root=Tk() root.geometry("600x400") root.minsize(400,400) root.maxsize(600,600) def getvals(): with open("C:\\Users\\sujee\\Desktop\\1.txt","a") as f: f.write("-----The New Entry----- \n") f.write(f"The name of student is {nameval.get()}") f.write('\n') f.write(str(f"The age of student is {ageval.get()}")) f.write('\n') f.write(f"The address of student is {addressval.get()}") f.write('\n') f.write(str(f"The contact number of student is {contactval.get()}")) f.write('\n') f.write(f"The email id of student is {emailval.get()}") f.write('\n') print("Registration Done!") root.title("XYZ Dance Classes") Label(root,text="Fill the dance registration form:",font="Serpia 18 bold",fg="red").grid(row=0,column=1) Label(root,text="").grid(row=1,column=1) name=Label(root,text="Name") age=Label(root,text="Age") address=Label(root,text="Address") contact_number=Label(root,text="Contact Number") email_id=Label(root,text="Email ID") name.grid(row=2) age.grid(row=3) address.grid(row=4) contact_number.grid(row=5) email_id.grid(row=6) nameval=StringVar() ageval=IntVar() addressval=StringVar() contactval=IntVar() emailval=StringVar() nameentry=Entry(root,textvariable=nameval) nameentry.grid(row=2,column=1) ageentry=Entry(root,textvariable=ageval) ageentry.grid(row=3,column=1) addressentry=Entry(root,textvariable=addressval) addressentry.grid(row=4,column=1) contactentry=Entry(root,textvariable=contactval) contactentry.grid(row=5,column=1) emailentry=Entry(root,textvariable=emailval) emailentry.grid(row=6,column=1) Label(root,text="").grid(row=7,column=1) Button(text="Submit",command=getvals).grid(column=1) root.mainloop()
075a5e5578e4fc6e4bc4afa515d22ec0a16c865d
mrfawy/ModernEnigma
/Shuffler.py
1,041
3.859375
4
from RandomGenerator import RandomGenerator from Util import Util #This class implements Fisher-Yates shuffle algorithm #Given random generator and a seed , it de/shuffles a string #http://stackoverflow.com/questions/3541378/reversible-shuffle-algorithm-using-a-key class Shuffler(object): @classmethod def shuffleSeq(cls,sequence,seed): seq=list(sequence) random=RandomGenerator(Util.hashString(str(seed))) for i in range(len(seq)-1,0,-1): j=random.nextInt(0,i) cls.swap(seq,i,j) return seq @classmethod def deshuffleSeq(cls,sequence,seed): seq=list(sequence) random=RandomGenerator(Util.hashString(str(seed))) changes=[] for i in range(len(seq)-1,0,-1): changes.append(random.nextInt(0,i)) changes=changes[::-1] for i in range(1,len(seq)): cls.swap(seq,i,changes[i-1]) return seq @classmethod def swap(cls,seq,i,j): tmp=seq[i] seq[i]=seq[j] seq[j]=tmp
cc27fdd745340d8f5ea7e55ca1674c69b6f3cb67
saroja-parida/mycode
/file_search.py
532
3.515625
4
def file_s(): f=open("test1.txt","r") count = 0 for line in f: if "saroj" in line: count+=1 print("The name 'saroj' is repeted =%d times "%(count)) s=0 if "saroj" in open("test1.txt").read(): s+=1 print s print open("test1.txt").read().find('saroj') file_s() list1 =["saroj","sp","saroj11","saroj1234","saroj"] def findl(lis): count=0 match="saroj\w+" for i in lis: if i == match: print "matched" count+=1 return count print findl(list1)
00400738bc74a5beb78e9dc2cd9020b84973faf3
shade-12/python-dsal
/09_Recursion/count_consonants.py
732
3.9375
4
consonants = "bcdfghjklmnpqrstvwxyz" def count_consonants_iterative(input): """ Returns the number of consonants present """ count = 0 for char in input: if char.lower() in consonants: count += 1 return count def count_consonants_recursive(input): """ Returns the number of consonants present """ if len(input) == 0: return 0 if input[0].lower() in consonants: return 1 + count_consonants_recursive(input[1:]) else: return count_consonants_recursive(input[1:]) input_str = "abc de" print(input_str) print(count_consonants_iterative(input_str)) input_str = "LuCiDPrograMMiNG" print(input_str) print(count_consonants_recursive(input_str))
05779eefe134b11c9b7d4b3d7977c675025a1ef2
torselden/advent_of_code_2018
/torselden-python/Day06/day06.py
3,542
3.515625
4
import os import sys import re from datetime import datetime def parse_input(file): with open(os.path.join(sys.path[0], file ), 'rU') as input_file: return [line.strip() for line in input_file.readlines()] def parse_coordinates(lines): return [tuple(map(int, coord.split(', '))) for coord in lines] def calculate_finite_coords(coords): finite_coords = [] for coord in coords: x, y = coord other_coords = [c for c in coords if c != coord] top_left = (0,0) bottom_left = (0,350) top_right = (350,0) bottom_right = (350,350) xy = False x_ = False y_ = False __ = False for other_coord in other_coords: x_o, y_o = other_coord if manhattan_dist(other_coord,top_left) < manhattan_dist(coord,top_left): xy = True if manhattan_dist(other_coord,bottom_left) < manhattan_dist(coord,bottom_left): x_ = True if manhattan_dist(other_coord,top_right) < manhattan_dist(coord,top_right): y_ = True if manhattan_dist(other_coord,bottom_right) < manhattan_dist(coord,bottom_right): __ = True # if x_o > x and y_o > y: # xy = True # if x_o > x and y_o < y: # x_ = True # if x_o < x and y_o > y: # y_ = True # if x_o < x and y_o < y: # __ = True if xy == True and x_ == True and y_ == True and __ == True: finite_coords.append(coord) break return finite_coords def manhattan_dist(c, finite_coord): return (abs(c[0]-finite_coord[0]) + abs(c[1]-finite_coord[1])) def calculate_largest_area(coords, finite_coords,size): result = {} # compare each of the finite coords with the all the rest between 0 and 351 for x in range(1,size): for y in range(1,size): test_coord = x, y for finite_coord in finite_coords: finite_coord_is_closest = True dist_to_test = manhattan_dist(test_coord, finite_coord) for coord in [c for c in coords if c != finite_coord]: if manhattan_dist(test_coord, coord) <= dist_to_test: finite_coord_is_closest = False break if finite_coord_is_closest: if finite_coord in result: result[finite_coord] += 1 else: result[finite_coord] = 1 largest_area = max(result.values()) print(result) print(sorted(result, key=result.get)) return largest_area def calculate_region(coords, size): region_size = 0 for x in range(1,size): for y in range(1,size): dist_sum = 0 for coord in coords: dist = manhattan_dist(coord, (x,y)) dist_sum +=dist if dist_sum < 10000: region_size += 1 return region_size def day_6a(): input = parse_input('6.txt') coords = parse_coordinates(input) finite_coords = calculate_finite_coords(coords) return calculate_largest_area(coords, finite_coords,351) def day_6b(): input = parse_input('6.txt') coords = parse_coordinates(input) return calculate_region(coords, 350) if __name__ == "__main__": print(day_6a()) print(day_6b())
01a0fcd757fa06a47c24b38fbf5df14e0061be65
ken-power/Foobar_Challenge
/Level_3/6_FuelInjectionPerfection/solution.py
6,416
4.28125
4
import unittest def reduce_to_one(n): """ Return the minimum number of operations to reduce 'n' to `1`. :param n: an integer value :return: the minimum number of operations, and the path from n to 1, and the sequence of operations (useful for debugging and understanding) """ operation_count = 0 path = [n] operations_sequence = [] while n != 1: # keep going until we transform the number of pellets to 1 if n % 2 == 0: # if we have an even number of pellets # Divide the entire group of fuel pellets by 2 (due to the destructive energy released when a quantum # antimatter pellet is cut in half, the safety controls will only allow this to happen if there is an even # number of pellets) n = n / 2 operations_sequence.append("DIVIDE") # Use bitwise "and" to make it easier to work out when we need to remove a pellet elif (n == 3) or (n & (n + 1)) > ((n - 2) & (n - 1)): # Remove one fuel pellet n -= 1 operations_sequence.append("REMOVE") else: # Add one fuel pellet n += 1 operations_sequence.append("ADD") path.append(n) operation_count += 1 return operation_count, path, operations_sequence def solution(n): """ Minions dump pellets in bulk into the fuel intake. This function figures out the most efficient way to sort and shift the pellets down to a single pellet at a time. The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits. :param n: a positive integer as a string representing the number of pellets dumped in bulk :return: the minimum number of operations needed to transform the number of pellets to 1 """ try: if len(n) > 309: return 0 n = int(n) except ValueError: return 0 except TypeError: return 0 if n == 0: return 0 count, _, _ = reduce_to_one(n) return count def list_to_string(s): stringified_list = "" for character in s: stringified_list += character return stringified_list class OperationCountTests(unittest.TestCase): def test_15_pellets(self): fuel_pellets = '15' expected = 5 min_operations_needed = solution(fuel_pellets) self.assertEqual(expected, min_operations_needed) def test_4_pellets(self): fuel_pellets = '4' expected = 2 min_operations_needed = solution(fuel_pellets) self.assertEqual(expected, min_operations_needed) def test_0_pellets(self): fuel_pellets = '0' expected = 0 min_operations_needed = solution(fuel_pellets) self.assertEqual(expected, min_operations_needed) def test_157_pellets(self): fuel_pellets = '157' expected = 10 min_operations_needed = solution(fuel_pellets) self.assertEqual(expected, min_operations_needed) def test_137_steps(self): fuel_pellets = '881442566340248816440069375573' expected = 137 min_operations_needed = solution(fuel_pellets) self.assertEqual(expected, min_operations_needed) def test_max_pellets(self): """ The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits. """ max_pellets = list_to_string(['9'] * 309) fuel_pellets = max_pellets expected = 1278 min_operations_needed = solution(fuel_pellets) self.assertEqual(expected, min_operations_needed) def test_too_many_pellets(self): """ The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits. """ fuel_pellets = list_to_string(['9'] * 310) expected = 0 min_operations_needed = solution(fuel_pellets) self.assertEqual(expected, min_operations_needed) def test_pellets_not_a_number(self): fuel_pellets = 'eleventy-six' expected = 0 min_operations_needed = solution(fuel_pellets) self.assertEqual(expected, min_operations_needed) def test_pellets_is_None(self): fuel_pellets = None expected = 0 min_operations_needed = solution(fuel_pellets) self.assertEqual(expected, min_operations_needed) class PathTests(unittest.TestCase): def test_15_pellets_path(self): fuel_pellets = 15 expected_path = [15, 16, 8, 4, 2, 1] _, path, _ = reduce_to_one(fuel_pellets) self.assertEqual(expected_path, path) def test_4_pellets_path(self): fuel_pellets = 4 expected_path = [4, 2, 1] _, path, _ = reduce_to_one(fuel_pellets) self.assertEqual(expected_path, path) def test_157_pellets_path(self): fuel_pellets = 157 expected_path = [157, 156, 78, 39, 40, 20, 10, 5, 4, 2, 1] _, path, _ = reduce_to_one(fuel_pellets) self.assertEqual(expected_path, path) class SequenceOfOperationsTests(unittest.TestCase): def test_15_pellets_path(self): fuel_pellets = 15 expected_operations = ['ADD', 'DIVIDE', 'DIVIDE', 'DIVIDE', 'DIVIDE'] _, _, operations = reduce_to_one(fuel_pellets) self.assertEqual(expected_operations, operations) def test_4_pellets_path(self): fuel_pellets = 4 expected_operations = ['DIVIDE', 'DIVIDE'] _, _, operations = reduce_to_one(fuel_pellets) self.assertEqual(expected_operations, operations) def test_157_pellets_path(self): fuel_pellets = 157 expected_operations = ['REMOVE', 'DIVIDE', 'DIVIDE', 'ADD', 'DIVIDE', 'DIVIDE', 'DIVIDE', 'REMOVE', 'DIVIDE', 'DIVIDE'] _, _, operations = reduce_to_one(fuel_pellets) self.assertEqual(expected_operations, operations)
84fc2a97dd33c22aef97c4417f56d10b2e643ff2
mlbernauer/drugstandards
/drugstandards/__init__.py
2,848
3.578125
4
import Levenshtein import operator import csv import os import re from pkg_resources import Requirement, resource_filename class DrugStandardizer(): def __init__(self): self.dictionary_file = resource_filename(Requirement.parse("drugstandards"), "drugstandards/data/synonyms.dat") self.drugdict = dict(i.strip().split("\t") for i in open(self.dictionary_file, "r")) def create_drug_dictionary(self, filename, delimiter = "\t"): """ This function creates a drug dictionary of the form {"synonym1":"generic1", "synonym2":"generic1"} using drug names (brand, generic, synonyms) found in DrugBank. """ self.drugdict= {} with csv.reader(open(filename, 'r'), delimiter = delimter) as csvfile: for k, v in csvfile: self.drugdict[k.upper()] = v def find_closest_string(self, query, dictionary, thresh=0.90): """ This function returns the closest match for a query string against a dictionary of terms using levenstein distance """ dist = {i:Levenshtein.jaro_winkler(query, i) for i in dictionary} dist = sorted(dist.items(), key=operator.itemgetter(1), reverse=True) if dist[0][1] >= thresh: return dist[0][0] else: return None def add_drug_mapping(self, mapdict): """ This function is used to add drug mappings to the drug dictionary. For example, if the term "benadry" is not found in the dictionary, you can add the custom mapping by using the following: drugs.add_drug_mapping({"benadryl":"diphenhydramine"}) Additionally, one might want to map all instances of "multi-vitamin" to "vitamin" in which case you would use: drugs.add_drug_mapping({"multi-vitamin":"vitamin"}) """ for k,v in mapdict.items(): self.drugdict[k.upper()] = v def standardize(self, druglist, thresh=0.90): """ This function takes a list of drugs (brand name, misspelled drugs, generic names) and converts them to the generic names. """ splitter = re.compile("\\W+|\d+") standardized_druglist = [] for drug in druglist: drug = drug.upper() drug = " ".join(splitter.split(drug)).strip() gen = self.drugdict.get(drug) if gen: standardized_druglist.append(gen) continue else: close_match = self.find_closest_string(str(drug), self.drugdict.keys(), thresh=thresh) close_match = self.drugdict.get(close_match) standardized_druglist.append(close_match) return standardized_druglist
f24038981ab0665e3d5f45f5be0b98be2cfe432d
tikishen/TuanZi
/Umich_AI_Intern/solution.py
747
3.890625
4
# Take a string as input and extract all digits in the string, delimited by any non-digit characters. # It should then sum those digits in the order they were provided and display the result. class Solution(object): def sum_digit(self, s): res = [] temp = [] def maybe_add_num(): if temp and temp[-1] != '-': res.append(int(''.join(temp))) temp.clear() for ch in s: if ch.isdigit(): temp.append(ch) elif ch == '-': maybe_add_num() temp.append(ch) else: maybe_add_num() maybe_add_num() if len(res) == 0: return '' return sum(res)