blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
80f97992306ea1e9b22767785777097708cd3489 | robertomacedo/exerc_python | /palindromo.py | 377 | 4.15625 | 4 | """
Exercicios com strings
"""
print("*"*40)
print("")
print("BRINCANDO COM STRING USANDO PALINDROMO")
print("")
print("*"*40)
enter = input("Digite uma palavra ou frase: ")
def palindromo(enter):
if enter[::-1] == enter:
return f"A palavra {enter} é um palindromo"
else:
return f"A palavra {enter} não é um palindromo"
print(palindromo(enter))
|
3f3707643ecf72b522ee2707df9c78d60ea7853a | zionhjs/algorithm_repo | /1on1/new_course/1074-numberofsubmatrix.py | 2,060 | 3.53125 | 4 | # 这个方法太过于暴力了 遭遇TLE
class Solution:
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
n, m = len(matrix), len(matrix[0])
self.count = 0
# 1.make the matrix to sum_matrix
for i in range(n):
for j in range(m):
#0, 0
if i == 0 and j != 0:
matrix[0][j] += matrix[0][j-1]
elif i != 0 and j == 0:
matrix[i][0] += matrix[i-1][0]
elif i != 0 and j != 0:
matrix[i][j] += matrix[i-1][j] + \
matrix[i][j-1] - matrix[i-1][j-1]
# 2.traverse the sum_matrix to see if any submatrices that sum to a target
for i in range(n):
for j in range(m):
self.count_target(i, j, matrix, target, n, m)
return self.count
# this travers is kind of brute/ anyway we can make it memorized?
def count_target(self, y, x, matrix, target, n, m):
for i in range(y, n):
for j in range(x, m):
if y != 0 and x != 0:
cur_sum = matrix[i][j] - matrix[y-1][j] - \
matrix[i][x-1] + matrix[y-1][x-1]
elif y == 0 and x != 0:
cur_sum = matrix[i][j] - matrix[i][x-1]
elif y != 0 and x == 0:
cur_sum = matrix[i][j] - matrix[y-1][j]
else:
cur_sum = matrix[i][j]
if cur_sum == target:
self.count += 1
def numSubmatrixSumTarget(self, A, target):
m, n = len(A), len(A[0])
for row in A:
for i in xrange(n - 1):
row[i + 1] += row[i]
res = 0
for i in xrange(n):
for j in xrange(i, n):
c = collections.defaultdict(int)
cur, c[0] = 0, 1
for k in xrange(m):
cur += A[k][j] - (A[k][i - 1] if i > 0 else 0)
res += c[cur - target]
c[cur] += 1
return res
|
d80a8b4c88c8d0851127747cfb717fb85dd1667b | franciscoquinones/Python | /Clase2/ACtividades/Fibona.py | 401 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
@author: Francixco
"""
#serie de Fibonacci
print "Mi primer reto"
n=input("Ingrese cantidad de terminos a mostrar: ")
i=1
num_ant=0
num_act=1
print num_ant
print num_act
while i<=n:
temp=num_act
num_act=num_act+num_ant
num_ant=temp
print num_act
i+=1
print "El valor es :",num_act
#0 1 1 2 3 5
|
3ab17af1e4ede7d43a224284e4894a2c3f3aef2c | nogajaakanksha/AQPG | /gui/login.py | 3,604 | 3.71875 | 4 | from Tkinter import *
import sqlite3
import main
import register
import sys
import os
#==============================METHODS========================================
def Database():
global conn, cursor
conn = sqlite3.connect("pythontut.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS `useraccount` (mem_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT)")
cursor.execute("SELECT * FROM `useraccount` WHERE `username` = 'admin' AND `password` = 'admin'")
if cursor.fetchone() is None:
cursor.execute("INSERT INTO `useraccount` (username, password) VALUES('admin', 'admin')")
conn.commit()
def helloCallBack():
root.destroy()
main.gui()
def HomeWindow():
helloCallBack()
def Register(event=None):
root.destroy()
register.gui()
def Login(event=None):
Database()
if USERNAME.get() == "" or PASSWORD.get() == "":
print("Please complete the required field!")
Register()
else:
cursor.execute("SELECT * FROM `useraccount` WHERE `username` = ? AND `password` = ?", (USERNAME.get(), PASSWORD.get()))
if cursor.fetchone() is not None:
HomeWindow()
USERNAME.set("")
PASSWORD.set("")
lbl_text.config(text="")
else:
print("Invalid username or password")
USERNAME.set("")
PASSWORD.set("")
Register()
cursor.close()
conn.close()
def gui():
global root
root = Tk()
root.title("Login Application")
width = 500
height = 300
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y))
root.resizable(0, 0)
#==============================VARIABLES======================================
global USERNAME,PASSWORD
USERNAME = StringVar()
PASSWORD = StringVar()
#==============================FRAMES=========================================
Top = Frame(root, bd=2, relief=RIDGE)
Top.pack(side=TOP, fill=X)
Form = Frame(root, height=200)
Form.pack(side=TOP, pady=20)
#==============================LABELS=========================================
lbl_title = Label(Top, text = "Login Application", font=('arial', 15))
lbl_title.pack(fill=X)
lbl_username = Label(Form, text = "Username:", font=('arial', 14), bd=15)
lbl_username.grid(row=0, sticky="e")
lbl_password = Label(Form, text = "Password:", font=('arial', 14), bd=15)
lbl_password.grid(row=1, sticky="e")
global lbl_text
lbl_text = Label(Form)
lbl_text.grid(row=2, columnspan=2)
#==============================ENTRY WIDGETS==================================
username = Entry(Form, textvariable=USERNAME, font=(14))
username.grid(row=0, column=1)
password = Entry(Form, textvariable=PASSWORD, show="*", font=(14))
password.grid(row=1, column=1)
#==============================BUTTON WIDGETS=================================
btn_login = Button(Form, text="Login", width=45, command=Login)
btn_login.grid(pady=25, row=3, columnspan=2)
btn_login.bind('<Return>', Login)
btn_register = Button(Form, text="Register User", width=45, height=3, command=Register)
btn_register.grid(pady=25, row=4, columnspan=2)
btn_register.bind('<Return>', Register)
root.mainloop()
|
3bb2c04db1ca5b446287800607c6e13d32b52e4f | pichu0528/Python | /Data Structure/Sorting and Searching/Sorting 6 - Quick Sort.py | 1,655 | 4.09375 | 4 | def quick_sort(arr):
quick_sort_help(arr,0,len(arr)-1)
def quick_sort_help(arr,first,last):
if first < last:
splitpoint = partition(arr,first,last)
quick_sort_help(arr,first,splitpoint-1)
quick_sort_help(arr,splitpoint+1,last)
def partition(arr,first,last):
# use the first item as the pivot point
pivotvalue = arr[first]
# left mark starts at one index after the pivot point
# and right mark starts at the end of array
leftmark = first + 1
rightmark = last
done = False
while not done:
# moving the leftmark to the right until the value is greater
# than the pivot value
while leftmark <= rightmark and arr[leftmark] <= pivotvalue:
leftmark += 1
# moving the rightmark to the left until the value is less than
# the pivot value
while rightmark >= leftmark and arr[rightmark] >= pivotvalue:
rightmark -= 1
if rightmark < leftmark:
done = True
else:
temp = arr[leftmark]
arr[leftmark] = arr[rightmark]
arr[rightmark] = temp
temp = arr[first]
arr[first] = arr[rightmark]
arr[rightmark] = temp
# return the right mark because that is where the pivot value
# is in the middle of the partition
# considering: [3, 2, 2, 4, 4]
# leftmark will result at index 3
# rightmark will result at index 2
# swapping rightmark and the pivot point will be the way to go in
# this sense.
return rightmark
|
431c7f7e5cfbfae71e2900cf562ce9fffad2de37 | lukihd06/B2-Python | /scripts/1c-moy.py | 1,176 | 3.734375 | 4 | #!/usr/bin/env python3
# nom : 1c-moy.py
# auteur : lucas erisset
# date : 15/10/18
# script affichant la moyenne des notes et prénoms des personnes et un top 5 des notes
# fonction top5 mais je n'arrive pas à la faire
#def Top5 (valueDict):
# i = 0
# concatVal = ""
# valueDict = sorted(valueDict)
# for name,score in valueDict.items():
# if i < 5:
# print(name + " " + score)
# i += 1
# return concatVal
# le script de la moyenne :
dict_score = {}
i = 0
exitWhile = False
while exitWhile == False:
i+= 1
name_input = input("le nom à insérer dans le dictionnaire : ")
if name_input == "q":
exitWhile = True
else:
score_input = input("la note de l'élève : ")
try:
score_input = int(score_input)
if score_input > 20 or score_input < 0:
print("la note doit être entre 0 et 20")
exit()
except ValueError:
print("ce n'est pas un chiffre")
exit()
dict_score[name_input] = score_input
score_total = 0
for name in dict_score:
score_total += dict_score[name]
quotient = len(dict_score)
moyenne = score_total/quotient
moyenne = str(moyenne)
print("la moyenne est de "+moyenne)
#Top5(dict_score) |
6b6e666d5a8f4e7a122c345abba56b9cdbaf1252 | aleenaadnan15/official-assignment | /pattern1.py | 317 | 4.125 | 4 | #Question num 41:
''' The following pattern, using a nested for loop '''
n = int(input("Enter no. of rows: "))
for i in range (0,n):
for j in range (0,i):
print("*",end="")
print("")
for i in reversed(range(0,n+1)):
for j in range(0,i):
print("*",end="")
print("")
|
1e31f026d689e97af4f110c031e9ef3ae3bbde7a | EstherChoi1245/Choi_Esther | /Semester1/Py_Lesson_04/Receipt2.py | 757 | 4.09375 | 4 | def printf (item, price):
print ("* {:>20} ........\t{:0.2f}".format(item, price))
item1 = input("Please enter Item 1: ")
price1 = float(input("Please enter the price: "))
item2 = input("Please enter Item 2: ")
price2 = float(input("Please enter the price: "))
item3 = input("Please enter Item 3: ")
price3 = float(input("Please enter the price: "))
subtotal = price1 + price2 + price3
tax = (price1 + price2 + price3)*0.07
total = (price1 + price2 + price3)*1.07
print ("<<<<<<<<<<<<<<<__Recipt__>>>>>>>>>>>>>>>")
printf (item1, price1)
printf (item2, price2)
printf (item3, price3)
printf ("Subtotal:", subtotal)
printf ("Tax:", tax)
printf ("Total:", total)
print ("____________________________________")
print ("* Thank you for your support *")
|
645eb53b784ee7972089a913571e307274f5396d | vidun1208/python-projects | /temperature 2.py | 89 | 3.796875 | 4 | value=int(input("enter fahrenheit value"))
celsius=((5*(value)-160)/9)
print(celsius)
|
0eb18aa441c32e0b2fe1aeffc23208535403f886 | felipemcm3/ExerPython | /Pythonexer/ExerPython/aprendendopython/testepython/aula09a.py | 195 | 3.59375 | 4 | frase: str = ' Olá felipe '
print(frase.replace('Olá', 'Oi'))
print(frase.upper())
print('w' in frase)
print(frase.find('ipe'))
print(frase.split('e'))
print(frase.strip())
print('+'.join(frase))
|
514861cab01147947da232796791bf261a1706c8 | tzytammy/requests_unittest | /学习/机器学习/Pandas2.py | 290 | 3.9375 | 4 | from pandas import Series,DataFrame
import pandas as pd
obj2=Series([4,7,-5,3],index=['d','b','c','a'])
print(obj2)
obj2['c']=6
print(obj2)
print('f' in obj2)
#字典变数组
sdata={'beijing':3500,'shanghai':60000}
obj3=Series(sdata)
print(obj3)
obj3.index=['bj','sh']
print(obj3)
|
0736d194f6328a17483e4f992711fb6017d2dbf8 | AndreyIvantsov/PythonBeginner | /Ex23.py | 970 | 4.1875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Блок finally
#
# При обработке исключений также можно использовать
# необязательный блок finally. Отличительной особенностью
# этого блока является то, что он выполняется вне
# зависимости, было ли сгенерировано исключение:
try:
number = int(input("Введите число: "))
print("Введенное число:", number)
except ValueError:
print("Не удалось преобразовать число")
finally:
print("Блок try завершил выполнение")
print("Завершение программы")
# Как правило, блок finally применяется для освобождения
# используемых ресурсов, например, для закрытия файлов. |
7c6cce33c0f9f8e00e8f5a562ef01600f49b8388 | MartinDardis/Algoritmos-2-FIUBA | /TP3/procesar_linea.py | 1,166 | 3.53125 | 4 | def separar(entrada):
split = entrada.split(' ')
if split [0] == 'viaje':
comando = split[0]+' '+split[1]
param_1=''
for i in range(2,len(split)):
param_1 +=split[i]
if not i == len(split):
param_1 += ' '
param_1 = param_1.rstrip()
comando = comando[:-1]
return comando , param_1
elif split [0] == 'ir':
param_1 =''
param_2 =''
ultimo = 1
for i in range(1,len(split)):
ultimo = i
param_1 += split[i]
if ',' in split[i]:
break
else:
param_1 += ' '
for i in range(ultimo+1,len(split)):
param_2 += split[i]
param_2 += ' '
param_1 = param_1[:-1]
param_2 = param_2[:-1]
return split[0],param_1,param_2
else:
return split[0],split[1]
print('ir moscu, restov del don')
print(separar('ir moscu, restov del don'))
print(separar('ir restov del don, restov del don'))
print(separar('viaje optimo, moscu'))
print(separar('itinerario Moscu'))
print(separar('reducir_caminos mapa.csv'))
|
f09a4f269957ef0653f7689469896b34d9eac8c1 | akishwary/Portfolio-Tracker | /Stock.py | 11,178 | 3.6875 | 4 | """
@author: Amrin.Kishwary
The purpose of this class is to create a single stock portfolio.
"""
#import libraries
import numpy as np #mathematical computation
import pandas as pd #dataframe and data structure
import matplotlib.pyplot as plt #plot and graph
from matplotlib import style #customized plot design
import matplotlib.ticker as mticks #customize tick and ticklables
import matplotlib.dates as mdates #format dates
import aop #cython code pxy file
class Stock:
''' the class takes in three arguments:
ticker = stritg object
transactions = a dataframe object which incls. Date as index, and 2 columns with
header Quantity and Price
mkt_price = a dataframe object with Date as index and market price of stock
'''
def __init__(self, ticker, transactions, mkt_price):
self.ticker = ticker #stock ticker symbol
self.trans = transactions #as pandas dataframe
self.mkt = mkt_price #get market price
#get ticker
def get_ticker(self):
return self.ticker;
#get transactions
def get_transactions(self):
return self.trans;
#get mkt_price
def get_mkt_price(self):
return self.mkt;
#get date
def get_date(self):
df = self.get_mkt_price()
return df.index.values
#start date
def get_start_date(self):
df = self.get_date()
return df[0];
#end date
def get_end_date(self):
df = self.get_date()
return df[-1];
#get transaction dates
def get_transDate(self):
df = self.get_transactions()
return df.index.values
#get tranaction cost in dollars
def get_cost(self):
df = self.get_transactions()
df["Cost"]= df["Quantity"]*df["Price"]
return df["Cost"];
#get pnl of single stock portfolio
def get_pnl(self, buy_or_sell=True, condition=True, quantity=True, price=True,
position=True, ave_open=True, mkt_price=True, realized=True, unrealized=True,
total=True):
df = self.get_transactions()
df1 = self.get_mkt_price()
#update positions based on transactions
df["Position"]= np.cumsum(df["Quantity"])
#set lagged position
df["Lag Position"] = df["Position"].shift(1)
df["Lag Position"] = df["Lag Position"].fillna(value=0)
#get trade type: open, increase, partially decrease, reverse or close position
df["Condition"]=0
#open position
df.loc[(df["Lag Position"]==0),"Condition"]= 1
#increase position
df.loc[(np.sign(df["Quantity"])==np.sign(df["Lag Position"])),
"Condition"]= 2
#partially decrease position
df.loc[(np.sign(df["Position"])==np.sign(df["Lag Position"])) &
(np.sign(df["Quantity"])!= np.sign(df["Lag Position"])),
"Condition"] = 3
#reverse position
df.loc[(np.sign(df["Position"])!=np.sign(df["Lag Position"]))&
(df["Lag Position"]!=0),"Condition"]= 4
#close position
df.loc[df["Position"]==0, "Condition"]= 5
#calculate average open price
temp = aop.ave_open_price(df["Condition"].values,df["Quantity"].values,
df["Price"].values,df["Lag Position"].values)
#add to dataframe
df["Ave_Open_Price"]=temp
#set tranaction type: buy or sell
df["Buy/Sell"]=np.where(df["Quantity"]>0,"B","S")
#calculate realized gains
df["r_gain"]=0.0
df["q"]=df["Quantity"].abs()
#realized gain when position reverse or partially decrease
df.loc[(df["Buy/Sell"]=="B") & ((df["Condition"]== 3)|
(df["Condition"]==4)),"r_gain"]=((df["Ave_Open_Price"].shift(1)-df["Price"])*
df["q"])
df.loc[(df["Buy/Sell"]=="S") & ((df["Condition"]== 3)|
(df["Condition"]==4)),"r_gain"] = ((df["Price"]-df["Ave_Open_Price"].shift(1))*
df["q"])
#realized gain when position closes
df.loc[(df["Buy/Sell"]=="B") & (df["Condition"]== 5),"r_gain"]=(
(df["Ave_Open_Price"].shift(1)-df["Price"])*df["q"])
df.loc[(df["Buy/Sell"]=="S") & (df["Condition"]== 5),"r_gain"]=(
(df["Price"]-df["Ave_Open_Price"].shift(1))*df["q"])
#add transactions for price and quanity columns
df1= df1.join(df, lsuffix="_df1", rsuffix="_df")
#replace NaN with zeros
df1= df1.fillna(value=0)
#update positions
df1["Position"]= np.cumsum(df1["Quantity"])
#update realized gains
df1["Realized"]=np.cumsum(df1["r_gain"])
#update average open price (cumsum() with reset @ !=0)
df1["temp"]=0
df1.loc[df1["Ave_Open_Price"]!=0,"temp"]=1
df1["temp2"]=df1["temp"].cumsum()
df1["temp"]=df1.groupby(["temp2"])["Ave_Open_Price"].cumsum()
df1["Ave_Open_Price"]=df1["temp"]
#drop uncessary columns
df1=df1.drop(["Lag Position","q","r_gain","temp","temp2"],axis=1)
#rearrange columns
df1 = df1[["Buy/Sell","Condition","Quantity","Price", "Position",
"Ave_Open_Price","Mkt_Price","Realized"]]
#calculate unrealized gains
df1["Unrealized"]=(df1["Mkt_Price"]-df1["Ave_Open_Price"])*df1["Position"]
#calculate total p&l
df1["Total P&L"]=df1["Realized"]+df1["Unrealized"]
#customize and returns data based on needs of the user
if buy_or_sell==False:
df1=df1.drop(["Buy/Sell"],axis=1)
if condition == False:
df1=df1.drop(["Condition"],axis=1)
if quantity == False:
df1=df1.drop(["Quantity"],axis=1)
if price == False:
df1=df1.drop(["Price"],axis=1)
if position == False:
df1=df1.drop(["Position"],axis=1)
if ave_open == False:
df1=df1.drop(["Ave_Open_Price"],axis=1)
if mkt_price == False:
df1=df1.drop(["Mkt_Price"],axis=1)
if realized == False:
df1=df1.drop(["Realized"],axis=1)
if unrealized == False:
df1=df1.drop(["Unrealized"],axis=1)
if total == False:
df1=df1.drop(["Total P&L"],axis=1)
return df1;
#get percent change in portfolio
def get_pct_change(self):
df= self.get_pnl()
df1= df["Total P&L"]
df1= (df1.pct_change())*100
df1= df1.replace([np.nan, np.inf],0)
return df1;
#calculates beta given two series
@staticmethod
def calculate_beta(returns,benchmark):
#correlateion between returns and benchmark
corr = returns.corrwith(benchmark)
#standard deviation of percent change
pct_returns = (returns.pct_change())
pct_benchmark = (benchmark.pct_change())
std_returns = pct_returns.std()
std_benchmark = pct_benchmark()
#formula for beta
beta = corr*(std_returns/std_benchmark)
return beta;
#get beta of stock
def get_stock_beta(self,benchmark):
df = self.get_mkt_price()
beta = Stock.calculate_beta(df,benchmark)
return beta
#get beta of returns
def get_returns_beta(self,benchmark):
df = self.get_pct_change()
beta = Stock.calculate_beta(df,benchmark)
return beta
#get market value
def get_mkt_value(self):
df= self.get_pnl()
df1 = df["Mkt_Price"]*df["Position"]
return df1;
#copy pnl to excel file
def copy_to_excel(self,filename, sheetname,
buy_or_sell=True, condition=True, quantity=True, price=True,
position=True, ave_open=True, mkt_price=True, realized=True, unrealized=True,
total=True):
df = self.get_pnl(buy_or_sell, condition, quantity, price, position, ave_open,
mkt_price, realized, unrealized, total)
writer = pd.ExcelWriter(filename)
df.to_excel(writer,sheetname)
writer.save()
#plot running position and p&l
def plot_stock(self,num=0):
style.use("ggplot")
#get data
tkr = self.get_ticker()
date= self.get_date()
df= self.get_pnl()
total_pnl = df["Total P&L"]/1000000
real_gains= df["Realized"]/1000000
unreal_gains= df["Unrealized"]/1000000
position= df["Position"]/1000
plt.figure(figsize=(10,7))
#create subplots
ax1 = plt.subplot2grid((6,1), (0,0), rowspan =5, colspan =1,)
plt.title(tkr.upper(),loc='left',color='#8b8b8b',fontsize=20)
plt.ylabel("PnL (in millions of US$)", color='#636363', labelpad=10)
ax2 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1, sharex=ax1)
plt.ylabel("Position" , color='#636363', labelpad=10)
#changes made to pnl plot(ax1)
ax1.plot_date(date,total_pnl,'-', label="Total", color="#0715FD",
linewidth=.7)#totla pnl
ax1.plot_date(date,real_gains,'--', label="Realized",color='#0715FD',
linewidth=.7)#realized pnl
ax1.plot_date(date,unreal_gains,'-', label="Unrealized",color='#aeabab',
linewidth=.7)#unrealized pnl
ax1.legend(loc=2, frameon=False,ncol=3)
ax1.set_facecolor('w')#change background of chart
ax1.spines["left"].set_color('#8b8b8b')
#formats y axis ticklabels to include commas
ax1.get_yaxis().set_major_formatter(mticks.FuncFormatter
(lambda x, p:format(int(x), ',')))
#max number of tickers
ax1.yaxis.set_major_locator(mticks.MaxNLocator(nbins=7, prune='both'))
ax1.tick_params(axis='both',labelcolor = '#636363',length=0)
ax1.axhline(y=0, color='#636363',linewidth=.7)
ax1.grid(False)
#changes made to position plot(ax2)
ax2.plot_date(date, position, '-', color='w',linewidth='.01')
ax2.set_facecolor('w')
ax2.spines["left"].set_color('#8b8b8b')
ax2.fill_between(date,0,position, facecolor='#aeabab')
#format date
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%b %y'))
ax2.set_xlim(xmin=date[0])#set x-axis minimum
ax2.get_yaxis().set_major_formatter(mticks.FuncFormatter
(lambda x, p:'{0}K'.format(int(x))))
ax2.xaxis.set_major_locator(mticks.MaxNLocator(nbins=10))
ax2.yaxis.set_major_locator(mticks.MaxNLocator(nbins=5,prune='upper'))
ax2.tick_params(axis='both',labelcolor = '#636363',length=0)
ax2.grid(False)
#hide x axis tick labels for ax1
plt.setp(ax1.get_xticklabels(),visible=False)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
return;
|
a068f91c95f9f7e57dd9135ee04abe37d4e97eda | Iam-El/Random-Problems-Solved | /leetcodePractice/easyProblems/Remove Outermost parenthesis.py | 476 | 3.578125 | 4 | def removeOuterParenthesis(s):
count1=0
count2=0
val=[]
res=''
for i in range(0,len(s)):
if s[i]==')':
count1=count1+1
val.append(s[i])
if s[i]=='(':
count2=count2+1
val.append(s[i])
if count1==count2:
val=val[1:-1]
res=res+''.join(val)
count1 = 0
count2 = 0
val=[]
return res
s='()()'
print(removeOuterParenthesis(s)) |
89111aea568a83e60c894492a56e2bdd11b561f2 | ResolveWang/algorithm_qa | /other/q7.py | 959 | 3.875 | 4 | """
问题描述:有一个机器按自然数序列的方式吐出球(1号球、2号球、3号球...),你有一个
袋子,袋子最多能装K个球,除了袋子外,没有别的可用空间。设计一种方案,使得当机器
吐出第N个球的时候(N>K),你袋子中的球数是K个,同时可以保证从1号球到N号球中的每一
个,被选进袋子的概率都是K/N.
"""
import random
class KNRandomGetter:
@classmethod
def get_res(cls, k, n):
if k < 1 or n < 1:
return
if n <= k:
return list(range(1, n+1))
res = list(0 for _ in range(k))
for i in range(k):
res[i] = i + 1
for i in range(k, n-k):
value = random.randint(1, i+1)
if value <= k:
random_index = random.randint(0, k-1)
res[random_index] = i
return res
if __name__ == '__main__':
print(KNRandomGetter.get_res(10, 10000)) |
57b1aa16ae56a639ddb8fbcd617cef833856c4ba | raulgranja/Python-Course | /PythonExercicios/calculadora.py | 2,310 | 4.3125 | 4 | # -*- coding: utf-8 -*-
print(" ")
print("-----------CALCULADORA v1.0-----------")
print(" ")
print("Realiza operações de soma, subtração, divisão, multiplicação e exponencial")
print("Os sinais de cada uma dessas operações são:")
print(" ")
print('(+): soma')
print("(-): subtração")
print("(/): divisão")
print("(*): multiplicação")
print("(**): exponencial")
print(" ")
print("Como utilizar:")
print("Por exemplo, se eu quero fazer uma soma de 2+2, eu coloco da seguinte forma:")
print("Digite o primeiro número: 2")
print("Qual é o operador? +")
print("Digite o segundo número: 2")
print("O resultado é: 4 <-- O resultado aparecerá aqui")
print(" ")
print(" ")
print(" ")
sair = False
while not sair:
valor1 = input("Digite o primeiro número: ")
valor1 = int(valor1)
operador = input("Qual é o operador? ")
valor2 = input("Digite o segundo número: ")
valor2 = int(valor2)
if operador == "+":
print(" ")
print("O resultado é: ", (valor1 + valor2))
print(" ")
if operador == "-":
print(" ")
print("O resultado é: ", (valor1 - valor2))
print(" ")
if operador == "*":
print(" ")
print("O resultado é: ", (valor1 * valor2))
print(" ")
if operador == "/":
print(" ")
print("O resultado é: ", (valor1 / valor2))
print(" ")
if operador == "**":
print(" ")
print("O resultado é: ", (valor1 ** valor2))
print(" ")
teste = input("Deseja sair? (s/n): ")
if teste == "s":
sair = True
if teste == "n":
sair = False
print(" ")
|
aba5c38867bf1f3106d9981090a874e9efe79b4b | mjaitly/LeetCode | /Algorithms/Easy/28_Implement_strStr.py | 1,610 | 4.1875 | 4 | '''
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
For the purpose of this problem, we will return 0 when needle is an empty string.
'''
# Runtime: 44 ms, faster than of Python3 online submissions for Implement strStr().
# Memory Usage: 14 MB, less than of Python3 online submissions for Implement
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
l = len(needle)
for i in range(len(haystack)):
if haystack[i] == needle[0]:
if len(haystack) >= i + l:
if haystack[i:i+l] == needle:
return i
return -1
if __name__ == "__main__":
haystack = "heloollollll"
needle = "llll"
sol = Solution()
result = sol.strStr(haystack, needle)
print(result)
'''
def strStr(self, haystack: str, needle: str) -> int:
if needle in haystack: return haystack.index(needle)
else: return -1
'''
'''
# Runtime: 36 ms, faster than of Python3 online submissions for Implement strStr().
# Memory Usage: 14 MB, less than of Python3 online submissions for Implement
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
for i in range(len(haystack) - len(needle) + 1):
if haystack[i:i + len(needle)] == needle:
return i
return -1
''' |
00ef0929c090c87e1ebfdb39005e5d95a95205be | meysiolio/Collections.OrderedDict | /Collections.OrderedDict.py | 273 | 3.6875 | 4 | from collections import OrderedDict
commodities = OrderedDict()
for _ in range(int(input())):
item, number = input().rsplit(maxsplit=1)
commodities[item] = commodities.get(item, 0 ) + int(number)
for item,quantity in commodities.items():
print(item,quantity) |
11346f1fb81cf64fd30becf83ce3bfa922dc98cf | zoobereq/comp-ling-assignments | /Methods in CompLing I/MP2/fibonacci_numbers.py | 1,180 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 13 13:42:21 2019
@author: zub
"""
"""
def fibonacci(number: int) -> int:
if number == 0:
return 0
elif number == 1:
return 1
else:
return fibonacci(number-1) + fibonacci(number-2)
print(fibonacci(100))
The above was the first attempt, which worked oonlhy for the first handful of numbers, and didn't finish computing the 100th position.
"""
def fibonacci(number: int) -> int:
first_number_in_sequence = 0
second_number_in_sequence = 1
if number <= 0:
return("Enter a positive integer.")
elif number == 1:
return first_number_in_sequence
elif number == 2:
return second_number_in_sequence
for number in range(2, number+1):
next_number_in_sequence = first_number_in_sequence + second_number_in_sequence
first_number_in_sequence = second_number_in_sequence
second_number_in_sequence = next_number_in_sequence
return(next_number_in_sequence)
print(fibonacci(100))
assert fibonacci(1) == 0
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(100) == 354224848179261915075
|
9f25b67229804e00964911da42f0d42a2e733dc7 | Charptr0/Kruptos-Encryption | /main.py | 6,996 | 3.84375 | 4 | import tkinter as tk
from tkinter import Label, filedialog
from encryption import *
from constants import *
app = tk.Tk() #Start the app
app.title("Kruptos Encryption") #Title
app.config(bg= darkColor)
app.geometry("800x800") #Resolution
app.resizable(0,0)
def openEncrypt(): #If the user clicked the "encrypted button"
decryptButton.place_forget()
creditsButton.place_forget()
encryptButton.place_forget()
chooseFileButton.place(relx=0.16, rely=0.3)
chooseFileButton.config(text="Click here to choose a file to encrypt")
def askUserForFile():# this lets the user select a file and the user can chose a different file if needed. Also restricts filetypes to .txt and .json
global fileName
fileName = filedialog.askopenfilename(title="Select a file to encrypt", filetypes=((".txt files", "*.txt"), (".json files", "*.json")))
if(fileName != ""):
fileSelectedLabel.place(relx=0.27, rely=0.27)
encryptConfirmationButton.place(relx=0.27, rely=0.5)
chooseFileButton.config(text="Choose a different file")
chooseFileButton.place(relx=0.27, rely=0.7)
def askUserForEncryptedtFile(): #User picks file to decrypt and the key. User can change the file if needed. File types are restricted to .txt and .json
global encryptedFilePath
encryptedFilePath = filedialog.askopenfilename(title="Select a file to decrypt", filetypes=((".txt files", "*.txt"), (".json files", "*.json")))
if(encryptedFilePath != ""):
fileSelectedLabel.place(relx=0.27, rely=0.2)
chooseKeyButton.place(relx=0.25, rely=0.5)
decryptChooseButton.config(text = "Select a new file", padx=112)
decryptChooseButton.place(relx=0.25,rely=0.65)
def askUserForKey(): #this lets the user decrypt the selected file when you click the decryptButtonFinal
global keyFilePath
keyFilePath = filedialog.askopenfilename(title="Select the appropriate key", filetypes=((".key files", "*.key"), ("all files", "*")))
if(keyFilePath != ""):
keySelectedLabel.place(relx=0.3609, rely=0.36)
decryptButtonFinal.place(relx=0.25, rely=0.8)
def actualDecrypting(): #this decrypts the file
errMsg = decryptFile(encryptedFilePath, keyFilePath)
if errMsg != "Error": #put the success label here
keySelectedLabel.place_forget()
fileSelectedLabel.place_forget()
decryptButtonFinal.place_forget()
unsuccessfullyDecryptedLabel.place_forget()
successfullyDecryptedLabel.place(relx=0.1,rely=0.15)
reEncryptButton.place(relx=0.25,rely=0.8)
else: #put the unsuccess label here
unsuccessfullyDecryptedLabel.place(relx=0.096,rely=0.1)
keySelectedLabel.place_forget()
fileSelectedLabel.place_forget()
decryptButtonFinal.place_forget()
def reEncrypt():
reEncryptTheFile()
mainMenuButton.place(relx=0.38, rely=0.5)
successfullyReEncryptLabel.place(relx=0.06,rely=0.17)
successfullyDecryptedLabel.place_forget()
chooseKeyButton.place_forget()
decryptChooseButton.place_forget()
reEncryptButton.place_forget()
def encryptFile(): #If the encrypt button has been pressed
global fileName
keyName = generateNewKey(fileName)
keyLabel.config(text="Please do not delete your key!\nYour key is saved in " + keyName)
keyLabel.place(relx=0.1, rely=0.8)
chooseFileButton.place_forget()
fileSelectedLabel.place_forget()
encryptConfirmationButton.place_forget()
fileEncryptMessage.place(relx=0.14, rely=0.27)
mainMenuButton.place(relx=0.38, rely=0.5)
def decryptFileMenu():
encryptButton.place_forget()
creditsButton.place_forget()
decryptButton.place_forget()
decryptChooseButton.place(relx=0.25, rely=0.2)
def returnToMainMenu(): #Return back to menu
names.place_forget()
successfullyReEncryptLabel.place_forget()
fileEncryptMessage.place_forget()
mainMenuButton.place_forget()
keyLabel.place_forget()
encryptButton.place(relx=0.34, rely=0.3)
decryptButton.place(relx=0.34, rely=0.5)
creditsButton.place(relx = 0.4, rely=0.8)
def contributions():
encryptButton.place_forget()
decryptButton.place_forget()
creditsButton.place_forget()
names.place(relx=0.25, rely=0.3)
mainMenuButton.place(relx=0.4, rely=0.8)
title = tk.Label(text="Kruptos Encryption", bg=darkColor, fg= whiteTextColor, font=(fontName, 20, "bold")) #Create the title
title.place(relx=0.337, rely=0)
encryptButton = tk.Button(text="Encrypt a file", padx=50, pady=10, font=(fontName, 20), bg = buttonsColor, fg = whiteTextColor, command=openEncrypt)
encryptButton.place(relx=0.34, rely=0.3)
decryptButton = tk.Button(text = "Decrypt a file", padx=50, pady=10, font =(fontName, 20), bg = buttonsColor, fg = whiteTextColor, command=decryptFileMenu)
decryptButton.place(relx=0.34, rely=0.5)
creditsButton = tk.Button(text = "Credits", padx=30, pady=10, font=(fontName, 20 ), bg = darkColor, fg = whiteTextColor, command=contributions)
creditsButton.place(relx = 0.4, rely=0.8)
chooseFileButton = tk.Button(text="Click here to choose a file to encrypt", padx=60, pady=10, font=(fontName, 20), command=askUserForFile)
encryptConfirmationButton = tk.Button(text="Encrypt the selected file", padx=50, pady=10, font=(fontName, 20), command=encryptFile)
mainMenuButton = tk.Button(text="Main Menu", padx=20, pady=10, font=(fontName, 20), command=returnToMainMenu)
fileEncryptMessage = tk.Label(text="File successfully encrypted", font=(fontName, 30), padx=80, pady=10, bg = darkColor, fg = fileSelectedColor)
fileSelectedLabel = tk.Label(text="File selected", font=(fontName, 30), padx=80, pady=10, bg = darkColor, fg = fileSelectedColor)
keyLabel = tk.Label(text="",font=(fontName, 20), padx=80, pady=10, bg = darkColor, fg = keyNameColor)
chooseKeyButton = tk.Button(text="Choose a appropriate key",padx=60, pady=10, font=(fontName, 20), command=askUserForKey)
decryptChooseButton = tk.Button(text="Choose a file to decrypt", padx=58, pady=10, font=(fontName, 20), command=askUserForEncryptedtFile)
decryptButtonFinal = tk.Button(text="Decrypt", padx=160, pady=10, font=(fontName, 20), bg="green", command=actualDecrypting)
keySelectedLabel = tk.Label(text="Key selected",font=(fontName, 30), bg = darkColor, fg = fileSelectedColor)
successfullyDecryptedLabel = tk.Label(text="The file has been successfully decrypted", font=(fontName, 30), bg=darkColor, fg="green")
unsuccessfullyDecryptedLabel = tk.Label(text="Something went wrong, wrong key or file", font=(fontName, 30), bg=darkColor, fg="red")
reEncryptButton = tk.Button(text="Re-encrypt", font=(fontName, 30), bg="green", command=reEncrypt, padx=113)
successfullyReEncryptLabel = tk.Label(text="The file has been successfully re-encrypted", font=(fontName, 30), bg=darkColor, fg="green")
names = tk.Label(text="Made by\nChenhao Li\nRiaz Ahmed\nYeiry Chaverra\nRamon Camilo\n\nCUNY Hackathon 2021 ", font=(fontName, 30), bg=darkColor, fg=whiteTextColor)
app.mainloop() #Start the app
|
61751a6a68d6237fec100933916bf9122697e82c | psihanorak/critter-creation | /animals/animal.py | 228 | 3.53125 | 4 | from datetime import date
class Animal:
def __init__(self, name, species, food, chip_num):
self.name = name
self.species = species
self.food = food
self.date_added = date.today()
self._chip_num = chip_num
|
7d245d99a0b417157de27fd129ae475b16beacda | lcppcl/S1 | /day3/8函数.py | 1,246 | 3.984375 | 4 | def say(): #定义函数
print('hello, python')
return 123 #函数返回值
f = say #把函数名赋给另一个变量,f指向这个函数
f() #执行函数
say() #执行函数
value = f() #拿到返回值
print(value)
#默认参数必须放在指定参数后面
def show(a1, a2=1, a3=3):
print('ok')
#指定参数
def show2(a1, a2):
print(a1, a2)
show2(a2=1,a1=3)
#动态参数
def show(*arg): #一个*把传入的参数当成元祖来处理
print(arg,type(arg))
show(1,2,3)
def show(**arg): #两个*把传入的参数当成字典来处理
print(arg,type(arg))
show(n1=99,bb='bb')
def show(*args, **kwargs): #两个*必须放在一个*之后
print(args,type(args))
print(kwargs,type(kwargs))
show(11, 22, 33, n1=22, ll='ll') #实参也要一一对应
l = [11, 22, 33, ]
d = {'n1': 22, 'll': 'll'}
show(*l, **d)
#动态参数实现格式化
s1 = '{0} is {1}'
s2 = '{name} is {actor}'
l = ['lcp', 'ok']
d = {'name': 'lcp', 'actor': 'ok'}
result = s1.format(*l)
result2 = s2.format(**d)
print(result)
print(result2)
#lambda表达式
#创建形式参数a
#函数内容a+1,并把结果return
fun = lambda a: a+1 #:前面的为形式参数,后面为函数体
ret = fun(99)
print(ret) |
19b68a9f81c246c5873563108031c09e9a131eb8 | kimxoals/Algorithm_Practice | /07/namu_0723.py | 335 | 3.828125 | 4 | n = int(input())
max = 2*n-1
for i in range(2*n-1):
if i < n - 1:
space = i
else:
space = 2*(n-1)-i
fill = max - 2 * space
print(' ' * space + '*' * fill)
''' OR
for i in range(n-1,0,-1):
print(('*' * (2 * i + 1)).center(2 * n))
for i in range(n):
print(('*' * (2 * i + 1)).center(2 * n))
'''
|
a12442a56ac007a1c54873f45ae2931e7c0309ee | Seiji-Armstrong/seipy | /seipy/pandas_/base.py | 14,195 | 4 | 4 | """
helper functions to use with pandas library.
Conventions:
df -> pd.DataFrame
Ideology:
- Write functions that do one thing
- Try write functions that are idempotent
"""
from functools import reduce
from collections import namedtuple
import numpy as np
import pandas as pd
import re
def drop_uniq_cols(df):
"""
Returns DataFrame with columns that have more than one value (not unique)
"""
return df.loc[:, df.apply(pd.Series.nunique) > 1]
def non_x_cols(df, x):
"""
Returns DataFrame with columns that contain values other than x.
Drops any column that only contains x.
"""
cond_1 = (df.apply(pd.Series.nunique) == 1)
cond_2 = (df.iloc[0] == x)
return df.loc[:, ~(cond_1 & cond_2)]
def df_duplicate_row(df, row, row_cols):
"""
(Check logic)
Creates numpy array from df (pd.DataFrame),
returns non_duplicate rows.
"""
X = df[row_cols].as_matrix().astype(np.float)
fv_ix = [ix for ix, el in enumerate(X) if (el == row.values).all()]
df_rows = df.ix[fv_ix]
return df_rows
def filt(orig_df, **params):
"""
Filter DataFrame on any number of equality conditions.
Example usage:
>> filt(df,
season="summer",
age=(">", 18),
sport=("isin", ["Basketball", "Soccer"]),
name=("contains", "Armstrong")
)
>> a = { 'season': "summer", 'age': (">", 18)}
>> filt(df, **a) # can feed in dict with **dict notation
notes:
any input with single value is assumed to use "equivalent" operation and is modified.
numpy.all is used to apply AND operation element-wise across 0th axis.
NA values are filled to False for conditions.
"""
input_df = orig_df.copy()
if not params.items():
return input_df
def equivalent(a, b): return a == b
def greater_than(a, b): return a > b
def greater_or_equal(a, b): return a >= b
def less_than(a, b): return a < b
def less_or_equal(a, b): return a <= b
def isin(a, b): return a.isin(b)
def notin(a, b): return ~(a.isin(b))
def contains(a, b): return a.str.contains(b)
def notcontains(a, b): return ~(a.str.contains(b))
def not_equivalent(a, b): return a != b
operation = {"==": equivalent,
"!=": not_equivalent,
">": greater_than,
">=": greater_or_equal,
"<": less_than,
"<=": less_or_equal,
"isin": isin,
"notin": notin,
"contains": contains,
"notcontains": notcontains}
cond = namedtuple('cond', 'key operator val')
filt_on = [(el[0], el[1]) if isinstance(el[1], tuple) else (el[0], ("==", el[1]))
for el in params.items()] # enforcing equivalence operation on single vals.
conds = [cond(el[0], el[1][0], el[1][1]) for el in filt_on]
logic = [operation[x.operator](input_df[x.key], x.val).fillna(False) for x in conds]
return input_df[np.all(logic, axis=0)]
def filt_read_csv(file_path, chunksize=100000, **filt_conds):
"""
read a csv in chunks while filtering on conditions
wrapper of pd.read_csv and uses pandas_.base.filt
"""
iter_csv = pd.read_csv(file_path, iterator=True, chunksize=chunksize)
return pd.concat([filt(chunk, **filt_conds) for chunk in iter_csv], ignore_index=True)
def display_max_rows(max_num=500):
"""sets number of rows to display (useful in Jupyter environment)
"""
pd.set_option('display.max_rows', max_num)
def assign_index(input_df, index_col='idx'):
"""Return input DataFrame with id col.
"""
out_df = input_df.reset_index(drop=True)
out_df.loc[:, index_col] = out_df.index
return out_df
def enumerate_col(input_df, enumerate_over, new_col="newCol"):
"""
Enumerate unique entries in enumerate_over_col and add new column newCol.
"""
new_df = input_df.copy()
unique_vals = new_df[enumerate_over].unique()
enumerated_dict = {vals: ix for ix, vals in enumerate(unique_vals)}
new_df.loc[:, new_col] = new_df[enumerate_over].map(lambda x: enumerated_dict[x])
return new_df
def concat_df_list(list_csv, comment='#', header='infer', sep=',', nrows=None):
"""Concatenates list of dataframes first created by list comprehension.
"""
return pd.concat([pd.read_csv(el, comment=comment, header=header, sep=sep, nrows=nrows)
for el in list_csv], ignore_index=True)
def merge_dfs(dataframe_list, join_meth='outer', on=None, left_index=False, right_index=False):
"""
Merge together a list of DataFrames.
"""
def simple_merge(df1, df2):
return pd.merge(left=df1, right=df2, on=on,
left_index=left_index, right_index=right_index, how=join_meth)
merged_frame = reduce(simple_merge, dataframe_list)
return merged_frame
def uniq_x_y(X, y, output_index=False):
"""
Given a X,y pair of numpy arrays (X:2D, y:1D),
return unique rows (arrays) of X, with corresponding y values.
"""
uniq_df = pd.DataFrame(X).drop_duplicates()
X_uniq = uniq_df.values
y_uniq = y[uniq_df.index]
if output_index:
return X_uniq, y_uniq, uniq_df.index
return X_uniq, y_uniq
def gby_count(df, col, col_full_name=False):
"""
Perform groupby count aggregation, rename column to count,
and keep flat structure of DataFrame.
Wrapper on pd.DataFrame.groupby
"""
if col_full_name:
col_name = "count_" + col
else:
col_name = "count"
return df.groupby(col).size().reset_index(name=col_name).sort_values(by=col_name, ascending=False)
def distribute_rows(df, key_col):
"""
Distributes rows according to the series found in key_col.
Example:
>> df = pd.DataFrame([(el+3, el) for el in range(4)], columns=['x', 'n'])
>> df.T
0 1 2 3
x 3 4 5 6
n 0 1 2 3
>> df.loc[np.repeat(df.index.values,df.n)].T
1 2 2 3 3 3
x 4 5 5 6 6 6
n 1 2 2 3 3 3
"""
distribution_index = np.repeat(df.index.values, df[key_col])
return df.loc[distribution_index]
def resample_by_col(df, gby_col='Cluster ID', scale_by='identity'):
"""
Resample the rows of DataFrame.
Groupby is first performed on gby_col, then counts are rescaled by
function defined in scale_by (identity, log, sqrt).
Groupby DataFrame is then resampled by new distribution, and an outer
join is performed with original.drop_duplicates(gby_col).
Note: inputting `df` and `df.drop_duplicates(gby_col)` lead to different
results in `gby_col_count` col. Always input original.
Improvements: create all_n func and do pass function curried like in scala
"""
gby_df = df.groupby(gby_col).size().reset_index(name=gby_col + "_count")
def identity(x): return x
def all_one(x): return 1
def all_two(x): return 2
def all_three(x): return 3
scale_funcs = {'log': np.log, 'sqrt': np.sqrt, 'identity': identity,
'all_one': all_one, 'all_two': all_two, 'all_three': all_three}
distribution = gby_df[gby_col + "_count"].map(scale_funcs[scale_by]).map(np.ceil).map(np.int)
df_new_dist = gby_df.loc[np.repeat(gby_df.index.values, distribution)]
return pd.merge(df_new_dist, df.drop_duplicates(gby_col), on=gby_col, how='outer')
def convert_all_elements_tuple(input_df):
"""
If all elements are lists or numpy arrays, these are not hashable.
So we can convert to tuples, in order to be able to perform groupbys.
"""
return input_df.applymap(tuple)
def explode_rows_vertically(df):
"""
For use on DataFrames containing lists in each field.
Note: per row, lists in each column must be equal in length.
They can, however, differ in length from row to row.
Explode lists in each column of input DataFrame vertically,
one row at a time.
Return DataFrame of exploded elements.
Note we could also use `+= zip(*[df[col][ix] for col in df])`
"""
exploded_list = []
for ix, row in df.iterrows():
exploded_list += zip(*row.values)
return pd.DataFrame(exploded_list)
def str_list_to_tuple_str_series(col, regex_pattern='[A-Z]\d+'):
"""
Convert string of lists into tuples of strings,
for each row in column.
regex_pattern determines string tokens.
"""
if not isinstance(col[0], str):
print("error: str expected, instead {} found.".format(type(col[0])))
return col
else:
p = re.compile(regex_pattern)
return col.apply(p.findall).apply(tuple)
def df_to_namedtups(df, name="Pandas"):
"""
Given a DataFrame, df, return a list of namedtuples
"""
return list(df.itertuples(index=False, name=name))
def gby_uniqlists(in_df, pivot_col=None, col=None) -> pd.DataFrame:
"""
Computes aggregates for each unique value in `pivot_col` and returns
new DataFrame with list of unique values in col + nunique in col.
:param in_df: pd.DataFrame; input DataFrame
:param pivot_col: str; column to groupby (pivot) off
:param col: str; column to aggregate values on.
:return: pd.DataFrame; groupby aggregates DataFrame with unique vals in list + length.
"""
gby_temp = in_df.groupby(pivot_col)[col].apply(set).apply(list).reset_index()
return gby_temp.assign(len_=gby_temp[col].apply(len)).rename(
columns={'len_': col + '_uniq_len', col: col + '_uniq'})
def gby_multiframe(in_df, pivot_col=None, cols=None) -> pd.DataFrame:
"""
wrapper of velpy.helper.pandas_.gby_uniqlists performed over list of cols,
then joined on pivot_col.
:param in_df: pd.DataFrame; input DataFrame
:param pivot_col: str; column to groupby (pivot) off
:param cols: list[str]; list of columns to aggregate values on.
:return: pd.DataFrame; merged groupby aggregates DataFrame
"""
cols = [col for col in cols if col in in_df.columns]
return merge_dfs([gby_uniqlists(in_df, pivot_col=pivot_col, col=col)
for col in cols], on=pivot_col)
def nonuniq(orig_df):
"""
return DataFrame of sorted non-uniq counts of fields (greater than 1).
"""
return (orig_df.apply(pd.Series.nunique)
.sort_values(ascending=False)
.reset_index(name='uniq_count')
.pipe(lambda x: x[x['uniq_count'] > 1])
)
def update_sub(orig_df, pivot_col=None, pivot_val=None, new_col=None, new_val=None):
"""
update a subset of DataFrame based on fixed boolean matching.
"""
out_df = orig_df.copy()
out_df.loc[out_df[pivot_col] == pivot_val, new_col] = new_val
return out_df
def sorted_cols(orig_df):
"""
sort columns by name and return df
"""
cols = sorted(orig_df.columns)
return orig_df[cols]
def ddupe_with_precision(orig_df, precision=10):
"""
round original DataFrame to a given precision, drop_duplicates,
return original dataframe with those rows indexed.
"""
return orig_df.loc[orig_df.round(precision).drop_duplicates().index]
def mapping_2cols(orig_df, colx, coly):
"""
return dict mapping vals in colx to coly. Order is important.
"""
return dict(orig_df[[colx, coly]].drop_duplicates().values)
def newcol_mapped(orig_df, orig_col, new_col, mapping):
"""
map a new column from an old column and a mapping dictionary
"""
new_vals = orig_df[orig_col].map(mapping).values
return orig_df.assign(**{new_col: new_vals})
def prepend_comment(orig_df):
"""
prepend the first column name with a '#'
"""
input_df = orig_df.copy()
first_col = input_df.columns[0]
return input_df.rename(columns={first_col: '#' + first_col})
def remove_prepended_comment(orig_df):
"""
remove the '#' prepend to the first column name
Note: if there is no comment, this won't do anything (idempotency).
"""
input_df = orig_df.copy()
first_col = input_df.columns[0]
return input_df.rename(columns={first_col: first_col.replace('#', "")})
def remove_double_quotes(orig_df: pd.DataFrame, quote_cols, all_cols=False) -> pd.DataFrame:
"""
Replace double quotes found in fields with two single quotes.
This must be done for SQL queries to correctly parse fields in Hive (and others)
"""
def replace_quotes(x):
if isinstance(x, str):
return x.replace("\"", "''")
return x
out_df = orig_df.copy()
if all_cols:
return out_df.applymap(replace_quotes)
else:
out_df[quote_cols] = out_df[quote_cols].applymap(replace_quotes)
return out_df
def apply_uniq(df, orig_col, new_col, _func):
"""
Apply func to only unique entries and join with original to fill.
Answered for:
https://stackoverflow.com/questions/46798532/how-do-you-effectively-use-pd-dataframe-apply-on-rows-with-duplicate-values/
"""
out_df = df.copy()
if new_col in out_df:
out_df = out_df.drop(new_col, axis='columns')
return out_df.merge(out_df[[orig_col]]
.drop_duplicates()
.assign(**{new_col: lambda x: x[orig_col].apply(_func)}
), how='inner', on=orig_col)
def mult_types(df):
"""
Return series of columns with unique number of types per col
Can be useful to see which cols have more than 1 type, for example:
>> counts = mult_types(df)
>> counts[counts != 1]
"""
return df.applymap(type).drop_duplicates().apply(pd.Series.nunique)
def collapse_hierarchy(orig_df: pd.DataFrame):
"""
this collapses multilevel pandas columns into a single level by joining tokens with underscore.
Example:
orig_cols = [('a', 'max'), ('a', 'size'), ('b', '')]
new_cols = ['a_max', 'a_size', 'b']
"""
gby = orig_df.copy()
if isinstance(gby.columns, pd.core.indexes.multi.MultiIndex):
gby.columns = ['_'.join(col).rstrip('_') for col in gby.columns.values]
else:
print("columns not MultiIndex, returning original.")
return gby
|
7f385ad49fd391f4d9c4ee8652e72a1e6a44bee0 | andylinpersonal/CSX.Python.Class.HW | /src/Lv8.3091.class.py | 790 | 3.921875 | 4 | #!/usr/bin/env python3
#-*- coding:utf8 -*-
import os
class student:
'''
說明文件區塊必須緊鄰class宣告
This is readme of class student
'''
name = ''
gender = ''
grades = []
def __init__(self):
self.name = input()
self.gender = input()
def avg(self):
summ = 0
for i in range(len(self.grades)):
summ += self.grades[i]
return summ / int(len(self.grades))
def add(self, grade):
self.grades.append(int(grade))
def fcount(self):
cnt = 0
for i in range(len(self.grades)):
if self.grades[i] < 60:
cnt += 1
person = student()
for i in range(3):
person.add(input())
print(student.name)
print(student.avg())
print(student.fcount()) |
3715f21805f93498d8736d1668cea43c7c5cffc4 | BelowzeroA/artificial-thinking | /src/simple_train.py | 93 | 3.640625 | 4 | a = 0
f = 1
for i in range(1, 10):
if i >= 5:
print(f)
else:
print(a) |
fd10658e7d4b2559afea854982342060a166aec2 | wedunsto/ContinuedPythonLearning | /testdf.py | 567 | 3.53125 | 4 | import pandas as pd
test = dict()
value = []
color = []
df = pd.DataFrame()
test["1"] = [1,2,3,4,5,6]
test["2"] = [7,8,9,10,11,12]
for keys in test.keys():
for val in test[keys]:
value.append(val)
color.append(keys)
df["Value"] = value
df["Color"] = color
df.to_csv("practicedictionary.csv")
print(df.columns)
#columns = ["Red","Green","Blue"]
#df = pd.DataFrame([[1,2,3],[4,5,6]],columns = columns)
#print(df,"\n\n")
#df['Yellow'] = [2,1]
#df.to_csv("testdf.csv")
#df = pd.DataFrame()
#df["Red"] = [1,2,3,4,5]
#df["Blue"] = []
#+print(df) |
d96dbc126677fb3b658644c693bf992ec5413ae8 | PacktPublishing/Advanced-Deep-Learning-with-Keras | /chapter1-keras-quick-tour/plot-linear-1.1.1.py | 668 | 4.03125 | 4 | '''Utility for plotting a linear function
with and without noise
'''
import numpy as np
import matplotlib.pyplot as plt
want_noise = True
# grayscale plot, comment if color is wanted
plt.style.use('grayscale')
# generate data bet -1,1 interval of 0.2
x = np.arange(-1,1,0.2)
y = 2*x + 3
plt.xlabel('x')
plt.ylabel('y=f(x)')
plt.plot(x, y, 'o-', label="y")
if want_noise:
# generate data with uniform distribution
noise = np.random.uniform(-0.2, 0.2, x.shape)
xn = x + noise
plt.ylabel('y=f(x)')
plt.plot(xn, y, 's-', label="y with noised x")
plt.legend(loc=0)
plt.grid(b=True)
plt.savefig("linear_regression.png")
plt.show()
plt.close('all')
|
4686fc9649755f93ea2ef8f534bfa39fd37ab726 | ranjithsekar/python | /py-core/variables/variables-casting.py | 442 | 4.15625 | 4 | # Declaration
my_num = 5
my_string = 'Ranjith'
print(my_num)
print(my_string)
# Casting
my_num1 = '4'
my_num1_int = int(my_num1)
print(my_num1_int)
my_num2 = 3
my_num2_str = str(my_num2)
print(my_num2_str)
my_num3 = '6'
my_num3_float = float(my_num3)
print(my_num3_float)
# Get the type
print(type(my_num3))
print(type(my_num3_float))
# Multiple values
one, two, three = "Lion", "Tiger", "Elephant"
print(one + ' ' + two + ' ' + three)
|
5fbeb1e7345d98cd35bf1a0552cf82bdc650af89 | jsh2333/pyml | /day6/gyudon_keras.py | 1,635 | 3.546875 | 4 | from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.utils import np_utils
import numpy as np
# 분류 대상 카테고리
root_dir = "./image/"
categories = ["normal", "beni", "negi", "cheese"]
nb_classes = len(categories)
image_size = 50
# 데이터 다운로드하기 --- (※1)
def main():
X_train, X_test, y_train, y_test = np.load("./image/gyudon.npy")
# 데이터 정규화하기
X_train = X_train.astype("float") / 256
X_test = X_test.astype("float") / 256
y_train = np_utils.to_categorical(y_train, nb_classes)
y_test = np_utils.to_categorical(y_test, nb_classes)
# 모델을 훈련하고 평가하기
model = model_train(X_train, y_train)
model_eval(model, X_test, y_test)
# 모델 구축하기 --- (※2)
def build_model(in_shape):
model = Sequential()
model.add(Convolution2D(32, 3, 3,
border_mode='same',
input_shape=in_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Convolution2D(64, 3, 3, border_mode='same'))
model.add(Activation('relu'))
model.add(Convolution2D(64, 3, 3))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes))
model.add(Activation('softmax'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
return model
|
641038f5b2009b7c769009bca9343deb301e2935 | niteesh2268/coding-prepation | /leetcode/Problems/1491--Average-Salary-Excluding-the-Minimum-and-Maximum-Salary-Easy.py | 190 | 3.578125 | 4 | class Solution:
def average(self, salary: List[int]) -> float:
sal = sum(salary)
sal -= max(salary)
sal -= min(salary)
return sal/(len(salary)-2) |
62a8885d420fb0036cb86ef861f3254c01d65414 | tarcisiocsn/4epy | /ex_03_02.py | 426 | 3.828125 | 4 | sh=input('Enter Hours: ')
sr=input('Enter Rate: ')
try:
fh=float(sh) # poderia colocar int(sh) mas é melhor assim
fr=float(sr)
except:
print('Error, please enter a numeric input')
quit() # não continua mais e não dará outro erro, só testar sem esse quit que verá o erro
print(fh, fr)
if fh>40:
reg=fh*fr
ovt=(fh-40.0)*(fr*0.5)
pay=reg+ovt
else:
reg=fh*fr
pay=reg
print('Pay: ', pay)
|
9add02e688ea39612ad038b54e3e1e5e8174dfd1 | python-13/homework | /04/宫祥瑞/str2int.py | 291 | 3.859375 | 4 | import cmath
nums = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
def char2int(s:str):
num = 0
for i in range(len(s)):
num += nums[s[i]]
if not i == len(s)-1:
num *= 10
return num
s = '123456789'
n = char2int(s)
print(n)
print(type(n)) |
8f40cd6705b014f2e2fa2ffd831171c77bd481f2 | jamalamar/Python-intro-Functions | /dogclass.py | 137 | 3.53125 | 4 | class Dog:
def __init__(self, name, age):
self.name = name
self.age = age * 7
alf = Dog("Alf", 5)
print(alf.name)
print(alf.age)
|
9287691cc3a376cfb3bfff8957b0a84520377f77 | harihara-n/nba_draft_lottery | /generate.py | 2,884 | 3.984375 | 4 | from numpy.random import choice
class TeamPercentage(object):
def __init__(self, team_name, team_lottery_pick_percentage):
self.team_name = team_name
self.team_lottery_pick_percentage = team_lottery_pick_percentage
def generate_draft_order(teams, num_lottery_picks):
draft_order = []
while len(draft_order) < num_lottery_picks:
chosen_team = choice([team.team_name for team in teams], 1, [team.team_lottery_pick_percentage for team in teams])
if chosen_team in draft_order:
continue
draft_order.append(chosen_team[0])
remaining_teams = filter(lambda team: team.team_name not in draft_order, teams)
return draft_order + [team.team_name for team in remaining_teams]
def get_file_input():
teams = []
print '\nInput file should be csv format with team name,lottery pick percentage in each line.'
input_file_path = raw_input('Enter file path: ')
with open(input_file_path) as file:
for line in file:
parts = line.strip().split(",")
teams.append(TeamPercentage(parts[0], float(parts[1])))
return teams
def get_console_input():
num_teams = int(raw_input('\nEnter the number of teams: '))
teams = []
print '\nWill now prompt you to enter the {} teams in draft order'.format(num_teams)
for num_team in xrange(num_teams):
team_name = raw_input('\nEnter team #{} name: '.format(num_team + 1))
team_lottery_pick_percentage = float(raw_input("Enter {}'s lottery pick percentage: ".format(team_name)))
teams.append(TeamPercentage(team_name, team_lottery_pick_percentage))
return teams
def verify_and_process_teams_input(teams):
sum_lottery_pick_percentages = sum([team.team_lottery_pick_percentage for team in teams])
if sum_lottery_pick_percentages != 100:
raise Exception('Lottery pick percentages of teams: {} is not 100'.format(sum_lottery_pick_percentages))
return map(lambda team: TeamPercentage(team.team_name, team.team_lottery_pick_percentage / 100.0), teams)
def get_num_lottery_picks_input(num_teams):
num_lottery_picks = int(raw_input('\nEnter the number of lottery picks: '))
if num_lottery_picks > num_teams:
raise Exception(
'Number of lottery picks: {} cannot be greater than the number of teams: {}'.format(
num_lottery_picks, num_teams
)
)
return num_lottery_picks
if __name__ == '__main__':
print 'Welcome to the NBA Lottery Draft Generator'
print '###########################################'
input_option = raw_input('\nEnter 1 to read team input from a file or anything else to type input into the console: ').strip()
if input_option == '1':
teams = get_file_input()
else:
teams = get_console_input()
teams = verify_and_process_teams_input(teams)
num_lottery_picks = get_num_lottery_picks_input(len(teams))
draft_order = generate_draft_order(teams, num_lottery_picks)
print '\nGenerated Draft Order'
print '########################'
for team in draft_order:
print team
print '\n'
|
0b503bd6eab4a7b2513b0265dab27b3c6abe3a4d | Will-Bailey/co | /coursework/SimulatedAnnealing.py | 1,778 | 3.671875 | 4 | from Ranking import Ranking
import random
import math
class SimulatedAnnealing:
tournament = None
initial_ranking = None
initial_temp = None
temp_length = None
cooling_ratio = None
num_non_improve = None
def __init__(self, tournament=None, initial_ranking=None, initial_temp=None, temp_length=None, cooling_ratio=None, num_non_improve=None):
self.tournament = tournament
self.initial_ranking = initial_ranking
self.initial_temp = initial_temp
self.temp_length = temp_length
self.cooling_ratio = cooling_ratio
self.num_non_improve = num_non_improve
def search(self):
stagnant_iterations = 0
current_ranking = self.initial_ranking
best_ranking = self.initial_ranking
current_temp = self.initial_temp
while stagnant_iterations < self.num_non_improve:
for i in range(1, self.temp_length):
new_ranking = Ranking(neighbour=current_ranking, swap_index=random.randint(0, len(current_ranking)-2))
delta_score = new_ranking.get_kemeny_score()-current_ranking.get_kemeny_score()
if new_ranking.get_kemeny_score() < best_ranking.get_kemeny_score():
best_ranking = new_ranking
stagnant_iterations = -1
if delta_score <= 0:
current_ranking = new_ranking
print("Making downhill move")
elif random.uniform(0,1) < math.e**((-delta_score)/current_temp):
print("Making uphill move")
current_ranking = new_ranking
stagnant_iterations += 1
current_temp *= self.cooling_ratio
return best_ranking |
b5fc6718662c77c3d7cf9a07c4047cc122418f98 | LizaChelishev/class1310 | /page32_11.py | 160 | 4 | 4 | a = int(input('Enter 1st number: '))
b = int(input('Enter 2nd number: '))
for i in range (a, b+1, 1):
print(i)
for t in range (b, a-1, -1):
print(t)
|
fe82faabfd06e204c1ff3d696862302cb5a1f16e | vdakinshin/learn1 | /list.py | 480 | 4.03125 | 4 | mylist = ['Вася', 'Маша', 'Петя', 'Саша']
#print(mylist)
#print(len(mylist))
mylist.append('Маша')
#print(mylist)
#print(len(mylist))
#a = mylist.count('Ольга')
#print('Сколько Маш в списке? Ответ:{}' .format(a))
#print(mylist)
#print(mylist[-2])
#mylist.sort()
#print(mylist)
#c = mylist.index('Петя')
#print(c)
#d = 'Вася' in mylist
#print(d)
#del mylist[3]
print(mylist)
mylist.remove('Маша')
print(mylist)
|
977c8624759726001ac752c1f2b734abf6d9144c | calvinsettachatgul/cara | /algorithms/test/test_count.py | 779 | 3.75 | 4 | from count import count
# sum up all the numbers from 1 to input_num
# if its less than 1 then return 0
def test_input_0():
'''testing input 0'''
assert count(0) == 0
def test_input_None():
'''testing input None'''
assert count(None) == 0
def test_input_1():
'''testing input 1'''
assert count(1) == 1
def test_input_2():
'''testing input 2'''
assert count(2) == 3
def test_input_5():
'''testing input 2'''
assert count(5) == 15
def test_input_neg3():
'''testing input 2'''
assert count(-3) == 0
'''
count(-1) => 0
count(None) => 0
count(0) => 0
count(1) => 1
count(2) => 3
count(3) => 6
count(4) => 10
count(5) => 15
'''
'''
from sample import func
def test_answer():
assert func(3) == 5
''' |
e7f57109d7751d446a5507cf1ecc12506f53be60 | squeakus/bitsandbytes | /astar/graph.py | 340 | 3.5 | 4 | all_nodes = []
for x in range(20):
for y in range(5):
all_nodes.append((y, x))
def neighbors(node):
dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]]
result = []
for dir in dirs:
neighbor = (node[0] + dir[0], node[1] + dir[1])
if neighbor in all_nodes:
result.append(neighbor)
return result
|
8f442a1871283ed5ed4c882b83d82710ec2ed10f | edunoodt/CFP_tkinter | /Tkinter Ej.2.a.py | 3,657 | 4.03125 | 4 | from tkinter import *
# Define la ventana principal
main = Tk()
main.title('Calculadora de Financiación')
C = StringVar()
F = StringVar()
I = StringVar()
# Función convocada desde el boton de cálculo de la financiacón.
# Utiliza la formula de calculo de valor actual de una renta fija prepaga:
# Va=R * {[1-(1+tasa)^(-n)]/tasa} * (1+tasa) donde:
# tasa: es el valor de la tasa anual por año, de interés compuesto
# y es el informado por el enunciado
# n: Es el número de períodos seleccionados que no puede exceder de 18
# R: es la renta o cuota, que despejada de esta formula y
# nos permite encontrar el valor buscado)
def valor_cuota ():
total = float(monto_Entry.get())
num_cuotas = float(cuotas_Entry.get())
int_dic = {'0-2': 0, '3-6': 0.1, '7-12': 0.2, '13-18': 0.3}
if num_cuotas < 19:
if num_cuotas > 2:
if 3 <= num_cuotas < 7:
int = int_dic['3-6']
elif num_cuotas < 13:
int = int_dic['7-12']
else:
int = int_dic['13-18']
cuota = round((total / (1 - (1 + int) ** (-num_cuotas))) * int / (1 + int), 2)
else:
cuota = round(total / num_cuotas, 2)
pagoTotal = round(cuota * num_cuotas, 2)
intereses = round(pagoTotal-total, 2)
C.set('$'+str(cuota))
F.set('$'+str(pagoTotal))
I.set('$'+str(intereses))
else:
C.set('18 cuotas màximo')
# Funcion ejecutada por el boton borrar
def borrar():
monto_Entry.delete(first=0,last=22)
monto_Entry.focus()
cuotas_Entry.delete(first=0,last=22)
ValorCuota_Entry.delete(first=0,last=22)
ValorFinal_Entry.delete(first=0,last=22)
ValorIntereses_Entry.delete(first=0,last=22)
# Funcion para salir del loop y cerrar la ventana
def salir():
main.destroy()
#Ingreso del monto total del producto o total a financiar (texto y ventana de entrada)
monto_Lbl=Label(text='Pago Total').grid(row=0,column=0)
monto_Entry = Entry(main)
monto_Entry.grid(row=0,column=1, padx=20, pady=20)
# Ingreso de la acntidad de cuotas (texto y ventana de entrada)
cuotas_Lbl=Label(text='Cantidad de cuotas').grid(row=1,column=0)
cuotas_Entry = Entry(main)
cuotas_Entry.grid(row=1, column=1, padx=20, pady=20)
# Presentación del valor de la cuota
ValorCuotaTxt_Lbl = Label(main, text='Valor de la cuota:').grid(row=2 , column=0)
ValorCuota_Entry = Entry(main, textvariable=C)
ValorCuota_Entry.grid(row=2, column=1, padx=20, pady=20)
# Pago total o suma de todas las cuotas. No tiene significación financiera, ya que son
# pagos realizados en distintos momentos.
# Para poder sumarlos habría que llevarlos al mismo momento.
ValorFinalTxt_Lbl= Label(main,text='Valor final pagado:')
ValorFinalTxt_Lbl.grid(row=3, column=0)
ValorFinal_Entry = Entry(main, textvariable=F)
ValorFinal_Entry.grid(row=3, column=1, padx=20, pady=20)
# Intereses Pagados. Diferencia entre el monto por unica vez y la suma de todos los pagos
ValorInteresesTxt_Lbl= Label(main, text='Intereses:')
ValorInteresesTxt_Lbl.grid(row=4, column=0)
ValorIntereses_Entry = Entry(main, textvariable=I)
ValorIntereses_Entry.grid(row=4, column=1, padx=20, pady=20)
# Botón para ejecutar los cálculos de la función "valor_cuota"
monto_BTN = Button(main, text = 'calcule la Financiación', command = valor_cuota, width=50)
monto_BTN.grid(row=5, columnspan=2, pady=20)
# Boton para limpiar y reiniciar el cálculo
nuevo_BTN = Button(main, text='Borrar', command=borrar).grid(row=6, column=0)
# Boton para salir del loop y cerrar la ventana
Salir_BTN = Button(main, text='Cerrar la ventana', command=salir).grid(row=6, column=1)
mainloop() |
10de64eadd037bdc642913d773eff0d6af7748f1 | tatsuya4559/ClassicComputerScienceProblemsInPython | /chap1/dna_search.py | 1,111 | 3.609375 | 4 | from enum import IntEnum
from typing import Tuple, List
import bisect
Nucleotide: IntEnum = IntEnum("Nucleotide", ("A", "C", "G", "T"))
Codon = Tuple[Nucleotide, Nucleotide, Nucleotide]
Gene = List[Codon]
def str2gene(s: str) -> Gene:
gene: Gene = []
for i in range(0, len(s), 3):
if (i + 2) >= len(s):
return gene
codon: Codon = (Nucleotide[s[i]], Nucleotide[s[i + 1]], Nucleotide[s[i + 2]])
gene.append(codon)
return gene
def bisect_contains(gene: Gene, key_codon: Codon) -> bool:
i = bisect.bisect_left(gene, key_codon)
if i != len(gene) and gene[i] == key_codon:
return True
return False
def main() -> None:
gene_str: str = "AGCAATACGGGTAAGCTAGTGTTGAAAATCGTTGACCCCATGATGGTGGG"
my_gene: Gene = str2gene(gene_str)
acg: Codon = (Nucleotide.A, Nucleotide.C, Nucleotide.G)
gat: Codon = (Nucleotide.G, Nucleotide.A, Nucleotide.T)
print(acg in my_gene)
print(gat in my_gene)
print(bisect_contains(sorted(my_gene), acg))
print(bisect_contains(sorted(my_gene), gat))
if __name__ == "__main__":
main()
|
454762aa7fd392bdc68ed3048b675393ac6a364b | Om-krishna/Tkinter_GUI_python | /bind_function.py | 324 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 5 20:28:18 2020
@author: Om Krishna
"""
from tkinter import*
root = Tk()
def printName(event):
print("Hello my Name is Turners")
button_1=Button(root, text="Print my name")
button_1.bind("<Button-1>",printName)
button_1.pack()
root.mainloop()
|
045bce7a658dfe085de8f8899af6a53c5905a910 | Kortemme-Lab/klab | /klab/pymath/discrete.py | 1,127 | 3.78125 | 4 | #!/usr/bin/python
# encoding: utf-8
"""
A module for discrete mathematics. Not that this is something we should do in Python.
Created by Shane O'Connor 2016
"""
import fractions
dumb_relative_prime_const = {
6 : 5,
5 : 2,
4 : 3,
3 : 2,
2 : 1, # yep, I know
1 : 0, # yadda yadda
}
def dumb_relative_half_prime(n, divisor = None):
'''A dumb brute-force algorithm to find a relative prime for n which is approximately n/2 through n/5.
It is used for generating spaced colors.
Written on a Friday evening. Do not judge!
'''
if n < 1 or not isinstance(n, int):
raise Exception('n must be a positive non-zero integer.')
elif n < 7:
return dumb_relative_prime_const[n]
elif n < 10:
divisor = 2.0
if not divisor:
if n <= 20:
divisor = 3.0
elif n <= 30:
divisor = 4.0
else:
divisor = 5.0
m = int(n / divisor)
while m > 1:
if fractions.gcd(n, m) == 1:
return m
m -= 1
if divisor > 2.0:
return dumb_relative_half_prime(n, divisor - 1.0) # e.g. 12 |
0643dba567afa8728eaedcf63df771f10da83178 | Bilsteen/Axenous_test | /Quest-2.py | 727 | 4.1875 | 4 | #Question 2:
#Find number of small and capital letters in a string and replace all capital letters by same small letter and all
#small letters by same capital letters
def capital_small(word):
new_word = []
cap = 0
small = 0
for char in word:
if char == " ":
new_word.append(char)
if char == char.upper():
cap += 1
new_word.append(char.lower())
else:
small += 1
new_word.append(char.upper())
return cap,small,"".join(new_word)
cap,small,output = capital_small("EduCatiON")
print(f"Number of capital letters are {cap}")
print(f"Number of small letters are {small}")
print(f"Output is {output}")
|
11e8a3fbc5670bc8428bf6457eca782aa37b87f2 | managorny/python_basic | /homework/les04/file6.py | 677 | 4.15625 | 4 | """
6. Реализовать два небольших скрипта:
а) бесконечный итератор, генерирующий целые числа, начиная с указанного,
б) бесконечный итератор, повторяющий элементы некоторого списка, определенного заранее.
Подсказка: использовать функцию count() и cycle() модуля itertools.
"""
from itertools import count, cycle
from time import sleep
# a)
start = 1
for i in count(start):
print(int(i))
# sleep(1)
# b)
lst = [1, 2, 3]
for i in cycle(lst):
print(i)
# sleep(1)
|
ac611914e59a93523a5c2946947adcbba9a50d78 | Jongy/knesset-committees-data | /make_wordcloud.py | 732 | 3.53125 | 4 | from typing import List
from wordcloud import WordCloud
def make_wordcloud(words: List[str], filename: str) -> None:
# reverse all words, because wordcloud doesn't handle rtl
words = list(map(lambda w: w[::-1], words))
font_path = "NotoSansHebrew-Regular.ttf" # copied from /usr/share/fonts
wordcloud = WordCloud(font_path=font_path, width=2000, height=2000, background_color='white',
collocations=False).generate(' '.join(words))
wordcloud.to_file(filename)
if __name__ == "__main__":
import sys
f = sys.argv[1]
name = sys.argv[2]
import json
j = json.load(open(f))
print("Total number of words:", len(j[name]))
make_wordcloud(j[name], name + ".png")
|
0561162acbe75d2d1693babb2c65601471afe0b6 | prathamtandon/g4gproblems | /Arrays/min_steps_to_desired_array.py | 1,529 | 4.21875 | 4 | import unittest
"""
Given an array with n elements, value of all the elements is zero.
We can perform following operations on the array:
1. Incremental operations:Choose 1 element from the array and increment its value by 1.
2. Doubling operation: Double the values of all the elements of array.
The desired array target[] contains n elements. Compute and return smallest possible number
of operations needed to change the array from all zeros to desired array.
Input: 2 3
Output: 4 (increment both zeros by 1 (2 ops), double them (1 op), increment 2nd 2 by 1 (1 op).
"""
"""
Approach:
1. Approach in reverse direction: make target array to an array of all zeros.
2. Decrement all odd elements by 1, increment count of operations for each such decrement.
3. Divide all elements by 2. Repeat from step 2 until all elements are zero.
"""
def min_steps_to_desired_array(target):
num_ops = 0
while True:
for i in range(len(target)):
if target[i] % 2 != 0:
target[i] -= 1
num_ops += 1
if target.count(0) == len(target):
break
target = [x / 2 for x in target]
num_ops += 1
return num_ops
class TestMinSteps(unittest.TestCase):
def test_min_steps(self):
target = [2, 3]
self.assertEqual(min_steps_to_desired_array(target), 4)
target = [2, 1]
self.assertEqual(min_steps_to_desired_array(target), 3)
target = [16, 16, 16]
self.assertEqual(min_steps_to_desired_array(target), 7)
|
d25907e014e9c425b00e242c82f6718abeb70f39 | kraktos/SimpleSearch | /Main.py | 1,372 | 3.5 | 4 | """
This is the single inception point for running the search mechanism.
This file primarily performs
(a) indexing the input file
(b) persisting the indices locally
(c) using indices to return search results for a given query
"""
import time
import sys
from optparse import OptionParser
import utils.Utility as utility
from core.Indexing import BuiltFileIndex
from core.Searching import SearchIndex
if __name__ == "__main__":
startTime = time.time()
print("Starting: {}".format(utility.get_date_time(startTime)))
try:
parser = OptionParser()
parser.add_option("-f", "--file", dest="file")
# parse the input
(options, args) = parser.parse_args()
# get the to be indexed file
input_file = options.file
# if not present throw exception
if input_file is None:
raise Exception("Missing Input File!")
# index the file
indexer = BuiltFileIndex()
indexer.create_inverted_index(input_file)
# query the index,
searcher = SearchIndex(indexer)
var = None
while var != 'q':
var = raw_input("Enter search item (press q to exit). ")
if var.lower() == 'q':
sys.exit()
# fire the index search
searcher.search(var)
except Exception as ex:
raise Exception(ex)
|
491b066f5e174c096d13c1ea6a4669f0bea0238c | xxwqlee/pylearn | /pydemo/mypy09.py | 522 | 3.8125 | 4 | # 嵌套函数(内部函数)
def print_name(is_chinese, name, family_name):
c = 10
def inner_print(a, b):
print("{0} {1}".format(a, b))
nonlocal c
print(c)
if is_chinese:
inner_print(family_name, name)
else:
inner_print(name, family_name)
print_name(True, "xx", "高")
print_name(False, "George", "Bush")
# 测试LEGB
# str = 'global'
def outer():
# str = 'outer'
def inner():
# str = 'inner'
print(str)
inner()
outer()
|
1ea82a86d5bc8ee8ad291009c1ea54e6827e6035 | CaoZhens/ML_Learning | /study/4_PythonFoundation/numpyBasics/flatx.py | 698 | 3.90625 | 4 | # coding: utf-8
'''
Created on Oct 16, 2017
@author:
CaoZhen
@desc:
Basic Usage of
numpy.chararray.flat
numpy.chararray.flatten
numpy.flatiter (class)
numpy.ravel
@reference:
'''
import numpy as np
x = np.arange(1, 7).reshape(2, 3)
print x
try:
print x[3]
except Exception,e:
print e
print x.flat[3]
print x.T
print x.T.flat[3]
print type(x.flat)
# flatier
for item in x.flat:
print item
print x.flat[2:4]
# flatten
a = np.array([[1,2], [3,4]])
print a
print a.flatten()
print a.flatten('F')
# np.ravel
a = np.array([[1,2,3],[4,5,6]])
print a
print a.ravel()
# ravel is equivalent to reshape(-1, order=order)
print a.reshape(-1) |
05d67ef3b5d13c5b8fc968fa393bf75f68634486 | manuelduarte12/iniciaci-n | /david aroesti/curso inicial/calendario.py | 215 | 3.921875 | 4 | contadorYear = 0
contadorMonths = 0
while contadorYear < 13:
while contadorMonths < 31:
print(f"{contadorYear}, { contadorMonths}")
contadorMonths += 1
contadorYear += 1
contadorMonths =1
|
14285cbd0273acd06045cca30c723a210a104de1 | tlvb25/AirBnB_clone | /tests/test_models/test_city.py | 1,447 | 3.59375 | 4 | #!/usr/bin/python3
"""Unittest for City class"""
import unittest
from models.city import City
from models.base_model import BaseModel
import os
class TestCity(unittest.TestCase):
"""Runs tests for City class"""
def setUp(self):
"""Sets up the testing environment"""
self.c1 = City()
self.c2 = City()
self.c2.name = "Santa_Cruz"
def tearDown(self):
"""Breaks down the testing environment"""
del self.c1
del self.c2
if os.path.exists("file.json"):
os.remove("file.json")
def test_checks_attributes(self):
"""Checks for class specific attributes"""
self.assertTrue(hasattr(City(), "state_id"))
self.assertTrue(hasattr(City(), "name"))
def test_new_instances(self):
"""Checks that new instances were created"""
self.assertTrue(self.c1)
self.assertTrue(self.c2)
def test_new_instances_attribute_creation(self):
"""Checks that new instances have designated attributes"""
self.assertIn("name", self.c2.__dict__)
self.assertEqual(self.c2.name, "Santa_Cruz")
def test_non_existant_instance(self):
"""Checks for a non-existant instance"""
self.c3 = City()
self.assertIsInstance(self.c3, City)
def test_inheritence(self):
"""Checks to make sure City inherits from BaseModel"""
self.assertTrue(issubclass(City, BaseModel))
|
668c4ccc2f619bb7d86307b1320f85928fef9421 | KiraGol/Hillel | /homework_3/3.3.py | 386 | 4.0625 | 4 | friends = ["John", "Marta", "James"]
enemies = ["John", "Johnatan", "Artur"]
for friend in friends:
if friend in enemies:
print(friend + ', we are not the friends anymore')
elif friend in friends and friend != 'James':
print(friend + ', we are the best friends')
# This pring is excess. Try to look on logical operators to cobine several conditions in one line. |
eac6431a44f9e9bdb23808cee245cdcd62462f22 | kwura/python-projects | /Foundations of Programming/phone.py | 880 | 4.15625 | 4 | def isPhoneNumber(text):
# Check if phone number is correct length
if( len(text) != 12 ):
return False
# Check for hyphens and numeric digits
for i in range(3):
if( text[i].isdigit() == False ):
return False
if(text[3] != "-"):
return False
for i in range(4,7):
if( text[i].isdigit() == False ):
return False
if( text[7] != "-"):
return False
for i in range(8, 12):
if( text[i].isdigit() == False ):
return False
return True
message = "Hi my name is lillian co you can contact me at 512-555-3434 or call my secretary at 712-555-3432
detectNum = False
def main():
for i in range len(message):
clump = message[i:i+12]
if isPhoneNumber(clump):
detectNum = True
print("Phone number found:", clump)
if detectNum = False:
print("No phone number could be found!")
main()
|
431d2f5111eb1ed266c777c04d448afd35c96165 | Bharadwaja92/HackerRank10DaysStats | /Day1_InterQuartileRange.py | 1,856 | 4.25 | 4 | """"""
"""
The interquartile range of an array is the difference between its first (Q1) and third (Q3) quartiles (i.e., Q3-Q1).
Given an array, X, of n integers and an array, F, representing the respective frequencies of X's elements, construct a
data set, S, where each xi occurs at frequency fi. Then calculate and print 's interquartile range, rounded to a scale
of 1 decimal place (i.e., 12.3 format).
Tip: Be careful to not use integer division when averaging the middle two elements for a data set with an even number
of elements, and be sure to not include the median in your upper and lower data sets.
"""
n = int(input())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
nums = []
for i in range(n):
nums.extend([l1[i]]*l2[i])
nums = sorted(nums)
def calc_median_uh_lh(n, nums):
if n % 2 == 0:
median = (nums[n//2] + nums[n//2 - 1]) / 2
lh, uh = nums[: n//2], nums[n//2:]
else:
median_index = n // 2
# print('Median index =', median_index)
median = nums[median_index]
lh, uh = nums[:median_index], nums[median_index+1: ]
return median, lh, uh
def get_q1_q3(nums):
n = len(nums)
if n % 2 == 0:
q = (nums[n // 2] + nums[n // 2 - 1]) / 2
else:
median_index = n // 2
q = nums[median_index]
return q
median, lh, uh = calc_median_uh_lh(len(nums), nums)
q1, q3 = get_q1_q3(lh), get_q1_q3(uh)
print(q1, q3)
print('%.1f'%(q3-q1))
"""
import statistics as st
n = int(input())
data = list(map(int, input().split()))
freq = list(map(int, input().split()))
s = []
for i in range(n):
s += [data[i]] * freq[i]
N = sum(freq)
s.sort()
if n%2 != 0:
q1 = st.median(s[:N//2])
q3 = st.median(s[N//2+1:])
else:
q1 = st.median(s[:N//2])
q3 = st.median(s[N//2:])
ir = round(float(q3-q1), 1)
print(ir)
""" |
39e0ff679a137244b15157e4b72215710e7a436e | maggielaughter/tester_school_dzien_6_v2 | /good_range.py | 329 | 3.640625 | 4 | def good_range(number1, number2):
while number 1 > number2:
try:
number1=int(input("Podaj liczbę :"))
number2=int(input("Podaj liczbę :"))
except ValueError:
print('Liczba nr 2 jest za mała w stosunku do liczby nr 1!')
return number1, number2
print(good_range(5,1)) |
93d98545748f35a2897631cdc1f85ac4a9680831 | freeOcen/algori | /algoriDiagram/charpter3/tail.py | 102 | 3.765625 | 4 | def fact(x,y):
if x==0:
return y
else :
return fact(x-1,y+1)
print(fact(3,0)) |
ab9bee7386b61a163e419c849482b574ecc2856e | TrellixVulnTeam/Demo_933I | /leetcode/994.py | 597 | 3.59375 | 4 | def main(grid):
l1, l2, l0 = [], [], []
for num, value in enumerate(grid):
for n, v in enumerate(value):
if v == 2:
l2.append([num, n])
elif v == 1:
l1.append([num, n])
elif v == 0:
l0.append([num, n])
if not l2:
return -1
for i in l2:
print(i)
if grid[i[0]+1][i[1]] or grid[i[0]][i[1]+1] or grid[i[0]-1][i[1]] or grid[i[0]][i[1]-1] == 1:
print(11111)
if __name__ == '__main__':
a = main([[2,1,1],[0,1,1],[1,0,1]])
print(a) |
55044e243dea9823e3f620b2d58f56af43757731 | holod2020/Laborator | /Lab1/1. calculator.py | 396 | 4.1875 | 4 | def calculator(a, b, c):
if c == "+":
return a + b
elif c == "-":
return a - b
elif c == "*":
return a*b
elif c == "/":
return a/b
else:
return "operation"
result = calculator (int(input("Enter number: ")),
int(input("Enter number: ")),
input("Enter operation:"))
print("Result : ", result) |
12097ef43fbf1387aae8880acb6f8c9c366295b7 | sornaami/luminarproject | /functionalprogramming/employeelist.py | 865 | 3.75 | 4 | class Employee:
def __init__(self,id,name,salary,desig):
self.id=id
self.name=name
self.salary=salary
self.desig=desig
def printEmployee(self):
print("id=", self.id)
print("name=", self.name)
print("salary=", self.salary)
print("desig=", self.desig)
def __str__(self):
return self.name
f=open("employee","r")
lst=[]
for lines in f:
data=lines.rstrip("\n").split(",")
print(data)
id=data[0]
name=data[1]
salary=int(data[2])
desig=data[3]
obj=Employee(id,name,salary,desig)
lst.append(obj)
#find all emplo desig developer
result=[obj.name for obj in lst if obj.desig=="developer"]
print(result)
nam=[obj.name.upper() for obj in lst]
print(nam)
ot=sum([obj.salary for obj in lst])
print(ot)
high=max([obj.salary for obj in lst])
print(high)
|
d6ba610db8415ed6469d26e7667d485060825a76 | xxxzc/public-problems | /PythonBasic/BasicGrammar/OOP/3_Point/solution.py | 393 | 3.5 | 4 | '''TESTCASE
3.0 4.0
6.0 0
-
1.4 -2.0
1.5 4.2
-
-1 1.2
-3.2 5
-
0 0
0 0
'''
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __sub__(self, rhs):
return ((self.x-rhs.x)**2+(self.y-rhs.y)**2)**0.5
x1, y1 = map(float, input().split())
x2, y2 = map(float, input().split())
p1 = Point(x1, y1)
p2 = Point(x2, y2)
print('{:.2f}'.format(p2 - p1))
|
3cc56898b36957ecd4da5dba46487cba571e2080 | karenahuang/BackUp_PythonClassCode | /in_class2/test1.py | 1,623 | 4.3125 | 4 | #asks user to input year
year = input("Enter the year: ")
#asks user to input name
name = input("Enter your name: ")
#asks user to input age
age = input("Enter your age: ")
#asks user if they already had their birthday
bday = input("Did you already have your bday this year? (Y or N): ")
#casts the input from years into an int
year = int(year)
#casts the input from age into an int
age = int(age)
try:
#if user inputs with the bday variable any of these strings, do this
if (bday == "N" or bday == "n" or bday == "no" or bday == "No"):
#create new variable yearBorn calculate year born without factoring in
#this year, so add 1
yearBorn = year - (age + 1)
#cast yearBorn into a string so it's possible to include in print statement
#later
yearBorn = str(yearBorn)
#print out what we need
print("Hello " + name + ", you were born in the year " + yearBorn + "\n" +
"Have a great birthday this year!")
#if user inputs with the bday variable any of these strings, do this
elif (bday == "Y" or bday == "y" or bday == "yes" or bday == "Yes"):
#declare new variable yearBorn calculate yearborn factoring in
#current year
yearBorn = year - age
#cast yearBorn as string to include in print statement later
yearBorn = str(yearBorn)
#print what we need
print("Hello " + name + ", you were born in the year " + yearBorn + "\n" +
"Happy delayed birthday.")
#if user inputs anything else into the bday variable, print out wrong answer
except:
print("Wrong answer")
|
523bdfc9afc82cd5198016181f4acb2cebe334e7 | juliansmoller/images | /timeline.py | 3,123 | 3.765625 | 4 | '''
Julian Smoller ~ 2017
This module contains a Timeline class, which can plot time ranges
as horizontal lines on an image.
'''
from PIL import Image
import pandas as pd
import numpy as np
from datetime import datetime
class Timeline:
def __init__(self,time_ranges,x_pixels=1000):
'''Given a dataframe of time ranges with start times and end times,
create a timeline image with horizontal lines for each time range:
Initialize with min time (time_0), max time (time_1), and the number of pixels
in the x dimension (x_pixels) that we can use for the width of the image'''
self.time_ranges = time_ranges[['start_time','end_time']].copy().reset_index(drop=True)
self.time_0 = self.time_ranges['start_time'].min()
self.time_1 = self.time_ranges['end_time'].max()
self.x_pixels = x_pixels
self.time_range = self.time_1-self.time_0
self.time_per_pixel = self.time_range/self.x_pixels
self.time_ranges_mapped = False # flag
def log(self):
'''Print out the object properties'''
print(self.time_0)
print(self.time_1)
print(self.x_pixels)
print(self.time_range)
print(self.time_per_pixel)
def map_time_to_x(self,t):
'''Given a time within the timeline range, convert to x pixel coordinates'''
if t>=self.time_0 and t<=self.time_1:
x = int(((t-self.time_0)/self.time_range)*self.x_pixels)
return x
else:
print(t)
raise Exception('Time value outside of timeline range')
def map_time_ranges(self,y_pixel_increment = 3,y_pixel_width=2):
'''Iterate through the set of time ranges and map each start time and
end time to corresponding pixel coordinates (x0 and x1); set y values to space out the
time ranges vertically, and give each line some width (y_pixel_width)'''
self.y_pixel_increment = y_pixel_increment
self.y_pixel_width = y_pixel_width
self.time_ranges['x0'] = self.time_ranges['start_time'].map(lambda t: self.map_time_to_x(t))
self.time_ranges['x1'] = self.time_ranges['end_time'].map(lambda t: self.map_time_to_x(t))
self.time_ranges['y0'] = self.time_ranges.index.map(lambda i:
(i+1)*self.y_pixel_increment+i*self.y_pixel_width)
self.time_ranges['y1'] = self.time_ranges['y0'].map(lambda y: y+self.y_pixel_width)
self.time_ranges_mapped = True
def plot(self):
'''Generate a timeline image and plot the time ranges as horizontal lines'''
if not self.time_ranges_mapped:
self.map_time_ranges()
x_max = self.x_pixels
y_max = self.time_ranges['y1'].max()+self.y_pixel_increment
self.image = Image.new('RGB',(x_max,y_max),'white')
for time_range in self.time_ranges.iterrows():
for x in range(time_range[1]['x0'],time_range[1]['x1']):
for y in range(time_range[1]['y0'],time_range[1]['y1']):
self.image.putpixel((x,y),(0,0,0))
return self.image |
728d94b3b8684c581ba068742ee48326df829d55 | JiaquanYe/LeetCodeSolution | /Array/leetcode164.py | 712 | 3.796875 | 4 | '''
给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。
如果数组元素个数小于 2,则返回 0。
示例 1:
输入: [3,6,9,1]
输出: 3
解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。
示例 2:
输入: [10]
输出: 0
解释: 数组元素个数小于 2,因此返回 0。
'''
class Solution:
def maximumGap(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)<2:
return 0
nums.sort()
store = []
for idx in range(len(nums)-1):
store.append(nums[idx+1]-nums[idx])
return max(store)
|
438767e8fe6e3f7315da5a5d276fa7dc8241ef14 | FiberJW/hsCode | /guess_my_number_v3.py | 3,930 | 3.96875 | 4 | def guess_user_num():
import random, time
print('\t\t\tGuess My Number!\nI will think of a number between 1 and 100 (Inclusive)\n\nTell me what you think the number is. I\'ll give you hints\n\n')
def main(): #define main instructions as function for calling later
num = random.randint(0, 100)
print('\nI\'m thinking of a number...')
def con():
response = str(input("Do you want to try again? Type 'yes' to continue or press the enter key to exit\n\t=>")).lower()
if response == 'yes' or response == 'y':
main()
elif response == '':
print('\nThanks for playing!')
time.sleep(2)
raise SystemExit
else:
print('Invalid Response', end='\n')
con()
def dec(): # Gets input and decides upon it what to do
nonlocal num
try:
guess = int(input('What am I thinking of?\n\t=>'))
except ValueError:
print('I don\'t think you entered a number-- try again.\n')
guessNum()
if guess == num:
con()
elif guess > num:
print('Too high')
guessNum()
elif guess < num:
print('Too low')
guessNum()
def guessNum():
time.sleep(1)
dec()
guessNum()
main()
def guess_cpu_num():
from random import randint
import time
print("\tEnter a number from 1 - 100. I'll try to guess it. Bring it on!")
num = 0 # Init Sentry Variable
# Checks if number is in proper range
while num < 1 or num >100:
try:
num = int(input("\n\t\tInput your number (I'm not looking):\n\t=>"))
except ValueError:
print('\n\t\t\tYou didn\'t input an integer')
continue
if num > 100:
print("Number is too high!")
if num < 1:
print("Number is too low!")
cpu_guess = randint(1, 100)
print('I think that your number is: ', cpu_guess)
sentry = 0
while cpu_guess != num:
res = input('\nType (1) if my guess is too high, or (2) if my guess is too low:\n\t=>')
if res == '1':
high_guess = cpu_guess
cpu_guess = randint(1, high_guess)
elif res == '2':
low_guess = cpu_guess
cpu_guess = randint(low_guess, 100)
else:
print('\nInvalid input.')
res = input('\nType (1) if my guess is too high; or (2) if my guess s too low:\n\t=>')
print("I'll try again...", cpu_guess)
time.sleep(0.1)
sentry += 1
if sentry > 4:
print('FINE. I\'LL DO IT BY MYSELF')
time.sleep(0.2)
while cpu_guess != num:
if cpu_guess > num:
high_guess = cpu_guess - 10
cpu_guess = randint(1, high_guess)
print("\nI'll try again...", cpu_guess)
elif cpu_guess < num:
low_guess = cpu_guess + 10
cpu_guess = randint(low_guess, 100)
print("\nI'll try again...", cpu_guess)
else:
break
print("FINALLY! I got it!\n")
print('Your number is: ', cpu_guess)
print('\n\tI was actually looking after all...')
def menu():
res = input('Do you want to [1] Have the computer guess your number, ' \
'[2] Guess the computer\'s number, or [3] Exit the program?\n\t=>')
if res == '1':
guess_user_num()
elif res == '2':
guess_cpu_num()
elif res == '3':
raise SystemExit
else:
print('\nBad choice.\n')
menu()
def main():
print('Welcome to the Guess My Number program!\n')
menu()
main()
|
70a5d68acbef715c691971e001abdcb60301905a | doomnonius/advent-of-code | /2017/day03.py | 2,795 | 4.09375 | 4 | class Coord:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"{(self.y, self.x)}"
def __add__(self, other):
return Coord(self.x + other.x, self.y + other.y)
def full_neighbors(self):
return [self + Coord(0, 1), self + Coord(0, -1), self + Coord(1, 0), self + Coord(-1, 0), self + Coord(1, 1), self + Coord(1, -1), self + Coord(-1, -1), self + Coord(-1, 1)]
def neighbors(self):
return [self + Coord(0, 1), self + Coord(0, -1), self + Coord(1, 0), self + Coord(-1, 0)]
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y))
def manhattan(point: Coord) -> int:
""" Takes a list of cross points and calculates the taxicab distance for each.
"""
return abs(point.y) + abs(point.x)
def part1(inp: int) -> int:
x = 0
square = 1
total = 1
while square**2 < inp:
x += 1
square += 2
total = square**2
m = square // 2
y = m - 1
total = (square - 2)**2 + 1
if (inp - total) <= (y + m):
y -= (inp - total)
print(f"Coord: {Coord(x, y)}")
return manhattan(Coord(x, y))
else:
total += y + m
y = -m
if (inp - total) <= (x + m):
x -= (inp - total)
print(f"Coord: {Coord(x, y)}")
return manhattan(Coord(x, y))
else:
total += x + m
x = -m
if (inp - total) <= (abs(y) + m):
y += (inp - total)
print(f"Coord: {Coord(x, y)}")
return manhattan(Coord(x, y))
else:
total += abs(y) + m
y = m
if (inp - total) <= (abs(x) + m):
x += (inp - total)
print(f"Coord: {Coord(x, y)}")
return manhattan(Coord(x, y))
else:
print("Something has gone wrong here...")
def part2(inp: int) -> int:
value = 1
square = 1
total = square**2
index = 1
x = y = 0
side_length = 1
side_progress = 1
side = 0
points = {(x, y): 1}
while value < inp:
## this part handles increasing x and y properly
if index == total: # ie square is completed
x += 1
square += 2
side_length = (square**2 - total)//4
side_progress = 1
side = 0
total = square**2
index += 1
elif side_progress < side_length:
side_progress += 1
index += 1
if side == 0:
y -= 1
if side == 1:
x -= 1
if side == 2:
y += 1
if side == 3:
x += 1
elif side_progress == side_length:
if side == 3:
x += 1
index += 1
else:
side += 1
side_progress = 0
continue
next_val = 0
p = Coord(x, y)
for n in p.full_neighbors():
# print(n)
if (n.x, n.y) in points.keys():
next_val += points[(n.x, n.y)]
points[(p.x, p.y)] = next_val
value = next_val
# print(value)
return value
if __name__ == "__main__":
import timeit
DATA = 289326
print(f"Part one: {part1(DATA)}")
print(f"Part two: {part2(DATA)}")
# print(f"Time: {timeit.timeit('', setup='from __main__ import ', number = 1)}") |
e610b93b76fcf4b5a5bb489ac781a51049fa93bd | rjc89/LeetCode_medium | /unique_paths.py | 651 | 3.671875 | 4 | #https://leetcode.com/problems/unique-paths/discuss/959838/12-MS-oror-EASY-oror-PYTHON-oror-RECURSION-oror-MEMOISATION-oror-DP
class Solution(object):
def uniquePaths(self, m, n, cache = dict()):
"""
:type m: int
:type n: int
:rtype: int
"""
if (m,n) in cache:
return cache[(m,n)]
if m == 1 and n == 1:
return 1
if m == 0 or n == 0:
return 0
cache[(m, n)] = self.uniquePaths(m - 1, n, cache) + self.uniquePaths(m, n - 1, cache)
return cache[(m, n)]
s = Solution()
print(s.uniquePaths(m = 3, n = 7)) |
b8a5a8f67384aee0caa6940c04c55ac1e246829d | 7Biscuits/Calculator_Tkinter | /app.py | 3,621 | 4.15625 | 4 | import tkinter
from tkinter import *
root = tkinter.Tk()
root.title("Calculator")
user_entry = Entry(root, width=35, borderwidth=5)
user_entry.grid( row=0, column=0, columnspan=3, padx=10, pady=10)
def on_button_click(number):
current = user_entry.get()
user_entry.delete(0, END)
user_entry.insert(0, str(current) + str(number))
def clear():
user_entry.delete(0, END)
def equal():
second_num = user_entry.get()
user_entry.delete(0, END)
if math == 'addition':
user_entry.insert(0, f_num + int(second_num))
elif math == 'substraction':
user_entry.insert(0, f_num - int(second_num))
elif math == 'multiplication':
user_entry.insert(0, f_num * int(second_num))
elif math == 'division':
user_entry.insert(0, f_num / int(second_num))
def addition():
first_num = user_entry.get()
global f_num
global math
math = 'addition'
f_num = int(first_num)
user_entry.delete(0, END)
def subtraction():
first_num = user_entry.get()
global f_num
global math
math = 'substraction'
f_num = int(first_num)
user_entry.delete(0, END)
def multiplication():
first_num = user_entry.get()
global f_num
global math
math = 'multiplication'
f_num = int(first_num)
user_entry.delete(0, END)
def division():
first_num = user_entry.get()
global f_num
global math
math = 'division'
f_num = int(first_num)
user_entry.delete(0, END)
button_1 = Button(root, text="1", padx=40, pady=20, borderwidth=3, command=lambda: on_button_click(1))
button_2 = Button(root, text="2", padx=40, pady=20, borderwidth=3, command=lambda: on_button_click(2))
button_3 = Button(root, text="3", padx=40, pady=20, borderwidth=3, command=lambda: on_button_click(3))
button_4 = Button(root, text="4", padx=40, pady=20, borderwidth=3, command=lambda: on_button_click(4))
button_5 = Button(root, text="5", padx=40, pady=20, borderwidth=3, command=lambda: on_button_click(5))
button_6 = Button(root, text="6", padx=40, pady=20, borderwidth=3, command=lambda: on_button_click(6))
button_7 = Button(root, text="7", padx=40, pady=20, borderwidth=3, command=lambda: on_button_click(7))
button_8 = Button(root, text="8", padx=40, pady=20, borderwidth=3, command=lambda: on_button_click(8))
button_9 = Button(root, text="9", padx=40, pady=20, borderwidth=3, command=lambda: on_button_click(9))
button_0 = Button(root, text="0", padx=40, pady=20, borderwidth=3, command=lambda: on_button_click(0))
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_0.grid(row=4, column=0)
equal_button = Button(root, text="=", padx=91, pady=20, command=equal)
clear_button = Button(root, text="Clear", padx=79, pady=20, command=clear)
equal_button.grid(row=5, column=1, columnspan=2)
clear_button.grid(row=4, column=1, columnspan=2)
add_button = Button(root, text="+", padx=39, pady=20, borderwidth=3, command=addition)
substract_button = Button(root, text="-", padx=42, pady=20, borderwidth=3, command=subtraction)
multiply_button = Button(root, text="*", padx=42, pady=20, borderwidth=3, command=multiplication)
divide_button = Button(root, text="/", padx=42, pady=20, borderwidth=3, command=division)
add_button.grid(row=5, column=0)
substract_button.grid(row=6, column=0)
multiply_button.grid(row=6,column=1)
divide_button.grid(row=6, column=2)
root.mainloop()
|
65790b34649ab12dd0015b0b17c02fd9f95c6b70 | CircularWorld/Python_exercise | /month_01/test_01/test_05.py | 564 | 3.953125 | 4 | '''
5.需求:在终端中录入5个疫情省份的确诊人数,
打印最大值、最小值、平均值.(使用内置函数实现)
步骤:循环获取信息,使用列表记录,使用内置函数计算。
'''
list_num = []
for __ in range(5):
confirm_num = int(input("请输入确诊人数:"))
list_num.append(confirm_num)
print(list_num)
print('最多的有%d人' % max(list_num))
print('做少的有%d人' % min(list_num))
print("平均有%d人'" % (sum(list_num) / len(list_num)))
# print(sum(list_num) / len(list_num))
|
360819013e0ba377002ccac046e9809bc1a9226c | CodecoolBP20161/python-data-visualisation-sf | /connection.py | 808 | 3.5625 | 4 | import psycopg2
class Database(object):
def __init__(self, dbname, user, password):
self.dbname = dbname
self.user = user
self.password = password
def connect(self):
connect_str = "dbname=%s user=%s host='localhost' password=%s" % (
self.dbname, self.user, self.password)
return psycopg2.connect(connect_str)
def execute(self, sql_command):
cursor = self.connect().cursor()
try:
cursor.execute("""%s""" % (sql_command))
rows = cursor.fetchall()
return rows
except Exception as e:
print("PROBLEM!!!!")
print(e)
mydb = Database(input('What is your database name? '), input('What is your user name? '),
input('What is your password? ')) |
60ad65bf86370b48796546ebbf53e4f88748f9f6 | Sonatrix/Sample-python-programs | /temp.py | 233 | 3.96875 | 4 | def reverse(a,start,stop):
if start>=stop:
return a
else:
a[start],a[stop-1] = a[stop-1],a[start]
reverse(a,start+1,stop-1)
if __name__ == '__main__':
a = reverse([3,7,198,32],0,3)
print a
#print reverse([1,2,3,4],0,3)
|
af68e75fa3e9cd2d2c4f77edf992f07677cdb555 | kli99/python_challenge | /PyPoll/main.py | 5,814 | 4.0625 | 4 | <<<<<<< HEAD
#load csv
import os
import csv
#Path to collect data
election_data_csv="C:/Users/Keke/git/python_challenge/PyPoll/Resources/election_data.csv"
#define variables
totalvotes= 0
#define column 3 as a dict to refer to occurence number of votes
candidates={}
#define value in column 3 as a list to cross reference to values
candidate= []
percentage=0
#read csv file
with open(election_data_csv)as csvfile:
csvreader=csv.reader(csvfile,delimiter=",")
#skip header row
csv_header = next(csvfile)
print(f"Election Results")
print("\n------------------------------------")
for row in csv.reader(csvfile):
#total casts
totalvotes += 1
candidate = row[2]
#voterid=row[0]
#calculate each candidate votes,if candidate name is not in the list
if candidate not in candidates:
#then the candidate will equal to it's name only
candidates[candidate]=1
else:
#otherwise each appearance will add to next appearance of the same candidate name
candidates[candidate]+=1
print(f"Total Votes:{totalvotes}")
print("\n------------------------------------")
#print(f"{candidates}")
# vote%= votes/totalvotes *100
for candidate in candidates:
#define a shorter name to refer in below function
votes=candidates[candidate]
#percentage= float(votes)/ float(totalvotes) * 100
for key in candidates:
percentage= candidates[key]/totalvotes*100
#print(key +':'+ str("{0:.3f}%".format(percentage))+'('+str(candidates[key])+')')
#print(f"{percentage:,.3f}%".format(percentage))
print(f"{key}:{percentage:,.3f}% ({str(candidates[key])})")
#the highest votes
Winner= max(candidates,key=candidates.get)
print("\n------------------------------------")
print(f"Winner:{Winner}")
print("\n------------------------------------")
text =(
f"Election Results\n"
f"------------------------------------\n"
f"Total Votes:{totalvotes}\n"
f"------------------------------------\n")
#set a new STRING variable to loop different names in the list ''is to including numbers, text,etcs
stringer=''
#set a new for statement to search for string of names
for key in candidates:
percentage= candidates[key]/totalvotes*100
stringer+= f"{key}:{percentage:,.3f}% ({str(candidates[key])})\n"
text2 =(
f"------------------------------------\n"
f"Winner:{Winner}\n"
f"------------------------------------\n")
#split the answer into 2 parts and combine at the end
Finaltext=text+stringer+text2
# Export the results to text file
Final= open('C:/Users/Keke/git/python_challenge/PyPoll/analysis/Final.text', 'w')
#the final answer should be output into the text file
Final.write(Finaltext)
Final.close()
=======
#load csv
import os
import csv
#Path to collect data
election_data_csv="C:/Users/Keke/git/python_challenge/PyPoll/Resources/election_data.csv"
#define variables
totalvotes= 0
#define column 3 as a dict to refer to occurence number of votes
candidates={}
#define value in column 3 as a list to cross reference to values
candidate= []
percentage=0
#read csv file
with open(election_data_csv)as csvfile:
csvreader=csv.reader(csvfile,delimiter=",")
#skip header row
csv_header = next(csvfile)
print(f"Election Results")
print("\n------------------------------------")
for row in csv.reader(csvfile):
#total casts
totalvotes += 1
candidate = row[2]
#voterid=row[0]
#calculate each candidate votes,if candidate name is not in the list
if candidate not in candidates:
#then the candidate will equal to it's name only
candidates[candidate]=1
else:
#otherwise each appearance will add to next appearance of the same candidate name
candidates[candidate]+=1
print(f"Total Votes:{totalvotes}")
print("\n------------------------------------")
#print(f"{candidates}")
# vote%= votes/totalvotes *100
for candidate in candidates:
#define a shorter name to refer in below function
votes=candidates[candidate]
#percentage= float(votes)/ float(totalvotes) * 100
for key in candidates:
percentage= candidates[key]/totalvotes*100
#print(key +':'+ str("{0:.3f}%".format(percentage))+'('+str(candidates[key])+')')
#print(f"{percentage:,.3f}%".format(percentage))
print(f"{key}:{percentage:,.3f}% ({str(candidates[key])})")
#the highest votes
Winner= max(candidates,key=candidates.get)
print("\n------------------------------------")
print(f"Winner:{Winner}")
print("\n------------------------------------")
text =(
f"Election Results\n"
f"------------------------------------\n"
f"Total Votes:{totalvotes}\n"
f"------------------------------------\n")
#set a new STRING variable to loop different names in the list ''is to including numbers, text,etcs
stringer=''
#set a new for statement to search for string of names
for key in candidates:
percentage= candidates[key]/totalvotes*100
stringer+= f"{key}:{percentage:,.3f}% ({str(candidates[key])})\n"
text2 =(
f"------------------------------------\n"
f"Winner:{Winner}\n"
f"------------------------------------\n")
#split the answer into 2 parts and combine at the end
Finaltext=text+stringer+text2
# Export the results to text file
Final= open('C:/Users/Keke/git/python_challenge/PyPoll/analysis/Final.text', 'w')
#the final answer should be output into the text file
Final.write(Finaltext)
Final.close()
>>>>>>> 97012a5334b31988da5776f6a60bc53f1646e686
|
bdda6bbe7a59096b4acdc3dc5a0a64a1c9a60fa0 | edgardeng/design-patterns-in-python | /Command/stock_buy_sell.py | 1,305 | 4.03125 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
class Order(ABC):
"""
Order: The Command interface to execute buy or sell command
"""
@abstractmethod
def execute(self) -> None:
pass
class Stock:
def __init__(self, name=None, q=None):
self.name = name or 'ABC'
self.quantity = q or 10
def buy(self):
print("Stock [ Name: %s , Quantity: %d] bought" % (self.name, self.quantity))
def sell(self):
print("Stock [ Name: %s , Quantity: %d] sold" % (self.name, self.quantity))
class BuyStock(Order):
def __init__(self, s):
self.stock = s
def execute(self):
self.stock.buy()
class SellStock(Order):
def __init__(self, s):
self.stock = s
def execute(self):
self.stock.sell()
class Broker:
def __init__(self):
self.orderList = []
def add_order(self, order):
self.orderList.append(order)
def place_all_order(self):
for order in self.orderList:
order.execute()
self.orderList.clear()
if __name__ == '__main__':
abcStock = Stock()
buy = BuyStock(abcStock)
sell = SellStock(abcStock)
broker = Broker()
broker.add_order(buy)
broker.add_order(sell)
broker.place_all_order()
|
e3c29413e3797a6840c964d573e9e424209e5d0a | jabedude/0x2 | /graduation.py | 134 | 3.796875 | 4 | #!/usr/bin/env python
from datetime import date
t = date(2018,2,16) -date.today()
print('{} days until graduation!'.format(t.days))
|
398123f4f74e9425725a0ae3a92ac3295a225c60 | bestchanges/hello_python | /sessions/4/konstantin_shrayber/main.py | 695 | 3.828125 | 4 | import rates
current_rates = rates.load_current_rates()
print(current_rates)
is_continue = True
while is_continue:
input_string = input("input: ")
if input_string == 'quit':
is_continue = False
else:
if " " in input_string:
for s in rates.calculate_currency_values(current_rates, input_string):
print(s)
elif r"/" in input_string and "=" in input_string:
current_rates = rates.update_currency_rates(current_rates, input_string)
print("updated!")
print(current_rates)
else:
print("Use only allowed notation! <amount> <currency> to convert; <cur1>/<cur2>=<rate> to setup") |
80f96519529e8434b05c2202c6e6094770e521a9 | jedzej/tietopythontraining-basic | /students/synowiec_krzysztof/lesson_01_basics/sum_of_digits.py | 242 | 3.65625 | 4 |
def main():
givenNumber = int(input())
lastDigit = givenNumber % 10
tensDigit = givenNumber // 10 % 10
hundredDigit = givenNumber // 100
print (lastDigit + tensDigit + hundredDigit)
if __name__ == '__main__':
main()
|
17eba7bcc0b449eaba26161f2d231300c98036a4 | MrRa1n/Python-Learning | /Random.py | 524 | 3.921875 | 4 | # The 'random' module can generate pseudo-random numbers
from random import *
# Random floating point number between 0 and 1
print(random())
# Random whole number between 1 and 100
print(randint(1,100))
x = randint(1,100)
print(x)
# Random floating point number between 1 and 10
print(uniform(1,10))
# Fun with lists
items = [1,2,3,4,5,6,7,8,9,10]
shuffle(items)
print(items)
x = sample(items, 1) # Pick a random item from list
print(x[0])
y = sample(items, 4) # Pick 4 random items from list
print(y)
|
8d6bb266015f82879680df4140dd6dde8b3a97c8 | harundemir918/Python-Samples | /02-basic_algorithms/02-reverse_text.py | 230 | 4.59375 | 5 | # Author: harundemir918
# Reverse text
print("The Program That Reverse The Text That Entered")
# Enter the text
text = input("Enter a text: ")
# The text will be reversed using indexes
print("Reversed: ", text[::-1])
|
06ffb2cdb079f0f10b1484d86a62a028baf44f08 | Brian-West/eclipse | /LearnPython/advanced/functional.py | 4,065 | 3.875 | 4 | # -*- coding: utf-8 -*-
# 高阶函数就是可以接受函数参数的函数
import math
def add(x, y, f):
return f(x) + f(y)
print add(25, 9, math.sqrt)
def format_name(s):
newS = ''
newS += s[0:1].upper()
newS += s[1:len(s)].lower()
return newS
print map(format_name, ['adam', 'LISA', 'barT']) # List的每一个元素作为定义域,返回值域的List
def prod(x, y):
return x * y
print reduce(prod, [2, 4, 5, 7, 12]) # 2*4*5*7*12
def is_not_empty(s):
return s and len(s.strip()) > 0
print filter(is_not_empty, ['test', None, '', 'str', ' ', 'END']) # Python把0、空字符串''和None看成 False,其他数值和非空字符串都看成 True
def test(s):
return s and len(s.strip()) > 0
print test(' ')
# 请利用filter()过滤出1~100中平方根是整数的数
def is_sqr(x):
return math.sqrt(x) % 1 == 0
print filter(is_sqr, range(1, 101))
# 自定义排序规则
def reversed_cmp(x, y):
if x > y:
return -1
if x < y:
return 1
return 0
print sorted([36, 5, 12, 9, 21], reversed_cmp)
def cmp_ignore_case(s1, s2):
return cmp(s1.lower(), s2.lower())
# if s1.upper()<s2.upper():
# return -1
# if s1.upper()>s2.upper():
# return 1
# return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
# 返回函数,可以延迟调用
def f():
print 'call f()...'
# 定义函数g:
def g():
print 'call g()...'
# 返回函数g:
return g
x = f()
print x
x()
def calc_sum(lst):
def lazy_sum():
return sum(lst)
return lazy_sum
f = calc_sum([1, 2, 3, 4, ])
print f()
def calc_prod(lst):
def lazy_prod():
p = 1
for x in lst:
p *= x
return p
return lazy_prod
f = calc_prod([1, 2, 3, 4])
print f()
# 希望一次返回3个函数,分别计算1x1,2x2,3x3:
# 返回函数不要引用任何循环变量,或者后续会发生变化的变量。
def count():
fs = []
for i in range(1, 4):
def f(m=i):
return m * m
fs.append(f)
return fs
f1, f2, f3 = count()
print f1(), f2(), f3()
# 匿名函数
print map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print sorted([1, 3, 9, 5, 0], lambda x, y:-cmp(x, y))
myabs = lambda x:-x if x < 0 else x
print myabs(-1)
print myabs(2)
print filter(lambda s:s and len(s.strip()) > 0, ['test', None, '', 'str', ' ', 'END'])
# 装饰器
# 无参装饰器
def log(f):
def fn(*args, **kw):
print 'call ' + f.__name__ + '()...'
return f(*args, **kw)
return fn
@log
def factorial(n):
return reduce(lambda x, y: x * y, range(1, n + 1))
print factorial(10)
@log
def adds(x, y):
return x + y
print adds(1, 2)
import time
def performance(f):
def fn(*args):
print 'call factorial_2() in', time.clock()
return f(*args)
return fn
@performance
def factorial_2(n):
return reduce(lambda x, y: x * y, range(1, n + 1))
print factorial_2(10)
# 有参装饰器
def log_2(prefix):
def log_decorator(f):
def wrapper(*args, **kw):
print '[%s] %s()...' % (prefix, f.__name__)
return f(*args, **kw)
return wrapper
return log_decorator
@log_2('DEBUG')
def test_2():
pass
print test_2()
import functools
def performance_2(unit):
def per_decorator(f):
@functools.wraps(f) # 把原函数的属性全复制到新函数wrapper_2上
def wrapper_2(*args, **kw):
sec = time.time() if unit == 's' else 1000 * time.time()
print 'call ' + f.__name__ + '() in ' + str(sec) + unit
return f(*args, **kw)
return wrapper_2
return per_decorator
@performance_2('s')
def factorial_3(n):
return reduce(lambda x, y: x * y, range(1, n + 1))
print factorial_3(10)
print factorial_3.__name__
# 偏函数
print int('12345') # 当仅传入字符串时,int()函数默认按十进制转换
sorted_ignore_case = functools.partial(sorted, cmp=cmp_ignore_case)
print sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])
|
836d31f3017a92bea77c2157a37799da087dde51 | TopaGeor/Hamiltonian-cycle-and-Plain-Graph | /hamilton_cycle_and_plain_graph.py | 6,665 | 3.765625 | 4 | import copy
import sys
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# For a graph, we calculate the neighbors of every point
# alphabet, every point has a character of the alphabet as id
# Returns a list that for every point in graph has another list
# that represents the neighbors of point
def neighbors(graph):
neighbors_table = []
for index, line in enumerate(graph):
neighbors_list = []
alphabet_pos = 0
for ch in line:
if(ch == "1" and index != alphabet_pos):
neighbors_list.append(alphabet[alphabet_pos])
if(ch != " "):
alphabet_pos += 1
neighbors_table.append(neighbors_list)
return neighbors_table
# Returns a list that for every point in graph has another list
# that holds vertices of the point
def vertices(M):
table = copy.deepcopy(M)
for index, neighbors_list in enumerate(table):
for index2, ch in enumerate(neighbors_list):
table[index][index2] = alphabet[index] + ch
return table
# creates a set so you can start working on checking if
# the graph is plain
def create_set(hamiltonian_cycle, updated_neighbors_table):
vertices_set = []
done = True
pos_hamilton = 0
# the first check at while is in case that no one has a second neighbor
# if the first node has no extra neighbors then go to the next node
# until you find a node with neighbors or reach the end of hamilton ccycleircle
while (pos_hamilton < len(hamiltonian_cycle) and done):
ch_in_ham = hamiltonian_cycle[pos_hamilton]
pos_in_alphabet = alphabet.find(ch_in_ham)
if (len(updated_neighbors_table[pos_in_alphabet]) > 0):
done = False
# Create set of vertices
for ch in updated_neighbors_table[pos_in_alphabet]:
vertices_set.append(ch_in_ham + ch)
updated_neighbors_table[alphabet.find(ch)].remove(ch_in_ham)
else:
pos_hamilton += 1
return (done, vertices_set, pos_hamilton)
def should_go(path, at_set, i, j):
for a in at_set:
# check 00,
# if one side of vertice is inside from j to i path
# check 01 and 02
# if the other side of vertice has anything to do with
# the path
check00 = (path.find(a[0]) >= 0)
check01 = (a[1] == alphabet[i])
check02 = (a[1] == j)
# checks10, 11 12 do the same as 00, 01, 02 for the other side
check10 = (path.find(a[1]) >= 0)
check11 = (a[0] == alphabet[i])
check12 = (a[0] == j)
if ((check00) and not (check01 or check02)
or (check10) and not (check11 or check12)):
return False
return True
def main():
graph = open("graph.txt", "r")
neighbors_table = neighbors(graph)
path_table = vertices(neighbors_table)
repeats = 0
while (repeats < len(path_table) - 2):
graph_path = []
for vertices_list in path_table:
temp_path = []
for path in vertices_list:
for ch in neighbors_table[alphabet.find(path[len(path) - 1])]:
if(path.find(ch) < 0):
temp_path.append(path + ch)
graph_path.append(temp_path)
path_table = copy.deepcopy(graph_path)
repeats += 1
# check if you can have a cycle
for vertices_list in path_table:
cycle = []
for path in vertices_list:
for ch in neighbors_table[alphabet.find(path[len(path) - 1])]:
if(path[0] == ch):
cycle.append(path + ch)
if (len(cycle) == 0):
print("No Hamiltonian cycle. Exit program")
sys.exit()
hamiltonian_cycle = cycle[0]
print("A Hamiltonian cycle is:")
print(hamiltonian_cycle)
# start the proccess to find if the graph is a plain
updated_neighbors_table = copy.deepcopy(neighbors_table)
# remove the paths from hamiltonian cycle
for i, j in zip(hamiltonian_cycle[:len(hamiltonian_cycle) - 1],
hamiltonian_cycle[1:]):
try:
updated_neighbors_table[alphabet.find(i)].remove(j)
updated_neighbors_table[alphabet.find(j)].remove(i)
except ValueError:
print("There was an error")
print("The graph should be undirected")
print("Exiting")
sys.exit()
# Creates group A and B
A = []
B = []
a_done, A, pos_hamilton = create_set(
hamiltonian_cycle,
updated_neighbors_table)
if (a_done):
print("There is no possible path for creating group A." +
"The graph is a level graph")
sys.exit()
# remove the vertices from neighbors_table
updated_neighbors_table[
alphabet.find(hamiltonian_cycle[pos_hamilton])] = []
b_done, B, pos_hamilton = create_set(
hamiltonian_cycle,
updated_neighbors_table)
if (b_done):
print("There is no possible path for creating the group B." +
"This is a level graph ")
sys.exit()
# remove the vertices from neighbors_table
updated_neighbors_table[alphabet.find(
hamiltonian_cycle[pos_hamilton])] = []
i = 0
while i < len(updated_neighbors_table):
if (len(updated_neighbors_table[i]) > 0):
for j in updated_neighbors_table[i]:
# find the path between j and one of his neighbors
# at hamiltonian path
a = hamiltonian_cycle.find(alphabet[i])
b = hamiltonian_cycle.find(j)
if a < b:
j_to_i = hamiltonian_cycle[a + 1: b]
else:
j_to_i = hamiltonian_cycle[b + 1: a]
# try to put j_to_i at A
a_done = True
b_done = True
a_done = should_go(j_to_i, A, i, j)
if (a_done):
A.append(alphabet[i] + j)
updated_neighbors_table[alphabet.find(j)].remove(
alphabet[i])
else:
b_done = should_go(j_to_i, B, i, j)
if(b_done):
B.append(alphabet[i] + j)
updated_neighbors_table[alphabet.find(j)].remove(
alphabet[i])
if(not a_done and not b_done):
print("This is not level graph ")
sys.exit()
i += 1
print("This is a level graph, the two groups of edges are: ")
print(A)
print(B)
if (__name__ == "__main__"):
main() # ABCDEFGHI
|
71bfcef2ff9305dd8313c1c89b9f266291f279c1 | maulita291/UAS_SMT2_2021 | /UAS_SMT2_2021.py | 2,242 | 3.546875 | 4 | ulang = 'y'
while ulang == 'y':
#Format UANG
def rp(uang):
x = str(uang)
if len(x) <= 3:
return 'Rp. ' + x
else:
a = x[:-3]
b = x[-3:]
return rp(a) + '.' + b
#SiapkanVar
kode = ['1','2','3']
uang = [2500000, 4500000, 6500000]
tunjanganIstri = [0.01, 0.03, 0.05]
tunjanganAnak = 0.02
biayaJabatan = 0.005
biayaPensiun = 15500
biayaOrganisasi = 3500
#Tampilkan inputan
nama = input('Masukkan Nama = ')
gol = input('Golongan Anda = ')
gender = input('Jenis Kelamin(L/P) = ')
sts = input('Status Kawin(S/B) = ')
print()
#Hitung gaji
i = 0
while i<len(uang):
if kode[i] == gol:
gaji = uang[i]
tunj = tunjanganIstri[i]
i+=1
#TunjanganIstri
if gender == 'l' and sts =='s':
istri = tunj * gaji
else:
istri = 0
#Tunjangan anak
if sts == 's':
anak = tunjanganAnak * gaji
else:
anak = 0
#Gaji bruto
bruto = gaji + istri + anak
#Biaya jabatan
jbtn = biayaJabatan * bruto
#Gaji netto
netto = bruto - biayaJabatan - biayaPensiun - biayaOrganisasi
#Tampilkan Hasil
print('SLIP GAJI'.center(50))
#Input tanggal
from datetime import date
x = date.today()
print(' Tanggal :', x.strftime('%d %B %Y'))
print('=============================================')
print('Gaji Pokok :', rp (str(gaji)))
print('Tunjangan Istri :', rp (str(istri)))
print('Tunjangan Anak :', rp (str(anak)))
print('--> Gaji Bruto :', rp (str(bruto)))
print('---------------------------------------------')
print('Biaya Jabatan :', rp (str(jbtn)))
print('Iuran Pensiun :', rp (str(biayaPensiun)))
print('Iuran Organisasi :', rp (str(biayaOrganisasi)))
print('--> Gaji Netto :', rp (str(netto)))
ulang = input('Ulangi Program? Y/T:')
print()
if ulang == 't':
break |
e069c7bff3bbf2f8833e6e44effb9052f5ee864b | dpaneda/code | /jams/advent/2021/5/solve.py | 931 | 3.546875 | 4 | #! /usr/bin/env python
import sys
from dataclasses import dataclass
def step(a, b):
if a == b:
return 0
else:
return 1 if a < b else -1
@dataclass(frozen=True)
class Point:
x : int
y : int
def parse(s):
return Point(*map(int, s.split(',')))
@dataclass
class Line:
a : Point
b : Point
def parse(s):
points = s.split(' -> ')
return Line(*map(Point.parse, points))
def inner_points(self):
xstep = step(self.a.x, self.b.x)
ystep = step(self.a.y, self.b.y)
p = self.a
l = [p]
while p != self.b:
p = Point(p.x + xstep, p.y + ystep)
l.append(p)
return l
lines = map(Line.parse, sys.stdin)
grid = {}
for line in lines:
for point in line.inner_points():
grid.setdefault(point, 0)
grid[point] += 1
count = sum(value > 1 for value in grid.values())
print(count)
|
5670860d909ed651cfaef4c3f67654b0c2870b68 | leslie-toone/Cat-or-Dog | /wk 1 Transfer Learning Programming Assignment.py | 15,565 | 4.15625 | 4 | # # Programming assignment: Customising your Models TensorFlow 2
# ## Transfer learning
# ### Instructions
# Create a neural network model to classify images of cats and dogs, using transfer
# learning: use part of a pre-trained image classifier model (trained on ImageNet)
# as a feature extractor,and train additional new layers to perform the cats and
# dogs classification task.
#
#### PACKAGE IMPORTS ####
import tensorflow as tf
from tensorflow.keras.models import Sequential, Model
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
from tensorflow.keras.layers import Conv2D, Input, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.models import Model, load_model
# #### The Dogs vs Cats dataset
#
# Use the [Dogs vs Cats dataset](https://www.kaggle.com/c/dogs-vs-cats/data),
# which was used for a 2013 Kaggle competition. It consists of 25000 images containing either a cat or a dog. We will
# only use a subset of 600 images and labels. The dataset is a subset of a much larger dataset of 3 million photos
# that were originally used as a CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans
# Apart), referred to as “Asirra” or Animal Species Image Recognition for Restricting Access.
#
# * J. Elson, J. Douceur, J. Howell, and J. Saul. "Asirra: A CAPTCHA that Exploits Interest-Aligned Manual Image
# Categorization." Proceedings of 14th ACM Conference on Computer and Communications Security (CCS), October 2007.
#
# Goal: train a classifier model using part of a pre-trained image classifier, using the principle of
# transfer learning.
# #### Load and preprocess the data
images_train = np.load('Customising your Models TensorFlow 2/Data/images_train.npy') / 255.
images_valid = np.load('Customising your Models TensorFlow 2/Data/images_valid.npy') / 255.
images_test = np.load('Customising your Models TensorFlow 2/Data/images_test.npy') / 255.
labels_train = np.load('Customising your Models TensorFlow 2/Data/labels_train.npy')
labels_valid = np.load('Customising your Models TensorFlow 2/Data/labels_valid.npy')
labels_test = np.load('Customising your Models TensorFlow 2/Data/labels_test.npy')
print("{} training data examples".format(images_train.shape[0]))
print("{} validation data examples".format(images_valid.shape[0]))
print("{} test data examples".format(images_test.shape[0]))
print(images_train.shape, images_valid.shape, images_test.shape)
# #### Display sample images and labels from the training set
# Display a few images and labels
class_names = np.array(['Dog', 'Cat'])
plt.figure(figsize=(15, 10))
inx = np.random.choice(images_train.shape[0], 15, replace=False)
for n, i in enumerate(inx):
ax = plt.subplot(3, 5,
n + 1) # nrows,ncols, index (plot number starts at 1 increments across rows first and has a max
# of nrow*ncols)
plt.imshow(images_train[i])
plt.title(class_names[labels_train[i]])
plt.axis('off')
# #### Create a benchmark model
#
# We will first train a CNN classifier model as a benchmark model before implementing the transfer learning approach.
# Using the functional API, build the benchmark model according to the following specifications:
#
# * The model should use the `input_shape` in the function argument to set the shape in the Input layer.
# * The first and second hidden layers should be Conv2D layers with 32 filters, 3x3 kernel size and ReLU activation.
# * The third hidden layer should be a MaxPooling2D layer with a 2x2 window size.
# * The fourth and fifth hidden layers should be Conv2D layers with 64 filters, 3x3 kernel size and ReLU activation.
# * The sixth hidden layer should be a MaxPooling2D layer with a 2x2 window size.
# * The seventh and eighth hidden layers should be Conv2D layers with 128 filters, 3x3 kernel size and ReLU activation.
# * The ninth hidden layer should be a MaxPooling2D layer with a 2x2 window size.
# * This should be followed by a Flatten layer, and a Dense layer with 128 units and ReLU activation
# * The final layer should be a Dense layer with a single neuron and sigmoid activation.
# * All of the Conv2D layers should use `'SAME'` padding.
#
# In total, the network should have 13 layers (including the `Input` layer).
#
# The model should then be compiled with the RMSProp optimiser with learning rate 0.001, binary cross entropy loss
# and and binary accuracy metric.
def get_benchmark_model(input_shape):
inputs = Input(shape=input_shape, name='input_layer')
h = Conv2D(32, (3, 3), activation='relu', name='Conv2D_layer1', padding='same')(inputs)
h = Conv2D(32, (3, 3), activation='relu', name='Conv2D_layer2', padding='same')(h)
h = MaxPooling2D((2, 2), name='maxpool2d_layer3')(h)
h = Conv2D(64, (3, 3), activation='relu', name='Conv2D_layer4', padding='same')(h)
h = Conv2D(64, (3, 3), activation='relu', name='Conv2D_layer5', padding='same')(h)
h = MaxPooling2D((2, 2), name='maxpool2d_layer6')(h)
h = Conv2D(128, (3, 3), activation='relu', name='Conv2D_layer7', padding='same')(h)
h = Conv2D(128, (3, 3), activation='relu', name='Conv2D_layer8', padding='same')(h)
h = MaxPooling2D((2, 2), name='maxpool2d_layer9')(h)
h = Flatten(name='flatten_layer10')(h)
h = Dense(128, activation='relu', name='Dense_layer11')(h)
outputs = Dense(1, activation='sigmoid', name='Out_Dense_sigmoid_layer12')(h)
model = Model(inputs=inputs, outputs=outputs)
model.compile(optimizer=tf.keras.optimizers.RMSprop(0.001),
loss='binary_crossentropy',
metrics=["acc"])
'''According to tf.keras.Model.compile() documentation: When you pass the strings 'accuracy' or 'acc',
we convert this to one of tf.keras.metrics.BinaryAccuracy, tf.keras.metrics.CategoricalAccuracy,
tf.keras.metrics.SparseCategoricalAccuracy based on the loss function used and the model output shape.
We do a similar conversion for the strings 'crossentropy' and 'ce' as well.
thus we can keep metric=acc rather than binary accuracy'''
return model
# Build and compile the benchmark model, and display the model summary
benchmark_model = get_benchmark_model(images_train[0].shape)
# use the binary crossentropy loss since this is a binary classification problem
benchmark_model.summary()
# #### Train the CNN benchmark model
#
# We will train the benchmark CNN model using an `EarlyStopping` callback.
# Fit the benchmark model and save its training history
earlystopping = tf.keras.callbacks.EarlyStopping(patience=2)
history_benchmark = benchmark_model.fit(images_train, labels_train, epochs=10, batch_size=32,
validation_data=(images_valid, labels_valid),
callbacks=[earlystopping])
# #### Plot the learning curves
# Run this cell to plot accuracy vs epoch and loss vs epoch
plt.figure(figsize=(15, 5))
plt.subplot(121)
try:
plt.plot(history_benchmark.history['accuracy'])
plt.plot(history_benchmark.history['val_accuracy'])
except KeyError:
plt.plot(history_benchmark.history['acc'])
plt.plot(history_benchmark.history['val_acc'])
plt.title('Accuracy vs. epochs')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Training', 'Validation'], loc='lower right')
plt.subplot(122)
plt.plot(history_benchmark.history['loss'])
plt.plot(history_benchmark.history['val_loss'])
plt.title('Loss vs. epochs')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Training', 'Validation'], loc='upper right')
plt.show()
# #### Evaluate the benchmark model
# Evaluate the benchmark model on the test set
benchmark_test_loss, benchmark_test_acc = benchmark_model.evaluate(images_test, labels_test, verbose=0)
print("Test loss: {}".format(benchmark_test_loss))
print("Test accuracy: {}".format(benchmark_test_acc))
# #### Load the pretrained image classifier model
#
#We will now begin to build our image classifier using transfer learning. Use the pre-trained MobileNet V2
# model, available to download from [Keras Applications](https://keras.io/applications/#mobilenetv2).
def load_pretrained_MobileNetV2(path):
model = load_model(path)
return model
# Call the function loading the pretrained model and display its summary
base_model = load_pretrained_MobileNetV2('Customising your Models TensorFlow 2/models/MobileNetV2.h5')
base_model.summary()
# #### Use the pre-trained model as a feature extractor
#
# Remove the final layer of the network and replace it with new, untrained classifier layers for our task.
# First create a new model that has the same input tensor as the MobileNetV2 model, and use the output
# tensor from the layer with name `global_average_pooling2d_6` as the model output.
def remove_head(pretrained_model):
model = Model(inputs=pretrained_model.input,
outputs=pretrained_model.get_layer('global_average_pooling2d_6').output)
return model
feature_extractor = remove_head(base_model)
feature_extractor.summary()
# Construct new final classifier layers for your model. Using the Sequential API, create a new model
# according to the following specifications:
#
# * The new model should begin with the feature extractor model.
# * This should then be followed with a new dense layer with 32 units and ReLU activation function.
# * This should be followed by a dropout layer with a rate of 0.5.
# * Finally, this should be followed by a Dense layer with a single neuron and a sigmoid activation function.
#
# In total, the network should be composed of the pretrained base model plus 3 layers.
def add_new_classifier_head(feature_extractor_model):
model = Sequential([
feature_extractor_model,
Dense(32, activation='relu'),
Dropout(0.5),
Dense(1, activation='sigmoid')
])
return model
# Call the function adding a new classification head and display the summary
new_model = add_new_classifier_head(feature_extractor)
new_model.summary()
# #### Freeze the weights of the pretrained model
# Freeze the weights of the pre-trained feature extractor (defined as the first layer of the model),
# so that only the weights of the new layers added will change during the training.
#
# Compile model as before: use the RMSProp optimiser with learning rate 0.001, binary cross
# entropy loss and and binary accuracy metric.
def freeze_pretrained_weights(model):
model.layers[0].trainable = False
model.compile(optimizer=tf.keras.optimizers.RMSprop(0.001),
loss='binary_crossentropy',
metrics=["acc"])
return model
# Call the function freezing the pretrained weights and display the summary
print(new_model.layers)
frozen_new_model = freeze_pretrained_weights(new_model)
frozen_new_model.summary()
n_trainable_variables = len(frozen_new_model.trainable_variables)
n_non_trainable_variables = len(frozen_new_model.non_trainable_variables)
print("\n After freezing:\n\t Number of trainable variables: ", len(frozen_new_model.trainable_variables),
"\n\t Number of non trainable variables: ", len(frozen_new_model.non_trainable_variables))
# #### Train the model
#
# Train the new model on the dogs vs cats data subset. We will use an `EarlyStopping` callback
# with patience set to 2 epochs, as before.
# Train the model and save its training history
earlystopping = tf.keras.callbacks.EarlyStopping(patience=2)
history_frozen_new_model = frozen_new_model.fit(images_train, labels_train, epochs=10, batch_size=32,
validation_data=(images_valid, labels_valid),
callbacks=[earlystopping])
# #### Plot the learning curves
# Run this cell to plot accuracy vs epoch and loss vs epoch
plt.figure(figsize=(15, 5))
plt.subplot(121)
try:
plt.plot(history_frozen_new_model.history['accuracy'])
plt.plot(history_frozen_new_model.history['val_accuracy'])
except KeyError:
plt.plot(history_frozen_new_model.history['acc'])
plt.plot(history_frozen_new_model.history['val_acc'])
plt.title('Accuracy vs. epochs')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Training', 'Validation'], loc='lower right')
plt.subplot(122)
plt.plot(history_frozen_new_model.history['loss'])
plt.plot(history_frozen_new_model.history['val_loss'])
plt.title('Loss vs. epochs')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Training', 'Validation'], loc='upper right')
plt.show()
# #### Evaluate the new model
# Evaluate the benchmark model on the test set
new_model_test_loss, new_model_test_acc = frozen_new_model.evaluate(images_test, labels_test, verbose=0)
print("Test loss: {}".format(new_model_test_loss))
print("Test accuracy: {}".format(new_model_test_acc))
# #### Compare both models
#
# Finally, we will look at the comparison of training, validation and test metrics between the benchmark and transfer
# learning model.
# Gather the benchmark and new model metrics
benchmark_train_loss = history_benchmark.history['loss'][-1]
benchmark_valid_loss = history_benchmark.history['val_loss'][-1]
try:
benchmark_train_acc = history_benchmark.history['acc'][-1]
benchmark_valid_acc = history_benchmark.history['val_acc'][-1]
except KeyError:
benchmark_train_acc = history_benchmark.history['accuracy'][-1]
benchmark_valid_acc = history_benchmark.history['val_accuracy'][-1]
new_model_train_loss = history_frozen_new_model.history['loss'][-1]
new_model_valid_loss = history_frozen_new_model.history['val_loss'][-1]
try:
new_model_train_acc = history_frozen_new_model.history['acc'][-1]
new_model_valid_acc = history_frozen_new_model.history['val_acc'][-1]
except KeyError:
new_model_train_acc = history_frozen_new_model.history['accuracy'][-1]
new_model_valid_acc = history_frozen_new_model.history['val_accuracy'][-1]
# Compile the metrics into a pandas DataFrame and display the table
comparison_table = pd.DataFrame([['Training loss', benchmark_train_loss, new_model_train_loss],
['Training accuracy', benchmark_train_acc, new_model_train_acc],
['Validation loss', benchmark_valid_loss, new_model_valid_loss],
['Validation accuracy', benchmark_valid_acc, new_model_valid_acc],
['Test loss', benchmark_test_loss, new_model_test_loss],
['Test accuracy', benchmark_test_acc, new_model_test_acc]],
columns=['Metric', 'Benchmark CNN', 'Transfer learning CNN'])
comparison_table.index = [''] * 6
print(comparison_table)
# Plot confusion matrices for benchmark and transfer learning models
plt.figure(figsize=(15, 5))
preds = benchmark_model.predict(images_test)
preds = (preds >= 0.5).astype(np.int32)
cm = confusion_matrix(labels_test, preds)
df_cm = pd.DataFrame(cm, index=['Dog', 'Cat'], columns=['Dog', 'Cat'])
plt.subplot(121)
plt.title("Confusion matrix for benchmark model\n")
sns.heatmap(df_cm, annot=True, fmt="d", cmap="YlGnBu")
plt.ylabel("Predicted")
plt.xlabel("Actual")
preds = frozen_new_model.predict(images_test)
preds = (preds >= 0.5).astype(np.int32)
cm = confusion_matrix(labels_test, preds)
df_cm = pd.DataFrame(cm, index=['Dog', 'Cat'], columns=['Dog', 'Cat'])
plt.subplot(122)
plt.title("Confusion matrix for transfer learning model\n")
sns.heatmap(df_cm, annot=True, fmt="d", cmap="YlGnBu")
plt.ylabel("Predicted")
plt.xlabel("Actual")
plt.show()
|
3865cc98acc46cf0f33c6ff8ccb756f795ccbe70 | csams/python_examples | /examples/functional/cons.py | 1,689 | 4.125 | 4 | """
Lists can represent uncertainty in calculations. They allow functions to
return several values instead of just one. Each of those values get fed to
the next function, which returns it's own list of possible values for each
input.
"""
from monad import Monad
class List(Monad):
@classmethod
def unit(cls, x):
return Cons(x)
def join(self, x):
""" x is Nil or a List(List a). Flatten it out. """
if isinstance(x, Nil):
return Nil()
if isinstance(x.head, Nil):
return Nil()
return Cons.mappend(x.head, self.join(x.tail))
@classmethod
def from_list(cls, l):
if not l:
return Nil()
return Cons(l[0], List.from_list(l[1:]))
def to_list(self):
p = self
results = []
while not isinstance(p, Nil):
results.append(p.head)
p = p.tail
return results
class Nil(List):
def fmap(self, func):
return Nil()
def mappend(self, value):
return value
def __repr__(self):
return "Nil"
class Cons(List):
def __init__(self, head, tail=None):
self.head = head
self.tail = tail or Nil()
def fmap(self, func):
return Cons(func(self.head), self.tail.fmap(func))
def mappend(self, y):
return Cons(self.head, self.tail.mappend(y))
def __repr__(self):
return repr(self.to_list())
# Just collect all combinations of x, y, and z.
combinations = List.from_list([1, 2, 3]).bind(lambda x:
List.from_list([5, 6, 7]).bind(lambda y:
List.from_list([8, 9, 0]).bind(lambda z:
List.unit((x, y, z)))))
|
11fb8a5fc1afc0866601643bea669d18eb872b28 | thebiochemguy/sre-class | /Python_101/medium_exercise/box.py | 264 | 4.03125 | 4 | #Exercise 4: Print a box
w=int(input("Width? "))
h=int(input("Height? "))
for y in range(h):
for x in range(w):
if(x == 0 or x == w-1 or y == 0 or y == h-1):
print("*", end ='')
else:
print(" ", end='')
print("")
|
2175c555d52ed7b48114f168fb784944145c6bce | vpisaruc/Python | /Программирование 2 сем/Лабараторные Python/Tkinter.py | 3,020 | 4.25 | 4 | # Бутолин Александер ИУ7-22
# Задано множество окружностей.
# Определить ту, которая пересекает больше всего окружностей.
from math import sqrt
from tkinter import *
try:
def distance(x1,y1,x2,y2):
return sqrt((x2 - x1)**2 + (y2 - y1)**2)
def pifagor(r):
return (sqrt((2*r)**2 + (2*r)**2))/2
## r = [0, 0, 0, 0, 0] # Радиусы
## x = [0, 0, 0, 0, 0] # Координаты центра по оси абцис
## y = [0, 0, 0, 0, 0] # Коорждинаты центра по оси оординат
## I = [0] * len(r) # Intersections(пересечения)
## r = [3, 2, 2, 1, 1] # Радиусы
## x = [5, 5, 8, 9, 10] # Координаты центра по оси абцис
## y = [4, 4, 4, 6, 1] # Коорждинаты центра по оси оординат
## I = [0] * len(r) # Intersections(пересечения)
## r = [2, 3, 4, 5, 6] # Радиусы
## x = [3, 3, 3, 3, 3] # Координаты центра по оси абцис
## y = [3, 3, 3, 3, 3] # Коорждинаты центра по оси оординат
## I = [0] * len(r) # Intersections(пересечения)
## r = [2, 2, 2] # Радиусы
## x = [0, 2, 3] # Координаты центра по оси абцис
## y = [0, 2, 0] # Коорждинаты центра по оси оординат
## I = [0] * len(r) # Intersections(пересечения)
x = []
y = []
r = []
n = int(input(('Введите количество окружностей: ')))
for i in range(n):
z = float(input('Введите кооридану Х центра окружности: '))
x.append(z)
z = float(input('Введите кооридану Y центра окружности: '))
y.append(z)
z = float(input('Введите радиус окружности: '))
r.append(z)
I = len(r)*[0]
for i in range(len(r)-1):
for j in range(i+1,len(r)):
if (distance(x[i],y[i],x[j],y[j]) <= (r[i] + r[j])) and (distance(x[i],y[i],x[j],y[j]) >= abs(r[i] - r [j])): #and ((x[i] != x[j]) and (y[i] != y[j])):
I[i] += 1
I[j] += 1
print('Intersections = ',I)
root=Tk()
max = I[0]
for i in range(len(I)):
if I[i] > max:
max = I[i]
canv = Canvas(root,width = 500, height = 500, bg = "white", cursor = "pencil")
for i in range(len(r)):
if I[i] == max:
canv.create_oval([100 + (x[i] - r[i])*30,100 + (y[i] - r[i])*30],[100 + (x[i] + r[i])*30, 100 + (y[i] + r[i])*30], outline='red')
else:
canv.create_oval([100 + (x[i] - r[i])*30,100 + (y[i] - r[i])*30],[100 + (x[i] + r[i])*30, 100 + (y[i] + r[i])*30], outline='black')
canv.pack()
root.mainloop()
except ValueError:
print('Неправильный ввод')
|
237c013d753d26cbe6210315978d3f7e87777ae5 | viralmehta9/Web-Scraping | /NFL_Weekly.py | 1,634 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 11 01:35:34 2016
@author: viral
"""
import urllib
from bs4 import BeautifulSoup
import csv
import os
#path and output data file
os.getcwd()
directoryPath = "..\.."
os.chdir(directoryPath)
f = csv.writer(open("NFL_Weekly.csv","w"))
f.writerow(['Team Rank','Team Name','Team Points','Team Comments'])
url = 'http://espn.go.com/college-football/powerrankings'
testUrl = urllib.request.urlopen(url)
readData = testUrl.read()
testUrl.close()
soup = BeautifulSoup(readData,'lxml')
# Using to track the no of movies
count = 0
# Fetchning the values present within the tags results
teams = soup.findChildren('table','tablehead')
# Changing movies into an iterator
iterableTeams = iter(teams[0].findAll('tr'))
# Skipping the first value of the iterator as it does not have the required data
next(iterableTeams)
next(iterableTeams)
# to count
n=0
# Finding the tr tag of iterableMovies. Every tr contains information of the movies.
for trItem in iterableTeams:
n += 1
#print(trItem)
teamRank = trItem.findChildren('td','pr-rank')[0].get_text()
#print(teamRank)
teamName = trItem.findAll('a')[1].contents[0]
#print(teamName)
#teamRecord = trItem.find('span','pr-record').contents[0]
#print(teamRecord)
teamPoints = trItem.findChildren('td')[3].contents[0]
#print(teamPoints)
teamComments = trItem.findChildren('td')[4].contents[0]
#print(teamComments)
f.writerow([teamRank,teamName,teamPoints,teamComments])
if n==25:
break
|
ae759ef6446371e39b537ef2e9a5a39e0bd33e44 | alcebytes/Phyton-Estudo | /Prandiano_Python I/03_estruturas_de_decisao/exemplos_de_ifs.py | 350 | 4.1875 | 4 | a = 3
if a > 0:
print("Você digitou um valor POSITIVO")
b = 3
if b>0:
print("Você digitou um valor POSITIVO")
else:
print("Você digitou um valor NÃO POSITIVO")
c = -3
if c>0:
print("Você digitou um valor POSITIVO")
elif c==0:
print("Você digitou um valor NULO")
else:
print("Você digitou um valor NEGATIVO")
|
9862d57ff5a87f7e2f4749b9d603dfbd6f0d8173 | Nkugsw/python-notes | /10152018.py | 242 | 3.765625 | 4 | Restaurant = ('rice','noodles','pizza','orange','ice cream')
for food in Restaurant:
print(food)
#Restaurant[0]='cake'
print('\n')
NewRestaurant = ('cake','falafel','pizza','orange','ice cream')
for food in NewRestaurant:
print(food)
|
a3985cc785da63b45670fe5d96c96d75fa4889ac | GuoYunZheSE/Leetcode | /Easy/1475/1475.py | 658 | 3.578125 | 4 | # @Date : 23:13 04/26/2022
# @Author : ClassicalPi
# @FileName: 1475.py
# @Software: PyCharm
class Solution:
def finalPrices(self, prices: [int]) -> [int]:
order_dic = {}
mono_stack = []
for index, price in enumerate(prices):
while mono_stack and mono_stack[-1][1] >= price:
order_dic.setdefault(mono_stack[-1][0], price)
mono_stack.pop()
mono_stack.append((index, price))
for index, price in enumerate(prices):
prices[index] -= order_dic.get(index, 0)
return prices
if __name__ == '__main__':
S = Solution()
print(S.finalPrices([])) |
818a80a935b3fb76bcdeeb5fb28a4309bf495d3d | kojuki/python_intense | /lesson4.3.py | 839 | 3.859375 | 4 |
def attack(atacker, victim):
victim['health'] = victim['health'] - atacker['damage']
return victim
# для игрока сделаем изменение значения существующего ключа
player = {
'name' : None,
'health' : 100,
'damage' : 50
}
# А для противниа сделаем ввод нового ключа со значением
enemy = {
'health' : 100,
'damage' : 50
}
player['name'] = input('введите имя игрока: ')
enemy['name'] = input('введите имя противника: ')
print(f'исходные параметры игрока: {player}')
print(f'исодные параметры врага: {enemy}')
attack(player, enemy)
print(f'параметры "{enemy["name"]}" после атаки "{player["name"]}": {enemy}')
|
bd50afd20753a90868d11916d15f54f9c5211743 | mikeehun/codewars | /kyu7/the-old-switcheroo/vowel_2_index.py | 593 | 3.96875 | 4 | def vowel_2_index(string):
switched_string = ''
position_in_string = 0
vowels = set('aeiouAEIOU')
for letter in string:
position_in_string += 1
if any((v in vowels) for v in letter):
switched_string += str(position_in_string)
else:
switched_string += letter
return switched_string
#vowel_2_index('this is my string') #== 'th3s 6s my str15ng'
print(vowel_2_index('this is my string')) #== 'th3s 6s my str15ng'
print(vowel_2_index('Codewars is the best site in the world')) #,'C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld')
|
40530c42b95e71a34858fa30860298450fcfb094 | mgundogan20/semester-1-Problem-Set-1 | /ps1d.py | 1,559 | 3.953125 | 4 | # Your solution for part d
# Your solution for part d
import math
monthly_salary = float(input("What is your monthly salary? "))
total_cost = float(input("What is the cost of your dream car? "))
percentage_increase = float(input("Enter the increase in said car's price in decimals: "))
salary_raise= float(input("Enter the percentage salary raise, as a decimal: "))
interest_rate = 0.01
def estimate(percentage_saved,):
"""
calculates the difference of savings and total cost at the end of 24 months for a given saving rate
"""
global monthly_salary, salary_raise
global total_cost, percentage_increase
cost = total_cost
salary = monthly_salary
percentage_saved /= 10000
current_savings = 0
time_estimate = 0
while True:
for x in range(1,13):
current_savings *= 1.01
current_savings += salary*percentage_saved
time_estimate += 1
#print(time_estimate, salary, current_savings)
if x%6 == 0:
salary *= 1 + salary_raise
if time_estimate == 24:
break
if time_estimate == 24:
break
else:
cost += cost*percentage_increase
return(current_savings-cost)
def binarySearch():
high = 10000
low = 0
mid = (high + low)/2
steps=0
if estimate(high) < 0:
print("It is not possible to buy the car in two years")
else:
while abs(estimate(mid)) > 1000:
if estimate(mid) >= 0:
steps += 1
high = mid
else:
steps += 1
low = mid
mid = math.ceil((high + low)/2)
print("Best savings rate: {:.3f}".format(mid/10000))
print("Steps in bisection search: {:d}".format(steps))
binarySearch() |
39cc60f18fa35bc0206229fb9fedc82ec5c9d230 | suyundukov/LIFAP1 | /TD/TD2/Code/Python/7.py | 410 | 3.875 | 4 | #!/usr/bin/python
# Calculer les racines rééles d'un polymer du second degré
from math import sqrt
print('Donne moi trois entiers, un par un : ', end='')
a = float(input())
b = float(input())
c = float(input())
d = b * b - 4 * a * c
if d < 0:
print('Pas de racine réels.')
elif d == 0:
print('Une racine double', -b / (2 * a))
else:
print((-b + sqrt(d)) / (2 * a), (-b - sqrt(d)) / (2 * a))
|
4a1f020ae889c7b6fa482726e811b2af33018ad0 | renaldyresa/Kattis | /oktalni.py | 520 | 3.703125 | 4 | biner = input()
while len(biner)%3!=0 :
biner = "0"+biner
hls = ""
for i in range(0,len(biner),3):
if biner[i:i+3] == "000" :
hls+="0"
elif biner[i:i+3] == "001" :
hls+="1"
elif biner[i:i+3] == "010" :
hls+="2"
elif biner[i:i+3] == "011" :
hls+="3"
elif biner[i:i+3] == "100" :
hls+="4"
elif biner[i:i+3] == "101" :
hls+="5"
elif biner[i:i + 3] == "110":
hls += "6"
elif biner[i:i+3] == "111" :
hls+="7"
print(int(hls))
|
7547ec70fea92c6d820293f47ae5c95c8446de38 | timsergor/StillPython | /068.py | 1,330 | 3.84375 | 4 | #1123. Lowest Common Ancestor of Deepest Leaves. Medium. 64.4%.
#Given a rooted binary tree, return the lowest common ancestor of its deepest leaves.
#Recall that:
#The node of a binary tree is a leaf if and only if it has no children
#The depth of the root of the tree is 0, and if the depth of a node is d, the depth of each of its children is d+1.
#The lowest common ancestor of a set S of nodes is the node A with the largest depth such that every node in S is in the subtree with root A.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
def hieght(Node):
if Node == None:
return(-1)
if not (Node.right or Node.left):
return(0)
else:
return(1 + max(hieght(Node.left), hieght(Node.right)))
def solution(Node):
L = hieght(Node.left)
R = hieght(Node.right)
if L == R:
return(Node)
elif L > R:
return(solution(Node.left))
else:
return(solution(Node.right))
return(solution(root))
# 15 min
|
e79778d274e9bf89b4ea4fa5fbb9780cbe6cbd4d | MihailMihaylov75/algorithms | /linked_lists.py | 2,282 | 3.984375 | 4 | __author__ = 'Mihail Mihaylov'
# Singly linked list
class Node(object):
def __init__(self, value):
self.value = value
self.next_node = None
@staticmethod
def cycle_check(node):
"""Check if linked list contains cycle"""
marker1, marker2 = node, node
# If link is None break -> it is not cycle
while marker1 and marker1.next_node:
marker1 = marker1.next_node
# Check if previous link is the same
if marker1 == marker2:
return True
marker1 = marker1.next_node
marker2 = marker2.next_node
return False
@staticmethod
def reverse(head):
current = head
previous = None
while current:
nextnode = current.next_node
current.next_node = previous
previous = current
current = nextnode
return previous
@staticmethod
def get_nth_to_last_node(n, head):
left_pointer, right_pointer = head, head
for i in range(n-1):
if not right_pointer.next_node:
raise Exception('Error: n is larger than size of the linked list.')
right_pointer = right_pointer.next_node
while right_pointer.next_node:
left_pointer = left_pointer.next_node
right_pointer = right_pointer.next_node
return left_pointer
a = Node(1)
b = Node(2)
c = Node(3)
# a.next_node.value has value 2
a.next_node = b
# b.next_node.value has value 3
b.next_node = c
"""
Linked Lists have constant-time insertions and deletions in any position,
in comparison, arrays require O(n) time to do the same thing.
Linked lists can continue to expand without having to specify their size ahead
of time.
To access an element in a linked list, you need to take O(k) time to go from the head
of the list to the kth element. In contrast, arrays have constant time operations to access elements in an array
"""
class DoublyLinkedListNode(object):
def __init__(self, value):
self.value = value
self.next_node = None
self.prev_node = None
a = DoublyLinkedListNode(1)
b = DoublyLinkedListNode(2)
c = DoublyLinkedListNode(3)
a.next_node = b
b.prev_node = a
b.next_node = c
c.prev_node = b
|
d8bc298b18d557b73c482a4990eade3fa8a9ea88 | marciofleitao/ifpi-ads-algoritmos2020 | /04 - Lista Fábio 01 - Parte 2 - Entrada, Saída e Operadores/f1_p2_q20_eq_linear.py | 457 | 3.921875 | 4 | # 20. Um sistema de equações lineares do tipo , pode ser resolvido segundo mostrado abaixo:
# ENTRADA
a = int(input('Insira o a: '))
b = int(input('Insira o b: '))
c = int(input('Insira o c: '))
d = int(input('Insira o d: '))
e = int(input('Insira o e: '))
f = int(input('Insira o f: '))
# PROCESSAMENTO
x = ((c*e - b*f) / (a*e - b*d))
y = ((a*f - c*d) / (a*e - b*d))
# SAIDA
print(f'O valor de x é {x:.2f} e o valor de y é {y:.2f}.') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.