blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
14bfcef09eb97eb175680810f519fba5e2910a25
LuizGustavo10/Algoritmos
/arq2/telaDeCadastro.py
1,518
3.765625
4
''' "r" = modo de leitura, "a" escrever, "w" apaga, e depois escreve''' option = 0 while option != 4: print('''Selecione a opção: -------------------------------- 1 - para cadastrar 2 - para listar 3 - para limpar e escrever 4 - para sair -------------------------------- ''') option = int(input('Insira um Nº:')) if option == 1: print("-------------------------------------------") arq = open("arquivos/nomes.txt","a")#trabalha com aquivo txt. #escrevendo na variável arq nome = input("informe seu nome completo: ") arq.write(nome+"\n") #Salva as modificações e salva o arquivo arq.close() elif option == 2: print("--------------cadastrados----------------------") arquivo = open("arquivos/nomes.txt","r") conteudo = arquivo.readlines() for x in range(0,len(conteudo)): print(conteudo[x]) arquivo.close() elif option == 3: print("-------------criar do zero - apaga tudo---------") arq = open("arquivos/nomes.txt","w")#trabalha com aquivo txt. #escrevendo na variável arq nome = input("informe seu nome completo") arq.write(nome+"\n") #Salva as modificações e salva o arquivo arq.close() #Open retorna um endereço para o arquivo #read = Le o arquivo inteiro / readlines() é como uma lista #fileid meenu > função guardar inf, > 1 opção para chamar a forca > usar biblioteca para importar a palavra aleatória >
e283c9d4ea791632dcc27d77856d44333b0b684f
emmett-shang/my-pandas
/sandbox/for_and_while_loops.py
519
4
4
for i in range(0, 10): print(i) names = ['Jim', 'Tom', "Nick", "Pam", "Sam", "Tim"] for name in names: print(name) for i in range(len(names)): print(names[i]) age = {"Jim":"31", "Nick": "31", "Pam": "27", "Sam": "35", "Tim": "31", "Tom": "50"} print(age) print(age.keys()) for name in age.keys(): print(name, age[name]) for name in age: print(name, age[name]) for name in sorted(age.keys()): print(name, age[name]) for name in sorted(age.keys(), reverse=True): print(name, age[name])
0e4667fdb9a5cd5eff9140505fb3d94fab13572e
xuedong/leet-code
/Problems/Algorithms/1575. Count All Possible Routes/count_all_routes.py
748
3.5625
4
#!/usr/bin/env python3 from typing import List class Solution: def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int: n = len(locations) memo = {} def aux(curr, rest): if rest < 0: return 0 if (curr, rest) in memo: return memo[(curr, rest)] ans = 0 if curr == finish: ans = 1 for next in range(n): if next != curr: cost = abs(locations[curr] - locations[next]) ans = (ans + aux(next, rest - cost)) % 1000000007 memo[(curr, rest)] = ans return ans return aux(start, fuel)
65f2f2edf091e64ceb3366a1e70907d64270d5ec
bikash0109/Python-Progs
/first sem/Lab7/test.py
586
3.71875
4
import sys def menu(userinput): while userinput is not 'q': if userinput == '1': print(userinput) if userinput == '2': print(userinput + str(2)) if userinput == 'q': sys.exit(0) print("1. GoDie \n 2. GoSwim\n 3. GoDance\n 4. q - Quit") userinput = input("Enter your choice: ") def test(): print("\n1. GoDie \n 2. GoSwim\n 3. GoDance\n 4. q - Quit") userinput = input("Enter your choice: ") if userinput == 'q': sys.exit(0) menu(userinput) if __name__ == '__main__': test()
16c8335764d3fac49fcb149a562c4608e714d601
anmolvirk1997/myrep1
/6.print patterns.py
1,476
4
4
"""for printing #### #### #### ####""" for i in range(4): for j in range(4): # continues printing in same line with charcter specified print('# ', end='*') print() for i in range(4): for j in range(i+1): # prints triangle print('#', end='') print() for i in range(4): for j in range(4-i): # reverse triangle print('#', end='') print() for i in range(5): # for equilateral trailangle for j in range(5-i): print(' ', end='') for k in range(i+1): print('*', end='') for l in range(i): print('*', end='') print() print('Triangle') for i in range(10): # Equilateral triangle using string repeating with * operand print(' '*(20-i), end='') # repeates blank space 20-i times print('*'*(2*i+1)) # reapeates * 2i+1 times eg 1,3,5,7,9... print('Triangle of numbers') for i in range(5): print(' '*(20-i), end='') for j in range(2*i+1): print(j, end='') print() print('Triangle of numbers with left right symmetry') for i in range(10): print(' '*(20-i), end='') for j in range(i, -1, -1): print(j, end='') for k in range(i): print(k+1, end='') print() print('Triangle of 0-9 with symmetry and rows>10') x = int(input('How many rows?')) for i in range(x): print(' '*((x+10)-i), end='') for j in range(i, -1, -1): print(j % 10, end='') for k in range(i): print((k+1) % 10, end='') print()
1152c077df98a4f95c605ccd3272dee91057dbf8
mohammad-/python_learner
/day23/ex23.py
632
3.890625
4
#!/usr/bin/python #Demostration of String function #.split -> split string by delimeter #sorted -> sorting #pop -> take out first element, last element when argument is -1 def splitWords(line): return line.split(' ') def sortIt(words): return sorted(words) def popFirst(words): return words.pop(0) def popLast(words): return words.pop(-1) def breakAndSort(line): l = splitWords(line) return sortIt(l) #open python cell and do import ex23 #then run following command in it #l = ex23.splitWords("one two three four") #m = ex23.sortIt(l) #m #ex23.popFirst(m) #ex23.popLast(m) #ex23.popFirst(breakAndSort("There you go!!"))
fb16518ec0868072253471acd9121c1bd04200bd
sharonsabu/pythondjango2021
/regular_expression/re9.py
251
4.03125
4
from re import * pattern='[^0-9]' #checking for other than digits from 0 to 9 source="ab Zk@9c" matcher=finditer(pattern,source) count=0 for match in matcher: print(match.start()) print(match.group()) count+=1 print("") print(count)
7a878483da9fed054dd8df84840ae713e5504cb2
udwivedi394/python
/delLLNodeGreaterValue.py
1,314
3.875
4
class Node: def __init__(self,data): self.data=data self.next=None def deleteNodeWithGreatRight(root): prev_node=root temp=root while temp: if temp.next: if temp.data < temp.next.data: if prev_node == temp: if prev_node == root: root = temp.next prev_node = temp.next else: prev_node.next = temp.next else: prev_node = temp temp = temp.next return root def traverseLL(root): temp = root while temp: print temp.data,"->", temp = temp.next print "None" root = Node(12) root.next = Node(15) root.next.next = Node(10) root.next.next.next = Node(11) root.next.next.next.next = Node(5) temp =root.next.next.next.next.next = Node(6) temp.next = Node(2) temp.next.next = Node(3) root = Node(10) root.next = Node(20) root.next.next = Node(30) root.next.next.next = Node(40) root.next.next.next.next = Node(50) temp =root.next.next.next.next.next = Node(60) #temp.next = Node(2) #temp.next.next = Node(3) root = Node(60) root.next = Node(50) root.next.next = Node(40) root.next.next.next = Node(30) root.next.next.next.next = Node(20) temp =root.next.next.next.next.next = Node(10) temp.next = Node(8) temp.next.next = Node(5) print "Before Deleting:", traverseLL(root) root = deleteNodeWithGreatRight(root) print "After Deleting:", traverseLL(root)
4961dd823db0d6f4e6ff0349b00ea74e06166c89
yuchen-he/algorithm016
/leetcode/editor/cn/[242]有效的字母异位词.py
1,996
3.609375
4
# 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。 # # 示例 1: # # 输入: s = "anagram", t = "nagaram" # 输出: true # # # 示例 2: # # 输入: s = "rat", t = "car" # 输出: false # # 说明: # 你可以假设字符串只包含小写字母。 # # 进阶: # 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况? # Related Topics 排序 哈希表 # 👍 251 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def isAnagram(self, s: str, t: str) -> bool: # 解法一: 字母排序后进行str比较(O(NlogN)) # 解法二: 建立一个hash表,对s和t各过一遍,统计每个字符的出现次数,然后比较字典是否相同(时间O(N),空间O(N)) # 解法二(一个hash): s的元素负责增加count,t的负责减少。看最后hash是否为0 if len(s) != len(t): return False # 首先长度不同则返回false hash_map = collections.defaultdict(int) # 不这样写的话,line33当dict里面没有key会报错 for i in range(len(s)): # 因为s和t长度相同,所以i能同时取到他俩的元素 hash_map[s[i]] = hash_map[s[i]] + 1 hash_map[t[i]] = hash_map[t[i]] - 1 for i in hash_map.values(): if i != 0: return False return True # 解法二(两个hash) # hash_c = {} # hash_t = {} # for c in s: # if c in hash_c.keys(): # hash_c[c] += 1 # else: hash_c[c] = 1 # # for c in t: # if c in hash_t.keys(): # hash_t[c] += 1 # else: hash_t[c] = 1 # # return hash_c == hash_t # 解法一 # s = sorted(s) # t = sorted(t) # return s == t # leetcode submit region end(Prohibit modification and deletion)
ab086ebf0fcefd1bb53671d5709d4bf4cdde13d8
FAHM7380/group6-Falahati
/Final Project/Project.py
31,428
3.90625
4
# for adding data(bills,elevator,etc.) as input please type append(root_out) in python console which root_out is the path including the name of the csv file that your inputs will be saved in there # for dividing expenses please type execute_all_division_funcs(root_in, root_out, root_info) in python console # for acquiring a balance for specific units and specified time period please type balance(root_in) in python console # for obtaining a csv file including a transaction history between a specific time period transaction_history(root_in) in python console # for acquiring a percent share from total expenses that categories or subcategories have, please type portion_by_category(root_in) or portion_by_subcategory(root_in) in python console # for acquiring a percent share from total expenses that units have, please type portion_by_unit(root_in) in python console # for acquiring a cumulative sum based on units type cumulative_sum_for_units(root_in) and for acquiring a cumulative sum based on subcategories type cumulative_sum_for_subcategories(root_in) in console python # for observing a status of the buildings total balance please type negative_balance_error(root_in) in python console # for acquiring an estimation of next year's monthly expenses for each unit please type next_year_expenditure_estimation(root_in, root_info) in python console def append(root_out: str): """ This function accepts inputs from the user. The root_out variable is the path and the name of the csv file that you want to save your inputs into. """ import pandas as pd import datetime as dt d = {'amount': [], 'time':[], 'category': [] , 'subcategory': [], 'responsible unit': [], 'related unit': [[]], 'div': [], 'description': []} amount = int(input('amount:')) d['amount'].append(amount) time = input('time( Example: 1399/09/21 ) : ') d['time'].append(dt.date(int(time[0:4]),int(time[5:7]), int(time[8:]))) category = input("category: 1) bill 2) cleaning 3) elevator 4) parking 5) repairs 6) charge 7) other [1/2/3/4/5/6/7] :") if category == '1': d['category'].append('bill') elif category == '2': d['category'].append('cleaning') elif category == '3': d['category'].append('elevator') elif category == '4': d['category'].append('parking') elif category == '5': d['category'].append('repairs') elif category == '6': d['category'].append('charge') elif category == '7': d['category'].append('other') if category == '1': subcategory = input('subcategory: 1) water 2) gas 3) electricity 4) tax [1/2/3/4] :') if subcategory == '1': subcategory = 'water' elif subcategory == '2': subcategory = 'gas' elif subcategory == '3': subcategory = 'electricity' elif subcategory == '4': subcategory = 'tax' else: subcategory = 'undefind' d['subcategory'].append(subcategory) responsible_unit = input('responsible unit:') d['responsible unit'].append(responsible_unit) related_unit = input('related unit:(please enter the related units as the form first unit number, second unit number,....Note that if you want to include all units you should enter the number of all units)').split(',') for e in related_unit: d['related unit'][0].append(eval(e)) div = input('div: 1) -e 2) -r 3) -d 4) -a 5) -p [1/2/3/4/5] :(Note that if you have selected charge as a category, -d must be chosen as the division type.)') if div == '1': div = 'equal' d['div'].append(div) elif div == '2': div = 'number' d['div'].append(div) elif div == '3': div = 'default' d['div'].append(div) elif div == '4': div = 'area' d['div'].append(div) elif div == '5': div = 'parking' d['div'].append(div) description = input('description:') d['description'].append(description) i = input('Is there anything left? A)yes B)no [A/B] :') if i == 'B': pd.DataFrame(d).to_csv(root_out, mode = 'a', header= False, index = False) return else: pd.DataFrame(d).to_csv(root_out, mode = 'a', header = False, index = False) append(root_out) ############# expense division functions # for dividing expenses please type execute_all_division_funcs(root_in, root_out, root_info) in python console def equal(root_in: str, root_out: str): """ This function divides expenses evenly between units. The root_in variable is the path and the name of your user input data excel file. The root_out variable is the path and the name of the csv file that you want to save your transactions after running the function. """ import pandas as pd import numpy as np user_input_df = pd.read_excel(root_in, names=['amount','time','category','subcategory','related unit','div'],index_col =False) user_input_df = user_input_df[user_input_df['div'] == 'equal'][['amount','time','category','subcategory','related unit']] # A series of operations for changing the related unit's class from object to a list. Useful when executing the explode method user_input_df['related unit'] = user_input_df['related unit'].str.replace('[','') user_input_df['related unit'] = user_input_df['related unit'].str.replace(']','') user_input_df['related unit'] = user_input_df['related unit'].str.replace(' ','') user_input_df['related unit'] = list(user_input_df['related unit'].str.split(',')) costs_for_each_unit = [] for i in range(len(user_input_df['related unit'])): costs_for_each_unit.append(user_input_df.iloc[i]['amount'] // len(user_input_df.iloc[i]['related unit'])) user_input_df['cost for each unit'] = np.array(costs_for_each_unit) user_input_df = user_input_df.explode('related unit') user_input_df.to_csv(root_out, mode = 'a', header = False, index = False) return def number(root_in: str, root_out: str, root_info: str): """ This function divides expenses according to the number of living in each apartment. The root_in variable is the path and the name of your user input data excel file. The root_out variable is the path and the name of the csv file that you want to save your transactions after running the function. The root_info variable is the path and the name your building residents' information excel file. """ import pandas as pd import numpy as np user_input_df = pd.read_excel(root_in, names=['amount','time','category','subcategory','related unit','div'],index_col=False) resident_info = pd.read_excel(root_info) # Changing the column name and making it the same as the other dataframe. Useful when performing merge resident_info = resident_info.rename(columns = {'number': 'related unit'}) user_input_df = user_input_df[user_input_df['div'] == 'number'][['amount','time','category','subcategory','related unit']] # A series of operations for changing the related unit's class from object to a list. Useful when executing the explode method user_input_df['related unit'] = user_input_df['related unit'].str.replace('[','') user_input_df['related unit'] = user_input_df['related unit'].str.replace(']','') user_input_df['related unit'] = user_input_df['related unit'].str.replace(' ','') user_input_df['related unit'] = list(user_input_df['related unit'].str.split(',')) # Calculating the total residents that each row's related units have and adding them as a new column to user_input_df. resident_info['related unit'] = resident_info['related unit'].astype(str) total_residents = [] for i in range(len(user_input_df['related unit'])): total = resident_info[resident_info['related unit'].isin(user_input_df.iloc[i]['related unit'])]['residents'].sum() total_residents.append(total) user_input_df['total resident'] = np.array(total_residents) user_input_df = user_input_df.explode('related unit',ignore_index = True) # Adding the related residents of each unit after the explosion method user_input_df = resident_info[['residents','related unit']].merge(user_input_df, on = 'related unit') user_input_df['cost for each unit'] = (user_input_df['amount'] * user_input_df['residents']) // user_input_df['total resident'] del user_input_df['total resident'] del user_input_df['residents'] user_input_df.to_csv(root_out, mode = 'a', header = False, index = False) return def area(root_in: str, root_out: str, root_info: str): """ This function divides expenses according to the area of each apartment. The root_in variable is the path and the name of your user input data excel file. The root_out variable is the path and the name of the csv file that you want to save your transactions after running the function. The root_info variable is the path and the name your building residents' information excel file. """ import pandas as pd import numpy as np user_input_df = pd.read_excel(root_in, names=['amount','time','category','subcategory','related unit','div'],index_col=False) resident_info = pd.read_excel(root_info) # Changing the column name and making it the same as the other dataframe. Useful when performing merge resident_info = resident_info.rename(columns = {'number': 'related unit'}) user_input_df = user_input_df[user_input_df['div'] == 'area'][['amount','time','category','subcategory','related unit']] # A series of operations for changing the related unit's class frm object to a list. Useful when executing the explode method user_input_df['related unit'] = user_input_df['related unit'].str.replace('[','') user_input_df['related unit'] = user_input_df['related unit'].str.replace(']','') user_input_df['related unit'] = user_input_df['related unit'].str.replace(' ','') user_input_df['related unit'] = list(user_input_df['related unit'].str.split(',')) # Calculating the total residents that each row's related units have and adding them as a new column to user_input_df. resident_info['related unit'] = resident_info['related unit'].astype(str) total_areas = [] for i in range(len(user_input_df['related unit'])): total = resident_info[resident_info['related unit'].isin(user_input_df.iloc[i]['related unit'])]['area'].sum() total_areas.append(total) user_input_df['total area'] = np.array(total_areas) user_input_df = user_input_df.explode('related unit',ignore_index = True) # Adding the related residents of each unit after the explosion method user_input_df = resident_info[['area','related unit']].merge(user_input_df, on = 'related unit') user_input_df['cost for each unit'] = (user_input_df['amount'] * user_input_df['area']) // user_input_df['total area'] del user_input_df['total area'] del user_input_df['area'] user_input_df.to_csv(root_out, mode = 'a', header = False, index = False) return def parking(root_in: str, root_out: str, root_info: str): """ This function divides expenses according to parkings owned by each apartment. The root_in variable is the path and the name of your user input data excel file. The root_out variable is the path and the name of the csv file that you want to save your transactions after running the function. The root_info variable is the path and the name your building residents' information excel file. """ import pandas as pd import numpy as np user_input_df = pd.read_excel(root_in, names=['amount','time','category','subcategory','related unit','div'], index_col= False) resident_info = pd.read_excel(root_info) # Changing the column name and making it the same as the other dataframe. Useful when performing merge resident_info = resident_info.rename(columns = {'number': 'related unit'}) user_input_df = user_input_df[user_input_df['div'] == 'parking'][['amount','time','category','subcategory','related unit']] # A series of operations for changing the related unit's class frm object to a list. Useful when executing the explode method user_input_df['related unit'] = user_input_df['related unit'].str.replace('[','') user_input_df['related unit'] = user_input_df['related unit'].str.replace(']','') user_input_df['related unit'] = user_input_df['related unit'].str.replace(' ','') user_input_df['related unit'] = list(user_input_df['related unit'].str.split(',')) # Calculating the total residents that each row's related units have and adding them as a new column to user_input_df. resident_info['related unit'] = resident_info['related unit'].astype(str) total_parkings = [] for i in range(len(user_input_df['related unit'])): total = resident_info[resident_info['related unit'].isin(user_input_df.iloc[i]['related unit'])]['parkings'].sum() total_parkings.append(total) user_input_df['total parking'] = np.array(total_parkings) user_input_df = user_input_df.explode('related unit',ignore_index = True) # Adding the related residents of each unit after the explosion method user_input_df = resident_info[['parkings','related unit']].merge(user_input_df, on = 'related unit') user_input_df['cost for each unit'] = (user_input_df['amount'] * user_input_df['parkings']) // user_input_df['total parking'] del user_input_df['total parking'] del user_input_df['parkings'] user_input_df.to_csv(root_out, mode = 'a', header = False, index = False) return def default(root_in: str, root_out: str, root_info: str): """ This function adds the amount to each units balance. The root_in variable is the path and the name of your user input data excel file. The root_out variable is the path and the name of the csv file that you want to save your transactions after running the function. The root_info variable is the path and the name your building residents' information excel file. """ import pandas as pd user_input_df = pd.read_excel(root_in, names=['amount','time','category','subcategory','related unit','div'],index_col=False) user_input_df = user_input_df[user_input_df['div'] == 'default'][['amount','time','category','subcategory','related unit']] # A series of operations for changing the related unit's class frm object to a list. Useful when executing the explode method user_input_df['related unit'] = user_input_df['related unit'].str.replace('[','') user_input_df['related unit'] = user_input_df['related unit'].str.replace(']','') user_input_df['related unit'] = user_input_df['related unit'].str.replace(' ','') user_input_df['related unit'] = list(user_input_df['related unit'].str.split(',')) user_input_df = user_input_df.explode('related unit',ignore_index = True) user_input_df['cost for each unit'] = user_input_df['amount'] user_input_df.to_csv(root_out, mode = 'a', header = False, index = False) return def execute_all_division_funcs(root_in: str, root_out: str, root_info: str): import pandas as pd equal(root_in, root_out) number(root_in, root_out, root_info) area(root_in, root_out, root_info) parking(root_in, root_out, root_info) a = pd.read_csv(root_out, names = ['unit','amount','time','category','subcategory','cost for each unit']) a.to_csv(root_out, mode = 'w') return ############# report functions def balance(root_in: str): """ This function calculates the balance for each unit within a specific time period. The root_in variable is the path and the name of the excel file containing transactions. """ import pandas as pd user_input_df = pd.read_excel(root_in) # the user enters the specified units and the time period selected_units = input('Please enter your selected units separated by commas. You can type all if you want to include all units:').split(',') time_period = input('please enter your selected time period as the form yyyy-mm-dd separated by commas with the earlier date typed first. If you want to receive a balance report up to now you must enter the first and the last date that a transaction has been made:').split(',') # changing the class of selected units from str to int for i in range(len(selected_units)): selected_units[i] = eval(selected_units[i]) if selected_units == 'all': final_balance = user_input_df[(user_input_df['date'] >= time_period[0]) & (user_input_df['date'] <= time_period[1])].groupby('unit').aggregate({'cost for each unit': 'sum'}).reset_index() return final_balance else: final_balance = user_input_df[(user_input_df['date'] >= time_period[0]) & (user_input_df['date'] <= time_period[1]) & (user_input_df['unit'].isin(selected_units))][['unit', 'cost for each unit']].groupby('unit').aggregate({'cost for each unit': 'sum'}).reset_index() return final_balance def transaction_histoy(root_in: str, root_out: str): """ This function returns transactions within a specific time period in the form of csv. The root_in variable is the path and the name of the excel file containing transactions. The root_out variable is the path and the name of the csv file that you want the reports to be saved. """ import pandas as pd transactions = pd.read_excel(root_in) # the user enters a time period time_period = input('please enter your selected time period as the form yyyy-mm-dd separated by commas with the earlier date typed first. If you want to receive a balance report up to now you must enter the first and the last date that a transaction has been made:').split(',') # filtering based on time period final_df = transactions[(transactions['date'] >= time_period[0]) & (transactions['date'] <= time_period[1])] final_df.to_csv(root_out, mode= 'w') return 'A csv file with the name of balance has been created. Please check it.' def portion_by_category(root_in: str): """ This function reports the amount share that each category has from the total expenses. The root_in variable is the path and the name of the excel file containing transactions.""" import pandas as pd import matplotlib.pyplot as plt user_input_df = pd.read_excel(root_in) shares = user_input_df.groupby('category').aggregate({'amount': 'sum'}).reset_index() # the % share column demonstrates that what fraction of total expenses belongs to each category shares['% share'] = (shares['amount'] / shares['amount'].sum()) * 100 # plotting for better understanding plt.pie(shares['amount'], labels = shares['category'], shadow = False, autopct ='%1.f%%') plt.title('portion by subcategory') plt.show() return shares,'A plot has been drawn in the plots pane.Please check it' def portion_by_subcategory(root_in: str): """ This function reports the amount share that each subcategory has from the total expenses costed by bills. The root_in variable is the path and the name of the excel file containing transactions.""" import pandas as pd import matplotlib.pyplot as plt user_input_df = pd.read_excel(root_in) user_input_df = user_input_df[user_input_df['category'] == 'bill'] shares = user_input_df.groupby('subcategory').aggregate({'amount': 'sum'}).reset_index() shares['% share'] = (shares['amount'] / shares['amount'].sum()) * 100 # plotting for better understanding plt.pie(shares['amount'], labels = shares['subcategory'], shadow = True, autopct = '%1.f%%') plt.title('portion by subcategory') plt.show() return shares,'A plot has been drawn in the plots pane.Please check it' def portion_by_unit(root_in: str): """ This function reports the amount share that each unit has from total expenses. The root_in variable is the path and the name of the excel file containing transactions.""" import pandas as pd import matplotlib.pyplot as plt transactions = pd.read_excel(root_in) shares = transactions.groupby('unit').aggregate({'cost for each unit': 'sum'}).reset_index() shares['% share'] = (shares['cost for each unit'] / shares['cost for each unit'].sum()) # plotting for better understanding plt.pie(shares['cost for each unit'], labels = shares['unit'], shadow = True, autopct = '%1.f%%') plt.title('portion by unit') plt.show() return shares,'A plot has been drawn in the plots pane. Please chack it.' def negative_balance_error(root_in: str): """ This function returns a warning if the buildings total balance is negative. The root_in variable is the path and the name of the excel file containing transactions. """ import pandas as pd transactions = pd.read_excel(root_in) income = transactions[transactions['category'] == 'charge']['cost for each unit'].sum() expenses = transactions[transactions['category'] != 'charge']['cost for each unit'].sum() total_balance = income - expenses if total_balance >= 0: return ('Your total balance is' + str(total_balance)+ ', All expenses have been paid.') else: return ('Warning! You have negative total balance. You need at least' + str(abs(total_balance))) def cumulative_sum_for_units(root_in: str): """ This function returns a cumulative sum for the expenses of each unit based on specified units within a specific time period. The root_in variable is the path and the name of the excel file containing transactions. """ import pandas as pd import matplotlib.pyplot as plt transactions = pd.read_excel(root_in) # the user enters the specified units and subcategories and time period selected_subcategories = input('Please enter your specified subcategories separated by commas. You can type all if you want to include all subcategories: ') selected_units = input('Please enter your specified units separated by commas and all lower case. You can type all if you want to include all units: ') time_period = input('please enter your selected time period as the form yyyy-mm-dd separated by commas with the earlier date typed first. If you want to receive a balance report up to now you must enter the first and the last date that a transaction has been made: ').split(',') if (selected_subcategories == 'all') and (selected_units == 'all'): # filtering by time period transactions = transactions[(transactions['date'] >= time_period[0]) & (transactions['date'] <= time_period[1])].groupby('unit').aggregate({'cost for each unit': 'sum'}).reset_index() units = transactions['unit'] del transactions['unit'] cumulative_sum = transactions.cumsum() # plotting plt.bar(units, cumulative_sum['cost for each unit']) plt.xlabel('unit') plt.ylabel('cumulative sum') plt.title('cumulative sum for units') plt.show() return 'A plot has been drawn in the plots pane. Please check it.' elif (selected_subcategories == 'all') and (selected_units != 'all'): selected_units = selected_units.split(',') # changing the class of selected units from str to int for i in range(len(selected_units)): selected_units[i] = int(selected_units[i]) # filtering by selected units and time period transactions = transactions[(transactions['date'] >= time_period[0]) & (transactions['date'] <= time_period[1]) & (transactions['unit'].isin(selected_units))].groupby('unit').aggregate({'cost for each unit': 'sum'}).reset_index() units = transactions['unit'] del transactions['unit'] cumulative_sum = transactions.cumsum() # plotting plt.bar(units, cumulative_sum['cost for each unit']) plt.xlabel('unit') plt.ylabel('cumulative sum') plt.title('cumulative sum for units') plt.show() return 'A plot has been drawn in the plots pane. Please check it.' elif (selected_subcategories != 'all') and (selected_units == 'all'): selected_subcategories = selected_subcategories.split(',') # if specific subcategories are included then the category column must be a bill transactions = transactions[(transactions['date'] >= time_period[0]) & (transactions['date'] <= time_period[1]) & (transactions['category'] == 'bill') & (transactions['subcategory'].isin(selected_subcategories))].groupby('unit').aggregate({'cost for each unit': 'sum'}).reset_index() units = transactions['unit'] del transactions['unit'] cumulative_sum = transactions.cumsum() # plotting plt.bar(units, cumulative_sum['cost for each unit']) plt.xlabel('unit') plt.ylabel('cumulative sum') plt.title('cumulative sum for units') plt.show() return 'A plot has been drawn in the plots pane. Please check it.' elif (selected_subcategories != 'all') and (selected_units != 'all'): selected_units = selected_units.split(',') selected_subcategories = selected_subcategories.split(',') # changing the class of selected units from str to int for i in range(len(selected_units)): selected_units[i] = int(selected_units[i]) # filtering by specified units and subcategories and time period transactions = transactions[(transactions['date'] >= time_period[0]) & (transactions['date'] <= time_period[1]) & (transactions['unit'].isin(selected_units)) & (transactions['category'] == 'bill') & (transactions['subcategory'].isin(selected_subcategories))].groupby('unit').aggregate({'cost for each unit': 'sum'}).reset_index() units = transactions['unit'] del transactions['unit'] cumulative_sum = transactions.cumsum() # plotting plt.bar(units, cumulative_sum['cost for each unit']) plt.xlabel('unit') plt.ylabel('cumulative sum') plt.title('cumulative sum for units') plt.show() return 'A plot has been drawn in the plots pane. Please check it.' def cumulative_sum_for_subcategories(root_in: str): """ This function returns a cumulative sum for the expenses of each subcategory within a specific time period. The root_in variable is the path and the name of the excel file containing transactions.""" import pandas as pd import matplotlib.pyplot as plt transactions = pd.read_excel(root_in) # if specific subcategories are included then the category column must be a bill transactions = transactions[transactions['category'] == 'bill'] # the user enters the specified subcategories and time period selected_subcategories = input('Please enter your specified subcategories separated by commas. You can type all if you want to include all subcategories: ') time_period = input('please enter your selected time period as the form yyyy-mm-dd separated by commas with the earlier date typed first. If you want to receive a balance report up to now you must enter the first and the last date that a transaction has been made: ').split(',') if selected_subcategories == 'all': # filtering by time period transactions = transactions[(transactions['date'] >= time_period[0]) & (transactions['date'] <= time_period[1])].groupby('subcategory').aggregate({'cost for each unit': 'sum'}).reset_index() subcategories = transactions['subcategory'] del transactions['subcategory'] cumulative_sum = transactions.cumsum() # plotting plt.bar(subcategories, cumulative_sum['cost for each unit']) plt.xlabel('subcategory') plt.ylabel('cumulative sum') plt.title('cumulative sum for subcategories') plt.show() return 'A plot has been drawn in the plots pane. Please check it.' else: selected_subcategories = selected_subcategories.split(',') # filtering by specified subcategories and time period transactions = transactions[(transactions['date'] >= time_period[0]) & (transactions['date'] <= time_period[1]) & (transactions['subcategories'].isin(selected_subcategories))].groupby('subcategory').aggregate({'cost for each unit': 'sum'}).reset_index() subcategories = transactions['subcategory'] del transactions['subcategory'] cumulative_sum = transactions.cumsum() # plotting plt.bar(subcategories, cumulative_sum['cost for each unit']) plt.xlabel('subcategory') plt.ylabel('cumulative sum') plt.title('cumulative sum for subcategories') plt.show() return 'A plot has been drawn in the plots pane. Please check it.' def next_year_expenditure_estimation(root_in: str, root_info: str): """ This function estimates the amount of expenses that each unit should pay in the next year. The root_in variable is the path and the name of the excel file containing transactions. """ import pandas as pd user_input_df = pd.read_excel(root_in) resident_info = pd.read_excel(root_info) inflation_rate = 1.1 user_input_df = user_input_df[user_input_df['category'] != 'charge'] last_year_total_costs = user_input_df[(user_input_df['time'] >= (user_input_df['time'].iloc[-1][0:5] + '01-01')) & (user_input_df['time'] <= user_input_df['time'].iloc[-1])]['amount'].sum() next_year_expenditure_projection = last_year_total_costs * inflation_rate unit_next_year_monthly_payment = next_year_expenditure_projection // (12 * len(resident_info['number'])) return unit_next_year_monthly_payment
968baf40e7290fe8f07570550d1a3df64c2eed02
sugia/leetcode
/Shortest Subarray with Sum at Least K.py
1,021
3.71875
4
''' Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1. Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3 Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9 ''' class Solution(object): def shortestSubarray(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ s = [0] for x in A: s.append(s[-1] + x) res = float('inf') vec = [] for i in xrange(len(s)): while vec and s[i] - s[vec[0]] >= K: res = min(res, i - vec[0]) vec.pop(0) while vec and s[i] <= s[vec[-1]]: vec.pop() vec.append(i) if res == float('inf'): return -1 else: return res
88ebbe7a367b82ed4bdb56d2d4297a0247770512
parisadikshit/Probability-Distributions
/ProbabilityDistributions.py
3,363
3.53125
4
#!/usr/bin/env python # coding: utf-8 # # Probability Distributions and plots using Python # In[1]: #importing all necessary python modules import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns get_ipython().run_line_magic('matplotlib', 'inline') # In[2]: #setting seaborn styles sns.set(color_codes=True) # In[3]: #setting plot size sns.set(rc={'figure.figsize':(5,5)}) # In[4]: #reading csv- marks of 60 students out of 50 data = pd.read_csv('fictional_marks.csv') # In[5]: #first five rows of the dataset data.head() # In[6]: #relational plot of students' marks and claiming the response eg.student with marks 25 doesn't want extra class #by default scatterplot ax = sns.relplot(x='Response for Extra Class',y='Total Marks',data=data) # In[7]: #line plot ax = sns.relplot(x='Response for Extra Class',y='Total Marks',data=data,kind='line') # In[8]: #column marks - array marks = data['Total Marks'] # In[9]: # a histogram ax = sns.distplot( marks, hist=True, bins=50, color='skyblue', hist_kws={'linewidth':20,'alpha':1} ) # # Another Dataset Analysis # In[10]: Data_2 = pd.read_csv('fictional_studentinfo.csv') # In[11]: Data_2.head() # In[ ]: # # Probability Distributions # # By using sns.displot(): # # Uniform Distribution: # In[12]: #importing uniform function from scipy stats from scipy.stats import uniform # In[13]: # generating uniform distributed random numbers starting from 10 with scale of 20 and size 1000 n=1000 start=10 width=20 data_uniform = uniform.rvs(size=n,loc=start,scale=width) # In[14]: ax= sns.displot( data_uniform, bins=100, kde=True, color='skyblue' ) ax.set(xlabel='Uniform Distribution',ylabel='Frequency') # # Normal Distribution: # In[15]: #importing normal function from scipy stats from scipy.stats import norm # In[16]: #generating normal distributed random variables;loc,scale being mean and standard deviation respectively data_normal = norm.rvs(size=1000,loc=0,scale=1) # In[17]: ax= sns.displot( data_normal, bins=100, kde=True, color='skyblue' ) ax.set(xlabel='Normal Distribution',ylabel='Frequency') # # Poisson Distribution: # In[18]: #importing poisson function from scipy stats from scipy.stats import poisson # In[19]: #generating poisson distributed random varibales data_poisson = poisson.rvs(mu=6,size=1000) # In[20]: ax= sns.displot( data_poisson, bins=100, kde=False, color='skyblue', ) ax.set(xlabel='Poisson Distribution',ylabel='Frequency') # # By using sns.distplot(): # # Poisson Distribution: # In[21]: ax= sns.distplot( data_poisson, bins=100, kde=False, color='skyblue', hist_kws={'linewidth':15,'alpha':1} ) ax.set(xlabel='Poisson Distribution',ylabel='Frequency') # # Normal Distribution: # In[22]: ax= sns.distplot( data_normal, bins=100, kde=True, color='skyblue', hist_kws={"linewidth":20,"alpha":1} ) ax.set(xlabel='Normal Distribution',ylabel='Frequency') # # Uniform Distribution: # In[23]: ax = sns.distplot( data_uniform, bins=100, kde=True, color='skyblue', hist_kws={'linewidth':20,'alpha':1} ) ax.set(xlabel='Uniform Distribution',ylabel='Frequency') # # Bernoulli Distribution # In[ ]: # In[ ]:
28021005df8644891a06d18939df2e56cb59b7fd
vasetousa/Python-Advanced
/Comprehensions/Heroes Inventory.py
400
3.6875
4
heroes = input().split(", ") inventory = {hero: {} for hero in heroes} items = input() while not items == "End": hero, item, cost = items.split('-') cost = int(cost) if item not in inventory[hero]: inventory[hero][item] = cost items = input() for hero, values in inventory.items(): print(f"{hero} -> Items: {len(inventory[hero])}, Cost: {sum(inventory[hero].values())}")
ee43fa69a43fac564afd56873bdf21676c9de4ae
maapinho/python_play
/rock_paper_scissors.py
1,819
4.0625
4
### Rock, paper, scissors from random import randint from time import sleep import sys # Constants BARS=20 OPTIONS=['Rock','Paper','Scissors'] WINNERLEFT = [ ['Rock','Scissors'], ['Paper','Rock'], ['Scissors','Paper'] ] # Result sentences RESULTWIN = 'You WON!' RESULTLOSE = 'You lost. Try one more time' RESULTTIE = 'Tie. Play again' def bars(): print('-'*BARS) def emptyline(): print('') # Function for the computer pick def computerpick(): return OPTIONS[randint(0,len(OPTIONS)-1)] # Decide on winner # Return True if first element is winner def winner(choice1,choice2): return [choice1,choice2] in WINNERLEFT # main program loop while True: # Print options and ask for player option for i in OPTIONS: print(OPTIONS.index(i)+1,':',i) # Ask for the player's option while True: try: emptyline() optstr=input('Pick your option (1-3) or "q" to exit:') opt=int(optstr) player=OPTIONS[opt-1] break except ValueError: if optstr=='q': # exit the program if q is pressed sys.exit('Bye') print('String input. The value must be a number between 1 and 3 \n') except IndexError: print('Wrong value. The number must be between 1 and 3 \n') # show player's option bars() print('Your pick: ',player) #bars() sleep(2) # Computer pick computer=computerpick() #bars() print('Computer pick: ',computer) bars() emptyline() sleep(1) # Compare picks and declare a winner bars() if computer == player: print(RESULTTIE) elif winner(player,computer): print(RESULTWIN) else: print(RESULTLOSE) bars() sleep(2) emptyline() # hmmmm...
6d7c1244c3a7df9c6a9daae78069ee46d7656e64
huandoit/pyStudy
/python3-cookbook/Chapter1/1.9.py
1,221
3.90625
4
# -*- coding: utf-8 -*- """ @Time : 2020/3/18 10:49 @Author : WangHuan @Contact : hi_chengzi@126.com @File : 1.9.py @Software: PyCharm @description: 在两个字典中寻寻找相同点(比如相同的键、相同的值等等) """ a = { 'x' : 1, 'y' : 2, 'z' : 3 } b = { 'w' : 10, 'x' : 11, 'y' : 2 } # 查看相同键,返回{'y', 'x'} print(a.keys() & b.keys()) # 查看不同键,返回{'z'} print(a.keys() - b.keys()) # 查看相同的键值对,返回{('y', 2)} print(a.items() & b.items()) # 以现有字典构造一个排除几个指定键的新字典,返回{'y': 2, 'x': 1} c = {key:a[key] for key in a.keys() - {'z', 'w'}} print(c) ''' 1.字典可以看成是一个键集合与一个值集合的映射关系,通过keys()方法获得的对象可以进行集合操作 2.values()方法获得的对象不支持集合操作,因为值视图不能保证所有的值互不相同,这样会导致某些集合操作会出现问题,可以使用set()转换为集合 3.集合操作包括并、交、差运算 4.集合内的元素是不重复且没有顺序的 5.字典的items()方法返回一个包含(键,值)对的元素视图对象,这个对象同样也支持集合操作 '''
609076bad51a47b390b000d810e4c1d598886955
AndersonBatalha/Programacao1
/Estrutura de Decisão/decisão-07.py
279
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 7. Faça um Programa que leia três números e mostre o maior e o menor deles. numeros = [] for i in range (1, 4): n = float(raw_input("Número %d: " % i)) numeros.append(n) print "Maior:", max(numeros), "\tMenor:", min(numeros)
54716be963e2737010aea77320eb204d53ba9983
AdamZhouSE/pythonHomework
/Code/CodeRecords/2743/40186/318996.py
703
3.859375
4
n=int(input()) a=[] for i in range(n): a.append(input()) if a==['1 2 3 4 5', '1 2', '2 4', '2 3', '4 5']: print(1) print(2) print(1) print(1) print(0) elif a==['1 5 6 4 3 2', '1 2', '2 4', '2 3', '4 5', '5 6']: print(1) print(2) print(1) print(2) print(2) print(1) elif a==['1 6 2 4 3 5', '1 2', '2 4', '2 3', '4 5', '5 6']: print(1) print(4) print(1) print(4) print(2) print(1) elif a==['1 6 2 4 3 5 7 8', '1 2', '1 7', '7 8', '2 4', '2 3', '4 5', '5 6']: print(2) print(5) print(1) print(5) print(3) print(1) print(1) print(0) else: print(1) print(2) print(1) print(2) print(1)
2860c04c1faaa33c4667c3efb3232a839f3d0678
DritiTannk/python-challanges
/string_permutation.py
971
4.3125
4
"""Given a string S. The task is to print all permutations of a given string. Example: Input: ABC Output: ABC ACB BAC BCA CAB CBA """ from itertools import permutations def string_permutation(word): """ This Function returns the permutated list of the user string """ words_list = [] permutations_list = permutations(word) # This function will generate all the strings and return a list. for item in permutations_list: format_word = ''.join(item) words_list.append(format_word) return words_list if __name__ == '__main__': usr_string = input("Enter The Word: ") if (usr_string == ''): print("\n *** Permutation of Empty Word cannot be found !!! *** ") else: result = string_permutation(usr_string) print('The Permutation List of the given \'{}\' Word are as follows:'.format(usr_string)) for i in range(1, len(result)): print(" Word {0}: {1}".format(i, result[i]))
287100c82952e05ef14ccb6d84add786f9600f28
Christopher-Cannon/python-docs
/Example code/24 - shift one.py
1,184
4.0625
4
# Attempt to match a letter to its position in the alphabet and return that number def find_letter(letter, my_list): for x in range(len(my_list)): # Return alphabet position if match if(letter == my_list[x]): return x # If no match, return original character return letter # Shift each letter in a string to the next letter in the alphabet def shift_one(string): alphabet, new_string = "abcdefghijklmnopqrstuvwxyz", "" for x in range(len(string)): # Check if letter is in the alphabet char_pos = find_letter(string[x].lower(), alphabet) # Int returned, we have a letter to shift along if(isinstance(char_pos, str) == False): # If pos == 25 (z) then pos = 0 (a), else shift by 1 if(char_pos == 25): char_pos = 0 else: char_pos += 1 # Insert char + 1 to new string new_string = new_string + alphabet[char_pos] # String returned, append char else: new_string += char_pos print("Original: {}\nShifted: {}".format(string, new_string)) shift_one("Shift each letter along one.")
d1876e41133f958367b76e994f4ecfe73919adc4
rc-xy/Data-structure
/BinarySearchTree.py
3,574
4.0625
4
""" This program implements a binary search tree that has functions according to assignment descriptions. Student number: 20146359 Student name: Xinyu Chen Date: Mar 5, 2021 """ # reference to creating BST: https://stackoverflow.com/questions/5444394/how-to-implement-a-binary-search-tree-in-python class Node: def __init__(self, val=None, left=None, right=None): self.val = val self.left = left self.right = right # Reference: CISC 235 Red and Black Tree implementation tutorial def is_a_leaf(self): if self.value == None: return True else: return False class BinarySearchTree: def __init__(self): self.root = None self.weight = [] self.totalHeight = 0 def insert(self, key): if self.root is None: self.root = Node(key) else: self.rec_insert(self.root, key) def rec_insert(self, node, key): if key > node.val: if node.right == None: node.right = Node(key) else: self.rec_insert(node.right, key) else: if node.left == None: node.left = Node(key) else: self.rec_insert(node.left, key) # This function with its helper function returns the sum of all nodes' height in the tree. def getTotalHeight(self, node): # If the node has no children if node == None: return 0 else: self.totalHeight = self.getTotalHeight(node.left) + self._getTotalHeight(node) + self.getTotalHeight(node.right) return self.totalHeight def _getTotalHeight(self, node): # If the tree is empty if node == None: return -1 else: return max(self._getTotalHeight(node.left), self._getTotalHeight(node.right))+1 # To implement the getWeightBalanceFactor, I referenced the way to get the size of a tree. # Reference to getting the size of a tree: https://www.geeksforgeeks.org/write-a-c-program-to-calculate-size-of-a-tree/ def getWeightBalanceFactor(self): if self.root == None: return None else: self._getWeightBalanceFactor(self.root) return max(self.weight) def _getWeightBalanceFactor(self, node): if node == None: return 0 else: left = self._getWeightBalanceFactor(node.left) right = self._getWeightBalanceFactor(node.right) self.weight.append(abs(right-left)) # '1' is the size for the node itself if it is not null. return self._getWeightBalanceFactor(node.left) + 1 + self._getWeightBalanceFactor(node.right) # reference code to printing out BST: https://www.geeksforgeeks.org/print-binary-tree-2-dimensions/ def print2DUtil(self, node, space): if node == None: return space += 5 self.print2DUtil(node.right, space) print() for i in range(5, space): print(end=" ") print(node.val) self.print2DUtil(node.left, space) def print2D(self, node): self.print2DUtil(node, 0) if __name__ == "__main__": tree = BinarySearchTree() tree.insert(6) tree.insert(4) tree.insert(9) tree.insert(5) tree.insert(8) tree.insert(7) print("Total height:", tree.getTotalHeight(tree.root)) print("Balance factor", tree.getWeightBalanceFactor()) print("\nBinary tree:\n") tree.print2D(tree.root)
2b1b042fae8cb95bff10fae51cdf1f9e36dfda5c
venusing1998/learning
/python3-liaoxuefeng.com/8.py
282
4.3125
4
"""以下函数允许计算两个数的乘积,请稍加改造,变成可接收一个或多个数并计算乘积: def product(x, y): return x * y """ def product(x, *args): num = 1 for i in args: num = num * i return num * x print(product(2, 5, 7))
954ee95d273b219a05745d67c0391bc9d235d0ba
elenaborisova/Python-OOP
/04. Classes and Instances - Exercise/05_time.py
660
3.96875
4
from datetime import datetime, timedelta class Time: def __init__(self, hours: int, minutes: int, seconds: int): self.time = datetime(100, 1, 1, hours, minutes, seconds) def set_time(self, hours: int, minutes: int, seconds: int): self.time = datetime(100, 1, 1, hours, minutes, seconds) def get_time(self): date, time = str(self.time).split() return time def next_second(self): self.time += timedelta(seconds=1) return self.get_time() time = Time(9, 30, 59) print(time.next_second()) time2 = Time(10, 59, 59) print(time2.next_second()) time3 = Time(23, 59, 59) print(time3.next_second())
bcd97963032818598a22286b629e6e241c539e9d
xaviergthiago/PycharmProjects
/ExerciciosPython/Desafios/desafio037.py
701
4.125
4
numero=(int(input('Digite um número inteiro: '))) opcao=(int(input('Selecione: 1-para binário, 2-para octal, 3-para hexadecimal '))) if opcao==1: print('Em binário o número {} é: {} ' .format(numero, bin(numero)[2:])) # [2:] para tratamento de String, pois Python imprime 0b antes do valor convertido elif opcao==2: print('Em octal o número {} é: {} ' .format(numero, oct(numero)[2:])) # [2:] para tratamento de String, pois Python imprime 0o antes do valor convertido elif opcao==3: print('Em hexadecimal o número {} é: {} ' .format(numero, hex(numero)[2:])) # [2:] para tratamento de String, pois Python imprime 0x antes do valor convertido else: print('Opção inválida!')
38752ccc4e47e741389098a14fc697c81ebebc20
hongminpark/Algorithms
/Sort/SelectionSort.py
737
3.71875
4
def selection_sort(a): """ [idea] 배열의 모든 아이템에 대하여 순차 탐방을 하는데, 매 i번째를 탐색하고, i+1부터의 리스트 중 최소값을 선택해 바꾼다. 매번 탐방 중인 값과 그 이후의 값들을 비교해서 앞에서부터 차례대로 가장 작은 값들이 나온다. """ for i, item in enumerate(a): tmp_idx = i tmp_min = item for i_, item_ in enumerate(a[i+1:]): if item_ < tmp_min: tmp_min = item_ tmp_idx = i + i_ + 1 a[i], a[tmp_idx] = a[tmp_idx], a[i] return a if __name__ == "__main__": a = [2,5,1,10,3,9] print(selection_sort(a))
5a2e54bda771efd0711321cda93af47bc77594ca
daniel-reich/ubiquitous-fiesta
/7nfSdzzpvTta8hhNe_13.py
129
3.609375
4
def organize(txt): if txt: n, a, o = txt.split(', ') return {'name': n, 'occupation': o, 'age': int(a)} return {}
4c94c0c1674ec8ab2f5a2f24da95721b1d51d46f
aryajayan/python-training
/day1/change-char.py
156
3.875
4
#Given a string python, try printing cython using slicing [start:stop] and concatenation. + str="python" newchar="c" newstr=newchar + str[1:] print(newstr)
4a8dff55d2212ba576c02cf278d771f4417791e3
abhi-laksh/Python
/Basics/summation.py
350
3.859375
4
n=int(input("Enter nth term : ")) def sumOfn(a): s1=0 for i in range(1,a+1): s1+=i return s1 def sumOfn2(a): s2=0 for i in range(1,a+1): s2+=i**2 return s2 def sumOfn3(a): s3=0 for i in range(1,a+1): s3+=i**3 return s3 sum1=sumOfn(n) sum2=sumOfn2(n) sum3=sumOfn3(n) print(sum1,sum2,sum3)
cd2edd4b14c0db5052370b71b2d9949f8821c524
prasadgopu/Competitive-Programming
/Week 3 Exam/Paranthesis.py
817
3.640625
4
global final_list def findcombinations(temp_list, position, n, open_bracket, close_bracket): if close_bracket==n: s='' for i in range(len(temp_list)): s+=temp_list[i] final_list.append(s) return else: if open_bracket > close_bracket : temp_list[position]='}' findcombinations(temp_list,position+1,n,open_bracket,close_bracket+1) if open_bracket <n: temp_list[position]='{' findcombinations(temp_list,position+1,n,open_bracket+1,close_bracket) def parenthisis(n): global final_list final_list=[] list=[None]*(2*n) findcombinations(list,0,n,0,0) print (final_list,len(final_list)) pass parenthisis(2) parenthisis(3) parenthisis(5) parenthisis(4) parenthisis(1) parenthisis(6)
e6aa2b937d79e09173cc4e9d52a2e76b30c44c6e
xingleigao/study
/python/base-knowloage/dictionary/test3.py
197
3.796875
4
#!/usr/bin/python #coding = utf-8 dict = {'name':'Zara','Age':7,'Class':'First'} del dict['Name'] dict.clear() del dict print("dict['Age']: ",dict['Age']) print("dict['School']:",dict['School'])
594ffb6c7aca99f4cde1677569a97a6a7ed36141
cjhopp/scripts
/python/lbnl/GPS.py
971
3.671875
4
#!/usr/bin/python """Functions for parsing and plotting GPS waveforms""" import numpy as np from datetime import datetime, timedelta def decyear_to_datetime(times): """ Helper to convert decimal years to datetimes SO Answer here: https://stackoverflow.com/questions/20911015/decimal-years-to-datetime-in-python """ # TODO Will accumulate errors for leap years over multiple years! start = times[0] year = int(start) rems = [t - int(t) for t in times] bases = [datetime(int(t), 1, 1) for t in times] dtos = [b + timedelta( seconds=(b.replace(year=b.year + 1) - b).total_seconds() * rems[i]) for i, b in enumerate(bases)] return dtos def read_PANGA(in_file): """ Read in data from CWU geodetic array website :param in_file: Path to data file :return: """ arr = np.loadtxt(in_file, skiprows=30) times = decyear_to_datetime(arr[:, 0]) return times, arr[:, 1], arr[:, 2]
92d32c68d87a7097dc311a4ce2218ed8b2f0e2a9
tdnzr/project-euler
/Euler019.py
1,915
4.125
4
# Solution to Project Euler problem 19 by tdnzr. # Preliminary thoughts: # I don't have to consider the special case for leap years on centuries, # because 2000 *is* divisible by 400. In this situation, leap years are just every 4 years. # Straightforward solution: Loop through all years and months, # and check if the current month is a Sunday. # How do I know that a month begins with a Sunday? # By taking the day count modulo 7, then comparing the remainder with an offset. # In my original solution, I reset the day count after each year, # so I also had to compute the weekday offset again for the next year. # But this is unnecessary; we can just keep a running total of the day we're currently # on, counting from the first day of 1901, rather than from the current year. def run(): monthLengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] first_sunday_count = 0 weekdayOffset = 6 # Meaning: 1901 began with a Tuesday, so days with first_of_month % 7 == 6 are Sundays. # We begin the 'day' counter at 1, corresponding to the first day of January 1901. # Then we check if this day is a Sunday. Finally, we add the length of the current month # to this count, after which its value corresponds to the first day of the next month. day = 1 for year in range(1901, 2000 + 1): # Loop through the months, then check if # the first of the month is a Sunday. for month in range(1, 12 + 1): if day % 7 == weekdayOffset: first_sunday_count += 1 day += monthLengths[month - 1] # In leap years, extend February by one day. if year % 4 == 0 and month == 2: day += 1 return first_sunday_count if __name__ == "__main__": print(f"The number of Sundays that fell on the first of a month in the time interval in question is: {run()}")
54fa7c490143b29f1ee853670af4f219cfe49e8c
anushthakalia/AlgoDS-python
/practice/strings/reverse_words.py
173
3.53125
4
def reverse_sentance(arr): print('.'.join(arr.split('.')[::-1])) if __name__ == '__main__': t = int(input()) for _ in range(t): arr = input() reverse_sentance(arr)
fd9ee9a7fa7404e8a005fa868cb2edffffc702b5
idilsulo/cracking-the-coding-interview
/ch_03_stacks_and_queues/stack_min.py
1,939
3.9375
4
""" PROBLEM Stack Min: * How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? * Push, pop and min should all operate in 0(1) time. """ """ Notes: * This question is really good. * Consider having each node know the minimum of its "substack" (all the elements beneath it, including itself). * If all the nodes know the minimum in its substack, access time to the minimum element is O(1). * On top of the default pop() and push() operations, we need to check if we have a new global minimum, and update it accordingly. * These checks also require O(1) time, so the time complexity of pop(), push() and minimum() is O(1). """ class StackNode: def __init__(self, x): self.data = x self.next = None self.min_node = self class Stack: def __init__(self): self.top = None self.min = None self.count = 0 def pop(self): if self.count == 0: print("Stack is empty.") elif self.count == 1: self.min = None self.top = None self.count = 0 else: self.min = self.top.next.min_node self.top = self.top.next self.count -= 1 def push(self, item): node = StackNode(item) node.next = self.top self.top = node self.count += 1 if self.count == 1: self.min = node else: node.min_node = self.min if self.minimum() > item: self.min = node def peek(self): if self.count > 0: return self.top.data return None def is_empty(self): return self.count == 0 def minimum(self): if self.count > 0: return self.min.data else: print("Stack is empty.") return None if __name__ == '__main__': s = Stack() s.push(1) s.push(2) s.push(0) s.push(3) print("Count: %d" % (s.count)) print("Min : %d" % (s.minimum())) s.pop() print("Count: %d" % (s.count)) print("Min : %d" % (s.minimum())) s.pop() print("Count: %d" % (s.count)) print("Min : %d" % (s.minimum()))
6964e72bfc2b075050428a76f2abb7cd3e34e1cf
JoyDu/Code
/python/designpatterns/code/单例模式.py
684
3.53125
4
# coding = utf-8 class Singleton(object): __instance = None def __new__(cls, age, name): # 如果类数字能够__instance没有或者没有赋值 # 那么就创建一个对象,并且赋值为这个对象的引用,保证下次调用这个方法时 # 能够知道之前已经创建过对象了,这样就保证了只有1个对象 if not cls.__instance: cls.__instance = object.__new__(cls) return cls.__instance a = Singleton(18, "dongGe") b = Singleton(8, "dongGe") print(id(a)) print(id(b)) a.age = 19 # 给a指向的对象添加一个属性 print(b.age) # 获取b指向的对象的age属性
b649f3a4f577a97d04d840c0b158988912919c84
darkaxelcodes/randompython
/JumpSearch.py
1,160
4.21875
4
''' Program to implement Jump Search. The time complexity of above algorithm is O(sqrt(n)). It works on a sorted array ''' def linear_search(list_of_numbers,digit_to_find): while list_of_numbers is not None: for i in range(len(list_of_numbers)): if digit_to_find == list_of_numbers[i]: return i+1 break else: return None def jump_search(sorted_list_of_digits, digit_to_find, jump_size): length = len(sorted_list_of_digits) for i in range(0,length,jump_size): if digit_to_find <= sorted_list_of_digits[i]: if digit_to_find == sorted_list_of_digits[i]: return True break else: return linear_search(sorted_list_of_digits[i-jump_size:i],digit_to_find) sorted_list_of_digits = [1,2,3,4,5,6,7,8,9,10] digit_to_find = int(input("Enter the digit to search: ")) jump_size = int(input("Enter the jump size: ")) position = jump_search(sorted_list_of_digits,digit_to_find, jump_size) if position is not None: print("Element found") else: print("Element not found")
2a9201d81707b8f9584e3b1666474011458424b9
jhonfa94/python
/4_ciclos/3_break_continue.py
526
4
4
# Palbras break y continue en los ciclos # break => rompe el ciclo por completo # continue => # Imprimir solo las lestras a for letra in "Holanda": if letra == "a": print(letra) break else: print("Fin del ciclo for") print("-----------------------------------------") # IMPRIMIR LOS NÚMEROS PARES EN EL RANGO ESTABLECIDO for i in range(6): if i % 2 != 0: continue print(i) print("-----------------------------------------") for i in range(6): if i % 2 == 0: print(i)
6d93d8698d11054822d44420e784deffab8dbe13
YordanPetrovDS/Python_Fundamentals
/_28_EXERCISE_TEXT_PROCESSING/_2_Character_Multiplier.py
425
3.859375
4
words = input().split() first_word = words[0] second_word = words[1] min_length = min(len(first_word), len(second_word)) total_sum = 0 for i in range(min_length): total_sum += ord(first_word[i]) * ord(second_word[i]) biggest_word = first_word if len(second_word) > len(first_word): biggest_word = second_word for i in range(min_length, len(biggest_word)): total_sum += ord(biggest_word[i]) print(total_sum)
718719f379975e9261766997620293796536847a
asadugalib/URI-Solution
/Python3/uri 1117.py
287
3.796875
4
#1117 count = 0 sum = 0 while True: score = float(input()) if score > 10 or score < 0: print("nota invalida") else: count += 1 sum += score if count == 2: break print("media = {:0.2f}".format(sum/2))
ca49523ccaa231397faa9453b28b2d6e405804ac
PrekshaShah17/PythonCodeChallenges
/find_all_list_items.py
831
3.984375
4
def search_indices(search_list: list, goal: int) -> list: """ find indices of the goal from the list :param search_list: list to search :param goal: value to search for :return: list with indexes """ indices = [] for i in range(len(search_list)): if search_list[i] == goal: indices.append([i]) elif isinstance(search_list[i], list): # to check if we have sub list for sub_i in search_indices(search_list[i], goal): indices.append([i]+sub_i) return indices if __name__ == "__main__": # test cases assert search_indices([1, 2, 3], 3) == [[2]] assert search_indices([[[1, 2, 3], 2, [1, 3]], [1, 2, 3]], 2) == [[0, 0, 1], [0, 1], [1, 1]] assert search_indices([[[1, 2, 3], 2, [1, 3]], [1, 2, 3]], [1, 2, 3]) == [[0, 0], [1]]
8646c686e7484ad63592d27bd40905b469bd4ad2
rdturnermtl/mlpaper
/mlpaper/data_splitter.py
12,571
3.53125
4
# Ryan Turner (turnerry@iro.umontreal.ca) from __future__ import absolute_import, division, print_function from builtins import range import numpy as np import pandas as pd RANDOM = "random" ORDRED = "ordered" LINEAR = "linear" ORDERED = ORDRED # Alias with extra char but correct spelling SFT_FMT = "L%d" INDEX = None # Dummy variable to represent index of dataframe DEFAULT_SPLIT = {INDEX: (RANDOM, 0.8)} # The ML standard for some reason def build_lag_df(df, n_lags, stride=1, features=None): """Build a lad dataframe from dataframe where the rows are ordered time indices for a time series data set. This is useful for autoregressive models. Parameters ---------- df : DataFrame, shape (n_samples, n_cols) Orginal dataset we want to build lag data set from. n_lags : int Number of lags. ``n_lags=1`` means only the original data set. Must be >= 1. stride : int Stride of the lags. For instance, ``stride=2`` means only even lags. features : array-like, shape (n_features,) Subset of columns in `df` to include in the lags data. All columns are retained for lag 0. For data frames containing features and targets, the features (inputs) can be placed in `features` so the targets (outputs) are only present for lag 0. If None, use all columns. Returns ------- df : DataFrame, shape (n_samples, n_cols + (n_lags - 1) * n_features) New data frame where lags data frames have been concat'ed tegether. The columns are a new hierarchical index with the lag at the lowest level. Examples -------- >>> data=np.random.choice(10,size=(4,3)) >>> df=pd.DataFrame(data=data,columns=['a','b','c']) >>> ds.build_lag_df(df,3,features=['a','b']) a b c a b a b lag L0 L0 L0 L1 L1 L2 L2 0 2 2 2 NaN NaN NaN NaN 1 2 9 4 2 2 NaN NaN 2 8 4 0 2 9 2 2 3 3 5 6 8 4 2 9 """ df_sub = df if features is None else df[list(features)] # Take all if None D = {(SFT_FMT % nn): df_sub.shift(stride * nn) for nn in range(1, n_lags)} D[SFT_FMT % 0] = df df = pd.concat(D, axis=1, names=["lag"]) # Re-order the levels so there are the same as before but lag at end df = df.reorder_levels(range(1, len(df.columns.names)) + [0], axis=1) return df def index_to_series(index): """Make a pandas series from a pandas index with the value equal to index. Parameters ---------- index : Index Pandas Index to make series from. Returns ------- S : Series Pandas series where ``s[idx] = idx``. Examples -------- >>> index_to_series(pd.Index([1,5,7])) 1 1 5 5 7 7 dtype: int64 """ S = pd.Series(index=index, data=index) return S def rand_subset(x, frac): """Take random subset of array `x` with a certain fraction. Rounds number of elements up to next integer when exact fraction is not possible. Parameters ---------- x : array-like, shape (n_samples,) List that we want a subset of. frac : float Fraction of `x` elements we want to keep in subset. Must be in [0,1]. Returns ------- L : ndarray, shape (m_samples,) Array that is subset with m_samples = ceil(frac * n_samples) samples. """ assert 0.0 <= frac and frac <= 1.0 N = int(np.ceil(frac * len(x))) assert 0 <= N and N <= len(x) L = np.random.choice(x, N, replace=False) assert len(L) >= len(x) * frac assert len(L) - 1 < len(x) * frac return L def rand_mask(n_samples, frac): """Make a random binary mask with a certain fraction. Rounds number of elements up to next integer when exact fraction is not possible. Parameters ---------- n_samples : int Length of mask. frac : float Fraction of elements we want to be True. Must be in [0,1]. Returns ------- L : ndarray of type bool, shape (n_samples,) Random binary mask. """ # Input validation on frac done in rand_subset() pos = rand_subset(range(n_samples), frac) mask = np.zeros(n_samples, dtype=bool) mask[pos] = True assert np.sum(mask) >= n_samples * frac assert np.sum(mask) - 1 < n_samples * frac return mask def random_split_series(S, frac, assume_sorted=False, assume_unique=False): """Create a binary mask to split a series into training/test based on a random split based on values of series. That is, elements with the same value in the series always get grouped into both train or both test. Parameters ---------- S : Series, shape (n_samples,) Pandas Series whose index will be used for binary mask. Random splitting is based on a random parititioning of the series *values*. frac : float Fraction of elements we want to be True. Must be in [0,1]. assume_sorted : bool If True, assume series is already sorted based on values. This can be used for computational speedups. assume_unique : bool If True, assume all values in series are unique. This can be used for computational speedups. Returns ------- train_curr : Series with values of type bool, shape (n_samples,) Random binary mask with index matching `S`. """ assert not S.isnull().any() # Ordering/comparing NaNs ambiguous # Frac range checking taken care of by sub-routines if assume_unique: train_curr = pd.Series(index=S.index, data=rand_mask(len(S), frac)) else: # Note: pd.unique() does not sort, this is required to maintain # identical result to assume_unique case (w/ same random seed). train_cases = rand_subset(S.unique(), frac) train_curr = S.isin(train_cases) return train_curr def ordered_split_series(S, frac, assume_sorted=False, assume_unique=False): """Create a binary mask to split a series into training/test based on a ordered split based on values of series. That is, indices with a lower value get put in train and the rest go in test. Parameters ---------- S : Series, shape (n_samples,) Pandas Series whose index will be used for binary mask. The ordered split is based on the series *values*. frac : float Fraction of elements we want to be True. Must be in [0,1]. assume_sorted : bool If True, assume series is already sorted based on values. This can be used for computational speedups. assume_unique : bool If True, assume all values in series are unique. This can be used for computational speedups. Returns ------- train_curr : Series with values of type bool, shape (n_samples,) Binary mask with index matching `S`. """ assert not S.isnull().any() # Ordering/comparing NaNs ambiguous assert 0.0 <= frac and frac <= 1.0 # Get all cases in sorted order if assume_sorted and assume_unique: all_cases = S.values elif assume_unique: # but not sorted all_cases = np.sort(S.values) else: all_cases = np.unique(S.values) idx = min(int(frac * len(all_cases)), len(all_cases) - 1) assert 0 <= idx # Should never happen due to frac check earlier pivotal_case = all_cases[idx] # Check we rounded to err just on side of putting more data in train assert np.mean(all_cases <= pivotal_case) >= frac assert idx == 0 or np.mean(all_cases <= all_cases[idx - 1]) < frac train_curr = S <= pivotal_case return train_curr def linear_split_series(S, frac, assume_sorted=False, assume_unique=False): """Create a binary mask to split a series into training/test based on a linear split based on values of series. That is, the train/test divide is based on a point that is a linear interpolation between lowest value and highest value in the series. Parameters ---------- S : Series, shape (n_samples,) Pandas Series whose index will be used for binary mask. The linear split is based on the series *values*. frac : float Fraction of region be between series min and series max we want to be True. Must be in [0,1]. assume_sorted : bool If True, assume series is already sorted based on values. This can be used for computational speedups. assume_unique : bool If True, assume all values in series are unique. This can be used for computational speedups. Returns ------- train_curr : Series with values of type bool, shape (n_samples,) Binary mask with index matching `S`. """ assert not S.isnull().any() # Ordering/comparing NaNs ambiguous assert 0.0 <= frac and frac <= 1.0 if assume_sorted: start, end = S.values[0], S.values[-1] else: start, end = np.min(S.values), np.max(S.values) assert np.isfinite(start) and np.isfinite(end) pivotal_point = (1.0 - frac) * start + frac * end # For numerics: pivotal_point = np.maximum(start, np.minimum(pivotal_point, end)) assert start <= pivotal_point and pivotal_point <= end train_curr = S <= pivotal_point return train_curr SPLITTER_LIB = {RANDOM: random_split_series, ORDRED: ordered_split_series, LINEAR: linear_split_series} def split_df(df, splits=DEFAULT_SPLIT, assume_unique=(), assume_sorted=()): """Split a pandas data frame based on criteria across multiple columns. A seperate train test split is done for each column specified as a split column in `splits`. A row is added to the final training set, only if it is placed in training by every column splits. Likewise, A row is added to the final test set, only if it is placed in test by every column splits. All other rows are placed in the unused data points DataFrame. Parameters ---------- df : DataFrame, shape (n_samples, n_features) DataFrame we wish to split into training and test chunks splits : dict of object to ({RANDOM, ORDRED, LINEAR}, float) Dictionary explaining how to do the split. The keys of the `splits` are the columns in `df` we will base the split on. The constant INDEX can be used to symbolize that the index is the desired column. Each value is a tuple with (split type, fraction for training). The split type can be either: random, ordered, or linear. The fraction for training must be in [0,1]. Fraction of region be between series min and series max we want to be True. The Fraction must be in [0,1]. If `splits` is omitted, the default is to perform a 80-20 random split based on the index. assume_sorted : array-like of str Columns that we can assume are alreay sorted by value. This can be used for computational speedups. assume_unique : array-like of str Columns that we can assume have unique values. This can be used for computational speedups. Returns ------- df_train : DataFrame, shape (n_train, n_features) Subset of `df` placed in training set. df_test : DataFrame, shape (n_test, n_features) Subset of `df` placed in test set. df_unused : DataFrame, shape (n_unused, n_features) Subset of `df` not in training or test. This will be empty if only a single column is ued in `splits`. """ assert len(splits) > 0 assert len(df) > 0 # It is not hard to get working with len 0, but why. assert INDEX not in df # None repr for INDEX, col name is reserved here. train_series = pd.Series(index=df.index, data=True) test_series = pd.Series(index=df.index, data=True) for feature, how in splits.items(): split_type, frac = how # Could throw exception for unknown splitter type splitter_f = SPLITTER_LIB[split_type] S = index_to_series(df.index) if feature is INDEX else df[feature] train_curr = splitter_f( S, frac, assume_sorted=(feature in assume_sorted), assume_unique=(feature in assume_unique) ) assert train_curr.dtype.kind == "b" # Make sure ~ does right thing train_series &= train_curr test_series &= ~train_curr assert not (train_series & test_series).any() df_train, df_test = df[train_series], df[test_series] df_unused = df[~(train_series | test_series)] assert len(df_train) + len(df_test) + len(df_unused) == len(df) return df_train, df_test, df_unused
f948a126d72a79cb42af086a9027bfca49f57752
figkim/TC2
/leetcode/2020/medium/00334_increasing_triplet_subsequence/solution_jk.py
938
3.765625
4
class Solution: def increasingTriplet(self, nums: List[int]) -> bool: if len(nums) < 3: return False queue = [nums[0]] for num in nums[1:]: if num < queue[0]: queue[0] = num elif num > queue[-1]: if len(queue) == 2: return True queue.append(num) elif queue[0] < num < queue[-1]: queue[-1] = num return False ''' - The better solution first_num = float('inf') second_num = float('inf') for n in nums: if n < first_num: first_num = n elif first_num < n < second_num: second_num = n elif second_num < n: return True return False '''
678d2cdede15d5a9f9fea581e28f25f0dcf41af5
lucyleeow/scikit-learn-mooc
/python_scripts/linear_models.py
31,464
3.90625
4
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.5.0 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] # # Linear Models # # In this notebook we will review linear models from `scikit-learn`. # We will : # - learn how to fit a simple linear slope and interpret the coefficients; # - discuss feature augmentation to fit a non-linear function; # - use `LinearRegression` and its regularized version `Ridge` which is more # robust; # - use `LogisticRegression` with `pipeline`; # - see examples of linear separability. # %% [markdown] # ## 1. Regression # %% [markdown] # ### The over-simplistic toy example # To illustrate the main principle of linear regression, we will use a dataset # containing information about penguins. # %% import pandas as pd data = pd.read_csv("../datasets/penguins.csv") data.head() # %% [markdown] # This dataset contains features of penguins. We will formulate the following # problem. Observing the flipper length of a penguin, we would like to infer # is mass. # %% import seaborn as sns feature_names = "Flipper Length (mm)" target_name = "Body Mass (g)" sns.scatterplot(data=data, x=feature_names, y=target_name) # select the features of interest X = data[[feature_names]].dropna() y = data[target_name].dropna() # %% [markdown] # In this problem, the mass of a penguin is our target. It is a continuous # variable that roughly vary between 2700 g and 6300 g. Thus, this is a # regression problem (in contrast to classification). We also see that there is # almost linear relationship between the body mass of the penguin and the # flipper length. Longer is the flipper, heavier is the penguin. # # Thus, we could come with a simple rule that given a length of the flipper # we could compute the body mass of a penguin using a linear relationship of # of the form `y = a * x + b` where `a` and `b` are the 2 parameters of our # model. # %% def linear_model_flipper_mass( flipper_length, weight_flipper_length, intercept_body_mass ): """Linear model of the form y = a * x + b""" body_mass = weight_flipper_length * flipper_length + intercept_body_mass return body_mass # %% [markdown] # Using the model that we define, we can check which body mass values we would # predict for a large range of flipper length. # %% import matplotlib.pyplot as plt import numpy as np def plot_data_and_model( flipper_length_range, weight_flipper_length, intercept_body_mass, ax=None, ): """Compute and plot the prediction.""" inferred_body_mass = linear_model_flipper_mass( flipper_length_range, weight_flipper_length=weight_flipper_length, intercept_body_mass=intercept_body_mass, ) if ax is None: _, ax = plt.subplots() sns.scatterplot(data=data, x=feature_names, y=target_name, ax=ax) ax.plot( flipper_length_range, inferred_body_mass, linewidth=3, label=( f"{weight_flipper_length:.2f} (g / mm) * flipper length + " f"{intercept_body_mass:.2f} (g)" ), ) plt.legend() weight_flipper_length = 45 intercept_body_mass = -5000 flipper_length_range = np.linspace(X.min(), X.max(), num=300) plot_data_and_model( flipper_length_range, weight_flipper_length, intercept_body_mass ) # %% [markdown] # The variable `weight_flipper_length` is a weight applied to the feature in # order to make the inference. When this coefficient is positive, it means that # an increase of the flipper length will induce an increase of the body mass. # If the coefficient is negative, an increase of the flipper length will induce # a decrease of the body mass. Graphically, this coefficient is represented by # the slope of the curve that we draw. # %% weight_flipper_length = -40 intercept_body_mass = 13000 flipper_length_range = np.linspace(X.min(), X.max(), num=300) plot_data_and_model( flipper_length_range, weight_flipper_length, intercept_body_mass ) # %% [markdown] # In our case, this coefficient has some meaningful unit. Indeed, its unit is # g/mm. For instance, with a coefficient of 40 g/mm, it means that for an # additional millimeter, the body weight predicted will increase of 40 g. body_mass_180 = linear_model_flipper_mass( flipper_length=180, weight_flipper_length=40, intercept_body_mass=0 ) body_mass_181 = linear_model_flipper_mass( flipper_length=181, weight_flipper_length=40, intercept_body_mass=0 ) print( f"The body mass for a flipper length of 180 mm is {body_mass_180} g and " f"{body_mass_181} g for a flipper length of 181 mm" ) # %% [markdown] # We can also see that we have a parameter `intercept_body_mass` in our model. # this parameter is the intercept of the curve when `x=0`. If the intercept is # null, then the curve will be passing by the origin: # %% weight_flipper_length = 25 intercept_body_mass = 0 flipper_length_range = np.linspace(0, X.max(), num=300) plot_data_and_model( flipper_length_range, weight_flipper_length, intercept_body_mass ) # %% [markdown] # Otherwise, it will be the value intercepted: # %% weight_flipper_length = 45 intercept_body_mass = -5000 flipper_length_range = np.linspace(0, X.max(), num=300) plot_data_and_model( flipper_length_range, weight_flipper_length, intercept_body_mass ) # %% [markdown] # Now, that we understood how our model is inferring data, one should question # on how to find the best value for the parameters. Indeed, it seems that we # can have several model which will depend of the choice of parameters: # %% _, ax = plt.subplots() flipper_length_range = np.linspace(X.min(), X.max(), num=300) for weight, intercept in zip([-40, 45, 90], [15000, -5000, -14000]): plot_data_and_model( flipper_length_range, weight, intercept, ax=ax, ) # %% [markdown] # To choose a model, we could use a metric indicating how good our model is # fitting our data. # %% from sklearn.metrics import mean_squared_error for weight, intercept in zip([-40, 45, 90], [15000, -5000, -14000]): inferred_body_mass = linear_model_flipper_mass( X, weight_flipper_length=weight, intercept_body_mass=intercept, ) model_error = mean_squared_error(y, inferred_body_mass) print( f"The following model \n " f"{weight:.2f} (g / mm) * flipper length + {intercept:.2f} (g) \n" f"has a mean squared error of: {model_error:.2f}" ) # %% [markdown] # Hopefully, this problem can be solved without the need to check every # potential parameters combinations. Indeed, this problem as a closed-form # solution (i.e. an equation giving the parameter values) avoiding for any # brute-force search. This strategy is implemented in scikit-learn. # %% from sklearn.linear_model import LinearRegression linear_regression = LinearRegression() linear_regression.fit(X, y) # %% [markdown] # The instance `linear_regression` will store the parameter values in the # attribute `coef_` and `intercept_`. We can check which is the optimal model # found: # %% weight_flipper_length = linear_regression.coef_[0] intercept_body_mass = linear_regression.intercept_ flipper_length_range = np.linspace(X.min(), X.max(), num=300) plot_data_and_model( flipper_length_range, weight_flipper_length, intercept_body_mass ) inferred_body_mass = linear_regression.predict(X) model_error = mean_squared_error(y, inferred_body_mass) print(f"The error of the optimal model is {model_error:.2f}") # %% [markdown] # ### What if your data don't have a linear relationship # Now, we will define a new problem where the feature and the target are not # linearly linked. For instance, we could defined `x` to be the years of # experience (normalized) and `y` the salary (normalized). Therefore, the # problem here would be to infer the salary given the years of experience of # someone. # %% # data generation # fix the seed for reproduction rng = np.random.RandomState(0) n_sample = 100 x_max, x_min = 1.4, -1.4 len_x = (x_max - x_min) x = rng.rand(n_sample) * len_x - len_x/2 noise = rng.randn(n_sample) * .3 y = x ** 3 - 0.5 * x ** 2 + noise # plot the data plt.scatter(x, y, color='k', s=9) plt.xlabel('x', size=26) _ = plt.ylabel('y', size=26) # %% [markdown] # ### Exercise 1 # # In this exercise, you are asked to approximate the target `y` by a linear # function `f(x)`. i.e. find the best coefficients of the function `f` in order # to minimize the error. # # Then you could compare the mean squared error of your model with the mean # squared error of a linear model (which shall be the minimal one). # %% def f(x): w0 = 0 # TODO: update the weight here w1 = 0 # TODO: update the weight here y_predict = w1 * x + w0 return y_predict # plot the slope of f grid = np.linspace(x_min, x_max, 300) plt.scatter(x, y, color='k', s=9) plt.plot(grid, f(grid), linewidth=3) plt.xlabel("x", size=26) plt.ylabel("y", size=26) mse = mean_squared_error(y, f(x)) print(f"Mean squared error = {mse:.2f}") # %% [markdown] # ### Solution 1. by fiting a linear regression # %% from sklearn import linear_model linear_regression = linear_model.LinearRegression() # X should be 2D for sklearn X = x.reshape((-1, 1)) linear_regression.fit(X, y) # plot the best slope y_best = linear_regression.predict(grid.reshape(-1, 1)) plt.plot(grid, y_best, linewidth=3) plt.scatter(x, y, color="k", s=9) plt.xlabel("x", size=26) plt.ylabel("y", size=26) mse = mean_squared_error(y, linear_regression.predict(X)) print(f"Lowest mean squared error = {mse:.2f}") # %% [markdown] # Here the coefficients learnt by `LinearRegression` is the best slope which # fit the data. We can inspect those coefficients using the attributes of the # model learnt as follow: # %% print( f"best coef: w1 = {linear_regression.coef_[0]:.2f}, " f"best intercept: w0 = {linear_regression.intercept_:.2f}" ) # %% [markdown] # It is important to note that the model learnt will not be able to handle # the non-linearity linking `x` and `y` since it is beyond the assumption made # when using a linear model. To obtain a better model, we have mainly 3 # solutions: (i) choose a model that natively can deal with non-linearity, # (ii) "augment" features by including expert knowledge which can be used by # the model, or (iii) use a "kernel" to have a locally-based decision function # instead of a global linear decision function. # # Let's illustrate quickly the first point by using a decision tree regressor # which natively can handle non-linearity. # %% from sklearn.tree import DecisionTreeRegressor tree = DecisionTreeRegressor(max_depth=3).fit(X, y) y_pred = tree.predict(grid.reshape(-1, 1)) plt.plot(grid, y_pred, linewidth=3) plt.scatter(x, y, color="k", s=9) plt.xlabel("x", size=26) plt.ylabel("y", size=26) mse = mean_squared_error(y, tree.predict(X)) print(f"Lowest mean squared error = {mse:.2f}") # %% [markdown] # In this case, the model can handle the non-linearity. Instead having a model # which natively can deal with non-linearity, we could modify our data: we # could create new features, derived from the original features, using some # expert knowledge. For instance, here we know that we have a cubic and squared # relationship between `x` and `y` (because we generated the data). Indeed, # we could create two new features that would add this information in the data. # %% X = np.vstack([x, x ** 2, x ** 3]).T linear_regression.fit(X, y) grid_augmented = np.vstack([grid, grid ** 2, grid ** 3]).T y_pred = linear_regression.predict(grid_augmented) plt.plot(grid, y_pred, linewidth=3) plt.scatter(x, y, color="k", s=9) plt.xlabel("x", size=26) plt.ylabel("y", size=26) mse = mean_squared_error(y, linear_regression.predict(X)) print(f"Lowest mean squared error = {mse:.2f}") # %% [markdown] # We can see that even with a linear model, we overcome the limitation of the # model by adding the non-linearity component into the design of additional # features. Here, we created new feature by knowing the way the target was # generated. In practice, this is usually not the case. Instead, one is usually # creating interaction between features with different order, at risk of # creating a model with too much expressivity and wich might overfit. In # scikit-learn, the `PolynomialFeatures` is a transformer to create such # feature interactions which we could have used instead of creating new # features ourself. # # To present the `PolynomialFeatures`, we are going to use a scikit-learn # pipeline which will first create the new features and then fit the model. # We will later comeback to details regarding scikit-learn pipeline. # %% from sklearn.pipeline import make_pipeline from sklearn.preprocessing import PolynomialFeatures X = x.reshape(-1, 1) model = make_pipeline( PolynomialFeatures(degree=3), LinearRegression() ) model.fit(X, y) y_pred = model.predict(grid.reshape(-1, 1)) plt.plot(grid, y_pred, linewidth=3) plt.scatter(x, y, color="k", s=9) plt.xlabel("x", size=26) plt.ylabel("y", size=26) mse = mean_squared_error(y, model.predict(X)) print(f"Lowest mean squared error = {mse:.2f}") # %% [markdown] # Thus, we saw that the `PolynomialFeatures` is actually doing the same # operation that we did manually above. # %% [markdown] # **FIXME: it might be to complex to be introduced here but it seems good in # the flow. However, we go away from linear model.** # # The last possibility to make a linear model more expressive is to use # "kernel". Instead of learning a weight per feature as we previously # emphasized, a weight will be assign by sample instead. However, not all # sample will be used. This is the base of the support vector machine # algorithm. # %% from sklearn.svm import SVR svr = SVR(kernel="linear").fit(X, y) y_pred = svr.predict(grid.reshape(-1, 1)) plt.plot(grid, y_pred, linewidth=3) plt.scatter(x, y, color="k", s=9) plt.xlabel("x", size=26) plt.ylabel("y", size=26) mse = mean_squared_error(y, svr.predict(X)) print(f"Lowest mean squared error = {mse:.2f}") # %% [markdown] # The algorithm can be modified such that it can use non-linear kernel. Then, # it will compute interaction between samples using this non-linear # interaction. svr = SVR(kernel="poly", degree=3).fit(X, y) y_pred = svr.predict(grid.reshape(-1, 1)) plt.plot(grid, y_pred, linewidth=3) plt.scatter(x, y, color="k", s=9) plt.xlabel("x", size=26) plt.ylabel("y", size=26) mse = mean_squared_error(y, svr.predict(X)) print(f"Lowest mean squared error = {mse:.2f}") # %% [markdown] # Therefore, kernel can make a model more expressive. # %% [markdown] # ### Linear regression in higher dimension # In the previous example, we usually used only a single feature. But we # already shown that we could add new feature to make the model more expressive # by deriving this new features based on the original feature. # # Indeed, we could also use additional features which are decorrelated with the # original feature and that could help us to predict the target. # # We will load a dataset reporting the median house value in California. # The dataset in made of 8 features regarding demography and geography of the # location and the aim is to predict the median house price. # %% from sklearn.datasets import fetch_california_housing X, y = fetch_california_housing(as_frame=True, return_X_y=True) X.head() # %% [markdown] # We will compare the score of `LinearRegression` and `Ridge` (which is a # regularized version of linear regression). # # We will evaluate our model using the mean squared error as in the previous # example. The lower the score, the better. # %% [markdown] # Here we will divide our data into a training set and a validation set. # The validation set will be used to assert the hyper-parameters selection. # While a testing set should only be used to assert the score of our final # model. # %% from sklearn.model_selection import train_test_split X_train_valid, X_test, y_train_valid, y_test = train_test_split( X, y, random_state=1 ) X_train, X_valid, y_train, y_valid = train_test_split( X_train_valid, y_train_valid, random_state=1 ) # %% [markdown] # Note that in the first example, we did not care about scaling our data to # keep the original units and have better intuition. However, this is a good # practice to scale the data such that each feature have a similar standard # deviation. It will be even more important if the solver used by the model # is a gradient-descent-based solver. # %% from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train_scaled = scaler.fit(X_train).transform(X_train) X_valid_scaled = scaler.transform(X_valid) # %% [markdown] # Scikit-learn provides several tools to preprocess the data. The # `StandardScaler` transforms the data such that each feature will have a zero # mean and a unit standard deviation. # # These scikit-learn estimators are known are transformer: they compute some # statistics and store them when calling `fit`. Using these statistics, they # transform the data when calling `transform`. Therefore, it is important to # note that `fit` should only be called on the training data similarly to the # classifier or regressor. # # In the example above, `X_train_scaled` are data scaled after computing the # mean and standard deviation of each feature considering the training data. # `X_test_scaled` are data scaled using the mean and standard deviation of each # feature on the training data. # %% linear_regression = LinearRegression() linear_regression.fit(X_train_scaled, y_train) y_pred = linear_regression.predict(X_valid_scaled) print( f"Mean squared error on the validation set: " f"{mean_squared_error(y_valid, y_pred):.4f}" ) # %% [markdown] # Instead of manually transforming the data by calling the transformer, # scikit-learn provide a `Pipeline` allowing to call a sequence of # transformer(s) followed by a regressor or a classifier. This pipeline exposed # the same API than the regressor and classifier and will manage the call to # `fit` and `transform` for you, avoiding any mistake with data leakage. # # We already presented `Pipeline` in the second notebook and we will use it # here to combine both the scaling and the linear regression. # # We will call `make_pipeline()` which will create a `Pipeline` by giving as # arguments the successive transformations to perform followed by the regressor # model. # # So the two cells above become this new one: # %% from sklearn.pipeline import make_pipeline linear_regression = make_pipeline(StandardScaler(), LinearRegression()) linear_regression.fit(X_train, y_train) y_pred_valid = linear_regression.predict(X_valid) linear_regression_score = mean_squared_error(y_valid, y_pred_valid) y_pred_test = linear_regression.predict(X_test) print( f"Mean squared error on the validation set: " f"{mean_squared_error(y_valid, y_pred_valid):.4f}" ) print( f"Mean squared error on the test set: " f"{mean_squared_error(y_test, y_pred_test):.4f}" ) # %% [markdown] # Now we want to compare this basic `LinearRegression` versus its regularized # form `Ridge`. # # We will tune the parameter alpha and compare it with the `LinearRegression` # model which is not regularized. # %% from sklearn.linear_model import Ridge ridge = make_pipeline(StandardScaler(), Ridge()) list_alphas = np.logspace(-2, 2.1, num=40) list_ridge_scores = [] for alpha in list_alphas: ridge.set_params(ridge__alpha=alpha) ridge.fit(X_train, y_train) y_pred = ridge.predict(X_valid) list_ridge_scores.append(mean_squared_error(y_valid, y_pred)) plt.plot( list_alphas, [linear_regression_score] * len(list_alphas), '--', label='LinearRegression', ) plt.plot(list_alphas, list_ridge_scores, "+-", label='Ridge') plt.xlabel('alpha (regularization strength)') plt.ylabel('Mean squared error (lower is better') _ = plt.legend() # %% [markdown] # We see that, just like adding salt in cooking, adding regularization in our # model could improve its error on the validation set. But too much # regularization, like too much salt, decrease its performance. # # We can see visually that the best alpha should be around 40. # %% best_alpha = list_alphas[np.argmin(list_ridge_scores)] best_alpha # %% [markdown] # At the end, we selected this alpha *without* using the testing set ; but # instead by extracting a validation set which is a subset of the training # data. This has been seen in the lesson *basic hyper parameters tuning*. # We can finally compared the `LinearRegression` model and the best `Ridge` # model on the testing set. # %% print("Linear Regression") y_pred_test = linear_regression.predict(X_test) print( f"Mean squared error on the test set: " f"{mean_squared_error(y_test, y_pred_test):.4f}" ) print("Ridge Regression") ridge.set_params(ridge__alpha=alpha) ridge.fit(X_train, y_train) y_pred_test = ridge.predict(X_test) print( f"Mean squared error on the test set: " f"{mean_squared_error(y_test, y_pred_test):.4f}" ) # FIXME add explication why Ridge is not better (equivalent) than linear # regression here. # %% [markdown] # The hyperparameter search could have been made using the `GridSearchCV` # instead of manually splitting the training data and selecting the best alpha. # %% from sklearn.model_selection import GridSearchCV ridge = GridSearchCV( make_pipeline(StandardScaler(), Ridge()), param_grid={"ridge__alpha": list_alphas}, ) ridge.fit(X_train_valid, y_train_valid) print(ridge.best_params_) # %% [markdown] # The `GridSearchCV` manage to test all possible given `alpha` value and picked # up the best one with a cross-validation scheme. We can now compare with # the `LinearRegression`. # %% print("Linear Regression") linear_regression.fit(X_train_valid, y_train_valid) y_pred_test = linear_regression.predict(X_test) print( f"Mean squared error on the test set: " f"{mean_squared_error(y_test, y_pred_test):.4f}" ) print("Ridge Regression") y_pred_test = ridge.predict(X_test) print( f"Mean squared error on the test set: " f"{mean_squared_error(y_test, y_pred_test):.4f}" ) # %% [markdown] # It is as well interesting to know that several regressors and classifiers # in scikit-learn are optimized to make this parameter tuning. They usually # finish with the term "CV" for "Cross Validation" (e.g. `RidgeCV`). # They are more efficient than making the `GridSearchCV` by hand and you # should use them instead. # # We will repeat the equivalent of the hyper-parameter search but instead of # using a `GridSearchCV`, we will use `RidgeCV`. # %% from sklearn.linear_model import RidgeCV ridge = make_pipeline( StandardScaler(), RidgeCV(alphas=[.1, .5, 1, 5, 10, 50, 100]) ) ridge.fit(X_train_valid, y_train_valid) ridge[-1].alpha_ # %% print("Linear Regression") y_pred_test = linear_regression.predict(X_test) print( f"Mean squared error on the test set: " f"{mean_squared_error(y_test, y_pred_test):.4f}" ) print("Ridge Regression") y_pred_test = ridge.predict(X_test) print( f"Mean squared error on the test set: " f"{mean_squared_error(y_test, y_pred_test):.4f}" ) # %% [markdown] # Note that the best parameter value is changing because the cross-validation # between the different approach is internally different. # %% [markdown] # ## 2. Classification # In regression, we saw that the target to be predicted was a continuous # variable. In classification, this target will be discrete. (e.g. categorical) # # We will go back to our penguin dataset. However, this time we will try to # predict the penguin species using the culmen information. We will also # simplify our classification problem by selecting only 2 of the penguin # species to solve a binary classification problem. # %% data = pd.read_csv("../datasets/penguins.csv") # select the features of interest culmen_columns = ["Culmen Length (mm)", "Culmen Depth (mm)"] target_column = "Species" data = data[culmen_columns + [target_column]] data[target_column] = data[target_column].str.split().str[0] data = data[data[target_column].apply(lambda x: x in ("Adelie", "Chinstrap"))] data = data.dropna() # %% [markdown] # We can quickly start by visualizing the feature distribution by class # %% _ = sns.pairplot(data=data, hue="Species") # %% [markdown] # So we can observe, that we have quite a simple problem. When the culmen # length increase, the probability to be a Chinstrap penguin is closer to 1. # However, the culmen length does not help at predicting the penguin specie. # # For the later model fitting, we will separate the target from the data and # we will create a training and a testing set. # %% from sklearn.model_selection import train_test_split X, y = data[culmen_columns], data[target_column] X_train, X_test, y_train, y_test = train_test_split( X, y, stratify=y, random_state=0, ) # %% [markdown] # To visualize the separation found by our classifier, we will define an helper # function `plot_decision_function` . In short, this function will fit our classifier and # plot the edge of the decision function, where the probability to be an Adelie or # Chinstrap will be equal (p=0.5). # %% def plot_decision_function(X, y, clf, title="auto", ax=None): """Plot the boundary of the decision function of a classifier.""" from sklearn.preprocessing import LabelEncoder clf.fit(X, y) # create a grid to evaluate all possible samples plot_step = 0.02 feature_0_min, feature_0_max = ( X.iloc[:, 0].min() - 1, X.iloc[:, 0].max() + 1, ) feature_1_min, feature_1_max = ( X.iloc[:, 1].min() - 1, X.iloc[:, 1].max() + 1, ) xx, yy = np.meshgrid( np.arange(feature_0_min, feature_0_max, plot_step), np.arange(feature_1_min, feature_1_max, plot_step), ) # compute the associated prediction Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = LabelEncoder().fit_transform(Z) Z = Z.reshape(xx.shape) # make the plot of the boundary and the data samples if ax is None: _, ax = plt.subplots() ax.contourf(xx, yy, Z, alpha=0.4) sns.scatterplot( data=pd.concat([X, y], axis=1), x=X.columns[0], y=X.columns[1], hue=y.name, ax=ax, ) if title == "auto": C = clf[-1].C if hasattr(clf[-1], "C") else clf[-1].C_ ax.set_title(f"C={C}\n with coef={clf[-1].coef_[0]}") else: ax.set_title(title) # %% [markdown] # ### Un-penalized logistic regression # # The linear regression that we previously saw will predict a continuous # output. When the target is a binary outcome, one can use the logistic # function to model the probability. This model is known as logistic # regression. # # Scikit-learn provides the class `LogisticRegression` which implement this # algorithm. # %% from sklearn.linear_model import LogisticRegression logistic_regression = make_pipeline( StandardScaler(), LogisticRegression(penalty="none") ) plot_decision_function(X_train, y_train, logistic_regression) # %% [markdown] # Thus, we see that our decision function is represented by a line separating # the 2 classes. Since the line is oblique, it means that we used a # combination of both features: # %% print(logistic_regression[-1].coef_) # %% [markdown] # Indeed, both coefficients are non-null. # # ### Apply some regularization when fitting the logistic model # # The `LogisticRegression` model # allows to apply regularization via the parameter `C`. It would be equivalent # to shift from `LinearRegression` to `Ridge`. On the contrary to `Ridge`, the # `C` parameter is the inverse of the regularization strength: a smaller `C` # will lead to a more regularized model. We can check the effect of # regularization on our model: # %% _, axs = plt.subplots(ncols=3, figsize=(12, 4)) for ax, C in zip(axs, [0.02, 0.1, 1]): logistic_regression = make_pipeline( StandardScaler(), LogisticRegression(C=C) ) plot_decision_function( X_train, y_train, logistic_regression, ax=ax, ) # %% [markdown] # A more regularized model will make the coefficients tend to 0. Since one of # the feature is considered less important when fitting the model (lower # coefficient magnitude), only one of the feature will be used when C is small. # This feature is the culmen length which is in line with our first insight # that we found when plotting the marginal feature probabilities. # # Just like the `RidgeCV` class which automatically find the optimal `alpha`, # one can use `LogisticRegressionCV` to find the best `C` on the training data. # %% from sklearn.linear_model import LogisticRegressionCV logistic_regression = make_pipeline( StandardScaler(), LogisticRegressionCV(Cs=[0.01, 0.1, 1, 10]) ) plot_decision_function(X_train, y_train, logistic_regression) # %% [markdown] # ### Beyond linear separation # # As we saw in regression, the linear classification model expects the data # to be linearly separable. When this assumption does not hold, the model # is not enough expressive to properly fit the data. One need to apply the same # tricks than in regression: feature augmentation (using expert-knowledge # potentially) or using method based on kernel. # # We will provide examples where we will use a kernel support vector machine # to make classification on some toy-dataset where it is impossible to find a perfect linear # separation # %% from sklearn.datasets import ( make_moons, make_classification, make_gaussian_quantiles, ) X_moons, y_moons = make_moons(n_samples=500, noise=.13, random_state=42) X_class, y_class = make_classification( n_samples=500, n_features=2, n_redundant=0, n_informative=2, random_state=2, ) X_gauss, y_gauss = make_gaussian_quantiles( n_samples=50, n_features=2, n_classes=2, random_state=42, ) datasets = [ [pd.DataFrame(X_moons, columns=["Feature #0", "Feature #1"]), pd.Series(y_moons, name="class")], [pd.DataFrame(X_class, columns=["Feature #0", "Feature #1"]), pd.Series(y_class, name="class")], [pd.DataFrame(X_gauss, columns=["Feature #0", "Feature #1"]), pd.Series(y_gauss, name="class")], ] # %% from sklearn.svm import SVC _, axs = plt.subplots(ncols=3, nrows=2, figsize=(12, 9)) linear_model = make_pipeline(StandardScaler(), SVC(kernel="linear")) kernel_model = make_pipeline(StandardScaler(), SVC(kernel="rbf")) for ax, (X, y) in zip(axs[0], datasets): plot_decision_function(X, y, linear_model, title="Linear kernel", ax=ax) for ax, (X, y) in zip(axs[1], datasets): plot_decision_function(X, y, kernel_model, title="RBF kernel", ax=ax) # %% [markdown] # We see that the $R^2$ score decrease on each dataset, so we can say that each # dataset is "less linearly separable" than the previous one. # %% [markdown] # # Main take away # # - `LinearRegression` find the best slope which minimize the mean squared # error on the train set # - `Ridge` could be better on the test set, thanks to its regularization # - `RidgeCV` and `LogisiticRegressionCV` find the best relugarization thanks # to cross validation on the training data # - `pipeline` can be used to combinate a scaler and a model # - If the data are not linearly separable, we shall use a more complex model # or use feature augmentation # # %%
5ce5e17f137cd393fbf2facee0011b5cfd516539
Prafullaraj/Python-with-django
/ATM.py
1,214
4
4
#ATM #Deposit #withdraw #check balance #change pin print("****welcome****") pin=int(input("Enter your pin:\n")) act_amt=1000 print("you have"+" ",act_amt," "+"in your account") print("1. Deposit\n2. Withdraw\n3. Check balance\n4. Change pin\n5. Exit") def deposite(amt): global act_amt act_amt=act_amt+amt return act_amt def withdraw(amt): global act_amt if(amt=<act_amt): act_amt=act_amt-amt return act_amt else: print("Insufficient balance!") def checkbal(): print("you amount is:",act_amt) def changepin(): pin=int(input("Enter the new pin:")) print("you have successfully changed the pin ") while(1): var=int(input("Enter your choice:\n")) if(var==1): amt=int(input("Enter the amount to be deposited:\n")) deposite(amt) print("your current balance is:",act_amt) elif(var==2): amt=int(input("Enter the withdraw amount:\n")) withdraw(amt) print("your current balance is:",act_amt) elif(var==3): checkbal() elif(var==4): changepin() elif(var==5): print("your current balance is:",act_amt) print("^^^^Thank You!^^^^") break
a398d073756b828db217acaa48ce1268e5a2a59a
ashutoshfolane/Design-1
/design_hashmap.py
2,510
4
4
""" - Problem: Design Hashmap (https://leetcode.com/problems/design-hashmap/) - Implement a HashMap without any built-in libraries. - Your implementation should include these three functions: put(key, value) : Insert a (key, value) pair into the HashMap or If the value already exists, update the value. get(key): Returns the value to which the specified key is mapped, or -1 if no mapping for the key. remove(key) : Remove the mapping for the value key if this map contains the mapping for the key. - Time Complexity: for each of the methods, the time complexity is O(N/K), where N is the number of all possible keys and K is the number of predefined buckets in the hashmap, which is 2069 in our case. - Space Complexity: O(K+M), where K is the number of predefined buckets in the hashmap and M is the number of unique keys that have been inserted into the hashmap. """ class Bucket: def __init__(self): # Initialize array self.bucket = [] def get(self, key): for k, v in self.bucket: if k == key: return v return -1 def update(self, key, value): found = False for i, kv in enumerate(self.bucket): if key == kv[0]: self.bucket[i] = (key,value) found = True break if not found: self.bucket.append((key,value)) def remove(self,key): for i, kv in enumerate(self.bucket): if key == kv[0]: del self.bucket[i] class MyHashMap: def __init__(self): # Initialize data structure self.key_space = 2027 # large prime number self.hash_table = [Bucket() for i in range(self.key_space)] def put(self, key, value) -> None: hash_key = key % self.key_space self.hash_table[hash_key].update(key, value) def get(self, key) -> int: hash_key = key % self.key_space return self.hash_table[hash_key].get(key) def remove(self, key) -> None: hash_key = key % self.key_space self.hash_table[hash_key].remove(key) # Driver code hashmap = MyHashMap() hashmap.put(1, 2) hashmap.put(2, 3) hashmap.get(1) # returns 2 hashmap.get(3) # returns -1 (not found) hashmap.put(2, 4) # update the existing value hashmap.get(2) # returns 4 hashmap.remove(2) # remove the mapping for 2 hashmap.get(2) # returns -1 (not found)
570d666057eb95e6b8cb7f382d3a0c80208bfc1d
L33tCh/leaguer
/models/team.py
1,651
3.921875
4
class Team(object): score = 0 def __init__(self, result): """ Initialise Team object :param str result: the string representation of a team result (<name score>) """ parsed = self.parse_result(result) self.name = parsed["name"] self.latest = parsed["score"] def add_points(self, points): """ Update score with input points :param int points: Integer point value :return: """ self.score += points def parse_result(self, result): """ Parse game score to retrieve name as string and score as integer :param str result: Result in the format <team_name team_score> :return: Dictionary including name and score """ result_list = result.split() score_index = len(result_list) - 1 score = result_list[score_index] name = " ".join(result_list[:score_index]) return { "name": name, "score": int(score) } def __str__(self): """ Override string output of Team object :return: """ return "%s, %d %s" % (self.name, self.score, "pt" if self.score is 1 else "pts") def __lt__(self, other): """ Override less-than operation on Team object for control of list sort result :param Team other: Other Team object to compare with :return: Ordered from highest to lowest by score but lowest to highest by name """ if self.score == other.score: return self.name.lower() < other.name.lower() return self.score > other.score
1062eb13cd831538a7f514b7d2669c8aa39a4ce6
AndongWen/leetcode
/0035sortColors.py
2,040
3.75
4
'''给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 注意: 不能使用代码库中的排序函数来解决这道题。''' ass Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ '''使用三指针,有点类似快排中的第二种,里面的特殊情况''' p = 0 # 标记0区域得右边界 q = len(nums)-1 # 标记2区域得左边界 cur = 0 # 正在处理得元素 while cur <= q: if nums[cur] == 0: nums[cur], nums[p] = nums[p], nums[cur] cur += 1 p += 1 elif nums[cur] == 2: nums[cur], nums[q] = nums[q], nums[cur] q -= 1 else: cur += 1 ''' 0元素取出来扔到最后面,2元素取出来扔到最前面,1元素不处理 从头开始遍历 1. 元素nums[i]为0 从当前位置弹出,插入到nums最前面 i自加 2. 元素nums[i]为1 不做处理,i自加跳过 3. 元素nums[i]为2 从当前位置弹出,插入到nums最后面 N自减 i不要自加 ''' class Solution(object): def sortColors(self, nums): N = len(nums) i = 0 while i < N: if nums[i] == 2: nums.pop(i) nums.append(2) N -= 1 elif nums[i] == 1: i += 1 elif nums[i] == 0: nums.pop(i) nums.insert(0,0) i += 1 class Solution(object): def sortColors(self, nums): '''利用collections中的Counter神器,不仅仅可以解决三色问题''' from collections import Counter c = Counter(nums) p = 0 for i in range(3): for j in range(c[i]): nums[p] = i p += 1
c8a2273c33db061cc8c9716a2624773710ea3caf
hugopatriciooliveira/python_easy
/classes_homework.py
3,764
4.4375
4
# Homework Assignment #9: Classes """ Details: Create a class called "Vehicle" and methods that allow you to set the "Make", "Model", "Year", and "Weight". The class should also contain a "NeedsMaintenance" boolean that defaults to False, and "TripsSinceMaintenance" Integer that defaults to 0. Next an inheritance classes from Vehicle called "Cars". The Cars class should contain a method called "Drive" that sets the state of a boolean isDriving to True. It should have another method called "Stop" that sets the value of isDriving to false. Switching isDriving from true to false should increment the "TripsSinceMaintenance" counter. And when TripsSinceMaintenance exceeds 100, then the NeedsMaintenance boolean should be set to true. Add a "Repair" method to either class that resets the TripsSinceMaintenance to zero, and NeedsMaintenance to false. Create 3 different cars, using your Cars class, and drive them all a different number of times. Then print out their values for Make, Model, Year, Weight, NeedsMaintenance, and TripsSinceMaintenance """ """ Extra Credit: Create a Planes class that is also an inheritance class from Vehicle. Add methods to the Planes class for Flying and Landing (similar to Driving and Stopping), but different in one respect: Once the NeedsMaintenance boolean gets set to true, any attempt at flight should be rejected (return false), and an error message should be printed saying that the plane can't fly until it's repaired. """ class Vehicle: def __init__(self, Make, Model, Year, Weight): self.Make = Make self.Model = Model self.Year = int(Year) self.Weight = float(Weight) self.TripsSinceMaintenance = int(0) self.NeedsMaintenance = False def Repair(self): self.NeedsMaintenance = False self.TripsSinceMaintenance = 0 class Cars(Vehicle): def __init__(self, Make, Model, Year, Weight): super(Cars, self).__init__(Make, Model, Year, Weight) self.isDriving = False def Drive(self): self.isDriving = True self.TripsSinceMaintenance += 1 if self.TripsSinceMaintenance > 100: self.NeedsMaintenance = True else: self.NeedsMaintenance = False def Stop(self): self.isDriving= False class Planes(Vehicle): def __init__(self, Make, Model, Year, Weight): super(Planes, self).__init__(Make, Model, Year, Weight) self.isFlying = False def Flying(self): self.isFlying = True self.TripsSinceMaintenance += 1 if self.TripsSinceMaintenance > 100: self.NeedsMaintenance = True print("This plane can't fly until it's repaired!!!" ) else: self.NeedsMaintenance = False def Landing(self): self.isFlying = False car1 = Cars("Ford","Mustang",1965, 3.093) car2 = Cars("Chevrolet","Camaro",1966, 3.353) car3 = Cars("Gurgel","BR-800",1988, 1.591) plane1 = Planes("Hawker Aircraft, Ltd.", "Hurricane", 1930, 7.670) plane2 = Planes("Boeing Company", "B-52", 1948, 23.000) # car2.Drive() # car1.Drive() # car1.Drive() # car3.Drive() # car2.Drive() # car2.Drive() # car1.Drive() # car1.Drive() # car1.Drive() # car1.Drive() # car1.Repair() # print(car1.TripsSinceMaintenance) # print(car1.NeedsMaintenance) # plane1.Flying() # plane1.Flying() # plane1.Flying() # plane1.Flying() # print(plane1.TripsSinceMaintenance) # print(car1.NeedsMaintenance) # "Ford","Mustang",1965, 3,093 # "Chevrolet","Camaro",1966, 3,353 # "Gurgel","BR-800",1988, 1,591 # "Hawker Aircraft, Ltd.", "Hurricane", 1930, 7.670 # "Boeing Company", "B-52", 1948, 23.000
4ee4aef1ad0609e1bac3955c60861adc464188f4
ZwEin27/Coding-Training
/LeetCode/python/lc206.py
1,134
4.03125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def __init__(self): self.next_node = None; def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ # iteratively """ if head == None: return head; header = head; cur = head.next; while cur != None: head.next = cur.next; cur.next = header; header = cur; cur = head.next; return header; """ # recursively if head == None: return head; lt = self.reverseList(head.next); if lt != None: # cur = lt; # while cur.next != None: # cur = cur.next; if not self.next_node: self.next_node = lt; self.next_node.next = head; self.next_node = head; head.next = None; return lt; else: return head;
3f05e92fa3308192bb07abce6893a75c3f4a6128
cmigazzi/P5_Pur_beurre
/database.py
7,539
3.796875
4
"""Contains the Schema class that creates schema and tables.""" import records from settings import DB_NAME, DB_CONNEXION, DB_HOST, DB_USER, DB_PASSWORD class SchemaCreator(): """Represent the Database to install.""" def __init__(self): """Get the DB_NAME to create the database.""" self.db_name = DB_NAME def create(self): """Create schema.""" db = records.Database( f"mysql+mysqlconnector://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:3306/") db.query( f"CREATE SCHEMA IF NOT EXISTS `{self.db_name}` " "DEFAULT CHARACTER SET utf8mb4;") db.close() class TableCreator(): """Represent the creator of the tables. Arguments: db_connection {<class records.Database>} -- database connection Object """ def __init__(self, db_connection): """Please see help(TableCreator) for more details.""" self.db = db_connection self.db_name = DB_NAME def create(self): """Create generic method.""" self.db.query(self.query) class CategoryCreator(TableCreator): """Represent the Category table creator. Inherit of TableCreator Arguments: db_connection {<class records.Database>} -- database connection Object """ def __init__(self, db_connection): """Set create query as attribute.""" super().__init__(db_connection) self.query = ("CREATE TABLE IF NOT EXISTS " f"`{self.db_name}`.`Category` (" "`id` SMALLINT NOT NULL AUTO_INCREMENT," "`name` VARCHAR(100) NOT NULL," "PRIMARY KEY (`id`))" "ENGINE = InnoDB;") class StoreCreator(TableCreator): """Represent the Store table creator. Inherit of TableCreator Arguments: db_connection {<class records.Database>} -- database connection Object """ def __init__(self, db_connection): """Set create query as attribute.""" super().__init__(db_connection) self.query = (f"CREATE TABLE IF NOT EXISTS `{self.db_name}`.`Store` (" "`id` SMALLINT NOT NULL AUTO_INCREMENT," "`name` VARCHAR(45) NOT NULL," "PRIMARY KEY (`id`))" "ENGINE = InnoDB;") class BrandCreator(TableCreator): """Represent the Brand table creator. Inherit of TableCreator Arguments: db_connection {<class records.Database>} -- database connection Object """ def __init__(self, db_connection): """Set create query as attribute.""" super().__init__(db_connection) self.query = (f"CREATE TABLE IF NOT EXISTS `{self.db_name}`.`Brand` (" "`id` SMALLINT NOT NULL AUTO_INCREMENT, " "`name` VARCHAR(45) NOT NULL," "PRIMARY KEY (`id`)) " "ENGINE = InnoDB;") class ProductCreator(TableCreator): """Represent the Product table creator. Inherit of TableCreator Arguments: db_connection {<class records.Database>} -- database connection Object """ def __init__(self, db_connection): """Set create query as attribute.""" super().__init__(db_connection) self.query = ("CREATE TABLE IF NOT EXISTS " f"`{self.db_name}`.`Product` (" "`id` INT NOT NULL AUTO_INCREMENT, " "`name` VARCHAR(150) NOT NULL, " "`description` TINYTEXT NULL, " "`url` VARCHAR(255) NOT NULL, " "`nutri_score` VARCHAR(1) NULL, " "`category` SMALLINT NOT NULL, " "`sub_category` SMALLINT NULL, " "`store_0` SMALLINT NOT NULL, " "`store_1` SMALLINT NULL, " "`brand` SMALLINT NULL, " "PRIMARY KEY (`id`), " "UNIQUE INDEX `id_UNIQUE` (`id` ASC) VISIBLE, " "INDEX `fk_category_idx` (`category` ASC) VISIBLE, " "INDEX `fk_sub_category_idx1` " "(`sub_category` ASC) VISIBLE, " "INDEX `fk_store_0_idx` (`store_0` ASC) VISIBLE, " "INDEX `fk_store_1_idx` (`store_1` ASC) VISIBLE, " "INDEX `fk_brand_idx` (`brand` ASC) VISIBLE, " "CONSTRAINT `fk_category` " "FOREIGN KEY (`category`) " f"REFERENCES `{self.db_name}`.`Category` (`id`) " "ON DELETE NO ACTION " "ON UPDATE NO ACTION, " "CONSTRAINT `fk_sub_category` " "FOREIGN KEY (`sub_category`) " f"REFERENCES `{self.db_name}`.`Category` (`id`) " "ON DELETE NO ACTION " "ON UPDATE NO ACTION, " "CONSTRAINT `fk_store_0` " "FOREIGN KEY (`store_0`) " f"REFERENCES `{self.db_name}`.`Store` (`id`) " "ON DELETE NO ACTION " "ON UPDATE NO ACTION, " "CONSTRAINT `fk_store_1` " "FOREIGN KEY (`store_1`) " f"REFERENCES `{self.db_name}`.`Store` (`id`) " "ON DELETE NO ACTION " "ON UPDATE NO ACTION, " "CONSTRAINT `fk_brand` " "FOREIGN KEY (`brand`) " f"REFERENCES `{self.db_name}`.`Brand` (`id`) " "ON DELETE NO ACTION " "ON UPDATE NO ACTION) " "ENGINE = InnoDB;") class SubstitutionCreator(TableCreator): """Represent the Substitution table creator. Inherit of TableCreator Arguments: db_connection {<class records.Database>} -- database connection Object """ def __init__(self, db_connection): """Set create query as attribute.""" super().__init__(db_connection) self.query = ("CREATE TABLE IF NOT EXISTS " f"`{self.db_name}`.`Substitution` (" "`id` SMALLINT NOT NULL AUTO_INCREMENT, " "`original` INT NOT NULL, " "`substitute` INT NOT NULL, " "PRIMARY KEY (`id`), " "INDEX `fk_substitution_idx` (`original` ASC) VISIBLE, " "INDEX `fk_substitute_idx` (`substitute` ASC) VISIBLE, " "CONSTRAINT `fk_original` " "FOREIGN KEY (`original`) " f"REFERENCES `{self.db_name}`.`Product` (`id`) " "ON DELETE NO ACTION " "ON UPDATE NO ACTION, " "CONSTRAINT `fk_substitute` " " FOREIGN KEY (`substitute`) " f"REFERENCES `{self.db_name}`.`Product` (`id`) " "ON DELETE NO ACTION " " ON UPDATE NO ACTION) " "ENGINE = InnoDB;") if __name__ == "__main__": db = records.Database(DB_CONNEXION) c = ProductCreator(db) print(c) print(c.db_name) print(c.query)
1afce41424bb8bfba6d3f2156aa96b34cc121f6c
jay754/riddles
/algorithms/dfs/dfs.py
311
3.90625
4
#http://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/ def dfs(G, start): stack = [start] visited = set() while Start: node = stack.pop() if node not in visited: visited.add(node) stack.extend(G[node] - visited) return visited
ff809d5be8dbbb840ac29d323272ece40aee85b7
helenamulcahy/Helena_Python
/replace_name_order.py
240
4.09375
4
def replace_order(x,y): return y + ", " + x def main(): first_name = str(input('Enter First Name: >> ')) last_name = str(input('Enter Last Name: >> ')) order = replace_order(first_name, last_name) print(order) main()
4ddd6789a2640aa348b950c0bbfe3f21a020df59
VerveIsBad/textgame
/src/enemy.py
2,759
3.8125
4
import random import player import utils class Enemy: def __init__(self, name, hp, attack, defense): self.name = name self.hp = hp self.defense = defense self.attack = attack self.held_item = None self.graphic = '?' self.interactable = True self.is_enemy = True """ Ideas: Elements Armor (Random chance * level / arena type) Status """ def interact(self, world, player, interact_type): # target.hp -= (attacker.damage - target.defense) '''Interacts with the enemy Arguments: world (World): the world (this is the 3rd unintentional JoJo reference) player (Player): the player interact_type: The type of interaction. Must be a string. ''' if interact_type == 'fighting': fighting = True print("An enemy has appeared!!") action = input(f'Fight or Run (You have {player.hp}) > ').lower() while fighting: print('(fight) Type \'help\' for fight help') if action == 'fight': utils.clear() player.fight_with(self) print(f'{player.hp} hp') if player.hp <= 0: print("You died . . . ") player.forceStop() break elif self.hp <= 0: print(f'{self.name} Has died!') player.hp = player.max_hp print("(attack/run)") action = input('Fight back or run\n').lower() if action == 'attack': if player.attack > self.defense: self.hp -= player.attack continue else: print("The enemies defense is to high! Damage negated") print(f"(your attack: {player.attack}, {self.name}'s defense: {self.defense}") print("after attackng the enenmy, you are no longer able to escape . . . you inevitably die.") player.forceStop() elif action == 'run': if random.randint(1,9) == 1 or 6 or 9: # random chance for user to run print("You ran away . . .") utils.clear() else: print("You failed to run away...") continue elif action == 'help': print('--Commands (Fight)--\nfight - Fight the enemy\nhelp - Get help') continue
f393c1618da8b73d6d2e7165c9c4c3b797f6b6ae
Lumary2/University
/calculator.py
1,526
4.65625
5
#This hashtag means, that this line is a comment and it is #not part of the actual code. #choice is a variable which saves what the user has entered. #"Select operation..." will be printed when you execute the #program. choice = input("Select operation(+ - * /): ") #The only thing different here is the int() before the input. #Variables can have different data types, like for example #Strings and Integers. A String consists of one or more #characters surrounded by 'x' or "x". An Integer is a #whole number like -1 or 2 without decimal places. #Because the user input is saved as a String and #we want to use it as a number to calulate with it, #int() changes it into an Integer. num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) #Now that we saved the user input in the choice #variable we want to check what the user has entered. #if the user entered a + sign, we print the addition #of num1 and num2. if choice == '+': print(num1+num2) #if the user didnt enter a plus sign, the line above #saying print(num1+num2) wont be executed and the #following line will be checked. If he entered #a - sign, the result of the substraction gets printed. elif choice == '-': print(num1-num2) #the following lines only get checked for when we #neither already had a case of addition or substraction. #Between the four operator possibilities only the #matching one gets executed, the others are skipped. elif choice == '*': print(num1*num2) elif choice == '/': print(num1/num2)
11e447dfdd2e7cc0ce1cc48986f00d1c41632af9
OleksiiKhivrenko/python-course
/Lesson 4 (Strings)/practice/string_methods.py
451
4.28125
4
# lower print('STRING'.lower()) # => 'string' # upper print('string'.lower()) # => 'STRING' # count - searching text by index print('this is long string'.count('iss', 6, 10)) # => 1) slicing string 'is long string' # => 2) returning first matched index # found, rfound - print('hello world'.find('ellk')) # searching for left to right print('hello world'.rfind('ello', 1, 10)) # => searching for right to left # returning -1 if nothing found
66d9d0085c79841cbf45bef85fa136a046311241
bhanu-python/Python-Data
/excep_handl/excep.py
156
3.84375
4
try: add=10+10 #add=10+"10" except: print("You are not passing the correct value") else: print("addition on the number is: {}".format(add))
a55666b24f6dcd7d79e84eeae1e9da43a3460f1c
kiara-williams/ProgrammingII
/prac_03/ascii_table.py
1,888
4.40625
4
"""Program that converts characters to ascii and vice versa.""" LOWER = 33 UPPER = 127 def main(): MENU = """ASCII Conversion Enter A to convert a character to ASCII Enter C to convert ASCII to a character Enter T to print an ASCII table Enter Q to quit""" print(MENU) selection = get_input() while selection != "Q": if selection == "A": character = str(input("Enter a character: ")) char_code = ord(character) print("The ASCII code for {} is {}".format(character, char_code)) print(MENU) selection = get_input() elif selection == "C": char_loop_sentinel = False while char_loop_sentinel == False: try: char_code = int(input("Enter a number between {} and {}".format(LOWER, UPPER))) if char_code >= LOWER and char_code <= UPPER: character = chr(char_code) print("The character for {} is {}".format(char_code, character)) else: print("Invalid Option") except ValueError: print("Invalid Option") char_loop_sentinel = True print(MENU) selection = get_input() elif selection == "T": for i in range(LOWER, UPPER,1): character = chr(i) print("| {:>3} | {:^3s} |".format(i, character)) print(MENU) selection = get_input() else: print("Invalid Option. Please select from the menu") print(MENU) selection = get_input() print("Exiting application. Goodbye") def get_input(): """Requests input and normalises it""" selection = str(input("Enter your selection")).upper() return selection main()
239f2a412892ad159bcf891027e296e4daabbe88
Lica3265/YunYun
/0828.py
94
3.625
4
from collections import Counter Value1=input("請輸入英文字符:") print(Counter(Value1))
5eb75f5a9d3f1653a034161865ea4d4552cd37ab
ok-nc/idlm_Pytorch
/Simulated DataSets/Gaussian Mixture/generate_Gaussian.py
2,228
3.578125
4
""" This is the function that generates the gaussian mixture for artificial model The simulated cluster would be similar to the artifical data set from the INN paper """ # Import libs import numpy as np import matplotlib.pyplot as plt # Define the free parameters dimension = 2 num_cluster = 8 num_points_per_cluster = 1000 num_class = 4 cluster_distance_to_center = 10 in_class_variance = 1 def plotData(data_x, data_y, save_dir='generated_gaussian_scatter.png'): """ Plot the scatter plot of the data to show the overview of the data points :param data_x: The 2 dimension x values of the data points :param data_y: The class of the data points :param save_dir: The save name of the plot :return: None """ f = plt.figure() plt.scatter(data_x[:, 0], data_x[:, 1], c=data_y) f.savefig(save_dir) if __name__ == '__main__': centers = np.zeros([num_cluster, dimension]) # initialize the center positions for i in range(num_cluster): # the centers are at the rim of a circle with equal angle centers[i, 0] = np.cos(2 * np.pi / num_cluster * i) * cluster_distance_to_center centers[i, 1] = np.sin(2 * np.pi / num_cluster * i) * cluster_distance_to_center print("centers", centers) # Initialize the data points for x and y data_x = np.zeros([num_cluster * num_points_per_cluster, dimension]) data_y = np.zeros(num_cluster * num_points_per_cluster) # allocate the class labels class_for_cluster = np.random.uniform(low=0, high=num_class, size=num_cluster).astype('int') print("class for cluster", class_for_cluster) # Loop through the points and assign the cluster x and y values for i in range(len(data_x[:, 0])): i_class = i // num_points_per_cluster data_y[i] = class_for_cluster[i_class] # Assign y to be 0,0,0....,1,1,1...,2,2,2.... e.g. data_x[i, 0] = np.random.normal(centers[i_class, 0], in_class_variance) data_x[i, 1] = np.random.normal(centers[i_class, 1], in_class_variance) print("data_y", data_y) plotData(data_x, data_y) np.savetxt('data_x.csv', data_x, delimiter=',') np.savetxt('data_y.csv', data_y, delimiter=',')
ff81ce14585b08f4939847317a6b22e4999fa6f1
SebasBaquero/taller1-algoritmo
/taller de estructuras de control de repeticion/punto4.py
233
3.875
4
""" Salidas Doceavo-->int-->doc Suma-->int-->suma """ doc=0 for a in range(1,13): if(a>=1): doc=5*a+1 if(doc==61): suma=(doc+6)*6 print("a12= "+str(doc)) print("suma= "+str(suma)) elif(a==13): break
2c9db4d306966be2bb0486707ab37e98808a29b1
Dzhevizov/SoftUni-Python-Fundamentals-course
/Text Processing - Exercise/03. Extract File.py
166
3.5625
4
path = input().split("\\") file = path[-1] file_name, file_extension = file.split(".") print(f"File name: {file_name}") print(f"File extension: {file_extension}")
bca3e7712913230444f075d619059f2ef2ef413e
VisargD/Problem-Solving
/Day-6/(Using Binary Search) Find-Minimum-in-Rotated-Sorted-Array.py
1,432
3.59375
4
""" Problem Name: Find Minimum in Rotated Sorted Array Platform: Leetcode Difficulty: Medium Problem Link: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ """ class Solution: def findMin(self, nums: List[int]) -> int: # Initializing low and high to first and last index respectively. low = 0 high = len(nums) - 1 # Using while-loop to perform iterative binary search. while high > low: # Calculating mid for each iteration. mid = (low + high) // 2 # If value at mid is greater than value at high, then the pivot element is on the right side of mid. # Set low to mid + 1 to perform binary search in the right side. if nums[mid] > nums[high]: low = mid + 1 # If the value at mid is lower than value at high, then either the value at mid can be pivot or the pivot can be in the left part of mid. # Set high = mid to search in the left part. # Here, it is not possible to set high = mid - 1 as the value at mid can also be a pivot element. else: high = mid # When the above loop breaks, then high will be equal to low. And that will be the required pivot element. # There are no more possibilities of pivot being on the left or right as high is equal to low. # So return it. return nums[low]
f859bbdfec37b3485c6074d7cf7dd926b9477995
vivian-peronnet/projet-NSI-trone
/.github/throne.py
3,537
3.765625
4
import tkinter as tk def triSelection_2(a) : n = len(a) for i in range(0,n-1,2) : k = i for j in range(i+1,n-1,2) : if a[k] > a[j] : k = j a[k],a[i] = a[i],a[k] a[k+1],a[i+1]=a[i+1],a[k+1] def comp_1(y,z): co1=y co2=z indice=[] element=co1[-2] triSelection_2(co1) triSelection_2(co2) prer=[] a = 0 b = len(co1)-1 m = (a+b)//2 while a < b : if co1[m] == element : indice.append(m) return m elif co1[m] > element : b = m-2 else : a = m+2 m = (a+b)//2 for i in indice: prer.append(co2[i+1]) element=co1[-1] a = 0 b = len(prer)-1 m = (a+b)//2 while a < b : if prer[m] == element : return m elif prer[m] > element : b = m-2 else : a = m+2 m = (a+b)//2 if a!=0: print("game over") def comp_2(co1,co2): indice=[] element=co1[-2] triSelection_2(co1) triSelection_2(co2) prer=[] a = 0 b = len(co2)-1 m = (a+b)//2 while a < b : if co2[m] == element : return m elif co2[m] > element : b = m-1 else : a = m+1 m = (a+b)//2 indice.append(a) for i in indice: prer.append(co1[i+1]) element=co1[-1] a = 0 b = len(prer)-1 m = (a+b)//2 while a < b : if prer[m] == element : return m elif prer[m] > element : b = m-1 else : a = m+1 m = (a+b)//2 if a!=0: print("game over") motion = { 'q': (-10, 0), 's': (10, 0), 'z': (0, -10), 'w': (0, 10), 'p': (-10, 0), 'l': (10, 0), 'm': (0, -10), ':': (0, 10), } motion1 = { 'q': (-10, 0), 's': (10, 0), 'z': (0, -10), 'w': (0, 10), } motion2 = { 'p': (-10, 0), 'l': (10, 0), 'm': (0, -10), ':': (0, 10), } co1=[] co2=[] def on_key1(event): if not event.char in motion.keys(): return if event.char in motion2.keys(): x20, y20=100,0 d2x, d2y = motion2[event.char] canvas.move('ball2', d2x, d2y) x20, y20, x21, y21 = canvas.bbox('ball2') c20 = (x20+x21)/2 c21 = (y20+y21)/2 line.extend([c20, c21]) canvas.coords('line2', line) print("c20=",c20,c21) co2.append(x20) co2.append(y20) if event.char in motion1.keys() : x10, y10= -100, 0 d1x, d1y = motion1[event.char] canvas.move('ball1', d1x, d1y) x10, y10, x11, y11 = canvas.bbox('ball1') c10 = (x10+x11)/2 c11 = (y10+y11)/2 line.extend([c10, c11]) canvas.coords('line1', line) print("c1=",x10, y10) co1.append(x10) co1.append(y10) comp_2(co2,co1) comp_1(co1, co2) canvas = tk.Canvas(width=600, height=600) canvas.pack() canvas.create_oval(5, 5, 15, 15, fill='red', tag='ball1') canvas.create_oval(5, 5, 15, 15, fill='red', tag='ball2') line = [10, 10, 10, 10] canvas.create_line(line, tag='line1') canvas.create_line(line, tag='line2') canvas.bind('<Key>', on_key1) canvas.focus_set() tk.mainloop()
4daf2486596ac4e65c2946db65b7fc81ce83deca
cxrodgers/Adapters
/base.py
5,567
3.515625
4
"""Module providing Adapter object.""" from __future__ import print_function from builtins import str from builtins import zip from builtins import object import numpy as np class Adapter(object): """Object representing inputs and outputs of a physical adapter. An Adapter is intialized with lists of all the input channels and output channels. It provides convenience methods to look up channnels or to chain adapters together using `+`. __getitem__ provides output look up for a given input. Methods: inv : return an Adapter with outputs and inputs reversed This is useful for looking up an input for a given output sort_by : inplace sort. Change the order of inputs and outputs. Properties: in2out : dict-like, looks up output for a specified input out2in : dict-like, looks up input for a specified output ins : array of inputs outs : array of outputs """ def __init__(self, l1, l2=None): """Initialize a new adapter. l1 : list-like, list of channel ids for each channel on the input of the adapter. The channel ids can be any hashable Python object, including integers or strings, but not a list. l2 : list-like, of same length as `d_or_l1`, of the outputs of the adapter, and in corresponding order to l1. If there is no corresponding input for a given output, put None at that point in the list (and vice versa). Therefore None cannot be used as a channel id. Internally everything is represented as a Nx2 ndarray called `table`. An alternative method of initialization is to pass this sort of array as `l1` and leave l2 as None. """ self.table = None self._in2out = None self._out2in = None # Determine type of initialization if l2 is not None: # two list mapping a = [[i1, i2] for i1, i2 in zip(l1, l2)] else: # interpret l1 as a tble a = l1 # Convert to internal representation self.table = np.asarray(a, dtype=np.object) if self.table.ndim != 2 or self.table.shape[1] != 2: raise Exception("table should be a Nx2 array") @property def in2out(self): # Return memoized dict if self._in2out is None: res = {} for row in self.table: i1, i2 = row[0], row[-1] if i1 is None: continue if i1 in res: print("warning: duplicate keys in 'in' column") res[i1] = i2 self._in2out = res return self._in2out @property def out2in(self): # Return memoized dict if self._out2in is None: res = {} for row in self.table: i2, i1 = row[0], row[-1] if i1 is None: continue if i1 in res: print("warning: duplicate keys in 'out' column") res[i1] = i2 self._out2in = res return self._out2in @property def outs(self): return self.table[:, -1] @property def ins(self): return self.table[:, 0] def __add__(self, a2): """Append a new column and keep the intermediaries?""" a3 = Adapter(self.ins.copy(), self.outs.copy()) a3.table = self.table.copy() d = a2.in2out new_table = list(a3.table.transpose()) new_table.append(new_table[-1]) a3.table = np.asarray(new_table, dtype=np.object).transpose() for n, i2 in enumerate(self.outs): try: a3.table[n, -1] = d[i2] except KeyError: a3.table[n, -1] = None return a3 def __getitem__(self, key): try: res = self.in2out[key] except TypeError: # key was a list res = np.array([self.in2out[kk] for kk in key], dtype=np.object) except KeyError: # key not an input return None return res @property def inv(self): a = Adapter(self.outs, self.ins) a.table = self.table[:, ::-1] return a def __str__(self): return str(self.table) def __repr__(self): return "Adapter(\n" + repr(self.table) + ")" def __getslice__(self, slc1, slc2): """Returns outputs from slc1 to slc2 inclusive""" i1 = np.where(self.ins == slc1)[0][0] i2 = np.where(self.ins == slc2)[0][0] + 1 return self.outs[i1:i2] def sort_by(self, keys, reverse=False): """Inplace sort by keys. If keys is: 'ins' : sort by inputs 'outs' : sort by outpus a list of inputs : sort in that order """ if keys == 'ins': keys = sorted(self.table[:, 0]) elif keys == 'outs': t = sorted(self.table[:, -1]) keys = [self.out2in[tt] for tt in t] if reverse: keys = keys[::-1] l = list(self.table[:,0]) idxs = [l.index(key) for key in keys] #l2 = self[keys] #self.table = np.array([[ll1, ll2] for ll1, ll2 in zip(keys, l2)], # dtype=np.object) self.table = self.table[idxs] return self
ce88a71efc15524fbb54822487f53e16feba81d1
Saon00/Coding-Small-Projects
/Digital_Clock.py
314
3.71875
4
# using python3 import time from tkinter import * import sys root = Tk() root.title("Digital Clock") def get_time(): time_string = time.strftime("%I:%M:%S %p") clock.config(text=time_string) clock.after(200,get_time) clock = Label(root,font=("time",90,"bold")) clock.pack() get_time() root.mainloop()
158c0071c0eb89bd507b59211df20879cd264c6c
ppruitt-sg/Ticket_RestAPI_Project
/create_table.py
1,540
3.5625
4
import sqlite3 connection = sqlite3.connect('data.db') cursor = connection.cursor() create_table = "CREATE TABLE IF NOT EXISTS customers (\ id INTEGER PRIMARY KEY AUTOINCREMENT,\ email text,\ name text)" cursor.execute(create_table) create_table = "CREATE TABLE IF NOT EXISTS employees (\ id INTEGER PRIMARY KEY AUTOINCREMENT,\ email text,\ name text)" cursor.execute(create_table) create_table = "CREATE TABLE IF NOT EXISTS tickets (\ number INTEGER PRIMARY KEY AUTOINCREMENT,\ customer_id int,\ employee_id int, \ subject text, \ FOREIGN KEY(customer_id) REFERENCES customers (id),\ FOREIGN KEY(employee_id) REFERENCES employees (id))" cursor.execute(create_table) create_table = "CREATE TABLE IF NOT EXISTS comments (\ id INTEGER PRIMARY KEY AUTOINCREMENT,\ number int,\ timestamp int,\ from_email text,\ content text,\ FOREIGN KEY (number) REFERENCES\ tickets(number) ON DELETE CASCADE)" cursor.execute(create_table) create_table = "CREATE TABLE IF NOT EXISTS accounts (\ id INTEGER PRIMARY KEY AUTOINCREMENT,\ username text,\ password text)" cursor.execute(create_table) connection.commit() connection.close()
1b15d5962831477358d9a3d0c38bc9a3f4ed900b
davidjhoff13/gw-bootcamp-homework
/Python-Challenge/Cereal DJH solved.py
1,727
4.15625
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 10 22:28:46 2020 @author: david """ #%% # Open the CSV #with open(csvpath) as csvfile: # csvreader = csv.reader(csvfile, delimiter=",") # Instructions #* Open the file, `cereal.csv` and start by skipping the #header row. See hints below for this. #* Read through the remaining rows and find the cereals #that contain five grams of fiber or more, printing the data from those rows to the terminal. ## Hint #* Everything within the csv is stored as a string and #certain rows have a decimal. This means that they will # have to be cast to be used. #* The csv.Reader begins reading the csv file at the #first row. `next(csv_reader, None)` will skip the #header row. Refer to this stackoverflow answer on #[how to skip the header](https://stackoverflow.com/a/14257599) for more information. #* Integers in Python are whole numbers and, as such, #cannot contain decimals. As such, your numbers #containing decimal points will have to be cast as a `float`. # Read through the remaining rows and find the cereals that contain five grams of fiber or more, #printing the data from those rows to the terminal. # Modules import os import csv # Set path for file csvpath = os.path.join("Resources", "cereal.csv") #%% # Open the CSV with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=",") next(csvreader, None) # Loop through looking for columns to print #for row in csvreader: for row in csvreader: Name = row[0] Fiber = row[7] #%% # Loop through looking for the fiber if float(Fiber) >= 5: print(Name) #End If csvfile.close()
0fceca1752409fabdcf57e92ae3ddf6dd3e88f33
Yiming-Gao/UIUC-Fall-2017
/CS_446/Homework/HW1/HW1_p4_sol.py
5,545
3.5625
4
import numpy as np def sigm(z): """ Computes the sigmoid function :type z: float :rtype: float """ return 1./(1. + np.exp(-z)) def compute_grad(w, x, y): """ Computes gradient of LL for logistic regression :type w: 1D np array of weights :type x: 2D np array of features where len(w) == len(x[0]) :type y: 1D np array of labels where len(x) == len(y) :rtype: 1D numpy array """ wx = np.dot(x, w) sigmwx = np.fromiter((sigm(wxi) for wxi in wx), wx.dtype) return np.sum(np.multiply(x, (y - sigmwx).reshape((len(y), 1))), 0) def gd_single_epoch(w, x, y, step): """ Updates the weight vector by processing the entire training data once :type w: 1D numpy array of weights :type x: 2D numpy array of features where len(w) == len(x[0]) :type y: 1D numpy array of labels where len(x) == len(y) :rtype: 1D numpy array of weights """ return w + step*compute_grad(w, x, y) def gd(x, y, stepsize): """ Iteratively optimizes the objective function by first initializing the weight vector with zeros and then iteratively updates the weight vector by going through the trianing data num_epoch_for_train(global var) times :type x: 2D numpy array of features where len(w) == len(x[0]) :type y: 1D numpy array of labels where len(x) == len(y) :type stepsize: float :rtype: 1D numpy array of weights """ w = np.zeros(len(x[0])) for i in range(num_epoch_for_train): w = gd_single_epoch(w, x, y, stepsize) return w def predict(w, x): """ Makes a binary decision {0,1} based the weight vector and the input features :type w: 1D numpy array of weights :type x: 1D numpy array of features of a single data point :rtype: integer {0,1} """ if sigm(np.dot(x, w)) > 0.5: return 1 return 0 def accuracy(w, x, y): """ Calculates the proportion of correctly predicted results to the total :type w: 1D numpy array of weights :type x: 2D numpy array of features where len(w) == len(x[0]) :type y: 1D numpy array of labels where len(x) == len(y) :rtype: float as a proportion of correct labels to the total """ prediction = np.fromiter((predict(w, xi) for xi in x), x.dtype) return float(np.sum(np.equal(prediction, y)))/len(y) def five_fold_cross_validation_avg_accuracy(x, y, stepsize): """ Measures the 5 fold cross validation average accuracy Partition the data into five equal size sets like |-----|-----|-----|-----| For all 5 choose 1 permutations, train on 4, test on 1. Compute the average accuracy using the accuracy function you wrote. :type x: 2D numpy array of features where len(w) == len(x[0]) :type y: 1D numpy array of labels where len(x) == len(y) :type stepsize: float :rtype: float as average accuracy across the 5 folds """ x_folds = np.split(x, 5) y_folds = np.split(y, 5) percent_acc_ith_test_fold = np.zeros(5) for i in range(5): test_index = (i-1)%5 x_test_fold = x_folds[test_index] y_test_fold = y_folds[test_index] x_train_folds = np.array([]).reshape((0,len(x[0]))) y_train_folds = np.array([]) for j in range(5-1): train_index = (i+j)%5 x_train_folds = np.concatenate((x_train_folds, x_folds[train_index]), axis=0) y_train_folds = np.concatenate((y_train_folds, y_folds[train_index]), axis=0) w = gd(x_train_folds, y_train_folds, stepsize) percent_acc_ith_test_fold[i] = accuracy(w, x_test_fold, y_test_fold) return np.average(percent_acc_ith_test_fold) def tune(x, y): """ Optimizes the stepsize by calculating five_fold_cross_validation_avg_accuracy with 10 different stepsizes from 0.001, 0.002,...,0.01 in intervals of 0.001 and output the stepsize with the highest accuracy For comparison: If two accuracies are equal, pick the lower stepsize. NOTE: For best practices, we should be using Nested Cross-Validation for hyper-parameter search. Without Nested Cross-Validation, we bias the model to the data. We will not implement nested cross-validation for now. You can experiment with it yourself. See: http://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html :type x: 2D numpy array of features where len(w) == len(x[0]) :type y: 1D numpy array of labels where len(x) == len(y) :rtype: float as best stepsize """ stepsizes = np.linspace(0.001, 0.01, num=10) acc = np.zeros(10) for (i, step) in enumerate(stepsizes): acc[i] = five_fold_cross_validation_avg_accuracy(x_train, y_train, step) return stepsizes[np.argmax(acc)] # Top three tuned stepsize values def tune_top_three(x, y): stepsizes = np.linspace(0.001, 0.01, num=10) acc = np.zeros(10) for (i, step) in enumerate(stepsizes): acc[i] = five_fold_cross_validation_avg_accuracy(x_train, y_train, step) return stepsizes[np.argpartition(acc, -3)[-3:]] # Correct Results w_single_epoch = gd_single_epoch(np.zeros(len(x_train[0])), x_train, y_train, default_stepsize) w_optimized = gd(x_train, y_train, default_stepsize) y_predictions = np.fromiter((predict(w_optimized, xi) for xi in x_test), x_test.dtype) five_fold_average_accuracy = five_fold_cross_validation_avg_accuracy(x_train, y_train, default_stepsize) # tuned_stepsize = tune(x_train, y_train) top_three_tuned_stepsizes = tune_top_three(x_train, y_train)
a3f38c39f56c5acf987e46525fc88377fb9b1816
jvpazotti/P1-A-TecWeb
/database.py
1,295
3.953125
4
import sqlite3 from dataclasses import dataclass @dataclass class Note: id: int = None title: str = None content: str = '' class Database: def __init__(self,nome): self.nome=nome self.conn=sqlite3.connect(self.nome+'.db') self.conn.execute('CREATE TABLE IF NOT EXISTS note (id INTEGER PRIMARY KEY,title STRING, content STRING NOT NULL);') def add(self,note): self.conn.execute(f"INSERT INTO note (title,content) VALUES ('{note.title}','{note.content}');") self.conn.commit() def get_all(self): cursor = self.conn.execute("SELECT id, title, content FROM note") list=[] for linha in cursor: self.id=linha[0] self.title=linha[1] self.content=linha[2] list.append(Note(id=self.id,title=self.title,content=self.content)) return list def update(self, entry): self.conn.execute(f"UPDATE note SET title = '{entry.title}' WHERE id = {entry.id}") self.conn.execute(f"UPDATE note SET content = '{entry.content}' WHERE id = {entry.id}") self.conn.commit() def delete(self, note_id): self.conn.execute(f"DELETE FROM note WHERE id = {note_id}") self.conn.commit()
7f6676c2b406e4ea619d09972693916bb21e4ef2
jamesdschmidt/exercises-for-programmers
/10-self-checkout/self_checkout.py
683
4.03125
4
TAX_RATE = 0.055 item1_price = float(input("Enter the price of item 1: ")) item1_quantity = int(input("Enter the quantity of item 1: ")) item2_price = float(input("Enter the price of item 2: ")) item2_quantity = int(input("Enter the quantity of item 2: ")) item3_price = float(input("Enter the price of item 3: ")) item3_quantity = int(input("Enter the quantity of item 3: ")) subtotal = item1_price * item1_quantity + \ item2_price * item2_quantity + \ item3_price * item3_quantity tax = subtotal * TAX_RATE total = subtotal + tax output = f"Subtotal: ${subtotal:,.2f}\n" \ f"Tax: ${tax:,.2f}\n" \ f"Total: ${total:,.2f}" print(output)
0488cfe130c2d273e797eca3991eb4d01e0acbe2
jsoto3000/js_udacity_Intro_to_Python
/list_comprehensions_squares.py
150
3.828125
4
# list of squares # squares = [] # for x in range(9): # squares.append(x**2) # print(squares) squares = [x**2 for x in range(9)] print(squares)
79fc7a321cdd70b3a5225ace12bf9f4630f1bb59
hiratakelab/nlp100
/02/ch02_07.py
589
3.53125
4
# coding: utf-8 u""" ファイルをN分割する 自然数Nをコマンドライン引数などの手段で受け取り、入力のファイルを行単位でn分割せよ。 同様の処理をsplitコマンドで実現せよ。 split -l n hightemp2.txt 出力ファイル名 """ file = open("./hightemp2.txt", "r") lines = [] for line in file: line = line.rstrip("\n") lines.append(line) n = input(">>>") sum = int(n) for i, line in enumerate(lines): print(line) if i + 1 == sum: print("-----------------") sum = sum + int(n)
45513c205aed7704f854a2b719291cb7497bcfdf
stsmith1991/opened-repository-for-homeworks
/hw6.py
788
3.765625
4
class Road: th = 1 __length = 5000 __width = 25 def __calc(self): m = int(self.__length) * int(self.__width) * int(self.th) print(f'Для дороги длинной и шириной {self.__length}х{self.__width} метров и толщиной {self.th} см потребуется ' f'{m} килограмм асфальта') my_r = Road() try: my_r._Road__length = int(input("Введите длинну дороги, м.\n")) my_r.th = input("Толщина покрытия, см.\n") my_r._Road__calc() except ValueError: print('Введено некорректное значение. Расчёт произведён из значений по умолчанию') my_r._Road__calc()
d5eeb4d581242881aeaa3779c87863bbc9f512a2
luryrodrigues/curso-python
/aula07.py
2,709
4.09375
4
# alinhamentos nome=input('Qual é seu nome? ') print('Prazer em te conhecer, {:20}!'.format(nome)) # escreve em 20 espaços (pode ser utilizado para casas decimais) print('Prazer em te conhecer, {:>20}!'.format(nome)) # alinhado a direita em 20 espaços print('Prazer em te conhecer, {:<20}!'.format(nome)) # alinhado a esqueda em 20 espaços print('Prazer em te conhecer, {:^20}!'.format(nome)) # centralizado print('Prazer em te conhecer, {:=^20}!'.format(nome)) # centralizado com caracteres ao invês de espaço vazio # operadores aritméticos n1=int(input('Digite um valor: ')) n2=int(input('Digite outro valor: ')) s=n1+n2 m=n1*n2 d=n1/n2 di=n1//n2 # divisão inteira ds=n1%n2 #sobra da divisão inteira e=n1**n2 #potência print('A soma vale {},\na multiplicação é {}, a divisão é {:.3f}.'.format(s,m,d)) #.3f: 3 casas flutuantes (decimais), \n : quebra de linha print('A divisão inteira é {}, a sobra é {}'.format(di,ds), end=' ') # end: faz com que a linha não quebre print ('e a potência é {}.'.format(e)) # desafio 005 n=int(input('Digite um número: ')) a=n-1 s=n+1 print('O antecessor de {} é {} e seu sucessor é {}.'.format(n,a,s)) # desafio 006 n=int(input('Digite um número: ')) d=n*2 t=n*3 r=n**(1/2) print('O dobro de {} é {}, seu triplo é {} e sua raiz quadrada é {:.3f}.'.format(n,d,t,r)) #desafio 007 n1=int(input('Qual é a nota da P1? ')) n2=int(input('Qual é a nota da P2? ')) m=(n1+n2)/2 print('A nota média do aluno é {:.1f}.'.format(m)) # desafio 008 m=float(input('Digite o comprimento em metros: ')) c=m*100 mm=m*1000 print('{} metros são {} centímetros e {} milímetros.'.format(m,c,mm)) # desafio 009 n=(int(input('Digite um número para ver sua tabuada: '))) print('-'*12) print('{} x {:>2} = {:<2}'.format(n,1,n*1)) print('{} x {:>2} = {:<2}'.format(n,2,n*2)) print('{} x {:>2} = {:<2}'.format(n,3,n*3)) print('{} x {:>2} = {:<2}'.format(n,4,n*4)) print('{} x {:>2} = {:<2}'.format(n,5,n*5)) print('{} x {:>2} = {:<2}'.format(n,6,n*6)) print('{} x {:>2} = {:<2}'.format(n,7,n*7)) print('{} x {:>2} = {:<2}'.format(n,8,n*8)) print('{} x {:>2} = {:<2}'.format(n,9,n*9)) print('{} x {:>2} = {:<2}'.format(n,10,n*10)) print('-'*12) #desafio 010 din=float(input('Quantos reais você tem na sua carteira? ')) print('Você pode comprar {:.2f} dólares.'.format(din/3.27)) #desafio 011 lar=float(input('Qual a largura da parede? ')) h=float(input('Qual a altura da parede? ')) a=lar*h lit=a/2 print('A parede tem {} metros quadrados e precisa-se de {} litros de tinta para pintá-la.'.format(a,lit)) # desafio 012 sal=float(input('Qual é o seu salário? ')) print('Seu salário com um aumento de 15% é igual a {:.2f}.'.format(sal*1.15))
c5a8eb1b37f1f6c59916a72f5fc3c56b01342378
bmorrishome/03_FFAWP
/first_script.py
18,578
3.8125
4
#! /usr/bin/env python3 # -*- coding: UTF-8 -*- from math import exp, log, sqrt import re from datetime import date, time, datetime, timedelta from operator import itemgetter import sys import glob import os print("Output #1: I'm excited to learn Python.") # 两个数值相加 x = 4 y = 5 z = x + y print("Output #2: Four plus five equals {0:d}.".format(z)) # 两个列表相加 a = [1, 2, 3, 4] b = ['first', 'second', 'third', 'fourth'] c = a + b print("Output #3: {0}, {1}, {2}.".format(a,b,c)) # 数值 - 整数 x = 9 print('Output #4: {0}'.format(x)) print('Output #5: {0}'.format(3**4)) print('Output #6: {0}'.format(int(8.3)/int(2.7))) # 数值 - 浮点数 print('Output #7: {0:.3f}'.format(8.3/2.7)) y = 2.5 * 4.8 print('Output #8: {0:.1f}'.format(y)) r = 8/float(3) print('Output #9: {0:.2f}'.format(r)) print('Output #10: {0:.4f}'.format(8.0/3)) # 数值 - math库基本函数演示 print('Output #11: {0:.4f}'.format(exp(3))) print('Output #12: {0:.2f}'.format(log(4))) print('Output #13: {0:.1f}'.format(sqrt(81))) # 字符串 print('Output #14: {0:s}'.format('I\'m enjoying learning Python.')) print('Output #15: {0:s}'.format('This is a long string. Without the backslash\ it would run off of the page on the right in the text editor and be very\ difficult to read and edit. By using the backslash you can split the long\ string into smaller strings on separate lines so that the whole string is easy\ to view in the text editor.')) print('Output #16: {0:s}'.format('''You can use triple single quotes for multi-line comment strings.''')) print('Output #17: {0:s}'.format("""You can also use triple double quotes for multi-line comment strings.""")) # 字符串 - 常用操作符和函数 string1 = 'This is a ' string2 = 'short string.' sentence = string1 + string2 print('Output #18: {0:s}'.format(sentence)) print('Output #19: {0:s} {1:s}{2:s}'.format('She is', 'very '* 4, 'beautiful.')) m = len(sentence) print('Output #20: {0:d}'.format(m)) # 字符串 - split string1 = 'My deliverable is due in May' string1_list1 = string1.split() string1_list2 = string1.split(' ', 2) print('Output #21: {0}'.format(string1_list1)) print('Output #22: FIRST PIECE:{0} SECOND PIECE:{1} THIRD PIECE:{2}'\ .format(string1_list2[0], string1_list2[1], string1_list2[2])) string2 = 'Your,deliverable,is,due,in,June' string2_list = string2.split(',') print('Output #23: {0}'.format(string2_list)) print('Output #24: {0} {1} {2}'.format(string2_list[1], string2_list[5], string2_list[-1])) # 字符串 - join print('Output #25: {0}'.format(','.join(string2_list))) # 字符串 - strip string3 = ' Remove unwated characters form this string.\t\t \n' print('Output #26: string3: {0:s}'.format(string3)) string3_lstrip = string3.lstrip() print('Output #27: lstrip: {0:s}'.format(string3_lstrip)) string3_rstrip = string3.rstrip() print('Output #28: rstrip: {0:s}'.format(string3_rstrip)) string3_strip = string3.strip() print('Output #29: strip: {0:s}'.format(string3_strip)) string4 = "$$Here's another string that has unwanted characters.__---++" print('Output #30: {0:s}'.format(string4)) string4 = "$$The unwanted characters have been removed.__---++" string4_strip = string4.strip('$_-+') print('Output #31: {0:s}'.format(string4_strip)) # 字符串 - replace string5 = "Let's replace the spaces in this sentence with other characters." string5_replace = string5.replace(' ', '!@!') print('Output #32 (with !@!): {0:s}'.format(string5_replace)) string5_replace = string5.replace(' ', ',') print('Output #33 (with commas): {0:s}'.format(string5_replace)) # 字符串 - lower、upper、capitalize string6 = "Here's WHAT Happens WHEN You Use lower." print('Output #34: {0:s}'.format(string6.lower())) string7 = "Here's what Happens when You Use UPPER." print('Output #35: {0:s}'.format(string7.upper())) string8 = "here's WHAT Happens WHEN you use Capitalize." print('Output #36: {0:s}'.format(string8.capitalize())) string8_list = string8.split() print('Output #37 (on each word):') for word in string8_list: print('{0:s}'.format(word.capitalize())) # 正则表达式 - 计算字符串中模式出现的次数 string = 'The quick brown fox jumps over the lazy dog.' string_list = string.split() pattern = re.compile(r'The', re.I) count = 0 for word in string_list: if pattern.search(word): count += 1 print('Output #38: {0:d}'.format(count)) # 正则表达式 - 在字符串中每次找到模式时将其打印出来 string = 'The quick brown fox jumps over the lazy dog.' string_list = string.split() pattern = re.compile(r'(?P<match_word>The)', re.I) print('Output #39:') for word in string_list: if pattern.search(word): print('{:s}'.format(pattern.search(word).group('match_word'))) # 正则表达式 - 使用字母'a'替换字符串中的单词'the' string = 'The quick brown fox jumps over the lazy dog.' string_to_find = r'The' pattern = re.compile(string_to_find, re.I) print('Output #40: {:s}'.format(pattern.sub('a', string))) # 日期 - 打印出今天的日期形式,以及年、月、日 today = date.today() print('Output #41: today: {0!s}'.format(today)) print('Output #42: {0!s}'.format(today.year)) print('Output #43: {0!s}'.format(today.month)) print('Output #44: {0!s}'.format(today.day)) current_datetime = datetime.today() print('Output #45: {0!s}'.format(current_datetime)) # 日期 - 使用timedelta计算一个新日期 one_day = timedelta(days= -1) yesterday = today + one_day print('Output #46: yesterday: {0!s}'.format(yesterday)) eight_hours = timedelta(hours= -8) print('Output #47: {0!s} {1!s}'.format(eight_hours.days, eight_hours.seconds)) # 日期 - 计算出两个日期之间的天数 date_diff = today - yesterday print('Output #48: {0!s}'.format(date_diff)) print('Output #49: {0!s}'.format(str(date_diff).split()[0])) # 日期 - 根据一个日期对象创建具有特定格式的字符串 print('Output #50: {:s}'.format(today.strftime('%m/%d/%Y'))) print('Output #51: {:s}'.format(today.strftime('%b %d, %Y'))) print('Output #52: {:s}'.format(today.strftime('%Y-%m-%d'))) print('Output #53: {:s}'.format(today.strftime('%B %d, %Y'))) # 日期 - 根据一个表示日期的字符串 # 创建一个带有特殊格式的datetime对象 date1 = today.strftime('%m/%d/%Y') date2 = today.strftime('%b %d, %Y') date3 = today.strftime('%Y-%m-%d') date4 = today.strftime('%B %d, %Y') # 基于4个具有不同日期格式的字符串 # 创建2个datetime对象和2个date对象 print('Output #54: {!s}'.format(datetime.strptime(date1, '%m/%d/%Y'))) print('Output #55: {!s}'.format(datetime.strptime(date2, '%b %d, %Y'))) # 仅显示日期部分 print('Output #56: {!s}'.format(datetime.date(datetime.strptime(date3, '%Y-%m-%d')))) print('Output #57: {!s}'.format(datetime.date(datetime.strptime(date4, '%B %d, %Y')))) # 列表 - 创建列表 # 使用方括号创建一个列表 # 用len()计算列表中元素的数量 # 用max()和min()找出最大值和最小值 # 用count()计算出列表中某个值出现的次数 a_list = [1, 2, 3] print('Output #58: {}'.format(a_list)) print('Output #59: a_list has {} elements.'.format(len(a_list))) print('Output #60: the maximum value in a_list is {}.'.format(max(a_list))) print('Output #61: the minimum value in a_list is {}.'.format(min(a_list))) another_list = ['printer', 5, ['star', 'circle', 9]] print('Output #62: {}'.format(another_list)) print('Output #63: another_list also has {} elements.'.format(len(another_list))) print('Output #64: 5 is in another_list {} time.'.format(another_list.count(5))) # 列表 - 索引值 # 使用索引值访问列表中的特定元素 # [0]是第1个元素,[-1]是最后一个元素 print('Output #65: {}'.format(a_list[0])) print('Output #66: {}'.format(a_list[1])) print('Output #67: {}'.format(a_list[2])) print('Output #68: {}'.format(a_list[-1])) print('Output #69: {}'.format(a_list[-2])) print('Output #70: {}'.format(a_list[-3])) print('Output #71: {}'.format(another_list[2])) print('Output #72: {}'.format(another_list[-1])) # 列表 - 列表切片 # 使用列表切片访问列表元素的一个子集 # 从开头开始切片,可以省略第1个索引值 # 一直切片刀末尾,可以省略第2个索引值 print('Output #73: {}'.format(a_list[0:2])) print('Output #74: {}'.format(another_list[:2])) print('Output #75: {}'.format(a_list[1:3])) print('Output #76: {}'.format(another_list[1:])) # 列表 - 列表复制 # 使用[:]复制一个列表 a_new_list = a_list[:] print('Output #77: {}'.format(a_new_list)) # 列表 - 列表链接 # 使用+将两个或更多个列表链接起来 a_longer_list = a_list + another_list print('Output #78: {}'.format(a_longer_list)) # 列表 - 使用in和not in # 使用in和not in来检查列表中是否有特定元素 a = 2 in a_list print('Output #79: {}'.format(a)) if 2 in a_list: print('Output #80: 2 is in {}'.format(a_list)) b = 6 not in a_list print('Output #81: {}'.format(b)) if 6 not in a_list: print('Output #82: 6 is not in {}'.format(a_list)) # 列表 - 追加、删除和弹出元素 # 使用append()向列表末尾追加一个新元素 # 使用remove()从列表中删除一个特定元素 # 使用pop()从列表末尾删除一个元素 a_list.append(4) a_list.append(5) a_list.append(6) print('Output #83: {}'.format(a_list)) a_list.remove(5) print('Output #84: {}'.format(a_list)) a_list.pop() a_list.pop() print('Output #85: {}'.format(a_list)) # 列表 - 列表反转 # 使用reverse()原地反转一个列表会修改原列表 # 要想反转列表同时又不修改原列表,可以先复制列表 a_list.reverse() print('Output #86: {}'.format(a_list)) a_list.reverse() print('Output #87: {}'.format(a_list)) # 列表 - 列表排序 # 使用sort()对列表进行原地排序会修改原列表 # 要想对列表进行排序同时又不修改原列表,可以先复制列表 unordered_list = [3, 5, 1, 7, 2, 8, 4, 9, 0, 6] print('Output #88: {}'.format(unordered_list)) list_copy = unordered_list[:] list_copy.sort() print('Output #89: {}'.format(list_copy)) print('Output #90: {}'.format(unordered_list)) # 列表 - sorted排序函数 # 使用sorted()对一个列表集合按照列表中某个位置的元素进行排序 my_lists = [[1, 2, 3, 4], [4, 3, 2, 1], [2, 4, 1, 3]] my_lists_sorted_by_index_3 = sorted(my_lists, key=lambda index_value:index_value[3]) print('Output #91: {}'.format(my_lists_sorted_by_index_3)) # 使用itemgetter()对一个列表集合按照两个索引位置来排序 my_lists = [[123, 2, 2, 444], [22, 6, 6, 444], [354, 4, 4, 678], [236, 5, 5, 678], [578, 1, 1, 290], [461, 1, 1, 290]] my_lists_sorted_by_index_3_and_0 = sorted(my_lists, key=itemgetter(3, 0)) print('Output #92: {}'.format(my_lists_sorted_by_index_3_and_0)) # 元组 - 创建元组 # 使用圆括号创建元组 my_tuple = ('x', 'y', 'z') print('Output #93: {}'.format(my_tuple)) print('Output #94: my_tuple has {} elements'.format(len(my_tuple))) print('Output #95: {}'.format(my_tuple[1])) longer_tuple = my_tuple + my_tuple print('Output #96: {}'.format(longer_tuple)) # 元组 - 元组解包 one, two, three = my_tuple print('Output #97: {0} {1} {2}'.format(one, two, three)) var1 = 'red' var2 = 'robin' print('Output #98: {} {}'.format(var1, var2)) # 在变量之间交换彼此的值 var1, var2 = var2, var1 print('Output #99: {} {}'.format(var1, var2)) # 元组 - 元组转换成列表(及列表转换成元组) # 将元组转换成列表,列表转换成元组 my_list = [1, 2, 3] my_tuple = ('x', 'y', 'z') print('Output #100: {}'.format(tuple(my_list))) print('Output #101: {}'.format(list(my_tuple))) # 字典 - 创建字典 # 使用花括号创建字典 # 用冒号分隔键-值对 # 用len()计算出字典中键-值对的数量 empty_dict = {} a_dict = {'one':1, 'two':2, 'three':3} print('Output #102: {}'.format(a_dict)) print('Output #103: a_dict has {!s} elements'.format(len(a_dict))) another_dict = {'x':'printer', 'y':5, 'z':['star', 'circle', '9']} print('Output #104: {}'.format(another_dict)) print('Output #105: another_dict also has {!s} elements'.format(len(another_dict))) # 字典 - 引用字典中的值 # 使用键来引用字典中特定的值 print('Output #106: {}'.format(a_dict['two'])) print('Output #107: {}'.format(another_dict['z'])) # 字典 - 复制 # 使用copy()复制一个字典 a_new_dict = a_dict.copy() print('Output #108: {}'.format(a_new_dict)) # 字典 - 键、值和项目 # 使用keys()、values()和items()分别引用字典中的键、值和键-值对 print('Output #109: {}'.format(a_dict.keys())) a_dict_keys = a_dict.keys() print('Output #110: {}'.format(a_dict_keys)) print('Output #111: {}'.format(a_dict.values())) print('Output #112: {}'.format(a_dict.items())) # 字典 - 使用in、not in和get if 'y' in another_dict: print('Output #114: y is a key in another_dict: {}.'.format(another_dict.keys())) if 'c' not in another_dict: print('Output #115: c is not a key in another_dict: {}.'.format(another_dict.keys())) print('Output #116: {!s}'.format(a_dict.get('three'))) print('Output #117: {!s}'.format(a_dict.get('four'))) print('Output #118: {!s}'.format(a_dict.get('four', 'Not in dict'))) # 字典 - 排序 # 使用sorted()对字典进行排序 # 要想对字典排序的同时不修改原字典 # 先复制字典 print('Output #119: {}'.format(a_dict)) dict_copy = a_dict.copy() ordered_dict1 = sorted(dict_copy.items(), key=lambda item: item[0]) print('Output #120: (order by keys): {}'.format(ordered_dict1)) ordered_dict2 = sorted(dict_copy.items(), key=lambda item: item[1]) print('Output #121: (order by values): {}'.format(ordered_dict2)) ordered_dict3 = sorted(dict_copy.items(), key=lambda x: x[1], reverse=True) print('Output #122: (order by values, descending): {}'.format(ordered_dict3)) ordered_dict4 = sorted(dict_copy.items(), key=lambda x: x[1], reverse=False) print('Output #123: (order by values, ascending): {}'.format(ordered_dict4)) # 控制流 - if-else语句 x = 5 if x > 4 or x != 9: print('Output #124: {}'.format(x)) else: print('Output #124: x is not greater than 4') # 控制流 - if-elif-else语句 if x > 6: print('Output #125: x is greater than six') elif x > 4 and x == 5: print('Output #125: {}'.format(x*x)) else: print('Output #125: x is not greater than 4') # 控制流 - for循环 y = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] z = ['Annie', 'Betty', 'Claire', 'Daphne', 'Ellie', 'Franchesca', 'Greta', 'Holly', 'Isabel', 'Jenny'] print('Output #126:') for month in y: print('{!s}'.format(month)) print('Output #127: (index value: name in list)') for i in range(len(z)): print('{0!s}: {1:s}'.format(i, z[i])) print("Output #128: (access elements in y with z's index values)") for j in range(len(z)): if y[j].startswith('J'): print('{!s}'.format(y[j])) print('Output #129:') for key, value in another_dict.items(): print('{0:s}, {1}'.format(key, value)) # 控制流 - 简化for循环:列表、集合与字典生成式 # 使用列表生成式选择特定的行 my_data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] rows_to_keep = [row for row in my_data if row[2] > 5] print('Output #130: (list comprehension): {}'.format(rows_to_keep)) # 使用集合生成式在列表中选择出一组唯一的元组 my_data = [(1, 2, 3), (4, 5, 6), (7, 8, 9), (7, 8, 9)] set_of_tuples1 = {x for x in my_data} print('Output #131: (set comprehension): {}'.format(set_of_tuples1)) set_of_tuples2 = set(my_data) print('Output #132: (set function): {}'.format(set_of_tuples2)) # 使用字典生成式选择特定的键-值对 my_dictionary = {'customer1': 7, 'customer2': 9, 'customer3': 11} my_results = {key : value for key, value in my_dictionary.items() if value >10} print('Output #133: (dictionary comprehension): {}'.format(my_results)) # 控制流 - while循环 print('Output #134:') x = 0 while x < 11: print('{!s}'.format(x)) x += 1 # 控制流 - 函数 # 计算一系列数值的均值: def getMean(numericValues): return sum(numericValues)/len(numericValues) if len(numericValues) > 0 else float('nan') my_list = [2, 2, 4, 4, 6, 6, 8, 8] print('Output #135 (mean): {!s}'.format(getMean(my_list))) # 控制流 - try-except # 计算一系列数值的均值 def getMean2(numericValues): return sum(numericValues)/len(numericValues) my_list2 = [] try: print('Output #138 {}'.format(getMean2(my_list2))) except ZeroDivisionError as detail: print('Output #138 (Error): {}'.format(float('nan'))) print('Output #138 (Error): {}'.format(detail)) # 控制流 - try-except-else-finally # 完整形式 try: result = getMean2(my_list2) except ZeroDivisionError as detail: print('Output #142 (Error): {}'.format(float('nan'))) print('Output #142 (Error): {}'.format(detail)) else: print('Output #142 (The mean is ): {}'.format(result)) finally: print('Output #142 (Finally): The finally block is executed every time') # 读取文件 # 读取单个文本文件 #input_file = sys.argv[1] #print('Output #143:') #filereader = open(input_file, 'r') #for row in filereader: # print(row.strip()) #filereader.close() # 读取文件的新型语法 #input_file = sys.argv[1] #print('Output #144:') #with open(input_file, 'r') as filereader: # for row in filereader: # print('{}'.format(row.strip())) # 读取多个文本文件 #print('Output #145:') #inputPath = sys.argv[1] #for input_file in glob.glob(os.path.join(inputPath, '*.txt')): # with open(input_file, 'r') as filereader: # for row in filereader: # print('{}'.format(row.strip())) # 写入文件 # 写入一个文本文件 my_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] max_index = len(my_letters) output_file = sys.argv[1] filewriter = open(output_file, 'w') for index_value in range(max_index): if index_value < (max_index - 1): filewriter.write(my_letters[index_value]+'\t') else: filewriter.write(my_letters[index_value]+'\n') filewriter.close() print('Output #146: Output written to file') # 写入CSV文件 my_numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] max_index = len(my_numbers) output_file = sys.argv[1] filewriter = open(output_file, 'a') for index_value in range(max_index): if index_value < (max_index - 1): filewriter.write(str(my_numbers[index_value])+',') else: filewriter.write(str(my_numbers[index_value])+'\n') filewriter.close() print('Output #147: Output appended to file')
fccadcf14bddd0c87eabbb31265a260f6771dbe0
sazima/leetcode
/python_code/q53/s.py
970
3.734375
4
""" 给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 子数组 是数组中的一个连续部分。 ---------------------- 示例 1: 输入:nums = [-2,1,-3,4,-1,2,1,-5,4] 输出:6 解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。 ---------------------- 示例 2: 输入:nums = [1] 输出:1 示例 3: 输入:nums = [5,4,-1,7,8] 输出:23 提示: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 """ from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: if len(nums) == 1: return nums[0] sum_ = nums[0] max_ans =nums[0] for index, n in enumerate(nums[1:]): sum_ = max(n, sum_ + n) max_ans = max(max_ans, sum_) return max_ans if __name__ == '__main__': res = Solution().maxSubArray([-2,1,-3,4,-1,2,1,-5,4]) print(res)
039e000c4b498a8b2911950fdd9216e0bec76cd5
bug5654/PythonRefresh
/stringmanip.py
3,473
4.09375
4
print("String analysis program") stringVar = " Greetings Program! " stringVarReset = stringVar print("string in question: '" + stringVar + "'") print( "type: " + str( type(stringVar) ) ) print( "number of 'e's: " + str(stringVar.count("e")) ) print( "position of 'P': " + str(stringVar.find('P')) ) #confirmed: 0-based string position (C-style) print( "lowercase: " + stringVar.lower() ) print( "uppercase: " + stringVar.upper() ) print( "e->q: " + stringVar.replace('e','q') ) stringVar = stringVarReset print( "strip whitespace: " + stringVar.strip() ) print( "positions 3-5: " + stringVar[3:5]) print( "remove last 3 characters: " + stringVar[:-3] ) print( "first 10 characters alternate route: %.10s" % stringVar) randNum=951.0372486 print("non-rounded float: %f" % randNum) print("rounded float: %.2f" % randNum) a = "C:\some\thing\near" print("accidental backslash usage:\n",a) a = r"C:\some\thing\near" print("corrected via r'...' raw quote:\n",a) print("multiline using backslashes for clarity:\n") s="""\ My bologna has a first name It's O-S-C-A-R My bologna has a second name It's M-A-Y-E-R """ print(s*3+"Oscar Mayer bologna!","At your supermarket now!") ### #replacing + with , yields a space at beginning of line visible & desirable between the second two strings alt = ("My bologna has a first name\n" "It's O-S-C-A-R\n" "My bologna has a second name\n" "It's M-A-Y-E-R\n") ### #putting string literals in parens concatenates them, but only exact literals print(alt+"Should look familiar") print("slicing (listing every index):",\ alt[3],alt[4],alt[5],alt[6],alt[7],alt[8],alt[9]) print("slicing the easy way(range): ",alt[3:10]) #don't forget [min,max) print("does it work backwards? ",alt[9:2:-1]) #have to specify step since min>max still [min,max) though print("back to:",a) print("len is string length in python:",len(a)) print("but it's one based:",a[:len(a)]) #would cut off a letter if len 0-based print("remember though, strings are immutable in python") b=a[:14]+r"wicked\this\way\comes" print("so create a new string instead:",b) a,b,c = ["d","e","f"] #multiple assignment print(a,b,c) #string literals print("str v repr:",str(alt),"repr:",repr(alt)) import math print(f'pi is legally {math.pi:.2f}.') #string format in string print("mathematically it's more like {0}".format(round(math.pi,15))) print("there are other approximations:") approxs = {"22/7":22/7, "333/106":333/106, "16/15":16/15} for title, fraction in approxs.items(): print(f"{title:10} ~= {fraction:1.8f}") #iterators s = "a string" it = iter(s) print("iterator after creation:",it) while True: try: print("next(it):",next(it)) except(StopIteration): print("StopIteration occured!") break; import random class randomLetterGen: """pulls random letters from a string""" def __init__(self, stringer): self.used = [] self.genString=stringer def __iter__(self): return self; def __next__(self): if(len(self.used) == len(self.genString)): #catch error on blank genString raise StopIteration distinct = False while distinct == False: index = random.randint(0,len(self.genString)-1) if index in self.used: continue self.used.append(index) yield self.genString[index] if(len(self.used) == len(self.genString)): raise StopIteration #stops hanging r = randomLetterGen("Bass Cannon") print("Base string: Bass Cannon") try: for char in r.__next__(): print("random letter from gen:",char) except: print("caught Exception!")
3d2439e1e554f4aaf5ef5941f3596068f766318d
cofo-coding-camp/Nemo
/0092.py
676
3.75
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: count = 1 cur = head if m == n: return head while count < m: first = cur cur = cur.next count += 1 pre = None last = cur while count <= n: cur.next, pre, cur = pre, cur, cur.next count += 1 last.next = cur if m != 1: first.next = pre return head else: return pre
66fec25f9812cc47ba8635ab17eb04797adb36cd
CianLR/advent-of-code-2017
/day03/first.py
1,122
3.765625
4
import numpy as np UP = np.array([0, 1]) LEFT = np.array([-1, 0]) DOWN = np.array([0, -1]) RIGHT = np.array([1, 0]) def get_spiral_level(n): l = 1 n -= 2 spiral_size = 8 while n - spiral_size >= 0: n -= spiral_size spiral_size += 8 l += 1 return l, n def walk_spiral(p, level, index): K = 2 * level i = 0 for _ in range(K - 1): if i == index: return p p += UP i += 1 for _ in range(K): if i == index: return p p += LEFT i += 1 for _ in range(K): if i == index: return p p += DOWN i += 1 for _ in range(K): if i == index: return p p += RIGHT i += 1 return p def dist(p): return abs(p[0]) + abs(p[1]) def main(): N = int(input()) if N == 1: print("No") return level, index = get_spiral_level(N) p = np.array([1, 0]) + (np.array([1, -1]) * (level - 1)) p = walk_spiral(p, level, index) print(p) print(dist(p)) if __name__ == '__main__': main()
911f6bed362e78a89ce99683add08caa52cf29c6
betty29/code-1
/recipes/Python/578617_small_stack_language/recipe-578617.py
3,199
3.828125
4
class Stack: def __init__(self): self.data = [] def push(self, x): self.data.append(x) def pop(self): return self.data.pop() class Interpreter: def __init__(self): self.stack = Stack() def process(self, word): if is_int(word): n = int(word) self.stack.push(n) elif '"' in word: self.stack.push(word.strip('"')) else: try: f = words[word] except KeyError: raise SyntaxError, 'ERRor Unknown word\n\t'+word+'!!!' # determine number of arguments n = num_args(f) # pop that number of args from stack args = reversed([self.stack.pop() for i in range(n)]) # call f with that list result = f(*args) # take return value (a list) # push elements on stack for x in result or []: self.stack.push(x) def process_line(self, line): words = line.split() for word in words: self.process(word) def _print(x): print x def _pas(): pass def _exit(): exit() def _help(): print ''' words = { '+': lambda x, y: [x+y], '-': lambda x, y: [x-y], '*': lambda x, y: [x*y], '/': lambda x, y: [x/y], '==': lambda x, y: [x==y], '!=': lambda x, y: [x!=y], '>': lambda x, y: [x>y], '<': lambda x, y: [x<y], 'dup': lambda x: [x, x], 'drop': lambda x: [], 'swap': lambda x, y: [y, x], 'print': _print, 'chr': lambda x: [chr(x)], 'sweep': _pas, 'scan': lambda x: [raw_input(x)], 'exit': _exit, 'help': _help } ''' words = { '+': lambda x, y: [x+y], '-': lambda x, y: [x-y], '*': lambda x, y: [x*y], '/': lambda x, y: [x/y], '==': lambda x, y: [x==y], '!=': lambda x, y: [x!=y], '>': lambda x, y: [x>y], '<': lambda x, y: [x<y], 'dup': lambda x: [x, x], 'drop': lambda x: [], 'swap': lambda x, y: [y, x], 'print': _print, 'chr': lambda x: [chr(x)], 'sweep': _pas, 'scan': lambda x: [raw_input(x)], 'exit': _exit, 'help': _help, '.': _pas } def num_args(f): """ Return the number of arguments that function <f> takes. """ return f.func_code.co_argcount def is_int(s): try: int(s) except ValueError: return False else: return True if __name__ == "__main__": import sys e = Interpreter() main = True print '===================================================' print '***************************************************' print 'drinkable_chicken modified version 1.0.0 6.13.2013' print 'A.W.T. 10 YRS. old' print '***************************************************' print 'IDE 1.0.1' print '===================================================' while main == True: line = raw_input('> ') if '.' in line: e.process_line(line) if 'sweep' in line: e.stack.data = [] print "stack:", e.stack.data else: print 'ERRor command \n\tterminator not found!'
11ac1da7b12cc3d70e80fca2179a30ac0201c0e4
laumitt/modsim-planes
/planes_v2.py
18,769
3.53125
4
import numpy as np import csv import string import matplotlib.pyplot as plt '''these global constants are parameters that can be varied as desired''' flying_prob = .95 # probability of a flight being scheduled at a particular time length_of_simulation = 125 # in hours airport_size = 10 # number of airplanes distributed to each airport at the beginning max_storm_length = 7 # max and min storm length min_storm_length = 3 length_of_schedule = 100 # in hours, the simulation will continue to run after the schedule ends to finish out flights started plot_arrivals = True # if True, will plot arrivals at the end; if False, will plot departures '''these things are all to be plotted at the end''' storm_planes_arriving = [] storm_planes_departing= [] storm_flights = [] storm_delays= [] no_storm_planes_arriving= [] no_storm_planes_departing = [] no_storm_flights= [] no_storm_delays= [] def read_csv(flight_time_array): '''reads airport names and flight times from csv''' airport_names = [] with open('flight_times.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in reader: if airport_names == []: # the first row of the csv is the names of the airports airport_names = (row[0].split(','))[1:] # exclude the first cell because it's a label for humans else: # the rest of the file is flight times to be separated out split = row[0].split(',') # split rows to give each airport flight times to the others split_ints = [] for i in split: if i not in airport_names: # if it's not an airport name it's a flight time split_ints.append(int(i)) flight_time_array.append(split_ints) return airport_names def create_schedule(airport_names, airport_size, total_time, airport_dict): ''' takes in list of airports, number of planes each start with, and simulation length returns a schedule listing the time of departure, the departure airport, and the arrival airport ''' sched = [] # sched: time leaving, departure airport, arrival airport arrivals = [] # arrivals: time, destination planes_in_ports = [] for i in airport_names: planes_in_ports.append([i,airport_size]) flight_number = 0 for i in range(total_time): #goes through each time to determine arrivals and departures for that time for port_number in range(len(planes_in_ports)): #figure out departures destinations = airport_names.copy() port = planes_in_ports[port_number] destinations.remove(airport_names[port_number]) if type(destinations) == None: return for individual_airplanes in range(planes_in_ports[port_number][1]): #this should go through and decide if each airplane available is flying if (planes_in_ports[port_number][1] > 0) and (np.random.random() > 1- flying_prob) and len(destinations) > 0: #PROBABLILITY HERE planes_in_ports[port_number][1] -= 1 dest = np.random.randint(0,len(airport_names)) time_to_dest = flight_time_array[port_number][dest] arrival_time = int(i) + int(time_to_dest) + 1 if airport_names[dest] in destinations: arrivals.append([arrival_time,dest]) sched.append([i,port[0],airport_names[dest], flight_number]) flight_number+=1 if len(destinations) == 1: destinations = [] else: destinations.remove(airport_names[dest]) for x in arrivals: #check for arrivals if x[0] == i: #if the time the arrival specifies is now for plane_num in range(len(planes_in_ports)): if planes_in_ports[plane_num][0] == airport_names[x[1]]: planes_in_ports[plane_num][1] += 1 return sched class ATC: def __init__(self): self.storm_time = -1 self.storm_length = -1 self.storm_location = None self.storm_info = [self.storm_time, self.storm_location, self.storm_length] def update(self): '''updates time until end of simulation''' global current_time if current_time < length_of_simulation: current_time += 1 # keeping track of time for the entire system def divide_schedule(self, schedule, airport_dict): '''takes the schedule and distributes between each airport so they know their own departures''' for step in schedule: airport_dict[step[1]].add_to_schedule(step) def storm_schedule(self): '''generates information about storms''' global length_of_schedule self.storm_length = np.random.randint(min_storm_length, max_storm_length) # randomly determines storm length if(self.storm_length < round(length_of_schedule/4)): # keeps time at the beginning of the model length for a full prestorm self.storm_time = np.random.randint(self.storm_length, (round(length_of_schedule/4))) else: self.storm_time = self.storm_length # because we want the storm at the beginning to be able to see the effects later self.storm_location = airport_names[np.random.randint(0, len(airport_names))] self.storm_info = [self.storm_time, self.storm_location, self.storm_length] class Airport: '''handles the departures of each airplane, as well as reciving airplanes from other airports''' def __init__(self, code, airport_schedule, planes_ready, planes_arriving): self.code = code self.airport_schedule = airport_schedule self.planes_ready = planes_ready self.planes_arriving = planes_arriving self.planes_arriving_log = [] self.planes_departing = [] self.planes_departing_log = [] self.storm_delays = 0 self.delays = 0 def add_to_schedule(self, step): '''takes info from the schedule distribution by the atc and compiles own schedule''' self.airport_schedule.append(step) def arriving_plane(self, plane): '''keep track of arriving planes and bring them in next time cycle after wait period''' self.planes_arriving.append(plane) def storm_check(self): '''checks storm info and update airport schedule with delays''' storm_info = atc.storm_info self.storm_delays = 0 for time_step in range(len(self.airport_schedule)): schedule_step = self.airport_schedule[time_step] if schedule_step[0] == current_time: flight_time = find_flight_time(airport_dict, airport_names, self.code, schedule_step[2]) # storm_info is formatted as storm_time, storm_location, storm_length if (storm_info[0] <= (current_time + flight_time)) and ((current_time + flight_time) <= (storm_info[0] + storm_info[2])) and (schedule_step[2] == storm_info[1]): # if the destination is under a storm self.airport_schedule[time_step][0] += 1 self.storm_delays += 1 elif (storm_info[0] <= current_time <= (storm_info[0] + storm_info[2])) and (self.code == storm_info[1]): # if the current airport is under a storm self.airport_schedule[time_step][0] += 1 self.storm_delays += 1 return self.storm_delays def departure_update(self): '''tells planes when to leave and for where''' global current_time planes_departing = [] # log what planes leave in this update self.delays = 0 for time_step in range(len(self.airport_schedule)): schedule_step = self.airport_schedule[time_step] if schedule_step[0] == current_time: # if there is a flight scheduled now if len(self.planes_ready) > 0: # if we have planes available plane_flying = self.planes_ready[0] # send out the next available plane flight_time = find_flight_time(airport_dict, airport_names, self.code, schedule_step[2]) plane_dict[plane_flying].assign_new_destination(schedule_step[2], flight_time, schedule_step[-1]) self.planes_departing.append(plane_flying) if len(self.planes_ready) == 1: # if that was the last available plane, the list becomes empty self.planes_ready = [] else: # otherwise just remove the plane from the list self.planes_ready.remove(plane_flying) else: # if we don't have planes available self.airport_schedule[time_step][0] += 1 # push back that flight self.delays +=1 # add an hour of delay self.planes_departing_log.append(len(self.planes_departing)) # track how many planes left in this update return self.delays def arrival_update(self): '''takes planes that have arrived and processes them to ready to fly''' for plane in self.planes_arriving: self.planes_ready.append(plane) self.planes_arriving_log.append(len(self.planes_arriving)) self.planes_arriving = [] class Plane: def __init__(self, code, location, destination, arrival_time): self.code = code self.location = location self.destination = destination self.arrival_time = arrival_time self.flying = False self.flight_number = 0 def assign_new_destination(self, destination, arrival_time, flight_number): '''assigns plane destination when airport tells it to take off''' global current_time self.destination = destination self.arrival_time = arrival_time + current_time self.flying = True self.flight_number = flight_number def update(self,airport_dict): '''logs plane info per time and checks if it's arrived at its destination yet''' global current_time global planes_in_air global plane_tracking plane_tracking.append([current_time, self.code, self.location, self.destination, self.flight_number]) if self.arrival_time == current_time: # if the plane has arrived self.location = self.destination airport_dict[self.destination].arriving_plane(self.code) # tell the destination airport the plane has arrived self.flying = False # remove itself from the list of planes in flight def create_airports(): '''loops through each airport name and creates an object based on that list''' airport_dict = {} for i in airport_names: name = i # the name is the airport code as a string schedule = [] # empty for initialization arrivals = [] # empty for initialization planes_ready = [] # empty for initialization i = Airport(name, schedule, planes_ready, arrivals) airport_dict[name] = i # dictionary to make it easier to refer to airport objects return airport_dict def create_airplanes(): '''creates airplanes and returns a dictionary with names and location''' plane_dict = {} names = [] for i in range(len(airport_names) * airport_size): # creates a series of names, a0, a1, a2, etc, as many as necessary names.append('a'+ str(i)) plane_num = 0 for i in range(len(airport_names)): for j in range(airport_size): # evenly distributes planes to airports name = names[plane_num] plane_names.append(name) names[plane_num] = Plane(name, airport_names[i], airport_names[i],-1) # the -1 gives all the airports their planes at the same time plane_dict[name] = names[plane_num] plane_num += 1 return plane_dict def find_flight_time(airport_dict, airport_names, port_one, port_two): '''returns the time from port one to port two''' for i in range(len(airport_names)): if airport_names[i] == port_one: # find the first airport port_one = i if airport_names[i] == port_two: # find the second airport port_two = i return flight_time_array[port_one][port_two] # consult the flight time array for flight time def run_simulation(storms): '''storm global variables''' global storm_delays global storm_flights global storm_planes_arriving global storm_planes_departing '''no storm global variables''' global no_storm_delays global no_storm_flights global no_storm_planes_arriving global no_storm_planes_departing '''loops through an entire simulation, takes in if there are storms or not''' #first, set up an array to keep track of how many planes are flying at each time and how many delays occur planes_in_air_at_time = [] delayed_per_hour = [] total_delays = 0 delays = 0 #then, step through each time in the run_simulation for step in range(length_of_simulation): delays = 0 #reset the number of delays for time step atc.update() #update the time each step for airport in airport_names: #run through each airport and check if there are any storms which affect the current flights and update accordingly, also add any delays caused by this if storms: delays += airport_dict[airport].storm_check() #send any flights, and if there arent enough airplanes then add that into our calculated delays too delays += airport_dict[airport].departure_update() for plane in plane_names: #have plane check if it should be arriving somewhere plane_dict[plane].update(airport_dict) for airport in airport_names: #then process the arriving planes in the airports airport_dict[airport].arrival_update() #determine how many planes are currently flying planes_currently_flying = 0 for plane in plane_names: if plane_dict[plane].flying == True: planes_currently_flying += 1 planes_in_air_at_time.append(planes_currently_flying) delayed_per_hour.append(delays) total_delays += delays #keeping track of metrics about how many storms and delays there were if storms: storm_flights = planes_in_air_at_time storm_delays = delayed_per_hour for airport in airport_names: storm_planes_arriving.append(airport_dict[airport].planes_arriving_log) storm_planes_departing.append(airport_dict[airport].planes_departing_log) else: no_storm_flights = planes_in_air_at_time no_storm_delays = delayed_per_hour for airport in airport_names: no_storm_planes_arriving.append(airport_dict[airport].planes_arriving_log) no_storm_planes_departing.append(airport_dict[airport].planes_departing_log) if __name__ == '__main__': '''allows us to run through the simulation twice with the same schedule to see how storms affect the pattern''' '''these global variable are changed throughout the simulation''' current_time = -2 flight_time_array = [] plane_names = [] airport_names = read_csv(flight_time_array) '''setting up the airports, planes, and schedule by initializing classes''' airport_dict = create_airports() plane_dict = create_airplanes() schedule = create_schedule(airport_names, airport_size, length_of_schedule, airport_dict) storm_planes = schedule.copy() atc = ATC() atc.storm_schedule() '''looping through the same schedule with and without a stom''' for storm in range(2): #resetting the airports and planes so each time they start from their initial values airport_dict = {} plane_dict = {} plane_names = [] airport_dict = create_airports() plane_dict = create_airplanes() plane_tracking = [] current_time = -2 if storm == 0: atc.divide_schedule(schedule, airport_dict) run_simulation(False) else: atc.divide_schedule(storm_planes, airport_dict) run_simulation(True) '''Plotting''' plotting = ['b', 'g', # colors for plotting later 'r', 'c', 'm', 'k', 'y', 'tab:pink', 'darkkhaki', 'maroon', 'gold', 'lawngreen', 'lightseagreen', 'olive', 'palevioletred', 'orchid', 'peru', 'coral', 'orangered', 'mediumspringgreen', 'rebeccapurple', 'teal'] plt.figure(0) plt.title("Flights Under No Storm Condition") plt.plot(no_storm_flights, label = 'Flights') plt.plot(no_storm_delays, label = 'Delays') i = 0 for airport_num in range(len(airport_names)): # graphing arrivals by airport over time airport = airport_names[airport_num] if plot_arrivals == True: plt.plot(no_storm_planes_arriving[airport_num], ':', color=plotting[i], label=str(airport) + ' Arrivals') else: plt.plot(no_storm_planes_departing[airport_num], ':', color=plotting[i+1], label=str(airport) + ' Departures') i += 2 plt.xlabel('Time (Hours)') plt.ylabel('Number of Planes') plt.legend() plt.figure(1) plt.title('Flights Under Storm Condition') plt.plot(storm_flights, label = 'Flights') plt.plot(storm_delays, label = 'Delays') i = 0 for airport_num in range(len(airport_names)): # graphing arrivals by airport over time airport = airport_names[airport_num] if plot_arrivals == True: plt.plot(storm_planes_arriving[airport_num], ':', color=plotting[i], label=str(airport) + ' Arrivals') else: plt.plot(storm_planes_departing[airport_num], ':', color=plotting[i+1], label=str(airport) + ' Departures') i += 2 plt.xlabel('Time (Hours)') plt.ylabel('Number of Planes') plt.legend() plt.figure(2) plt.title('Number of Flights, Storm vs No Storm Condition') plt.plot(storm_flights, label = 'Flights with Storm') plt.plot(no_storm_flights, label = 'Flights without Storm') plt.plot(storm_delays, label = 'Delays caused by Storm') plt.legend() print('PLANE INCREASE') print('Storm time {}, location {}, length {}'.format(atc.storm_time, atc.storm_location, atc.storm_length)) print('Flying probability {}%, length of simulation {}, length of schedule {}, airport size {}'.format((flying_prob*100), length_of_simulation, length_of_schedule, airport_size)) plt.show()
5fd80ba37a48dcee9d08a573b8bea93457df991d
anjali-garadkar/loopa
/trangal.py
399
3.796875
4
# anju=int(input("enter the number")) # i=1 # while i<=anju: # print(i,end=" ") # i=i+1 # n=int(input("enter the number")) # i=1 # while i<=n: # print(i) # i=i+1 # k=1 # i=1 # while i<=6: # j=1 # while j<=6-i: # print(" ",end="") # j=j+1 # l=1 # while l<=k: # print("*",end="") # l=l+1 # k=k+2 # print() # i=i+1
9bb27696b36c6cc7da3a9e5a84a95be0a9b52198
UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018
/students/ghassan/lesson06/calculator/calculator/subtracter.py
459
4
4
""" This module provides a subtraction operator """ class Subtracter(object): """ Subtractor class Produces operand 1 - operand 2 """ @staticmethod def calc(operand_1, operand_2): """ method to subtract operand2 from operand1 :param operand_1: first operand (a number) :param operand_2: second operand (a number) :return: result of subtraction """ return operand_1 - operand_2
9fff09787fa21efb8fabf6742632e1cbfbd359c0
asconem/PythonFundamentals.Exercises.Part3
/multilingual_greeter.py
1,268
4.6875
5
def language_input(): """ This function will allow the user to select a language that the program will communicate in """ language = int(input("Please select a language from the following options: \n" "1. English \n" "2. Français \n" "3. Español \n")) while language < 1 or language > 3: language = int(input("Invalid choice. Please select a language from the following options: \n" "1. English \n" "2. Français \n" "3. Español \n")) return language def name_input(language): """ This function requests a user to enter their name via an input prompt based on their selected language """ if language == 1: user_name = input("Please enter your name: ") print("Hello " + user_name + "! How are you today?") elif language == 2: user_name = input("S'il vous plaît entrez votre nom: ") print("Bonjour " + user_name + "! Comment vas-tu aujourd'hui?") elif language == 3: user_name = input("Por favor, escriba su nombre: ") print("Hola " + user_name + "! Como estas hoy?") name_input(language_input())
1f83ec55087b8d1025fe7fd9cb5233a60e1bc731
votb92/AlignmentTools
/StringManipulation.py
487
3.59375
4
def reverse(String): return String[::-1] def circularString(refString, length, startIndex, moveNumb): string = refString[startIndex-1:startIndex-1+length+1] if moveNumb > 0: string = refString[startIndex+abs(moveNumb)-1:startIndex+abs(moveNumb)+length-1] return string elif moveNumb == 0: return string else: temp = refString[len(refString)+moveNumb:] temp += string[:len(string)-moveNumb] return temp
bbcb49e5dc0e24ff9110c7ffe8c37164a82765ec
nathanlo99/dmoj_archive
/done/gfssoc3s1.py
85
3.640625
4
n = int(input()) count = 0 while n >= (1 << count): count += 1 print("1" * count)
2abb7c8e4b22b3cf63ac636df1ef0db3bfb61bc7
HansMPrieto/CIS-210-Coursework
/Python Week 2 Project/p21_netpay.py
1,109
4.0625
4
''' # FILE HEADER Determining Net Pay CIS 210 F18 Project 2 Author: Hans Prieto Credits: [N/A] Determine the netpay based on the number of hours worked. ''' def tax(gross_pay): '''int -> float Returns tax, based on gross pay. The tax rate is 15%, so gross pay is multiplied by the tax rate to get the amount of tax. >>> tax(107.5) 16.12 >>> tax(430) 64.5 ''' tax = round(gross_pay * 0.15, 2) return tax def netpay(hours): '''int -> float Returns netpay, based on the number of hours worked. >>> netpay(10) 91.38 >>> netpay(40) 365.5 ''' hourly_rate = 10.75 gross_pay = hourly_rate * hours netpay = gross_pay - tax(gross_pay) return netpay def main(): '''Net pay program driver. Prints the netpay for 10 hours of work, and the netpay for 40 hours of work. ''' print('For 10 hours work, netpay is: ', netpay(10)) print('For 40 hours work, netpay is: ', netpay(40)) return None main()
12f9ee058056c70eee725b9a15441a95d0bc461d
yunakim2/Algorithm_Python
/백준/큐(덱)/백준18258_큐2.py
1,083
3.609375
4
from collections import deque from sys import stdin class queue(object): def __init__(self): self.q = deque() def push(self, item): self.q.append(item) def pop(self): if self.empty() != 1: return self.q.popleft() else: return -1 def size(self): return len(self.q) def empty(self): if self.size() == 0: return 1 else: return 0 def front(self): if self.empty() != 1: return self.q[0] else: return -1 def back(self): if self.empty() != 1: return self.q[-1] else: return -1 n = stdin.readline() q = queue() for _ in range(int(n)): run = list(stdin.readline().split()) if run[0] == "push": q.push(int(run[1])) elif run[0] == "pop": print(q.pop()) elif run[0] == "size": print(q.size()) elif run[0] == "empty": print(q.empty()) elif run[0] == "front": print(q.front()) else: print(q.back())
e5a53a6acf72cd1983bac1339dead0dde8b6205e
MisterCruz/BigONotation
/worseSolution.py
536
4.15625
4
def get_greatest_difference(nums): greatest_difference = 0 for num1 in nums: for num2 in nums: difference = num1 - num2 if difference > greatest_difference: greatest_difference = difference return greatest_difference ''' This code gets the job done by finding every possible difference and comparing it with each other and finding the max. While it gets the job done, it has a runtime of O(n²) because the outer loop runs n times and the inner loop runs for each time the outer loop is run (n * n). '''
aac7564d1705881b216554a4d60e09b92fb4d258
HanHyunsoo/Python_Programming
/University_Study/9498.py
639
3.90625
4
""" 챕터: day4 주제: 조건문(elif 이용) 문제: 시험 점수를 입력받아 90 ~ 100점은 A, 80 ~ 89점은 B, 70 ~ 79점은 C, 60 ~ 69점은 D, 나머지 점수는 F를 출력하는 프로그램을 작성하시오. 작성자: 한현수 작성일: 2018.9.18. """ # a에 점수값 입력 a = int(input()) # 90 이상이면 "A"를 출력 if a >= 90: print("A") # 90 미만 80 이상이면 "B"를 출력 elif a >= 80: print("B") # 80 미만 70 이상이면 "C"를 출력 elif a >= 70: print("C") # 70 미만 60 이상이면 "D"를 출력 elif a >= 60: print("D") # 60 미만이면 "F"를 출력 else: print("F")
f69e7a3be41dac4ac96141f4a15a82e614455708
rschanak/LAtCS
/Lab1/Task5-6.py
358
4
4
"""Task 5: Write a comprehension over {1,2,3,4,5} whose value is the set consisting of the square of the first five positive integers. Task 6: Write a comprehension over {0,1,2,3,4} whose value is the set consisting of the first five powers of two, starting at 0.""" S1 = {1,2,3,4,5} S2 = {0,1,2,3,4} print({x**2 for x in S1}) print({2**x for x in S2})
b3ced40036d602b882fb5183dca74c3cb385ed6a
helenasouto/estudos_python
/pythonexercicios/desafio 35.py
351
4.0625
4
print('-=-'*10) print('Analisador de triângulos') print('-=-'*10) a = float(input('Primeiro segmento:')) b = float(input('Segundo segmento:')) c = float(input('Terceiro segmento:')) if a< b+c and b< a+c and c< a+b: print('Os segmentos acima PODEM FORMAR triângulos') else: print('Os segmentos acima NÃO PODEM FORMAR triângulos')
6718cdaa04578a59de29682da0aac7f2be8c2caf
cgxabc/Online-Judge-Programming-Exercise
/Leetcode/ImplementstrStr.py
597
4.25
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Dec 13 17:09:11 2017 @author: apple """ """ Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 """ def strStr(haystack, needle): for i in xrange(len(haystack)-len(needle)+1): if haystack[i:i+len(needle)]==needle: return i return -1 def strStr2(haystack, needle): return haystack.find(needle)
f9784cd22a9c3565b6d11b99b15601e7deeb298d
hackjoy/fizzbuzz
/python/fizzbuzz.py
618
3.9375
4
import unittest # returns an array from 1 to max_number with values according to the fizzbuzz rules def fizzbuzz(max_number): result = [] for n in range(1, max_number+1): if (n % 5 == 0) and (n % 3 == 0): result.append("FizzBuzz") elif (n % 3 == 0): result.append("Fizz") elif (n % 5 == 0): result.append("Buzz") else: result.append(n) return result ### ### Tests ### class FizzBuzz_Test(unittest.TestCase): def test_fizzbuzz(self): self.assertEqual(fizzbuzz(15), [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"]) unittest.main()
77152b5129bdca45ddbcbcbe5be7d5e9f5d970e5
megan-black/362-act4
/test_palindrome.py
1,097
3.578125
4
import unittest import pytest def pal(string): if(string == string[::-1]): return "The string is a palindrome" return "The string is not a palindrome" #unittest class for palindrome testing # class TestCase(unittest.TestCase): # def test_good_is(self): # self.assertEqual(pal('racecar'), "The string is a palindrome") # def test_good_isnt(self): # self.assertEqual(pal('hello'), "The string is not a palindrome") # def test_excep(self): # self.assertRaises(TypeError, pal, 1234) # def test_bad_err(self): # self.assertEqual(pal(1234), "The string is not a palindrome") # if __name__ == "__main__": # unittest.main(verbosity=2) # pytest class for palindrome testing class TestClass: def test_one(self): assert pal('asdfdsa') == "The string is a palindrome" def test_two(self): assert pal('hello') == "The string is not a palindrome" def test_three(self): assert pal('hi') == "The string is a palindrome" def test_four(self): assert pal(1) == "The string is a palindrome"
93d6862d5930aa0d397485094314a532f6ab902d
joshurban5/Data-Structures-and-Algorithms
/multip_recur_funct.py
376
4.34375
4
# Skyler Kuhn # This function multiplies two number using recursion. # Parameters must be two positive integers. def multiply_recur(a, b): if a == 0 or b == 0: return 0 if a == 1: return b # if a > 700: # return 'R.I.P Computer, just use a calculator!' if a > 1: return multiply_recur(a-1, b) + b a = multiply_recur(2, 3) print(a)
4b3aa2b7f61be71e34a5b75e0faf129704cf70bb
KedarJani/dsa-analysis
/sgp2/temp.py
955
3.921875
4
calendar = [] for i in range( 0,12 ): month = [] for j in range( 0,4 ): month.append( [] ) calendar.append( month ) def get_index( name ): months = ['january','february','march','april','may','june','july','august','september','october','november','december','january','february','march','april','may','june','july','august','september','october','november','december'] ind = months.index( name.lower() ) if( ind != -1 ): return ind else: return -1 month = "july" week = 2 calendar[ get_index(month) ][ week-1 ].append( '''Orientation: \nDay 1: Welcome ceremony\n\ Day 2: Principal sir's speech \n\ Day 3: Industry visit \n\ Day 4: Showing different labs of college \n\ Day 5: Introduction of seniors\n\ Day 6: Introduction to different clubs in college\n\ Day 7: Teaching about Subject outcome\n''' ) print( calendar[ get_index("july") ][week-1] )
28e1c1317148b72ca14a773453ee9c21bf87c7b9
BhaskarSharma245/Assignment2
/Code1.py
231
4.09375
4
n=int(input('Enter no of star you want to print ')) for i in range(n+1): for j in range(i): print('*',end='') print() for i in range(n+1): for j in range(n+1-i): print('*',end='') print()
9a5a0acd52a6341813afe0d93f292c0c5b3b1377
SeanJxie/Approx-Pi
/TheGoodStuff/MonteCarlo.py
1,236
3.984375
4
import random as rnd # Approximating pi using the Monte Carlo method. # ---------------------------------------------- # The Monte Carlo method # - Let there be a circle of radius 1/2 within a square of side length 1 both centered at the same point. # For clarity, the center is (1/2, 1/2). # # - Points with uniformly distributed random coordinates are placed on the open interval [0, 1]. # # - The quotient of the amount of points within the circle and the amount of points in total is taken and # and multiplied by 4. This number is the approximation of pi. SQUARE_SIDE_LENGTH = 1 CIRCLE_RADIUS = SQUARE_SIDE_LENGTH / 2 points_in_circle = 0 total_points = 0 point_quantity = 1000000 def calculate_approx(inner, total): return 4 * inner / total for _ in range(point_quantity): x = rnd.uniform(0, SQUARE_SIDE_LENGTH) y = rnd.uniform(0, SQUARE_SIDE_LENGTH) dist_from_center = ((CIRCLE_RADIUS - x) ** 2 + (CIRCLE_RADIUS - y) ** 2) ** 0.5 if abs(dist_from_center) < CIRCLE_RADIUS: points_in_circle += 1 total_points += 1 print(f"Approx: {calculate_approx(inner=points_in_circle, total=total_points)} # Points: {total_points}")
2971a23c7f2ff9d47baa3a76e9b7228c9a60428d
anjaligupta17/Datastructure
/starting.py
814
3.890625
4
class Node: def __init__(self,data=None): self.data=data self.next=next class LinkedList: def __init__(self): self.head=None #Traverse def listprint(self): temp=self.head if temp is None: print("is emoty") out="" while temp is not None: out += str(temp.data) print(" ") temp=temp.next print (out) def Atbegining(self,newdata): NewNode=Node(newdata) #insertion NewNode.next=self.head self.head=NewNode list1=LinkedList() e1=Node("Mon") list1.head=e1 e2=Node("Tue") e3=Node("wed") e4=Node("thur") #link first node to next node list1.head.next=e2 #link second node to third and fourth e2.next=e3 e3.next=e4 list1.listprint()
4596ed87758cac83f268d18cdb489c47b2bf007e
PriyanshuChatterjee/30-Days-of-Python
/day_9/Question5.py
383
4.34375
4
month = input("Enter the month: ") if month == 'September' or month == 'October' or month == 'November': print("The season is Autumn") elif month == 'December' or month == 'January' or month == 'February': print("The season is Winter") elif month == 'March' or month == 'April' or month == 'May': print("The season is Spring") else: print("The season is summer")