blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
841ebb2d8c2e526f43adbeddde5169f28c84855d
sanketpatel0512/python_class_project
/clean.py
542
3.515625
4
import pandas as pd #cleanlinessdata def BoroClean(y): cleandata = pd.read_csv("cleanliness.csv",usecols = ['Month', 'Borough', 'Acceptable Streets %', 'Acceptable Sidewalks %']) cleandata = cleandata.rename(columns = {'Acceptable Streets %': 'clean%','Borough':'boro'}) cleandata['boro']=cleandata['boro'].str.upper() cleandata = cleandata.fillna(cleandata.mean()) cleandata = cleandata[cleandata['Month'].str.contains(str(y))] cleandata = cleandata.groupby(['boro']).mean().reset_index() return cleandata
f9fce75b7e79c014a21fd8d365e93f069e6e1c99
sanketpatel0512/python_class_project
/age.py
370
3.5625
4
import pandas as pd def BoroAge(): popdata = pd.read_csv("age.csv", usecols = ['Borough','Age','2010','2015']) popdata = popdata.rename(columns = {'Borough':'boro'}) popdata['boro'] = popdata['boro'].str.upper() popdata = popdata[~popdata['boro'].isin(['NYC TOTAL'])] popdata = popdata[~popdata['Age'].isin(['9-May','14-Oct'])] return popdata
41ac934e1707d6573ecfe86fa8442adb0cc2b7ff
Neirda8282/Tipe
/pwmarduino/pwmarduino/TestPWMv0.py
1,415
3.609375
4
#!/usr/bin/python # -*- coding: latin-1 -*- """ Contr�le de la luminosit� d'une LED l'Arduino � partir d'un PC au moyen du protocole Firmata Interface graphique (Tkinter) """ from tkinter import * import pyfirmata pin1 = 2 pin2 = 3 pin3 = 4 port = 'COM27' #windows #port = '/dev/ttyACM0' #linux board = pyfirmata.Arduino(port) LEDpin = board.get_pin('d:9:p') #on r�gle la pin 11 en mode PWM # S'ex�cute lors d'un changement du slider: def reglageLED(valeur): board.digital[LEDpin.pin_number].write(float(valeur)/100.0) class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("LED") #titre de la fen�tre self.pack(fill=BOTH, expand=1) # Label (le texte dans la fen�tre): w = Label(self, wraplength = 200, pady = 10, text="Veuillez glisser le curseur pour contr�ler la luminosit� de la LED") w.pack() # Curseur: self.var1 = IntVar() w2 = Scale(self, from_=0, to=100, orient=HORIZONTAL, command = reglageLED) w2.pack() def main(): root = Tk() root.geometry("250x200+300+300") # dimension et position initiale de la fen�tre app = Example(root) root.mainloop() if __name__ == '__main__': main()
7addcc49c0a4d47f13862584874bcb93cb530dc0
Mahmud-Buet15/Projects
/python/OOP/Snake Game/scoreboard.py
625
3.609375
4
from turtle import Turtle ALIGNMENT="center" FONT=("Courier", 18, "normal") class Scoreboard(Turtle): def __init__(self): super().__init__() self.score=0 self.goto(0,270) self.hideturtle() self.color("white") self.write(f"Score: {self.score}",align=ALIGNMENT,font=FONT) def game_over(self): self.goto(0,0) self.write("GAME OVER",align=ALIGNMENT,font=FONT) def write_score(self): self.clear() self.score+=1 self.write(f"Score: {self.score}",align=ALIGNMENT,font=FONT)
fdf7bcd8f67cc81eb1f1032caf065feefed992d2
bhammack/machine-learning
/supervised_learning/algorithms/k_nearest_neighbor.py
862
3.578125
4
from sklearn.neighbors import KNeighborsClassifier import numpy as np from . import AbstractLearner class KNNLearner(AbstractLearner): def __init__(self): self.knn_classifier = KNeighborsClassifier(n_neighbors=10) def classifier(self): return self.knn_classifier # For KNN, there are really two hyperparameters we need to tune # 1. the number of neighbors, K # 2. the distance/similarity function def tune(self, x, y): params = { "n_neighbors": np.arange(1, 51), "metric": ["manhattan", "euclidean", "chebyshev"] } return self._tune(params, x, y) def experiment(self, xtrain, xtest, ytrain, ytest): pass # self.plot_learning_curve(xtrain, ytrain) # self.plot_validation_curve(xtrain, ytrain, 'n_neighbors', np.arange(1, 51), 'roc_auc')
cc932e04234c69a33247bec761408d9b647829a5
VictorIvanMr/Mision_02
/distanciaPuntos.py
401
3.828125
4
#Víctor Iván Morales Ramos a01377601 #analisis: Crear un algoritmo que calcule la distancia de dos puntos (x1, y1 y x2, y2). import math x1 = float(input("Dame la coordenada x1: ")) y1 = float(input("Dame la coordenada y1: ")) x2 = float(input("Dame la coordenada x2: ")) y2 = float(input("Dame la coordenada y2: ")) d = math.sqrt(((x2 - x1)**2)+((y2 - y1)**2)) print("La distancia entre ambos puntos es: %.3f"%(d))
8d07752c569dd372e6f8c2db6bf74494410b9b5d
fredsonchaves07/book-list
/utils/database.py
1,406
4
4
import sqlite3 books_file = 'books.txt' def create_book_table(): connection = sqlite3.connect('data.db') cursor = connection.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS books(name text primary key, author text, read integer)') connection.commit() connection.close() def add_book(name, author): connection = sqlite3.connect('data.db') cursor = connection.cursor() cursor.execute(f'INSERT INTO books VALUES(?, ?, 0)', (name, author)) connection.commit() connection.close() def list_book(): connection = sqlite3.connect('data.db') cursor = connection.cursor() cursor.execute(f'SELECT * FROM books') books = [ {'name': row[0], 'author': row[1], 'read': row[2]} for row in cursor.fetchall() ] connection.close() return books def read_book(name): books = list_book() for book in books: if name == book['name']: book['read'] = 1 _save_all_books(books) def _save_all_books(books): with open(books_file, 'w') as file: for book in books: file.write(f'{book["name"]},{book["author"]},{book["read"]}\n') def delete_book(name): books = list_book() books = [ book for book in books if book['name'] != name ] _save_all_books(books)
5d6d8d557279b809dba055dc702c186c0a5abebd
carlson9/KocPython2020
/in-classMaterial/day4/exception.py
375
4.1875
4
raise Exception print("I raised an exception!") raise Exception('I raised an exception!') try: print(a) except NameError: print("oops name error") except: print("oops") finally: print("Yes! I did it!") for i in range(1,10): if i==5: print("I found five!") continue print("Here is five!") else: print(i) else: print("I went through all iterations!")
5fdb3d71246fd6d7c94bcb4f7f900d1566acdec7
oscarzu/Python-Poll-Results
/Pypoll.py
1,808
3.546875
4
import os import csv #Declaring the variables csvpath = os.path.join("Resources","Election_Data.csv") Vote_Totals = 0 List_of_Candidates = [] List_of_Votes_Counted = [] Data_File_List = ["Resources/Election_Data.csv"] #Opening the file and reading it for file in Data_File_List: print(csvpath) with open(csvpath, newline = '') as csvfile: csvfile.readline() csvreader = csv.reader(csvfile, delimiter = ',') for row in csvreader: Vote_Totals = Vote_Totals + 1 candidate = row[2] if not candidate in List_of_Candidates: List_of_Candidates.append(candidate) List_of_Votes_Counted.append(1) else: indexofCandidate = List_of_Candidates.index(candidate) curVoteTally = List_of_Votes_Counted[indexofCandidate] List_of_Votes_Counted[indexofCandidate] = curVoteTally + 1 #Declaring the output file with the results and doing the math ops resultsfile = open( "Election Results.txt","w") lines = [] lines.append("Election Results") lines.append("__________________________") lines.append("Total Votes: " + str(Vote_Totals)) lines.append("___________________________") winningVotes = 0 for candidate in List_of_Candidates: votes = List_of_Votes_Counted[List_of_Candidates.index(candidate)] pctVotes = (votes/Vote_Totals) * 100 if votes > winningVotes: winner = candidate winningVotes = votes lines.append(candidate + ": " + str(round(pctVotes,2)) + "% " + "(" + str(votes) + ")") lines.append("___________________________") lines.append("Winner: " + winner) for line in lines: print(line) print(line, file = resultsfile) resultsfile.close()
6b100c2d18461401f3176dacedfafb4f1919a285
dahcase/Seattle-Mobility-Index
/seamo/preproc/csv_to_sql.py
949
4.03125
4
""" This module takes a data input as a csv file, and converts it to a sqlite3 dbfile. """ import pandas as pd import sqlite3 import sys import re import os def convert_csv(path, dbfile): """ Path is entered as a command-line argument. """ conn = sqlite3.connect(dbfile) # cur = conn.cursor() table_name = re.search(r'([\w]+)[.csv]', path).group(1) csv_file = pd.read_csv(path) csv_file.to_sql(table_name, conn, schema=None, if_exists='fail') conn.commit() conn.close() def main(argv): """ Main function for conversion module. input argv is from command line. """ data_path = "../seamo/data/" path = os.path.join(data_path + "raw/", str(sys.argv[1]) + ".csv") dbfile = os.path.join(data_path + "processed/", str(sys.argv[2]) + ".sqlite3") convert_csv(path, dbfile) if __name__ == "__main__": main(sys.argv[1:])
08d47dfcb82b042197b02b7b501add8a843f10e7
f1025395916/untitled
/pac/24.py
714
3.828125
4
''' 正则使用方法: -match:从开始位置开始查找,一次匹配 -search:从任何位置查找,一次匹配 -finall:把符合条件的全部查找出来 ''' import re s = r'([a-z]+)([a-z]+)' pattern = re.compile(s,re.I) #re.I标识忽略大小写 m = pattern.match("hello world wide web") all =pattern.findall("hello world wide web") print(all) print(type(all)) for i in all: print(i) s = m.group(0) print(s) a = m.span(0) print(a) s = m.group(1) print(s) a = m.span(1) print(a) a = m.span(2) print(a) print(".................") s = m.groups() print(s) print(".............") all =pattern.finditer("hello world wide web") print(all) print(type(all)) for i in all: print(i)
77f8f8cf9fbdc01fbdb3bcf9d1cf1da0f71d7160
f1025395916/untitled
/12-多线程/04.py
268
3.84375
4
from collections import Iterable from collections import Iterator ll =[1,2,3,4,5] #是可迭代的,但不是迭代器 print(isinstance(ll,Iterable)) print(isinstance(ll,Iterator)) l = [x*x for x in range(5)] g = (x*x for x in range(5)) print(type(l)) print(type(g))
e9516fdad10efbf87d90abd2bf0e558b4e790db2
f1025395916/untitled
/pac/06.py
763
3.515625
4
from urllib import request,parse import json baseurl="https://fanyi.baidu.com/sug" # 存放模拟form的数据一定是dict格式 data ={ 'kw':'girl' } # 需要使用parse对data进行编码 data = parse.urlencode(data).encode() # 我们需要构造一个请求头 headers = { # 因为使用post,至少应该包含content-length字段 'Content-Length':len(data) } rep = request.Request(url=baseurl,data=data,headers=headers) # 有了headers,data,url就可以发送请求了 rsp = request.urlopen(baseurl,data=data) json_data = rsp.read().decode("utf-8") print(type(json_data)) print(json_data) # 把json字符串转换成字典 json_data = json.loads(json_data) print(type(json_data)) print(json_data) for item in json_data["data"]: print(item)
8fda441a1d31dfda3b67f3bdaab5709c36224334
subham-paul/Quiz-Test-System
/SIGNIN.py
1,517
3.546875
4
# Login.py import mysql.connector # Open database connection db = mysql.connector.connect(user='root', password='',host='127.0.0.1',database='quiz') # prepare a cursor object using cursor() method cursor = db.cursor() try: print('\n\t\t~:LOGIN PAGE:~') New=input("\n\t\t ARE YOU NEW USER??? <<<(Type Y/N)>>>") if New =='Y' or New=='y': import SIGNUP if New =='N' or New=='n': U=input("\nEnter the Username [Email-ID]=") Pwd=input("Enter the Password=") except: print('Invalid data!!!') db.close() exit() # Prepare SQL query MySQL Table Names under the User. sql = "SELECT * FROM login WHERE Uname='%s' AND Pwd='%s' AND Status=1" % (U,Pwd) try: # Execute the SQL command cursor.execute(sql) # Fetch all the rows in a list of lists. results = cursor.fetchall() for row in results: Uname = row[0] Pwd = row[1] Fname = row[2] Mob = row[3] Status=row[4] # Now print fetched result print("\n\nWelcome %s to UNIQUE LEARNING..." % \ (Fname)) # Write the username to the LoggedUser.txt f=open("Login.txt","w") f.write(Uname) f.close() if Uname=="[email protected]": import ADMIN else: import USER if Uname: print('') except: print("Error: Invalid Username or Password or you are blocked!!!") exit() # disconnect from server cursor.close() db.close()
0c16089c61dc7194a9fb0802387dbdd9fada8fda
mattkim8/Logic
/Matthew_Kim_Assignment_4.py
507
3.703125
4
from fractions import Fraction ##Fraction class automatically reduces fractions def enum(): print "0" ls = [] n = 1 d = 1 f = Fraction(n,d) count = 2 while True: for i in range(count): f = Fraction(n,d) n = i + 1 d = count - i if f not in ls: print str(f) print "-" + str(f) ls.append(f) count = count + 1 print enum()
76cac0ce5b448c1c3d82702d8070b460bcb96931
LechX/PDXCG_projects
/blackjack/deck.py
830
3.5
4
import random class Deck: id = 0 deck_list = [] def __init__(self): ranks = list("A23456789TJQK") ranks[ranks.index("T")] = "10" suits = list("HSCD") self.cards = [] for i in suits: for j in ranks: self.cards.append(j + i) self.id = Deck.id Deck.id += 1 Deck.deck_list.append(self) def draw_card(self): drawn_card = self.cards[random.randint(0,len(self.cards) - 1)] self.cards.remove(drawn_card) return drawn_card def print_card_count(self): count = len(self.cards) if count == 1: print("1 card remaining in the deck.") else: print("{} cards remaining in the deck.".format(str(count))) def __repr__(self): return int(self.id)
19b6587a9c26924cbf8354c0e1713b5d6db05ad3
LechX/PDXCG_projects
/week_two_day_five.py
4,667
4.15625
4
''' # print vowels from a user string using a for loop user_vowels = input("Please enter your favorite band > ").lower() vowels = list("aeiouy") for i in range(0,len(user_vowels)): if user_vowels[i] not in vowels: print(user_vowels[i]) else: continue # print consonants from a user string using a for loop user_consonants = input("Please enter your favorite city > ").lower() consonants = list("bcdfghjklmnpqrstvwxz") for i in range(0,len(user_consonants)): if user_consonants[i] not in consonants: print(user_consonants[i]) else: continue ''' ''' # create list of randomly generated numbers between 100 and 10000 import random random_number_list = [] insert_number = 0 blocked_list = [] # user integer input user_number = int(input("Please pick a number between 1 and 9 > ")) # for loop to add 200 values for i in range(0,200): insert_number = random.randint(100,10000) if insert_number % user_number == 0: random_number_list.insert(i,insert_number) else: blocked_list.insert(i,insert_number) print("The sum of numbers divisible by {} is {}. There are {} in the list.".format(user_number,sum(random_number_list),len(random_number_list))) print("The sum of numbers not divisible by {} is {}. There are {} in the list.".format(user_number,sum(blocked_list),len(blocked_list))) ''' ''' # replace vowels with the index number that it is vowel_replace = list(input("Please enter your favorite vegetable > ")) vowels = list("aeiouy") for i in range(0,len(vowel_replace)): if vowel_replace[i] in vowels: vowel_replace[i] = str(i) else: continue print("".join(vowel_replace)) ''' # print a tic-tac-toe board using 2D lists import random board = [] for i in range(0,3): squares = ["*"] * 3 board.append(squares) def print_board(board): """ function to print current status of board takes a list as an argument, in this case the board list output is printing the board list contents with spaces in between """ for row in board: print(" ".join(row)) # USE DOUBLE FOR LOOP TO INITIALIZE BOARD # INSERT CREATE_BOARD FUNCTION # ADD IS_WIN(TURN) FUNCTION THAT RETURNS TRUE OR FALSE -- if is false, make next turn # SWITCH TO WORKING ON CONNECT FOUR def app(): """ function to play tic tac toe with user vs computer selecting at random function takes no input but it will prompt the user to enter row and column output is printing either the winner or a tie game to the console """ # create and set variables for row, column, turn, and winning row = 3 column = 3 current_turn = "x" game_over = "no" for i in range(0,9): print("It is the {}'s turn.".format(current_turn)) if current_turn == "o": # computer selection row = random.randint(0,2) column = random.randint(0,2) elif current_turn == "x": # user selection row = int(input("Please enter a row number (0-2) > ")) column = int(input("Please enter a column number (0-2) > ")) while board[row][column] != "*": # check to make sure spot is open, ask again if necessary if current_turn == "o": row = random.randint(0,2) column = random.randint(0,2) elif current_turn == "o": print("That spot is already taken.") row = int(input("Please enter a row number (0-2) > ")) column = int(input("Please enter a column number (0-2) > ")) if current_turn == "o": print("The computer chose row {} and column {}.".format(row,column)) board[row][column] = current_turn # change * to x or o for i in range(0,3): # check to see if any winning condition is met if board[i][0] == board[i][1] == board[i][2] != "*": game_over = "yes" elif board[0][i] == board[1][i] == board[2][i] != "*": game_over = "yes" elif board[0][0] == board[1][1] == board[2][2] != "*": game_over = "yes" elif board[0][2] == board[1][1] == board[2][0] != "*": game_over = "yes" if game_over == "yes": # win condition is met, break break if current_turn == "x": # switch turns current_turn = "o" else: current_turn = "x" print_board(board) # print current status of board if game_over == "yes": print("CONGRATULATIONS to team {}, you win!".format(current_turn)) else: print("Sometimes nobody wins! Game over.") print_board(board) app()
80c8a329ddc548479eaba93186f8f65c832763c1
pratikarulkar/Monte-Carlo-Simulation
/Project 2.py
1,745
3.859375
4
import numpy as np import math import random import pandas as pd import matplotlib.pyplot as plt ##Creating a function to get the point on a circle whose centre is (0,0) and having radius of 1. def generating_points_on_perimeter_circle(): k=random.choices([1,0,2])[0] if k==1: x=random.uniform(-1,1) y =math.sqrt(1-(x**2)) elif k==0: y=random.uniform(-1,1) x =math.sqrt(1-(y**2)) else: y=random.uniform(-1,1) x =math.sqrt(1-(y**2)) if y>0: y=-1*y if x>0: x=-1*x return x,y ###To check whether 10000 number of simulation are enough to cover all the points on perimeter of circle... z=pd.DataFrame(index=range(10000),columns=["x","y"]) for i in range(10000): z.loc[i,"x"],z.loc[i,"y"]=generating_points_on_perimeter_circle() plt.scatter(z["x"],z["y"]) def func(simulation=10000): z=[] acute_triangle=0 for i in range(simulation): a=generating_points_on_perimeter_circle() b=generating_points_on_perimeter_circle() c=generating_points_on_perimeter_circle() z1= (math.sqrt((a[0]-b[0])**2+(a[1]-b[1])**2)**2+math.sqrt((a[0]-c[0])**2+(a[1]-c[1])**2)**2)>math.sqrt((b[0]-c[0])**2+(b[1]-c[1])**2)**2 z2= (math.sqrt((a[0]-c[0])**2+(a[1]-c[1])**2)**2+math.sqrt((b[0]-c[0])**2+(b[1]-c[1])**2)**2)>math.sqrt((a[0]-b[0])**2+(a[1]-b[1])**2)**2 z3= (math.sqrt((a[0]-b[0])**2+(a[1]-b[1])**2)**2+math.sqrt((b[0]-c[0])**2+(b[1]-c[1])**2)**2)>math.sqrt((a[0]-c[0])**2+(a[1]-c[1])**2)**2 if z1 and z2 and z3: acute_triangle+=1 return print("The probability of getting an acute angle is ",acute_triangle/simulation) func()
66fb96bf4a2de48163c0dd4c1d2aa1f954fe21fc
bryanlimy/calculate-time-on-mars
/julian_date.py
3,029
4.40625
4
def julian_date(day, month, year, hour, minute, second): '''(int, int, int, int, int, int) -> float Returns the Julian Date (as used in astronomy), given a Gregorian date and time. If given an invalid date/time, returns None. In the NASA calculations this is known as the JDUT.''' a = (14 - month)//12 y = year + 4800 - a m = month + 12*a - 3 julian_day_number = day + ((153*m + 2)//5) + 365*y + (y//4) - (y//100) + (y//400) - 32045 julian_date = julian_day_number + (hour - 12)/24 + minute/1440 + second/86400 if year > 1581: if month > 0 and month < 13: if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12: if day > 0 and day < 32: if hour >= 0 and hour <= 23: if minute >= 0 and minute < 60: if second >= 0 and second < 60: return julian_date else: return None else: return None else: return None else: return None elif month == 4 or month == 6 or month == 9 or month == 11: if day > 0 and day < 31: if hour >= 0 and hour <= 23: if minute >= 0 and minute < 60: if second >= 0 and second < 60: return julian_date else: return None else: return None else: return None else: return None elif month == 2: if day > 0 and day < 29: return julian_date elif day > 0 and day < 30: if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: if hour >= 0 and hour <= 23: if minute >= 0 and minute < 60: if second >= 0 and second < 60: return julian_date else: return None else: return None else: return None else: return None else: return None else: return None else: return None else: return None else: return None else: return None
d48e0a108d580d38f7534d759944b30379f14ce3
amrutagaikwad20/Calendar_2020
/calender.py
71,131
3.953125
4
from tkinter import Tk from tkinter import Button from tkinter import Scrollbar t=Tk() t.minsize(1500,700) t.title("Calender 2020") def january(): January=Button(text="JANUARY",font=("Algerian",25),background="Orange") January.place(x=500,y=0,width="200",height="70") sun=Button(text="SUN",font=("Algerian",25),background="red") sun.place(x=155,y=100,width="100",height="95") Mon=Button(text="MON",font=("Algerian",25),background="yellow") Mon.place(x=155,y=200,width="100",height="95") Tue=Button(text="TUE",font=("Algerian",25),background="blue") Tue.place(x=155,y=300,width="100",height="95") Wed=Button(text="WED",font=("Algerian",25),background="pink") Wed.place(x=155,y=400,width="100",height="95") Thur=Button(text="THUR",font=("Algerian",25),background="violet") Thur.place(x=155,y=500,width="100",height="95") Fri=Button(text="FRI",font=("Algerian",25),background="purple") Fri.place(x=155,y=600,width="100",height="95") Sat=Button(text="SAT",font=("Algerian",25),background="green") Sat.place(x=155,y=700,width="100",height="95") #days jan1=Button(text="",font=("Times New Roman",30),background="white") jan1.place(x=260,y=100,width="200",height="95") jan2=Button(text="",font=("Times New Roman",30),background="white") jan2.place(x=260,y=200,width="200",height="95") jan3=Button(text="",font=("Times New Roman",30),background="white") jan3.place(x=260,y=300,width="200",height="95") jan4=Button(text="1",font=("Times New Roman",30),background="white") jan4.place(x=260,y=400,width="200",height="95") jan5=Button(text="2",font=("Times New Roman",30),background="white") jan5.place(x=260,y=500,width="200",height="95") jan6=Button(text="3",font=("Times New Roman",30),background="white") jan6.place(x=260,y=600,width="200",height="95") jan7=Button(text="4",font=("Times New Roman",30),background="white") jan7.place(x=260,y=700,width="200",height="95") jan8=Button(text="5",font=("Times New Roman",30),background="white",foreground="red") jan8.place(x=460,y=100,width="200",height="95") jan9=Button(text="6",font=("Times New Roman",30),background="white") jan9.place(x=460,y=200,width="200",height="95") jan10=Button(text="7",font=("Times New Roman",30),background="white") jan10.place(x=460,y=300,width="200",height="95") jan11=Button(text="8",font=("Times New Roman",30),background="white") jan11.place(x=460,y=400,width="200",height="95") jan12=Button(text="9",font=("Times New Roman",30),background="white") jan12.place(x=460,y=500,width="200",height="95") jan13=Button(text="10",font=("Times New Roman",30),background="white") jan13.place(x=460,y=600,width="200",height="95") jan14=Button(text="11",font=("Times New Roman",30),background="white") jan14.place(x=460,y=700,width="200",height="95") jan15=Button(text="12",font=("Times New Roman",30),background="white",foreground="red") jan15.place(x=660,y=100,width="200",height="95") jan16=Button(text="13",font=("Times New Roman",30),background="white") jan16.place(x=660,y=200,width="200",height="95") jan17=Button(text="14",font=("Times New Roman",30),background="white") jan17.place(x=660,y=300,width="200",height="95") jan18=Button(text="15",font=("Times New Roman",30),background="white") jan18.place(x=660,y=400,width="200",height="95") jan19=Button(text="16",font=("Times New Roman",30),background="white") jan19.place(x=660,y=500,width="200",height="95") jan20=Button(text="17",font=("Times New Roman",30),background="white") jan20.place(x=660,y=600,width="200",height="95") jan21=Button(text="18",font=("Times New Roman",30),background="white") jan21.place(x=660,y=700,width="200",height="95") jan22=Button(text="19",font=("Times New Roman",30),background="white",foreground="red") jan22.place(x=860,y=100,width="200",height="95") jan23=Button(text="20",font=("Times New Roman",30),background="white") jan23.place(x=860,y=200,width="200",height="95") jan24=Button(text="21",font=("Times New Roman",30),background="white") jan24.place(x=860,y=300,width="200",height="95") jan25=Button(text="22",font=("Times New Roman",30),background="white") jan25.place(x=860,y=400,width="200",height="95") jan26=Button(text="23",font=("Times New Roman",30),background="white") jan26.place(x=860,y=500,width="200",height="95") jan27=Button(text="24",font=("Times New Roman",30),background="white") jan27.place(x=860,y=600,width="200",height="95") jan28=Button(text="25",font=("Times New Roman",30),background="white") jan28.place(x=860,y=700,width="200",height="95") jan29=Button(text="26",font=("Times New Roman",30),background="white",foreground="red") jan29.place(x=1060,y=100,width="200",height="95") jan30=Button(text="27",font=("Times New Roman",30),background="white") jan30.place(x=1060,y=200,width="200",height="95") jan31=Button(text="28",font=("Times New Roman",30),background="white") jan31.place(x=1060,y=300,width="200",height="95") jan32=Button(text="29",font=("Times New Roman",30),background="white") jan32.place(x=1060,y=400,width="200",height="95") jan33=Button(text="30",font=("Times New Roman",30),background="white") jan33.place(x=1060,y=500,width="200",height="95") jan34=Button(text="31",font=("Times New Roman",30),background="white") jan34.place(x=1060,y=600,width="200",height="95") jan35=Button(text="",font=("Times New Roman",30),background="white") jan35.place(x=1060,y=700,width="200",height="95") def february(): January=Button(text="FEBRUARY",font=("Algerian",25),background="Orange") January.place(x=500,y=0,width="200",height="70") sun=Button(text="SUN",font=("Algerian",25),background="red") sun.place(x=155,y=100,width="100",height="95") Mon=Button(text="MON",font=("Algerian",25),background="yellow") Mon.place(x=155,y=200,width="100",height="95") Tue=Button(text="TUE",font=("Algerian",25),background="blue") Tue.place(x=155,y=300,width="100",height="95") Wed=Button(text="WED",font=("Algerian",25),background="pink") Wed.place(x=155,y=400,width="100",height="95") Thur=Button(text="THUR",font=("Algerian",25),background="violet") Thur.place(x=155,y=500,width="100",height="95") Fri=Button(text="FRI",font=("Algerian",25),background="purple") Fri.place(x=155,y=600,width="100",height="95") Sat=Button(text="SAT",font=("Algerian",25),background="green") Sat.place(x=155,y=700,width="100",height="95") #Days jan1=Button(text="",font=("Times New Roman",30),background="white") jan1.place(x=260,y=100,width="200",height="95") jan2=Button(text="",font=("Times New Roman",30),background="white") jan2.place(x=260,y=200,width="200",height="95") jan3=Button(text="",font=("Times New Roman",30),background="white") jan3.place(x=260,y=300,width="200",height="95") jan4=Button(text="",font=("Times New Roman",30),background="white") jan4.place(x=260,y=400,width="200",height="95") jan5=Button(text="",font=("Times New Roman",30),background="white") jan5.place(x=260,y=500,width="200",height="95") jan6=Button(text="",font=("Times New Roman",30),background="white") jan6.place(x=260,y=600,width="200",height="95") jan7=Button(text="1",font=("Times New Roman",30),background="white") jan7.place(x=260,y=700,width="200",height="95") jan8=Button(text="2",font=("Times New Roman",30),background="white",foreground="red") jan8.place(x=460,y=100,width="200",height="95") jan9=Button(text="3",font=("Times New Roman",30),background="white") jan9.place(x=460,y=200,width="200",height="95") jan10=Button(text="4",font=("Times New Roman",30),background="white") jan10.place(x=460,y=300,width="200",height="95") jan11=Button(text="5",font=("Times New Roman",30),background="white") jan11.place(x=460,y=400,width="200",height="95") jan12=Button(text="6",font=("Times New Roman",30),background="white") jan12.place(x=460,y=500,width="200",height="95") jan13=Button(text="7",font=("Times New Roman",30),background="white") jan13.place(x=460,y=600,width="200",height="95") jan14=Button(text="8",font=("Times New Roman",30),background="white") jan14.place(x=460,y=700,width="200",height="95") jan15=Button(text="9",font=("Times New Roman",30),background="white",foreground="red") jan15.place(x=660,y=100,width="200",height="95") jan16=Button(text="10",font=("Times New Roman",30),background="white") jan16.place(x=660,y=200,width="200",height="95") jan17=Button(text="11",font=("Times New Roman",30),background="white") jan17.place(x=660,y=300,width="200",height="95") jan18=Button(text="12",font=("Times New Roman",30),background="white") jan18.place(x=660,y=400,width="200",height="95") jan19=Button(text="13",font=("Times New Roman",30),background="white") jan19.place(x=660,y=500,width="200",height="95") jan20=Button(text="14",font=("Times New Roman",30),background="white") jan20.place(x=660,y=600,width="200",height="95") jan21=Button(text="15",font=("Times New Roman",30),background="white") jan21.place(x=660,y=700,width="200",height="95") jan22=Button(text="16",font=("Times New Roman",30),background="white",foreground="red") jan22.place(x=860,y=100,width="200",height="95") jan23=Button(text="17",font=("Times New Roman",30),background="white") jan23.place(x=860,y=200,width="200",height="95") jan24=Button(text="18",font=("Times New Roman",30),background="white") jan24.place(x=860,y=300,width="200",height="95") jan25=Button(text="19",font=("Times New Roman",30),background="white") jan25.place(x=860,y=400,width="200",height="95") jan26=Button(text="20",font=("Times New Roman",30),background="white") jan26.place(x=860,y=500,width="200",height="95") jan27=Button(text="21",font=("Times New Roman",30),background="white") jan27.place(x=860,y=600,width="200",height="95") jan28=Button(text="22",font=("Times New Roman",30),background="white") jan28.place(x=860,y=700,width="200",height="95") jan29=Button(text="23",font=("Times New Roman",30),background="white",foreground="red") jan29.place(x=1060,y=100,width="200",height="95") jan30=Button(text="24",font=("Times New Roman",30),background="white") jan30.place(x=1060,y=200,width="200",height="95") jan31=Button(text="25",font=("Times New Roman",30),background="white") jan31.place(x=1060,y=300,width="200",height="95") jan32=Button(text="26",font=("Times New Roman",30),background="white") jan32.place(x=1060,y=400,width="200",height="95") jan33=Button(text="27",font=("Times New Roman",30),background="white") jan33.place(x=1060,y=500,width="200",height="95") jan34=Button(text="28",font=("Times New Roman",30),background="white") jan34.place(x=1060,y=600,width="200",height="95") jan35=Button(text="29",font=("Times New Roman",30),background="white") jan35.place(x=1060,y=700,width="200",height="95") def march(): January=Button(text="MARCH",font=("Algerian",25),background="Orange") January.place(x=500,y=0,width="200",height="70") sun=Button(text="SUN",font=("Algerian",25),background="red") sun.place(x=155,y=100,width="100",height="95") Mon=Button(text="MON",font=("Algerian",25),background="yellow") Mon.place(x=155,y=200,width="100",height="95") Tue=Button(text="TUE",font=("Algerian",25),background="blue") Tue.place(x=155,y=300,width="100",height="95") Wed=Button(text="WED",font=("Algerian",25),background="pink") Wed.place(x=155,y=400,width="100",height="95") Thur=Button(text="THUR",font=("Algerian",25),background="violet") Thur.place(x=155,y=500,width="100",height="95") Fri=Button(text="FRI",font=("Algerian",25),background="purple") Fri.place(x=155,y=600,width="100",height="95") Sat=Button(text="SAT",font=("Algerian",25),background="green") Sat.place(x=155,y=700,width="100",height="95") #Days jan1=Button(text="1",font=("Times New Roman",30),background="white",foreground="red") jan1.place(x=260,y=100,width="200",height="95") jan2=Button(text="2",font=("Times New Roman",30),background="white") jan2.place(x=260,y=200,width="200",height="95") jan3=Button(text="3",font=("Times New Roman",30),background="white") jan3.place(x=260,y=300,width="200",height="95") jan4=Button(text="4",font=("Times New Roman",30),background="white") jan4.place(x=260,y=400,width="200",height="95") jan5=Button(text="5",font=("Times New Roman",30),background="white") jan5.place(x=260,y=500,width="200",height="95") jan6=Button(text="6",font=("Times New Roman",30),background="white") jan6.place(x=260,y=600,width="200",height="95") jan7=Button(text="7",font=("Times New Roman",30),background="white") jan7.place(x=260,y=700,width="200",height="95") jan8=Button(text="8",font=("Times New Roman",30),background="white",foreground="red") jan8.place(x=460,y=100,width="200",height="95") jan9=Button(text="9",font=("Times New Roman",30),background="white") jan9.place(x=460,y=200,width="200",height="95") jan10=Button(text="10",font=("Times New Roman",30),background="white") jan10.place(x=460,y=300,width="200",height="95") jan11=Button(text="11",font=("Times New Roman",30),background="white") jan11.place(x=460,y=400,width="200",height="95") jan12=Button(text="12",font=("Times New Roman",30),background="white") jan12.place(x=460,y=500,width="200",height="95") jan13=Button(text="13",font=("Times New Roman",30),background="white") jan13.place(x=460,y=600,width="200",height="95") jan14=Button(text="14",font=("Times New Roman",30),background="white") jan14.place(x=460,y=700,width="200",height="95") jan15=Button(text="15",font=("Times New Roman",30),background="white",foreground="red") jan15.place(x=660,y=100,width="200",height="95") jan16=Button(text="16",font=("Times New Roman",30),background="white") jan16.place(x=660,y=200,width="200",height="95") jan17=Button(text="17",font=("Times New Roman",30),background="white") jan17.place(x=660,y=300,width="200",height="95") jan18=Button(text="18",font=("Times New Roman",30),background="white") jan18.place(x=660,y=400,width="200",height="95") jan19=Button(text="19",font=("Times New Roman",30),background="white") jan19.place(x=660,y=500,width="200",height="95") jan20=Button(text="20",font=("Times New Roman",30),background="white") jan20.place(x=660,y=600,width="200",height="95") jan21=Button(text="21",font=("Times New Roman",30),background="white") jan21.place(x=660,y=700,width="200",height="95") jan22=Button(text="22",font=("Times New Roman",30),background="white",foreground="red") jan22.place(x=860,y=100,width="200",height="95") jan23=Button(text="23",font=("Times New Roman",30),background="white") jan23.place(x=860,y=200,width="200",height="95") jan24=Button(text="24",font=("Times New Roman",30),background="white") jan24.place(x=860,y=300,width="200",height="95") jan25=Button(text="25",font=("Times New Roman",30),background="white") jan25.place(x=860,y=400,width="200",height="95") jan26=Button(text="26",font=("Times New Roman",30),background="white") jan26.place(x=860,y=500,width="200",height="95") jan27=Button(text="27",font=("Times New Roman",30),background="white") jan27.place(x=860,y=600,width="200",height="95") jan28=Button(text="28",font=("Times New Roman",30),background="white") jan28.place(x=860,y=700,width="200",height="95") jan29=Button(text="29",font=("Times New Roman",30),background="white",foreground="red") jan29.place(x=1060,y=100,width="200",height="95") jan30=Button(text="30",font=("Times New Roman",30),background="white") jan30.place(x=1060,y=200,width="200",height="95") jan31=Button(text="31",font=("Times New Roman",30),background="white") jan31.place(x=1060,y=300,width="200",height="95") jan32=Button(text="",font=("Times New Roman",30),background="white") jan32.place(x=1060,y=400,width="200",height="95") jan33=Button(text="",font=("Times New Roman",30),background="white") jan33.place(x=1060,y=500,width="200",height="95") jan34=Button(text="",font=("Times New Roman",30),background="white") jan34.place(x=1060,y=600,width="200",height="95") jan35=Button(text="",font=("Times New Roman",30),background="white") jan35.place(x=1060,y=700,width="200",height="95") def april(): January=Button(text="APRIL",font=("Algerian",25),background="Orange") January.place(x=500,y=0,width="200",height="70") #Week sun=Button(text="SUN",font=("Algerian",25),background="red") sun.place(x=155,y=100,width="100",height="95") Mon=Button(text="MON",font=("Algerian",25),background="yellow") Mon.place(x=155,y=200,width="100",height="95") Tue=Button(text="TUE",font=("Algerian",25),background="blue") Tue.place(x=155,y=300,width="100",height="95") Wed=Button(text="WED",font=("Algerian",25),background="pink") Wed.place(x=155,y=400,width="100",height="95") Thur=Button(text="THUR",font=("Algerian",25),background="violet") Thur.place(x=155,y=500,width="100",height="95") Fri=Button(text="FRI",font=("Algerian",25),background="purple") Fri.place(x=155,y=600,width="100",height="95") Sat=Button(text="SAT",font=("Algerian",25),background="green") Sat.place(x=155,y=700,width="100",height="95") #Days jan1=Button(text="",font=("Times New Roman",30),background="white",foreground="red") jan1.place(x=260,y=100,width="200",height="95") jan2=Button(text="",font=("Times New Roman",30),background="white") jan2.place(x=260,y=200,width="200",height="95") jan3=Button(text="",font=("Times New Roman",30),background="white") jan3.place(x=260,y=300,width="200",height="95") jan4=Button(text="1",font=("Times New Roman",30),background="white") jan4.place(x=260,y=400,width="200",height="95") jan5=Button(text="2",font=("Times New Roman",30),background="white") jan5.place(x=260,y=500,width="200",height="95") jan6=Button(text="3",font=("Times New Roman",30),background="white") jan6.place(x=260,y=600,width="200",height="95") jan7=Button(text="4",font=("Times New Roman",30),background="white") jan7.place(x=260,y=700,width="200",height="95") jan8=Button(text="5",font=("Times New Roman",30),background="white",foreground="red") jan8.place(x=460,y=100,width="200",height="95") jan9=Button(text="6",font=("Times New Roman",30),background="white") jan9.place(x=460,y=200,width="200",height="95") jan10=Button(text="7",font=("Times New Roman",30),background="white") jan10.place(x=460,y=300,width="200",height="95") jan11=Button(text="8",font=("Times New Roman",30),background="white") jan11.place(x=460,y=400,width="200",height="95") jan12=Button(text="9",font=("Times New Roman",30),background="white") jan12.place(x=460,y=500,width="200",height="95") jan13=Button(text="10",font=("Times New Roman",30),background="white") jan13.place(x=460,y=600,width="200",height="95") jan14=Button(text="11",font=("Times New Roman",30),background="white") jan14.place(x=460,y=700,width="200",height="95") jan15=Button(text="12",font=("Times New Roman",30),background="white",foreground="red") jan15.place(x=660,y=100,width="200",height="95") jan16=Button(text="13",font=("Times New Roman",30),background="white") jan16.place(x=660,y=200,width="200",height="95") jan17=Button(text="14",font=("Times New Roman",30),background="white") jan17.place(x=660,y=300,width="200",height="95") jan18=Button(text="15",font=("Times New Roman",30),background="white") jan18.place(x=660,y=400,width="200",height="95") jan19=Button(text="16",font=("Times New Roman",30),background="white") jan19.place(x=660,y=500,width="200",height="95") jan20=Button(text="17",font=("Times New Roman",30),background="white") jan20.place(x=660,y=600,width="200",height="95") jan21=Button(text="18",font=("Times New Roman",30),background="white") jan21.place(x=660,y=700,width="200",height="95") jan22=Button(text="19",font=("Times New Roman",30),background="white",foreground="red") jan22.place(x=860,y=100,width="200",height="95") jan23=Button(text="20",font=("Times New Roman",30),background="white") jan23.place(x=860,y=200,width="200",height="95") jan24=Button(text="21",font=("Times New Roman",30),background="white") jan24.place(x=860,y=300,width="200",height="95") jan25=Button(text="22",font=("Times New Roman",30),background="white") jan25.place(x=860,y=400,width="200",height="95") jan26=Button(text="23",font=("Times New Roman",30),background="white") jan26.place(x=860,y=500,width="200",height="95") jan27=Button(text="24",font=("Times New Roman",30),background="white") jan27.place(x=860,y=600,width="200",height="95") jan28=Button(text="25",font=("Times New Roman",30),background="white") jan28.place(x=860,y=700,width="200",height="95") jan29=Button(text="26",font=("Times New Roman",30),background="white",foreground="red") jan29.place(x=1060,y=100,width="200",height="95") jan30=Button(text="27",font=("Times New Roman",30),background="white") jan30.place(x=1060,y=200,width="200",height="95") jan31=Button(text="28",font=("Times New Roman",30),background="white") jan31.place(x=1060,y=300,width="200",height="95") jan32=Button(text="29",font=("Times New Roman",30),background="white") jan32.place(x=1060,y=400,width="200",height="95") jan33=Button(text="30",font=("Times New Roman",30),background="white") jan33.place(x=1060,y=500,width="200",height="95") jan34=Button(text="",font=("Times New Roman",30),background="white") jan34.place(x=1060,y=600,width="200",height="95") jan35=Button(text="",font=("Times New Roman",30),background="white") jan35.place(x=1060,y=700,width="200",height="95") def may(): January=Button(text="MAY",font=("Algerian",25),background="Orange") January.place(x=500,y=0,width="200",height="70") sun=Button(text="SUN",font=("Algerian",25),background="red") sun.place(x=155,y=100,width="100",height="95") Mon=Button(text="MON",font=("Algerian",25),background="yellow") Mon.place(x=155,y=200,width="100",height="95") Tue=Button(text="TUE",font=("Algerian",25),background="blue") Tue.place(x=155,y=300,width="100",height="95") Wed=Button(text="WED",font=("Algerian",25),background="pink") Wed.place(x=155,y=400,width="100",height="95") Thur=Button(text="THUR",font=("Algerian",25),background="violet") Thur.place(x=155,y=500,width="100",height="95") Fri=Button(text="FRI",font=("Algerian",25),background="purple") Fri.place(x=155,y=600,width="100",height="95") Sat=Button(text="SAT",font=("Algerian",25),background="green") Sat.place(x=155,y=700,width="100",height="95") #Days jan1=Button(text="31",font=("Times New Roman",30),background="white",foreground="red") jan1.place(x=260,y=100,width="200",height="95") jan2=Button(text="",font=("Times New Roman",30),background="white") jan2.place(x=260,y=200,width="200",height="95") jan3=Button(text="",font=("Times New Roman",30),background="white") jan3.place(x=260,y=300,width="200",height="95") jan4=Button(text="",font=("Times New Roman",30),background="white") jan4.place(x=260,y=400,width="200",height="95") jan5=Button(text="",font=("Times New Roman",30),background="white") jan5.place(x=260,y=500,width="200",height="95") jan6=Button(text="1",font=("Times New Roman",30),background="white",foreground="red") jan6.place(x=260,y=600,width="200",height="95") jan7=Button(text="2",font=("Times New Roman",30),background="white") jan7.place(x=260,y=700,width="200",height="95") jan8=Button(text="3",font=("Times New Roman",30),background="white",foreground="red") jan8.place(x=460,y=100,width="200",height="95") jan9=Button(text="4",font=("Times New Roman",30),background="white") jan9.place(x=460,y=200,width="200",height="95") jan10=Button(text="5",font=("Times New Roman",30),background="white") jan10.place(x=460,y=300,width="200",height="95") jan11=Button(text="6",font=("Times New Roman",30),background="white") jan11.place(x=460,y=400,width="200",height="95") jan12=Button(text="7",font=("Times New Roman",30),background="white") jan12.place(x=460,y=500,width="200",height="95") jan13=Button(text="8",font=("Times New Roman",30),background="white") jan13.place(x=460,y=600,width="200",height="95") jan14=Button(text="9",font=("Times New Roman",30),background="white") jan14.place(x=460,y=700,width="200",height="95") jan15=Button(text="10",font=("Times New Roman",30),background="white",foreground="red") jan15.place(x=660,y=100,width="200",height="95") jan16=Button(text="11",font=("Times New Roman",30),background="white") jan16.place(x=660,y=200,width="200",height="95") jan17=Button(text="12",font=("Times New Roman",30),background="white") jan17.place(x=660,y=300,width="200",height="95") jan18=Button(text="13",font=("Times New Roman",30),background="white") jan18.place(x=660,y=400,width="200",height="95") jan19=Button(text="14",font=("Times New Roman",30),background="white") jan19.place(x=660,y=500,width="200",height="95") jan20=Button(text="15",font=("Times New Roman",30),background="white") jan20.place(x=660,y=600,width="200",height="95") jan21=Button(text="16",font=("Times New Roman",30),background="white") jan21.place(x=660,y=700,width="200",height="95") jan22=Button(text="17",font=("Times New Roman",30),background="white",foreground="red") jan22.place(x=860,y=100,width="200",height="95") jan23=Button(text="18",font=("Times New Roman",30),background="white") jan23.place(x=860,y=200,width="200",height="95") jan24=Button(text="19",font=("Times New Roman",30),background="white") jan24.place(x=860,y=300,width="200",height="95") jan25=Button(text="20",font=("Times New Roman",30),background="white") jan25.place(x=860,y=400,width="200",height="95") jan26=Button(text="21",font=("Times New Roman",30),background="white") jan26.place(x=860,y=500,width="200",height="95") jan27=Button(text="22",font=("Times New Roman",30),background="white") jan27.place(x=860,y=600,width="200",height="95") jan28=Button(text="23",font=("Times New Roman",30),background="white") jan28.place(x=860,y=700,width="200",height="95") jan29=Button(text="24",font=("Times New Roman",30),background="white",foreground="red") jan29.place(x=1060,y=100,width="200",height="95") jan30=Button(text="25",font=("Times New Roman",30),background="white") jan30.place(x=1060,y=200,width="200",height="95") jan31=Button(text="26",font=("Times New Roman",30),background="white") jan31.place(x=1060,y=300,width="200",height="95") jan32=Button(text="27",font=("Times New Roman",30),background="white") jan32.place(x=1060,y=400,width="200",height="95") jan33=Button(text="28",font=("Times New Roman",30),background="white") jan33.place(x=1060,y=500,width="200",height="95") jan34=Button(text="29",font=("Times New Roman",30),background="white") jan34.place(x=1060,y=600,width="200",height="95") jan35=Button(text="30",font=("Times New Roman",30),background="white") jan35.place(x=1060,y=700,width="200",height="95") def june(): January=Button(text="JUNE",font=("Algerian",25),background="Orange") January.place(x=500,y=0,width="200",height="70") sun=Button(text="SUN",font=("Algerian",25),background="red") sun.place(x=155,y=100,width="100",height="95") Mon=Button(text="MON",font=("Algerian",25),background="yellow") Mon.place(x=155,y=200,width="100",height="95") Tue=Button(text="TUE",font=("Algerian",25),background="blue") Tue.place(x=155,y=300,width="100",height="95") Wed=Button(text="WED",font=("Algerian",25),background="pink") Wed.place(x=155,y=400,width="100",height="95") Thur=Button(text="THUR",font=("Algerian",25),background="violet") Thur.place(x=155,y=500,width="100",height="95") Fri=Button(text="FRI",font=("Algerian",25),background="purple") Fri.place(x=155,y=600,width="100",height="95") Sat=Button(text="SAT",font=("Algerian",25),background="green") Sat.place(x=155,y=700,width="100",height="95") #Days jan1=Button(text="",font=("Times New Roman",30),background="white",foreground="red") jan1.place(x=260,y=100,width="200",height="95") jan2=Button(text="1",font=("Times New Roman",30),background="white") jan2.place(x=260,y=200,width="200",height="95") jan3=Button(text="2",font=("Times New Roman",30),background="white") jan3.place(x=260,y=300,width="200",height="95") jan4=Button(text="3",font=("Times New Roman",30),background="white") jan4.place(x=260,y=400,width="200",height="95") jan5=Button(text="4",font=("Times New Roman",30),background="white") jan5.place(x=260,y=500,width="200",height="95") jan6=Button(text="5",font=("Times New Roman",30),background="white") jan6.place(x=260,y=600,width="200",height="95") jan7=Button(text="6",font=("Times New Roman",30),background="white") jan7.place(x=260,y=700,width="200",height="95") jan8=Button(text="7",font=("Times New Roman",30),background="white",foreground="red") jan8.place(x=460,y=100,width="200",height="95") jan9=Button(text="8",font=("Times New Roman",30),background="white") jan9.place(x=460,y=200,width="200",height="95") jan10=Button(text="9",font=("Times New Roman",30),background="white") jan10.place(x=460,y=300,width="200",height="95") jan11=Button(text="10",font=("Times New Roman",30),background="white") jan11.place(x=460,y=400,width="200",height="95") jan12=Button(text="11",font=("Times New Roman",30),background="white") jan12.place(x=460,y=500,width="200",height="95") jan13=Button(text="12",font=("Times New Roman",30),background="white") jan13.place(x=460,y=600,width="200",height="95") jan14=Button(text="13",font=("Times New Roman",30),background="white") jan14.place(x=460,y=700,width="200",height="95") jan15=Button(text="14",font=("Times New Roman",30),background="white",foreground="red") jan15.place(x=660,y=100,width="200",height="95") jan16=Button(text="15",font=("Times New Roman",30),background="white") jan16.place(x=660,y=200,width="200",height="95") jan17=Button(text="16",font=("Times New Roman",30),background="white") jan17.place(x=660,y=300,width="200",height="95") jan18=Button(text="17",font=("Times New Roman",30),background="white") jan18.place(x=660,y=400,width="200",height="95") jan19=Button(text="18",font=("Times New Roman",30),background="white") jan19.place(x=660,y=500,width="200",height="95") jan20=Button(text="19",font=("Times New Roman",30),background="white") jan20.place(x=660,y=600,width="200",height="95") jan21=Button(text="20",font=("Times New Roman",30),background="white") jan21.place(x=660,y=700,width="200",height="95") jan22=Button(text="21",font=("Times New Roman",30),background="white",foreground="red") jan22.place(x=860,y=100,width="200",height="95") jan23=Button(text="22",font=("Times New Roman",30),background="white") jan23.place(x=860,y=200,width="200",height="95") jan24=Button(text="23",font=("Times New Roman",30),background="white") jan24.place(x=860,y=300,width="200",height="95") jan25=Button(text="24",font=("Times New Roman",30),background="white") jan25.place(x=860,y=400,width="200",height="95") jan26=Button(text="25",font=("Times New Roman",30),background="white") jan26.place(x=860,y=500,width="200",height="95") jan27=Button(text="26",font=("Times New Roman",30),background="white") jan27.place(x=860,y=600,width="200",height="95") jan28=Button(text="27",font=("Times New Roman",30),background="white") jan28.place(x=860,y=700,width="200",height="95") jan29=Button(text="28",font=("Times New Roman",30),background="white",foreground="red") jan29.place(x=1060,y=100,width="200",height="95") jan30=Button(text="29",font=("Times New Roman",30),background="white") jan30.place(x=1060,y=200,width="200",height="95") jan31=Button(text="30",font=("Times New Roman",30),background="white") jan31.place(x=1060,y=300,width="200",height="95") jan32=Button(text="",font=("Times New Roman",30),background="white") jan32.place(x=1060,y=400,width="200",height="95") jan33=Button(text="",font=("Times New Roman",30),background="white") jan33.place(x=1060,y=500,width="200",height="95") jan34=Button(text="",font=("Times New Roman",30),background="white") jan34.place(x=1060,y=600,width="200",height="95") jan35=Button(text="",font=("Times New Roman",30),background="white") jan35.place(x=1060,y=700,width="200",height="95") def july(): January=Button(text="JULY",font=("Algerian",25),background="Orange") January.place(x=500,y=0,width="200",height="70") sun=Button(text="SUN",font=("Algerian",25),background="red") sun.place(x=155,y=100,width="100",height="95") Mon=Button(text="MON",font=("Algerian",25),background="yellow") Mon.place(x=155,y=200,width="100",height="95") Tue=Button(text="TUE",font=("Algerian",25),background="blue") Tue.place(x=155,y=300,width="100",height="95") Wed=Button(text="WED",font=("Algerian",25),background="pink") Wed.place(x=155,y=400,width="100",height="95") Thur=Button(text="THUR",font=("Algerian",25),background="violet") Thur.place(x=155,y=500,width="100",height="95") Fri=Button(text="FRI",font=("Algerian",25),background="purple") Fri.place(x=155,y=600,width="100",height="95") Sat=Button(text="SAT",font=("Algerian",25),background="green") Sat.place(x=155,y=700,width="100",height="95") #Days jan1=Button(text="",font=("Times New Roman",30),background="white",foreground="red") jan1.place(x=260,y=100,width="200",height="95") jan2=Button(text="",font=("Times New Roman",30),background="white") jan2.place(x=260,y=200,width="200",height="95") jan3=Button(text="",font=("Times New Roman",30),background="white") jan3.place(x=260,y=300,width="200",height="95") jan4=Button(text="1",font=("Times New Roman",30),background="white") jan4.place(x=260,y=400,width="200",height="95") jan5=Button(text="2",font=("Times New Roman",30),background="white") jan5.place(x=260,y=500,width="200",height="95") jan6=Button(text="3",font=("Times New Roman",30),background="white") jan6.place(x=260,y=600,width="200",height="95") jan7=Button(text="4",font=("Times New Roman",30),background="white") jan7.place(x=260,y=700,width="200",height="95") jan8=Button(text="5",font=("Times New Roman",30),background="white",foreground="red") jan8.place(x=460,y=100,width="200",height="95") jan9=Button(text="6",font=("Times New Roman",30),background="white") jan9.place(x=460,y=200,width="200",height="95") jan10=Button(text="7",font=("Times New Roman",30),background="white") jan10.place(x=460,y=300,width="200",height="95") jan11=Button(text="8",font=("Times New Roman",30),background="white") jan11.place(x=460,y=400,width="200",height="95") jan12=Button(text="9",font=("Times New Roman",30),background="white") jan12.place(x=460,y=500,width="200",height="95") jan13=Button(text="10",font=("Times New Roman",30),background="white") jan13.place(x=460,y=600,width="200",height="95") jan14=Button(text="11",font=("Times New Roman",30),background="white") jan14.place(x=460,y=700,width="200",height="95") jan15=Button(text="12",font=("Times New Roman",30),background="white",foreground="red") jan15.place(x=660,y=100,width="200",height="95") jan16=Button(text="13",font=("Times New Roman",30),background="white") jan16.place(x=660,y=200,width="200",height="95") jan17=Button(text="14",font=("Times New Roman",30),background="white") jan17.place(x=660,y=300,width="200",height="95") jan18=Button(text="15",font=("Times New Roman",30),background="white") jan18.place(x=660,y=400,width="200",height="95") jan19=Button(text="16",font=("Times New Roman",30),background="white") jan19.place(x=660,y=500,width="200",height="95") jan20=Button(text="17",font=("Times New Roman",30),background="white") jan20.place(x=660,y=600,width="200",height="95") jan21=Button(text="18",font=("Times New Roman",30),background="white") jan21.place(x=660,y=700,width="200",height="95") jan22=Button(text="19",font=("Times New Roman",30),background="white",foreground="red") jan22.place(x=860,y=100,width="200",height="95") jan23=Button(text="20",font=("Times New Roman",30),background="white") jan23.place(x=860,y=200,width="200",height="95") jan24=Button(text="21",font=("Times New Roman",30),background="white") jan24.place(x=860,y=300,width="200",height="95") jan25=Button(text="22",font=("Times New Roman",30),background="white") jan25.place(x=860,y=400,width="200",height="95") jan26=Button(text="23",font=("Times New Roman",30),background="white") jan26.place(x=860,y=500,width="200",height="95") jan27=Button(text="24",font=("Times New Roman",30),background="white") jan27.place(x=860,y=600,width="200",height="95") jan28=Button(text="25",font=("Times New Roman",30),background="white") jan28.place(x=860,y=700,width="200",height="95") jan29=Button(text="26",font=("Times New Roman",30),background="white",foreground="red") jan29.place(x=1060,y=100,width="200",height="95") jan30=Button(text="27",font=("Times New Roman",30),background="white") jan30.place(x=1060,y=200,width="200",height="95") jan31=Button(text="28",font=("Times New Roman",30),background="white") jan31.place(x=1060,y=300,width="200",height="95") jan32=Button(text="29",font=("Times New Roman",30),background="white") jan32.place(x=1060,y=400,width="200",height="95") jan33=Button(text="30",font=("Times New Roman",30),background="white") jan33.place(x=1060,y=500,width="200",height="95") jan34=Button(text="31",font=("Times New Roman",30),background="white") jan34.place(x=1060,y=600,width="200",height="95") jan35=Button(text="",font=("Times New Roman",30),background="white") jan35.place(x=1060,y=700,width="200",height="95") def august(): January=Button(text="AUGUST",font=("Algerian",25),background="Orange") January.place(x=500,y=0,width="200",height="70") #Week sun=Button(text="SUN",font=("Algerian",25),background="red") sun.place(x=155,y=100,width="100",height="95") Mon=Button(text="MON",font=("Algerian",25),background="yellow") Mon.place(x=155,y=200,width="100",height="95") Tue=Button(text="TUE",font=("Algerian",25),background="blue") Tue.place(x=155,y=300,width="100",height="95") Wed=Button(text="WED",font=("Algerian",25),background="pink") Wed.place(x=155,y=400,width="100",height="95") Thur=Button(text="THUR",font=("Algerian",25),background="violet") Thur.place(x=155,y=500,width="100",height="95") Fri=Button(text="FRI",font=("Algerian",25),background="purple") Fri.place(x=155,y=600,width="100",height="95") Sat=Button(text="SAT",font=("Algerian",25),background="green") Sat.place(x=155,y=700,width="100",height="95") #Days jan1=Button(text="30",font=("Times New Roman",30),background="white",foreground="red") jan1.place(x=260,y=100,width="200",height="95") jan2=Button(text="31",font=("Times New Roman",30),background="white") jan2.place(x=260,y=200,width="200",height="95") jan3=Button(text="",font=("Times New Roman",30),background="white") jan3.place(x=260,y=300,width="200",height="95") jan4=Button(text="",font=("Times New Roman",30),background="white") jan4.place(x=260,y=400,width="200",height="95") jan5=Button(text="",font=("Times New Roman",30),background="white") jan5.place(x=260,y=500,width="200",height="95") jan6=Button(text="",font=("Times New Roman",30),background="white") jan6.place(x=260,y=600,width="200",height="95") jan7=Button(text="1",font=("Times New Roman",30),background="white") jan7.place(x=260,y=700,width="200",height="95") jan8=Button(text="2",font=("Times New Roman",30),background="white",foreground="red") jan8.place(x=460,y=100,width="200",height="95") jan9=Button(text="3",font=("Times New Roman",30),background="white") jan9.place(x=460,y=200,width="200",height="95") jan10=Button(text="4",font=("Times New Roman",30),background="white") jan10.place(x=460,y=300,width="200",height="95") jan11=Button(text="5",font=("Times New Roman",30),background="white") jan11.place(x=460,y=400,width="200",height="95") jan12=Button(text="6",font=("Times New Roman",30),background="white") jan12.place(x=460,y=500,width="200",height="95") jan13=Button(text="7",font=("Times New Roman",30),background="white") jan13.place(x=460,y=600,width="200",height="95") jan14=Button(text="8",font=("Times New Roman",30),background="white") jan14.place(x=460,y=700,width="200",height="95") jan15=Button(text="9",font=("Times New Roman",30),background="white",foreground="red") jan15.place(x=660,y=100,width="200",height="95") jan16=Button(text="10",font=("Times New Roman",30),background="white") jan16.place(x=660,y=200,width="200",height="95") jan17=Button(text="11",font=("Times New Roman",30),background="white") jan17.place(x=660,y=300,width="200",height="95") jan18=Button(text="12",font=("Times New Roman",30),background="white") jan18.place(x=660,y=400,width="200",height="95") jan19=Button(text="13",font=("Times New Roman",30),background="white") jan19.place(x=660,y=500,width="200",height="95") jan20=Button(text="14",font=("Times New Roman",30),background="white") jan20.place(x=660,y=600,width="200",height="95") jan21=Button(text="15",font=("Times New Roman",30),background="white",foreground="red") jan21.place(x=660,y=700,width="200",height="95") jan22=Button(text="16",font=("Times New Roman",30),background="white",foreground="red") jan22.place(x=860,y=100,width="200",height="95") jan23=Button(text="17",font=("Times New Roman",30),background="white") jan23.place(x=860,y=200,width="200",height="95") jan24=Button(text="18",font=("Times New Roman",30),background="white") jan24.place(x=860,y=300,width="200",height="95") jan25=Button(text="19",font=("Times New Roman",30),background="white") jan25.place(x=860,y=400,width="200",height="95") jan26=Button(text="20",font=("Times New Roman",30),background="white",foreground="purple") jan26.place(x=860,y=500,width="200",height="95") jan27=Button(text="21",font=("Times New Roman",30),background="white") jan27.place(x=860,y=600,width="200",height="95") jan28=Button(text="22",font=("Times New Roman",30),background="white") jan28.place(x=860,y=700,width="200",height="95") jan29=Button(text="23",font=("Times New Roman",30),background="white",foreground="red") jan29.place(x=1060,y=100,width="200",height="95") jan30=Button(text="24",font=("Times New Roman",30),background="white") jan30.place(x=1060,y=200,width="200",height="95") jan31=Button(text="25",font=("Times New Roman",30),background="white") jan31.place(x=1060,y=300,width="200",height="95") jan32=Button(text="26",font=("Times New Roman",30),background="white") jan32.place(x=1060,y=400,width="200",height="95") jan33=Button(text="27",font=("Times New Roman",30),background="white") jan33.place(x=1060,y=500,width="200",height="95") jan34=Button(text="28",font=("Times New Roman",30),background="white") jan34.place(x=1060,y=600,width="200",height="95") jan35=Button(text="29",font=("Times New Roman",30),background="white") jan35.place(x=1060,y=700,width="200",height="95") def september(): January=Button(text="SEPTEMBER",font=("Algerian",25),background="Orange") January.place(x=500,y=0,width="200",height="70") sun=Button(text="SUN",font=("Algerian",25),background="red") sun.place(x=155,y=100,width="100",height="95") Mon=Button(text="MON",font=("Algerian",25),background="yellow") Mon.place(x=155,y=200,width="100",height="95") Tue=Button(text="TUE",font=("Algerian",25),background="blue") Tue.place(x=155,y=300,width="100",height="95") Wed=Button(text="WED",font=("Algerian",25),background="pink") Wed.place(x=155,y=400,width="100",height="95") Thur=Button(text="THUR",font=("Algerian",25),background="violet") Thur.place(x=155,y=500,width="100",height="95") Fri=Button(text="FRI",font=("Algerian",25),background="purple") Fri.place(x=155,y=600,width="100",height="95") Sat=Button(text="SAT",font=("Algerian",25),background="green") Sat.place(x=155,y=700,width="100",height="95") #Days jan1=Button(text="",font=("Times New Roman",30),background="white",foreground="red") jan1.place(x=260,y=100,width="200",height="95") jan2=Button(text="",font=("Times New Roman",30),background="white") jan2.place(x=260,y=200,width="200",height="95") jan3=Button(text="1",font=("Times New Roman",30),background="white") jan3.place(x=260,y=300,width="200",height="95") jan4=Button(text="2",font=("Times New Roman",30),background="white") jan4.place(x=260,y=400,width="200",height="95") jan5=Button(text="3",font=("Times New Roman",30),background="white") jan5.place(x=260,y=500,width="200",height="95") jan6=Button(text="4",font=("Times New Roman",30),background="white") jan6.place(x=260,y=600,width="200",height="95") jan7=Button(text="5",font=("Times New Roman",30),background="white") jan7.place(x=260,y=700,width="200",height="95") jan8=Button(text="6",font=("Times New Roman",30),background="white",foreground="red") jan8.place(x=460,y=100,width="200",height="95") jan9=Button(text="7",font=("Times New Roman",30),background="white") jan9.place(x=460,y=200,width="200",height="95") jan10=Button(text="8",font=("Times New Roman",30),background="white") jan10.place(x=460,y=300,width="200",height="95") jan11=Button(text="9",font=("Times New Roman",30),background="white") jan11.place(x=460,y=400,width="200",height="95") jan12=Button(text="10",font=("Times New Roman",30),background="white") jan12.place(x=460,y=500,width="200",height="95") jan13=Button(text="11",font=("Times New Roman",30),background="white") jan13.place(x=460,y=600,width="200",height="95") jan14=Button(text="12",font=("Times New Roman",30),background="white") jan14.place(x=460,y=700,width="200",height="95") jan15=Button(text="13",font=("Times New Roman",30),background="white",foreground="red") jan15.place(x=660,y=100,width="200",height="95") jan16=Button(text="14",font=("Times New Roman",30),background="white") jan16.place(x=660,y=200,width="200",height="95") jan17=Button(text="15",font=("Times New Roman",30),background="white") jan17.place(x=660,y=300,width="200",height="95") jan18=Button(text="16",font=("Times New Roman",30),background="white") jan18.place(x=660,y=400,width="200",height="95") jan19=Button(text="17",font=("Times New Roman",30),background="white") jan19.place(x=660,y=500,width="200",height="95") jan20=Button(text="18",font=("Times New Roman",30),background="white") jan20.place(x=660,y=600,width="200",height="95") jan21=Button(text="19",font=("Times New Roman",30),background="white") jan21.place(x=660,y=700,width="200",height="95") jan22=Button(text="20",font=("Times New Roman",30),background="white",foreground="red") jan22.place(x=860,y=100,width="200",height="95") jan23=Button(text="21",font=("Times New Roman",30),background="white") jan23.place(x=860,y=200,width="200",height="95") jan24=Button(text="22",font=("Times New Roman",30),background="white") jan24.place(x=860,y=300,width="200",height="95") jan25=Button(text="23",font=("Times New Roman",30),background="white") jan25.place(x=860,y=400,width="200",height="95") jan26=Button(text="24",font=("Times New Roman",30),background="white") jan26.place(x=860,y=500,width="200",height="95") jan27=Button(text="25",font=("Times New Roman",30),background="white") jan27.place(x=860,y=600,width="200",height="95") jan28=Button(text="26",font=("Times New Roman",30),background="white") jan28.place(x=860,y=700,width="200",height="95") jan29=Button(text="27",font=("Times New Roman",30),background="white",foreground="red") jan29.place(x=1060,y=100,width="200",height="95") jan30=Button(text="28",font=("Times New Roman",30),background="white") jan30.place(x=1060,y=200,width="200",height="95") jan31=Button(text="29",font=("Times New Roman",30),background="white") jan31.place(x=1060,y=300,width="200",height="95") jan32=Button(text="30",font=("Times New Roman",30),background="white") jan32.place(x=1060,y=400,width="200",height="95") jan33=Button(text="",font=("Times New Roman",30),background="white") jan33.place(x=1060,y=500,width="200",height="95") jan34=Button(text="",font=("Times New Roman",30),background="white") jan34.place(x=1060,y=600,width="200",height="95") jan35=Button(text="",font=("Times New Roman",30),background="white") jan35.place(x=1060,y=700,width="200",height="95") def october(): January=Button(text="OCTOBER",font=("Algerian",25),background="Orange") January.place(x=500,y=0,width="200",height="70") sun=Button(text="SUN",font=("Algerian",25),background="red") sun.place(x=155,y=100,width="100",height="95") Mon=Button(text="MON",font=("Algerian",25),background="yellow") Mon.place(x=155,y=200,width="100",height="95") Tue=Button(text="TUE",font=("Algerian",25),background="blue") Tue.place(x=155,y=300,width="100",height="95") Wed=Button(text="WED",font=("Algerian",25),background="pink") Wed.place(x=155,y=400,width="100",height="95") Thur=Button(text="THUR",font=("Algerian",25),background="violet") Thur.place(x=155,y=500,width="100",height="95") Fri=Button(text="FRI",font=("Algerian",25),background="purple") Fri.place(x=155,y=600,width="100",height="95") Sat=Button(text="SAT",font=("Algerian",25),background="green") Sat.place(x=155,y=700,width="100",height="95") #Days jan1=Button(text="",font=("Times New Roman",30),background="white",foreground="red") jan1.place(x=260,y=100,width="200",height="95") jan2=Button(text="",font=("Times New Roman",30),background="white") jan2.place(x=260,y=200,width="200",height="95") jan3=Button(text="",font=("Times New Roman",30),background="white") jan3.place(x=260,y=300,width="200",height="95") jan4=Button(text="",font=("Times New Roman",30),background="white") jan4.place(x=260,y=400,width="200",height="95") jan5=Button(text="1",font=("Times New Roman",30),background="white") jan5.place(x=260,y=500,width="200",height="95") jan6=Button(text="2",font=("Times New Roman",30),background="white") jan6.place(x=260,y=600,width="200",height="95") jan7=Button(text="3",font=("Times New Roman",30),background="white") jan7.place(x=260,y=700,width="200",height="95") jan8=Button(text="4",font=("Times New Roman",30),background="white",foreground="red") jan8.place(x=460,y=100,width="200",height="95") jan9=Button(text="5",font=("Times New Roman",30),background="white") jan9.place(x=460,y=200,width="200",height="95") jan10=Button(text="6",font=("Times New Roman",30),background="white") jan10.place(x=460,y=300,width="200",height="95") jan11=Button(text="7",font=("Times New Roman",30),background="white") jan11.place(x=460,y=400,width="200",height="95") jan12=Button(text="8",font=("Times New Roman",30),background="white") jan12.place(x=460,y=500,width="200",height="95") jan13=Button(text="9",font=("Times New Roman",30),background="white") jan13.place(x=460,y=600,width="200",height="95") jan14=Button(text="10",font=("Times New Roman",30),background="white") jan14.place(x=460,y=700,width="200",height="95") jan15=Button(text="11",font=("Times New Roman",30),background="white",foreground="red") jan15.place(x=660,y=100,width="200",height="95") jan16=Button(text="12",font=("Times New Roman",30),background="white") jan16.place(x=660,y=200,width="200",height="95") jan17=Button(text="13",font=("Times New Roman",30),background="white") jan17.place(x=660,y=300,width="200",height="95") jan18=Button(text="14",font=("Times New Roman",30),background="white") jan18.place(x=660,y=400,width="200",height="95") jan19=Button(text="15",font=("Times New Roman",30),background="white") jan19.place(x=660,y=500,width="200",height="95") jan20=Button(text="16",font=("Times New Roman",30),background="white") jan20.place(x=660,y=600,width="200",height="95") jan21=Button(text="17",font=("Times New Roman",30),background="white") jan21.place(x=660,y=700,width="200",height="95") jan22=Button(text="18",font=("Times New Roman",30),background="white",foreground="red") jan22.place(x=860,y=100,width="200",height="95") jan23=Button(text="19",font=("Times New Roman",30),background="white") jan23.place(x=860,y=200,width="200",height="95") jan24=Button(text="20",font=("Times New Roman",30),background="white") jan24.place(x=860,y=300,width="200",height="95") jan25=Button(text="21",font=("Times New Roman",30),background="white") jan25.place(x=860,y=400,width="200",height="95") jan26=Button(text="22",font=("Times New Roman",30),background="white") jan26.place(x=860,y=500,width="200",height="95") jan27=Button(text="23",font=("Times New Roman",30),background="white") jan27.place(x=860,y=600,width="200",height="95") jan28=Button(text="24",font=("Times New Roman",30),background="white") jan28.place(x=860,y=700,width="200",height="95") jan29=Button(text="25",font=("Times New Roman",30),background="white",foreground="red") jan29.place(x=1060,y=100,width="200",height="95") jan30=Button(text="26",font=("Times New Roman",30),background="white") jan30.place(x=1060,y=200,width="200",height="95") jan31=Button(text="27",font=("Times New Roman",30),background="white") jan31.place(x=1060,y=300,width="200",height="95") jan32=Button(text="28",font=("Times New Roman",30),background="white") jan32.place(x=1060,y=400,width="200",height="95") jan33=Button(text="29",font=("Times New Roman",30),background="white") jan33.place(x=1060,y=500,width="200",height="95") jan34=Button(text="30",font=("Times New Roman",30),background="white") jan34.place(x=1060,y=600,width="200",height="95") jan35=Button(text="31",font=("Times New Roman",30),background="white") jan35.place(x=1060,y=700,width="200",height="95") def november(): January=Button(text="NOVEMBER",font=("Algerian",25),background="Orange") January.place(x=500,y=0,width="200",height="70") sun=Button(text="SUN",font=("Algerian",25),background="red") sun.place(x=155,y=100,width="100",height="95") Mon=Button(text="MON",font=("Algerian",25),background="yellow") Mon.place(x=155,y=200,width="100",height="95") Tue=Button(text="TUE",font=("Algerian",25),background="blue") Tue.place(x=155,y=300,width="100",height="95") Wed=Button(text="WED",font=("Algerian",25),background="pink") Wed.place(x=155,y=400,width="100",height="95") Thur=Button(text="THUR",font=("Algerian",25),background="violet") Thur.place(x=155,y=500,width="100",height="95") Fri=Button(text="FRI",font=("Algerian",25),background="purple") Fri.place(x=155,y=600,width="100",height="95") Sat=Button(text="SAT",font=("Algerian",25),background="green") Sat.place(x=155,y=700,width="100",height="95") #Days jan1=Button(text="1",font=("Times New Roman",30),background="white",foreground="red") jan1.place(x=260,y=100,width="200",height="95") jan2=Button(text="2",font=("Times New Roman",30),background="white") jan2.place(x=260,y=200,width="200",height="95") jan3=Button(text="3",font=("Times New Roman",30),background="white") jan3.place(x=260,y=300,width="200",height="95") jan4=Button(text="4",font=("Times New Roman",30),background="white") jan4.place(x=260,y=400,width="200",height="95") jan5=Button(text="5",font=("Times New Roman",30),background="white") jan5.place(x=260,y=500,width="200",height="95") jan6=Button(text="6",font=("Times New Roman",30),background="white") jan6.place(x=260,y=600,width="200",height="95") jan7=Button(text="7",font=("Times New Roman",30),background="white") jan7.place(x=260,y=700,width="200",height="95") jan8=Button(text="8",font=("Times New Roman",30),background="white",foreground="red") jan8.place(x=460,y=100,width="200",height="95") jan9=Button(text="9",font=("Times New Roman",30),background="white") jan9.place(x=460,y=200,width="200",height="95") jan10=Button(text="10",font=("Times New Roman",30),background="white") jan10.place(x=460,y=300,width="200",height="95") jan11=Button(text="11",font=("Times New Roman",30),background="white") jan11.place(x=460,y=400,width="200",height="95") jan12=Button(text="12",font=("Times New Roman",30),background="white") jan12.place(x=460,y=500,width="200",height="95") jan13=Button(text="13",font=("Times New Roman",30),background="white") jan13.place(x=460,y=600,width="200",height="95") jan14=Button(text="14",font=("Times New Roman",30),background="white") jan14.place(x=460,y=700,width="200",height="95") jan15=Button(text="15",font=("Times New Roman",30),background="white",foreground="red") jan15.place(x=660,y=100,width="200",height="95") jan16=Button(text="16",font=("Times New Roman",30),background="white") jan16.place(x=660,y=200,width="200",height="95") jan17=Button(text="17",font=("Times New Roman",30),background="white") jan17.place(x=660,y=300,width="200",height="95") jan18=Button(text="18",font=("Times New Roman",30),background="white") jan18.place(x=660,y=400,width="200",height="95") jan19=Button(text="19",font=("Times New Roman",30),background="white") jan19.place(x=660,y=500,width="200",height="95") jan20=Button(text="20",font=("Times New Roman",30),background="white") jan20.place(x=660,y=600,width="200",height="95") jan21=Button(text="21",font=("Times New Roman",30),background="white") jan21.place(x=660,y=700,width="200",height="95") jan22=Button(text="22",font=("Times New Roman",30),background="white",foreground="red") jan22.place(x=860,y=100,width="200",height="95") jan23=Button(text="23",font=("Times New Roman",30),background="white") jan23.place(x=860,y=200,width="200",height="95") jan24=Button(text="24",font=("Times New Roman",30),background="white") jan24.place(x=860,y=300,width="200",height="95") jan25=Button(text="25",font=("Times New Roman",30),background="white") jan25.place(x=860,y=400,width="200",height="95") jan26=Button(text="26",font=("Times New Roman",30),background="white") jan26.place(x=860,y=500,width="200",height="95") jan27=Button(text="27",font=("Times New Roman",30),background="white") jan27.place(x=860,y=600,width="200",height="95") jan28=Button(text="28",font=("Times New Roman",30),background="white") jan28.place(x=860,y=700,width="200",height="95") jan29=Button(text="29",font=("Times New Roman",30),background="white",foreground="red") jan29.place(x=1060,y=100,width="200",height="95") jan30=Button(text="30",font=("Times New Roman",30),background="white") jan30.place(x=1060,y=200,width="200",height="95") jan31=Button(text="",font=("Times New Roman",30),background="white") jan31.place(x=1060,y=300,width="200",height="95") jan32=Button(text="",font=("Times New Roman",30),background="white") jan32.place(x=1060,y=400,width="200",height="95") jan33=Button(text="",font=("Times New Roman",30),background="white") jan33.place(x=1060,y=500,width="200",height="95") jan34=Button(text="",font=("Times New Roman",30),background="white") jan34.place(x=1060,y=600,width="200",height="95") jan35=Button(text="",font=("Times New Roman",30),background="white") jan35.place(x=1060,y=700,width="200",height="95") def december(): January=Button(text="DECEMBER",font=("Algerian",25),background="Orange") January.place(x=500,y=0,width="200",height="70") sun=Button(text="SUN",font=("Algerian",25),background="red") sun.place(x=155,y=100,width="100",height="95") Mon=Button(text="MON",font=("Algerian",25),background="yellow") Mon.place(x=155,y=200,width="100",height="95") Tue=Button(text="TUE",font=("Algerian",25),background="blue") Tue.place(x=155,y=300,width="100",height="95") Wed=Button(text="WED",font=("Algerian",25),background="pink") Wed.place(x=155,y=400,width="100",height="95") Thur=Button(text="THUR",font=("Algerian",25),background="violet") Thur.place(x=155,y=500,width="100",height="95") Fri=Button(text="FRI",font=("Algerian",25),background="purple") Fri.place(x=155,y=600,width="100",height="95") Sat=Button(text="SAT",font=("Algerian",25),background="green") Sat.place(x=155,y=700,width="100",height="95") #Days jan1=Button(text="",font=("Times New Roman",30),background="white",foreground="red") jan1.place(x=260,y=100,width="200",height="95") jan2=Button(text="",font=("Times New Roman",30),background="white") jan2.place(x=260,y=200,width="200",height="95") jan3=Button(text="1",font=("Times New Roman",30),background="white") jan3.place(x=260,y=300,width="200",height="95") jan4=Button(text="2",font=("Times New Roman",30),background="white") jan4.place(x=260,y=400,width="200",height="95") jan5=Button(text="3",font=("Times New Roman",30),background="white") jan5.place(x=260,y=500,width="200",height="95") jan6=Button(text="4",font=("Times New Roman",30),background="white") jan6.place(x=260,y=600,width="200",height="95") jan7=Button(text="5",font=("Times New Roman",30),background="white") jan7.place(x=260,y=700,width="200",height="95") jan8=Button(text="6",font=("Times New Roman",30),background="white",foreground="red") jan8.place(x=460,y=100,width="200",height="95") jan9=Button(text="7",font=("Times New Roman",30),background="white") jan9.place(x=460,y=200,width="200",height="95") jan10=Button(text="8",font=("Times New Roman",30),background="white") jan10.place(x=460,y=300,width="200",height="95") jan11=Button(text="9",font=("Times New Roman",30),background="white") jan11.place(x=460,y=400,width="200",height="95") jan12=Button(text="10",font=("Times New Roman",30),background="white") jan12.place(x=460,y=500,width="200",height="95") jan13=Button(text="11",font=("Times New Roman",30),background="white") jan13.place(x=460,y=600,width="200",height="95") jan14=Button(text="12",font=("Times New Roman",30),background="white") jan14.place(x=460,y=700,width="200",height="95") jan15=Button(text="13",font=("Times New Roman",30),background="white",foreground="red") jan15.place(x=660,y=100,width="200",height="95") jan16=Button(text="14",font=("Times New Roman",30),background="white") jan16.place(x=660,y=200,width="200",height="95") jan17=Button(text="15",font=("Times New Roman",30),background="white") jan17.place(x=660,y=300,width="200",height="95") jan18=Button(text="16",font=("Times New Roman",30),background="white") jan18.place(x=660,y=400,width="200",height="95") jan19=Button(text="17",font=("Times New Roman",30),background="white") jan19.place(x=660,y=500,width="200",height="95") jan20=Button(text="18",font=("Times New Roman",30),background="white") jan20.place(x=660,y=600,width="200",height="95") jan21=Button(text="19",font=("Times New Roman",30),background="white") jan21.place(x=660,y=700,width="200",height="95") jan22=Button(text="20",font=("Times New Roman",30),background="white",foreground="red") jan22.place(x=860,y=100,width="200",height="95") jan23=Button(text="21",font=("Times New Roman",30),background="white") jan23.place(x=860,y=200,width="200",height="95") jan24=Button(text="22",font=("Times New Roman",30),background="white") jan24.place(x=860,y=300,width="200",height="95") jan25=Button(text="23",font=("Times New Roman",30),background="white") jan25.place(x=860,y=400,width="200",height="95") jan26=Button(text="24",font=("Times New Roman",30),background="white") jan26.place(x=860,y=500,width="200",height="95") jan27=Button(text="25",font=("Times New Roman",30),background="white") jan27.place(x=860,y=600,width="200",height="95") jan28=Button(text="26",font=("Times New Roman",30),background="white") jan28.place(x=860,y=700,width="200",height="95") jan29=Button(text="27",font=("Times New Roman",30),background="white",foreground="red") jan29.place(x=1060,y=100,width="200",height="95") jan30=Button(text="28",font=("Times New Roman",30),background="white") jan30.place(x=1060,y=200,width="200",height="95") jan31=Button(text="29",font=("Times New Roman",30),background="white") jan31.place(x=1060,y=300,width="200",height="95") jan32=Button(text="30",font=("Times New Roman",30),background="white") jan32.place(x=1060,y=400,width="200",height="95") jan33=Button(text="31",font=("Times New Roman",30),background="white") jan33.place(x=1060,y=500,width="200",height="95") jan34=Button(text="",font=("Times New Roman",30),background="white") jan34.place(x=1060,y=600,width="200",height="95") jan35=Button(text="",font=("Times New Roman",30),background="white") jan35.place(x=1060,y=700,width="200",height="95") #MONTH b0=Button(text="2020",font=("",25),background="Blue",foreground="white") b0.place(x=700,y=0,width="150",height="70") b1=Button(text="January",font=("",25),background="grey",foreground="white",activebackground="pink",activeforeground="purple",command=january) b1.place(x=0,y=0,width="150",height="65") b2=Button(text="February",font=("",25),background="grey",foreground="white",activebackground="pink",activeforeground="purple",command=february) b2.place(x=0,y=65,width="150",height="65") b3=Button(text="March",font=("",25),background="grey",foreground="white",activebackground="pink",activeforeground="purple",command=march) b3.place(x=0,y=130,width="150",height="65") b4=Button(text="April",font=("",25),background="grey",foreground="white",activebackground="pink",activeforeground="purple",command=april) b4.place(x=0,y=195,width="150",height="65") b5=Button(text="May",font=("",25),background="grey",foreground="white",activebackground="pink",activeforeground="purple",command=may) b5.place(x=0,y=260,width="150",height="65") b6=Button(text="June",font=("",25),background="grey",foreground="white",activebackground="pink",activeforeground="purple",command=june) b6.place(x=0,y=325,width="150",height="65") b7=Button(text="July",font=("",25),background="grey",foreground="white",activebackground="pink",activeforeground="purple",command=july) b7.place(x=0,y=390,width="150",height="65") b8=Button(text="August",font=("",25),background="grey",foreground="white",activebackground="pink",activeforeground="purple",command=august) b8.place(x=0,y=455,width="150",height="65") b9=Button(text="September",font=("",25),background="grey",foreground="white",activebackground="pink",activeforeground="purple",command=september) b9.place(x=0,y=520,width="150",height="65") b10=Button(text="October",font=("",25),background="grey",foreground="white",activebackground="pink",activeforeground="purple",command=october) b10.place(x=0,y=585,width="150",height="65") b11=Button(text="November",font=("",25),background="grey",foreground="white",activebackground="pink",activeforeground="purple",command=november) b11.place(x=0,y=650,width="150",height="65") b12=Button(text="December",font=("",25),background="grey",foreground="white",activebackground="pink",activeforeground="purple",command=december) b12.place(x=0,y=715,width="150",height="65") t.mainloop()
2ea33d9ddddb918a3489fab0186fe17488c12805
Constantine19/leetcode
/922-Sort-Array-By-Parity-II.py
433
3.71875
4
def sortArrayByParityII(A): """ :type A: List[int] :rtype: List[int] """ odd = 1 even = 0 combined = [] for i in range(len(A)): combined.append(0) for i in range(len(A)): if A[i] % 2 == 0: combined[even] = A[i] even += 2 else: combined[odd] = A[i] odd += 2 return combined A = [4, 2, 5, 7] print sortArrayByParityII(A)
2ff68d9e460387b855a676a7c8c1f0646b101758
Constantine19/leetcode
/1004-Max-Consecutive-Ones-III.py
286
3.578125
4
def longestOnes(a): count = 0 result = [] for i in range(len(a)): if a[i] == 1: count += 1 else: result.append(count) count = 0 return max(result) a = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0] # K = 2 print longestOnes(a)
9abf4ee9238f0b612e51526bf54074150fa6524d
Constantine19/leetcode
/058-Length-of-Last-Word.py
175
3.90625
4
def lengthOfLastWord(s): my_list = s.split() if len(my_list) <= 0: return 0 else: return len(my_list[-1]) s = "Hellou j" print lengthOfLastWord(s)
98e2ad4171682a02c558d00b245a512c71190412
Constantine19/leetcode
/268-Missing-Number.py
135
3.734375
4
def missingNumber(nums): n = len(nums) # 5 return n * (n+1) / 2 - sum(nums) nums = [0, 1, 2, 4, 5] print missingNumber(nums)
156e9d178477dbb770d537ced639272ea6f16d23
Constantine19/leetcode
/844-Backspace-String-Compare.py
445
3.625
4
def backspaceCompare(S, T): def process(my_str): result = [] for i in range(len(my_str)): if my_str[i] == "#": if len(result) == 0: continue else: result.pop() else: result.append(my_str[i]) return ''.join(result) return process(S) == process(T) S = "a##c" T = "c#d#" print backspaceCompare(S, T)
274b2160ffc8c41e5a6aca576e0b23085175ac37
Constantine19/leetcode
/389-Find-the-Difference.py
206
3.828125
4
def findTheDifference(s, t): s_set = set(s) t_set = set(t) result = "" for i in t_set - s_set: result += i return result s = "abcd" t = "abcde" print findTheDifference(s, t)
7dd21306bac85d6d6e00e20f3233befde0564c7c
Constantine19/leetcode
/819-Most-Common-Word.py
601
3.671875
4
def mostCommonWord(paragraph, banned): #words = paragraph.replace(',', '').replace('.', '').replace("!", "").lower().split() counts = {} for i in paragraph.split(','): print i # for i in range(len(words)): # if words[i] not in counts: # counts[words[i]] = 1 # else: # counts[words[i]] += 1 # # for key in counts.keys(): # if key in banned: # del counts[key] # # return (max(counts, key=counts.get)) paragraph = "a, a, a, a, b, b, b, c, c" banned = ["a"] print mostCommonWord(paragraph, banned)
fea65472badbeade0825992ec9937ca95410dbbe
stan-alam/Python
/algo/src/BubbleSort.py
464
4
4
#!/usr/bin/python import sys def sort(array): length = len(array) for i in range(0, length - 1): for j in range(0, length - 1): if array[j] > array[ j + 1 ]: tag = array[j] array[j] = array[j + 1] array[j + 1] = tag def main(): grades = [85, 90, 65, 70, 92, 97] sort(grades) for grade in grades: print(grade, ", ", end = "") if __name__ == "__main__": main()
29f6a4560eb8e0e8dce2188a22a5f960b60a1e76
CZHerrington/day-2-python
/bonus_challenge_histogram.py
869
4.03125
4
sentence_list = str(input('please enter a sentence: ')).split(' ') def generate_histogram(sentence): word_hist_dict = {} for word in sentence_list: try: word_hist_dict[word] except: word_hist_dict[word] = 0 finally: word_hist_dict[word] += 1 return word_hist_dict # only return top 3 words def process_histogram(histogram): res = {} i = 0 while i < 3: ref = 0 for word in histogram: if histogram[word] > ref: ref = histogram[word] for word in histogram: if histogram[word] == ref: res[word] = ref histogram[word] = 0 break i += 1 return res print( "top 3 most common words:\n", process_histogram( generate_histogram(sentence_list) ) )
09d289eae36e1e9e5513e51391e8403060e05f0f
dbolshak/ml
/python-scripts/load_iris.py
1,601
3.671875
4
from sklearn.datasets import load_iris iris_dataset = load_iris() ''' The data itself is contained in the target and data fields. data contains the numeric measurements of sepal length, sepal width, petal length, and petal width in a NumPy array ''' print("dir on iris_dataset: \n{}".format(dir(iris_dataset))) print("Keys of iris_dataset: \n{}".format(iris_dataset.keys())) print("Value of the DESCR key:\n{}".format(iris_dataset['DESCR'][:193] + "\n...")) print("Target names: {}".format(iris_dataset['target_names'])) print("Feature names: \n{}".format(iris_dataset['feature_names'])) print("Type of data: {}".format(type(iris_dataset['data']))) print("Type of target: {}".format(type(iris_dataset['target']))) ''' The rows in the data array correspond to flowers, while the columns represent the four measurements that were taken for each flower: ''' print("Shape of data: {}".format(iris_dataset['data'].shape)) print("Here are the feature values for the first five samples(five columns of data):\n{}".format(iris_dataset['data'][:5])) print("Target is a one-dimensional array, with one entry per flower.Shape of target: {}".format(iris_dataset['target'].shape)) print("Target:\n{}".format(iris_dataset['target'])) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( iris_dataset['data'], iris_dataset['target'], random_state = 0) print("X_train shape: {}".format(X_train.shape)) print("y_train shape: {}".format(y_train.shape)) print("X_test shape: {}".format(X_test.shape)) print("y_test shape: {}".format(y_test.shape))
7521bc35afaa483532901803d6da7e1ac6a17b2a
yuvipatil007/python_new
/day_8/day-8-2.py
446
3.53125
4
# Review: # Create a function called greet(). # Write 3 print statements inside the function. # Call the greet() function and run your code. # def greet(): # print("this is function") # print("this is greet function") # print("this call from outside") # greet() def greet_with(name,location): print(f"Hello {name}") print(f"what is it like in {location}") greet_with('yuvraj','mumbai') greet_with(location='mumbai',name='yuvraj')
fd76372728187bd13740d3c237db61671b8b5e4d
taebinjjang/Pre_KSA_Computer_Science_Python
/week3/function/python1.py
351
3.71875
4
import math def distance(x1, y1, x2, y2): u = (x2-x1)**2 v = (y2-y1)**2 return math.sqrt(u+v) def circleArea(radius): return math.pi * radius**2 def printCircleArea(radius): print(math.pi * radius**2) if __name__=='__main__': a = circleArea(10) b = distance(0, 0, 3, 4) printCircleArea(10) print(a) print(b)
55c5f0abb51029823c4e95203187a587a9d37df6
diana-okrut/by_nesusvet
/medium-kth_largest.py
770
3.90625
4
import heapq def kth_largest(numbers, k): """ See https://leetcode.com/problems/kth-largest-element-in-an-array/ >>> kth_largest([3, 2, 1, 5, 6, 4], 2) 5 >>> kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) 4 >>> kth_largest([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2) 9 >>> kth_largest([10, 9, 5, 6, 4, 7, 2, 1, 3, 8], 3) 8 >>> kth_largest([], 0) 0 >>> kth_largest([0, -10, 1, 2, 3, -5], 6) -10 """ if not numbers: return 0 result = [] for value in numbers: if len(result) != k: heapq.heappush(result, value) elif result[0] < value: heapq.heappushpop(result, value) return result[0] if __name__ == '__main__': import doctest doctest.testmod()
2f02541681935c442b6132e4ea2ad6a25be391d6
diana-okrut/by_nesusvet
/medium-facebook.py
1,395
4
4
def main(text: str) -> bool: """ Implement a function which will check if it is possible to build a valid palindrome from a sequence of letters. Only permutations are allowed. >>> main("anna") True >>> main("nana") True >>> main("nanam") True >>> main("dogo") False """ counting_by_letters = {} for i in text: counting_by_letters.setdefault(i, 0) counting_by_letters[i] += 1 counter = 0 for j in counting_by_letters.values(): if j % 2 != 0: counter += 1 if counter > 1: return False result = [] len_new_result = 0 for key, value in counting_by_letters.items(): len_new_result += value if value % 2 == 0: new_key = key * (value // 2) result.append(new_key) result.insert(0, new_key) elif (value % 2 != 0) and (value // 2 == 0): center = len(result) // 2 result = result[0:center] + [key] + result[center::] elif (value % 2 != 0) and (value // 2 != 0): new_key = key * (value // 2) result.append(new_key) result.insert(0, new_key) center = len(result) // 2 result = result[0:center] + [key] + result[center::] text_result = "".join(result) return text_result
ed2fbd0b2fb93871b3056f8508aae1befd44d0e2
diana-okrut/by_nesusvet
/easy-love-vs-friendship.py
313
3.609375
4
""" https://www.codewars.com/kata/love-vs-friendship/train/python """ import string def words_to_marks(word): alphabet = { char: i for i, char in enumerate(string.ascii_lowercase, start=1) } values = [alphabet[letter] for letter in word if letter in alphabet] return sum(values)
22539a3cdb2beba7629a7d01ed1918bb4106b9a6
realsungyoun/3.1-Informal-Intro-to-Python
/3.+An+informal+introduction+to+Python.py
7,600
4.34375
4
# coding: utf-8 # # 3.1 Using python as a calculator # ## 3.1.1. Numbers # Operators +, -, *, and / are normal, with () used for grouping. # # # In[8]: 2+2 # In[9]: 50 - 5*6 # In[10]: (50 - 5*6)/4 # In[11]: 8/5 # division always returns a floating point # Integer numbers have type int, fractional part have type float. # In[12]: 17/3 #float # In[13]: 17//3 #floor division discards fraction # In[14]: 17%3 #% operator returns remainder # In[15]: 5*3+2 #result * divisor +remainder # ** operator calculates powers # In[16]: 5**2 #5 squared # In[17]: 2**7 #2 to the power of 7 # In[18]: width = 20 height = 5*9 # If a variable is not assigned a value, it will error # In[19]: n # there is full support for floating poing (example: 5.66666); operators with mixed type operands convert the integer operand to floating point. # In[20]: 4* 3.75 -1 # last printe expression is assigned to the variable _. This means that when you are using python as a desk calculator, it is somewhat easier to continue calculations. # # In[22]: tax = 12.5/100 price = 100.5 price * tax # In[23]: price + _ #<- # In[24]: round(_, 2) #<- continues calculations by inserting previous output # In addition to int and float, python supports other types of numberes such as Decimal and Fraction. Python also has built-in support for complex numbers, and uses the j or J suffix to indicatethe imagineary part (e.g. 3+5j) # # ## 3.1.2. String # Manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ('...') or double quotes ("...") with the same result. \ can be used to escape quotes. # In[25]: 'spam eggs' # single quotes # In[27]: 'doesn\'t' #'\ escapes single quote # In[29]: '"Yes,"he said.' # In[30]: "\"Yes,\" he said." # In[31]: '"Isn\'t," she said.' # In[33]: '"Isn\'t," she said.' print('"Isn\'t," she said.') # In[34]: s = 'first line. \nSecond line.' # \n means new line s # In[35]: print(s) # In[36]: print('C:\some\name') # In[37]: print(r'C:\some\name') #r is raw springs # In[39]: print ("""Usage: thingy [OPTIONs] -h -H hostname """) # In[40]: 3*'un' +'ium' # In[43]: 'py''thon' # In[45]: text = ('Put several strings within parentheses''tohave them joined together.') text # In[46]: prefix = 'py' prefix 'thon' #can't concatenate a variable # In[47]: ('un' *3) 'ium' # In[50]: prefix = 'py' # In[51]: prefix +'thon' # Strings can be indexed (subscripted) with the first character having index 0. There is no seperate character type; a character is simply a string of size one. # In[52]: word = 'python' # In[53]: word[0] # In[54]: word[5] # In[55]: word [-1] # In[56]: word [-2] # In[57]: word[-6] # slicing allows you to obtain substring # In[58]: word[0:2] # In[59]: word[2:5] # s[:i]+s[i:]=s # In[62]: word[:2] # In[63]: word[4:] # In[64]: word[-2: ] # In[65]: word[42] # In[66]: word[4:42] # In[67]: word[42:] # Python strings are immutable # In[68]: word[0] = 'J' # In[69]: word[2:] # In[70]: 'J'+word[1:] # In[72]: word[:2]+'py' # len() returns the length of a string # In[75]: s = 'supercalifragilisticexpialidocious' # In[77]: len(s) # # ### Text Sequence Type — str # Strings are examples of sequence types, and support the common operations supported by such types. # ### String Methods # Strings support a large number of methods for basic transformations and searching. # ### Formatted string literals # String literals that have embedded expressions. # ### Format String Syntax # Information about string formatting with str.format(). # ### printf-style String Formatting # The old formatting operations invoked when strings are the left operand of the % operator are described in more detail here. # # 3.1.3 Lists # Lists can be written as a list of comma-seperated values between square brackets. # # In[78]: squares = [1,4,9,16,25] squares # In[79]: squares[0] #indexing # In[82]: squares [-1] #indexing # In[84]: squares [-3:] #slicing # In[85]: squares[:] #new shallow copy of list # In[86]: squares + [36,49, 64, 81, 100] # In[87]: cubes = [1, 8, 27, 65, 125] # In[88]: 4**3 # In[89]: cubes[3] = 64 #strings are immutable HOWEVR lists are mutable, meaning it is possible to change their content. # In[90]: cubes # In[91]: cubes.append(216) # In[92]: cubes.append(7**3) # In[93]: cubes # In[94]: letters = ['a','b','c','d','e','f','g'] # In[95]: letters # In[96]: letters[2:5] = ['C','D','E'] # In[97]: letters # In[98]: letters[2:5] = [] # In[99]: letters # In[102]: letters[:]=[] # [:]=[] replaces all elements # In[101]: letters # In[103]: letters = ['a','b','c','d'] # In[105]: len(letters) #len() counts how many in the list # It is possible to nest lists (create lists containing other lists) # In[106]: a = ['a','b','c'] n = [1,2,3] x = [a,n] x # In[107]: x[0] # In[108]: x[0][1] # ## 3.2. First steps towards programming # initial sub-sequence Fibonacci series # In[109]: a, b = 0,1 while a < 10: print (a) a, b = b, a+b # - first line contains a multiple assignment. on the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignents take place. The right-hand side expressions are evaluated from the left to the right. # - the while loop executes as long as the condition a<10 remains true. Any non-zero integer value is true, zero is false. The condition may also be a string or list value, in fact ay sequence; are false. The test used in the example isa simple comparison. The standard comparison operators are written the same as in C: < (less than), >(greater than), ==(equal to), <=(less than or equal to), >=(greater than or equal to) and !=(not equal to) # - the body of te loop is indented: indentation is python's way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively. it must be followed by a black line to indicate completion ( since the parser cannot guess when you have typed the last line.) Note that each line within a basic block must be indented by the same amount. # - The print() function writes the value of the arguents(s) it is given. It differs from just writing the expression yo want to write in the way it handles multiple arguments, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this: # In[110]: i = 256*256 print('The value of i is', i) # The keyword argument end can be used to avoid the newline after the output, or end the output with a different string. # In[112]: a, b = 0, 1 while a < 1000: print(a, ',') a, b = b, a+b # In[113]: a, b = 0,1 while a < 1000: print(a, end=',') a, b = b, a+b # # Footnotes: # 1. Since ** higher precedence than -, -3**2 will be -(3**2) result in -9. To avoid this and get 9, you can use (-3)**2 # 2. \n have the same meaning with both single '...' and double "..." quotes. The only difference between the two is that within single quotes you don't need to escape " ( but you have to escape \') and vice versa
8a71c83758318114c1ba91c8ff7ea461bc0f9933
workready/pythonbasic
/sources/t10/t10ej11.py
235
3.546875
4
import numpy as np A = np.array([[1, 2], [3, 4]]) A """ array([[1, 2], [3, 4]]) """ # Esto sería un puntero: si cambiamos B, A también cambia B = A # Esto sería una copia: si cambiamos B, A no cambia B = np.copy(A)
9cd21f87bf6287987e843ec94f090e5da367fbd3
workready/pythonbasic
/sources/t09/t09ej05.py
1,275
3.890625
4
# Corrutina def minimize(): try: # La primera vez que se llame a next(), el generador arrancará y se ejecutará hasta encontrar un yield. # La llamada a next() es equivalente a send(none), de manera que se guardará None en current, # y entonces parará, a esperas de la siguiente llamada current = yield # El resto de llamadas después del primer next() entrarán en el bucle. Con yield current recogemos el valor que nos llegue cada vez. while True: value = yield current current = min(value, current) except GeneratorExit: # Cuando alguien llame a close, implícita o explícitamente (ej: al terminar el programa), # se lanzará la excepción GeneratorExit dentro del generador. Por supuesto, nosotros # podemos capturar dicha excepción, y ejecutar cualquier tarea de limpieza necesaria dentro # de nuestro generador print("Terminando corrutina") # Construimos corrutina it = minimize() # La iniciamos next(it) # Le enviamos valores print(it.send(10)) # min: 10 print(it.send(1)) # min: 1 print(it.send(1055)) # min: 1 print(it.send(-4)) # min: -4 it.close() # Llamada explicita a close, aunque no es necesaria
027b9c9e4c7e54eff46c9c06dc8836dcea3f1fd0
workready/pythonbasic
/sources/t07/t07ej19.py
169
3.8125
4
# Ejemplo de uso de expresión lambda en Python a = [1, 2, 3] b = [4, 5, 6] suma_cuadrados = lambda x, y: x**2 + y**2 print([suma_cuadrados(x, y) for x, y in zip(a, b)])
270458e2e003680f78a0a3f2f4b17e0978554f1f
workready/pythonbasic
/sources/t03/t03ej18.py
681
3.828125
4
# pop devuelve el último elemento extraído, y clear elimina todos los elementos a_set = {1, 3, 6, 10, 15, 21, 28, 36, 45} print(a_set) # {1, 3, 6, 10, 15, 21, 28, 36, 45} a_set.pop() # 1 a_set.pop() # 3 a_set.clear() print(a_set) # set() # Discard y remove se diferencian en que, si el elemento no existe, remove lanza una excepcion y discard no a_set = {1, 3, 6, 10, 15, 21, 28, 36, 45} print(a_set) # {1, 3, 36, 6, 10, 45, 15, 21, 28} a_set.discard(10) print(a_set) # {1, 3, 36, 6, 45, 15, 21, 28} a_set.discard(10) print(a_set) # {1, 3, 36, 6, 45, 15, 21, 28} a_set.remove(21) print(a_set) # {1, 3, 36, 6, 45, 15, 28} a_set.remove(21) # Excepción
96885ba346fbe52f4a8b06675576076e22754726
workready/pythonbasic
/sources/t11/t11ej03.py
224
3.609375
4
import numpy as np import matplotlib.pyplot as plt def f(x): return np.exp(-x ** 2) x = np.linspace(-1, 3, 100) plt.plot(x, f(x), color='red', linestyle='', marker='o') plt.plot(x, 1 - f(x), c='g', ls='--') plt.show()
c282e4d0a3c4b12a4bb47981dde76d2685ad00e2
workready/pythonbasic
/sources/t12/t12ej09.py
144
3.578125
4
import numpy as np import pandas as pd df = pd.DataFrame(np.random.randn(3,4), index=['2','4','8'], columns=list('ABCD')) print(df) print(df.T)
fd0db944628970f8771143a1bdfb073edda6faca
workready/pythonbasic
/ejercicios_resueltos/t03/t03ejer05.py
578
3.8125
4
def sumatorio_tope(tope): """ Va sumando números naturales hasta llegar al tope. Ejemplos -------- >>> sumatorio_tope(9) 6 # 1 + 2 + 3 >>> sumatorio_tope(10) 10 # 1 + 2 + 3 + 4 >>> sumatorio_tope(12) 10 # 1 + 2 + 3 + 4 >>> sumatorio_tope(16) 15 # 1 + 2 + 3 + 4 + 5 """ s = 0 n = 1 while s + n <= tope: s += n n += 1 return s assert(sumatorio_tope(9) == 6) assert(sumatorio_tope(10) == 10) assert(sumatorio_tope(12) == 10) assert(sumatorio_tope(16) == 15)
901e7a3327f2da3817d48f0cd748031a7361c1ae
workready/pythonbasic
/sources/t06/t06ejer06.py
824
4.1875
4
class Item: pass # Tu codigo aqui. Estos son los elementos a guardar en las cajas class Box: pass # Tu codigo aqui. Esta clase va a actuar como abstracta class ListBox(Box): pass # Tu codigo aqui class DictBox(Box): pass # Tu codigo aqui # Esto prueba las clases i1 = Item("Item 1", 1) i2 = Item("Item 2", 2) i3 = Item("Item 3", 3) listbox = ListBox() dictbox = DictBox() listbox.add(i1, i2, i3) dictbox.add(i1) dictbox.add(i2) dictbox.add(i3) assert(listbox.count() == 3) assert(dictbox.count() == 3) for i in listbox.items(): print(i) for k, item in dictbox.items().items(): print(i) listbox.empty() dictbox.empty() assert(listbox.count() == 0) assert(dictbox.count() == 0) for i in listbox.items(): print(i) for k, item in dictbox.items().items(): print(i)
77cbc8d529d408766074baf0a80db7c5cd479861
workready/pythonbasic
/sources/t04/t04ej14.py
1,147
4
4
# Construir iterador para generar secuencia de Fibonacci import itertools class Fib: '''Iterador que genera la secuencia de Fibonacci''' # Constructor def __init__(self): self.prev = 0 self.curr = 1 # Esto es llamado cada vez que se llama a iter(Fib). Algo que for hace automáticamente, pero lo podríamos hacer a mano. # La función __iter__ debe devolver cualquier objeto que implemente __next__. En este caso, la propia clase def __iter__(self): return self # Esto es llamado cada vez que se llama a next(Fib). Algo que for hace automáticamente, pero lo podríamos hacer a mano. def __next__(self): value = self.curr self.curr += self.prev self.prev = value return value # f guarda un iterador. En este momento no se ha llamado a nada, solo se ha construido el iterador f = Fib() # Recorremos nuestro iterador, llamando a next(). Dentro del for se llama automáticamente a iter(f) print(0, end=' ') for n in range(16): print(next(f), end=' ') # Otra manera más elegante de hacerlo, con itertools #print([0] + list(itertools.islice(f, 0, 16)))
594505fb1c0e2dc163eefd6b23d996f7258a8783
workready/pythonbasic
/sources/t06/t06ej08.py
683
4.0625
4
# Python añadirá internamente el nombre de la clase delante de __baz class Foo(object): def __init__(self): self.__baz = 42 def foo(self): print(self.__baz) # Como el método __init__ empieza por __, en realidad será Bar__init__, y el del padre Foo__init__. Así existen por separado class Bar(Foo): def __init__(self): super().__init__() self.__baz = 21 def bar(self): print(self.__baz) x = Bar() x.foo() # 42, porque el método imprime Foo__baz x.bar() # 21, porque el método imprime Bar__baz # Podemos ver los miembros "mangleados" que tiene la instancia x print(x.__dict__) # {'_Bar__baz': 21, '_Foo__baz': 42}
aa3ce5e3f0253d2065b99dd809b0fe29992dd954
workready/pythonbasic
/sources/t04/t04ej04.py
297
4.28125
4
# Una lista es un iterable a_list = [1, 2, 3] for a in a_list: # Tip: para que print no meta un salto de línea al final de cada llamada, pasarle un segundo argumento end=' ' print (a, end=' ') # Un string también es un iterable a_string = "hola" for a in a_string: print(a, end=' ')
f7a033999cdeef6b0b4c523cd03839e7ba7f0b22
workready/pythonbasic
/sources/t06/t06ejer03.py
410
3.765625
4
class Shape: pass # Tu codigo aqui class Rectangle(Shape): pass # Tu codigo aqui newRectangle = Rectangle(12, 10) print(newRectangle.area) # 120 print(newRectangle.perimeter) # 44 newRectangle.width = 5 newRectangle.height = 8 print(newRectangle.area) # 60 print(newRectangle.perimeter) # 34 newRectangle.width = -10 # El valor de width ha de ser mayor que 0
c669dfa12e759faa2498748d22314c604138273c
workready/pythonbasic
/ejercicios_resueltos/t06/t06ejer06.py
1,689
3.875
4
class Item: def __init__(self, name, value): self.name = name self.value = value def __str__(self): return "{} => {}".format(self.name, self.value) class Box: def add(self, *items): raise NotImplementedError() def empty(self): raise NotImplementedError() def count(self): raise NotImplementedError() def items(self): raise NotImplementedError() class ListBox(Box): def __init__(self): self._items = [] def add(self, *items): self._items.extend(items) def empty(self): items = self._items self._items = [] return items def count(self): return len(self._items) def items(self): return self._items class DictBox(Box): def __init__(self): self._items = {} def add(self, *items): self._items.update(dict((i.name, i) for i in items)) def empty(self): items = list(self._items.values()) self._items = {} return items def count(self): return len(self._items) def items(self): return self._items # Esto prueba las clases i1 = Item("Item 1", 1) i2 = Item("Item 2", 2) i3 = Item("Item 3", 3) listbox = ListBox() dictbox = DictBox() listbox.add(i1, i2, i3) dictbox.add(i1) dictbox.add(i2) dictbox.add(i3) assert(listbox.count() == 3) assert(dictbox.count() == 3) for i in listbox.items(): print(i) for k, item in dictbox.items().items(): print(i) listbox.empty() dictbox.empty() assert(listbox.count() == 0) assert(dictbox.count() == 0) for i in listbox.items(): print(i) for k, item in dictbox.items().items(): print(i)
6c7bf95347870300b8aa50a34f4810ff4da20427
workready/pythonbasic
/sources/t09/t09ejer01.py
362
3.890625
4
import multiprocessing # Funcion a ejecutar con multiproceso def worker(num): return num*2 # Lista de numeros con los que trabajar nums = [1,2,3,4,5,6,7,8,9] values = None # En values obtendremos el resultado de aplicar worker a la lista, utilizando un pool de 2 procesos # Tu codigo aqui assert(values == [2, 4, 6, 8, 10, 12, 14, 16, 18]) print(values)
3beae445297c50305023fb275c91f58872facca8
workready/pythonbasic
/sources/t08/t08ej02.py
541
3.90625
4
class Empleado(object): "Clase para definir a un empleado" def __init__(self, nombre, email): self.nombre = nombre self.email = email def getNombre(self): return self.nombre jorge = Empleado("Jorge", "[email protected]") jorge.guapo = "Por supuesto" # Probando hasattr, getattr, setattr print(hasattr(jorge, 'guapo')) # True print(getattr(jorge, 'guapo')) # Por supuesto print(hasattr(jorge, 'listo')) # False setattr(jorge, 'listo', 'Más que las monas') print(getattr(jorge, 'listo')) # Mas que las monas
5397542b7edb1969c2bb9ee2c3533179a6e4370a
jose-cavalcante/teste
/eq2.py
559
3.96875
4
import math a=float(input("Digite o valor de a: ")) b=float(input("Digite o valor de b: ")) c=float(input("Digite o valor de c: ")) if a==0: print("Impossível de calcular, pois a não pode ser zero.") else: d=(b**2)-(4*a*c) if d<0: print("A equação não tem solução real") else: if d==0: x=-b/(2*a) print("Existe uma única raiz real com valor",x) else: x1=(-(b) + math.sqrt(d))/(2*a) x2=(-(b) - math.sqrt(d))/(2*a) print("Existem duas raízes reais com valores",x1,"e",x2)
94b26dcd00e1a5ba7e3e4473cb2920cda95f5a14
nberr/pycaster
/src/data.py
2,463
3.8125
4
# point contains 3 values: x, y, z class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z # comparing two points def __eq__(self, other): return (epsilon_eq(self.x, other.x) and epsilon_eq(self.y, other.y) and epsilon_eq(self.z, other.z)) # vector contains 3 values: x, y, z class Vector: def __init__(self, x, y, z): self.x = x self.y = y self.z = z # comparing two vectors def __eq__(self, other): return (epsilon_eq(self.x, other.x) and epsilon_eq(self.y, other.y) and epsilon_eq(self.z, other.z)) # ray contains a point: pt and vector: dir class Ray: def __init__(self, pt, dir): self.pt = pt self.dir = dir # comparing two rays def __eq__(self, other): return (self.pt == other.pt and self.dir == other.dir) # sphere contains a point: center, radius, color, and finish class Sphere: def __init__(self, center, radius, color, finish): self.center = center self.radius = float(radius) self.color = color self.finish = finish # comparing two spheres def __eq__(self, other): return (self.center == other.center and epsilon_eq(self.radius, other.radius) and self.color == other.color and self.finish == other.finish) # color contains RGB values r, g, and b class Color: def __init__(self, r, g, b): self.r = r self.g = g self.b = b # comparing two colors def __eq__(self, other): return (epsilon_eq(self.r, other.r) and epsilon_eq(self.g, other.g) and epsilon_eq(self.b, other.b)) class Finish: def __init__(self, ambient, diffuse, specular, roughness): self.ambient = ambient self.diffuse = diffuse self.specular = specular self.roughness = roughness def __eq__(self, other): return (epsilon_eq(self.ambient, other.ambient) and epsilon_eq(self.diffuse, other.diffuse) and epsilon_eq(self.specular, other.specular) and epsilon_eq(self.roughness, other.roughness)) class Light: def __init__(self, pt, color): self.pt = pt self.color = color def __eq__(self, other): return self.pt == other.pt and self.color == other.color # helper functions # used for comparing two objects def epsilon_eq(n, m, epsilon=0.00001): return (n - epsilon) < m and (n + epsilon > m)
460471be68523b7d92a5e49a17dc9cc032121f1a
Neyaz123/Python
/3.2.py
414
3.921875
4
def summ(x, y, z): return x+y+z def proizv(x, y, z): return x*y*z X = int(input('Введите первое число: ')) Y = int(input('Введите второе число: ')) Z = float(input('Введите третье число: ')) print('Сумма введенных чисел: ', summ(X, Y, Z)) print('Произведение введенных чисел', proizv(X, Y, Z))
1cfb7e5543b30f0f7d2a22779852ade27ece4b5c
PaulJardel/molecule_parser
/molecular/molecule_parser.py
5,829
3.609375
4
from typing import Dict import re from molecular.monitoring.log import get_logger logger = get_logger() class MoleculeParser: """ This class allows to parse molecules, and get the number of atoms that compose it. It is mainly string operations. See documentation used : https://docs.python.org/3/library/stdtypes.html """ def parse_molecule(self, molecule: str) -> Dict[str, int]: """ This method returns the dictionary of atoms for a specified molecule. :param molecule: the molecule to parse :return: the dictionary of atoms, containing the amount for each atom """ logger.info(f"Molecule : '{molecule}'") # check if the molecule has a valid format for parenthesis if not self._is_valid_parenthesis(molecule=molecule): logger.info(f"Molecule '{molecule}' has not a valid format.\n") return None # get list of molecule elements list_molecules_elements = self.get_list_molecules_elements(molecule=molecule) logger.info(f'list_molecules_elements = {list_molecules_elements}') # recursively parse each molecule element, counting them, using parenthesis_multiplier atoms_dict = self.parse_group(list_molecules_elements=reversed(list_molecules_elements), atoms_dict={}) logger.info(f"Dictionary of atoms for '{molecule}' : {atoms_dict}\n") return atoms_dict def _is_valid_parenthesis(self, molecule: str) -> bool: """ This method ensures the validity of the number of parenthesis opening / closing. For the second part of the function, it was inspired by : https://www.w3resource.com/python-exercises/class-exercises/python-class-exercise-3.php https://docs.python.org/3/tutorial/datastructures.html :param molecule: the molecule to analyse :return: True if the parenthesis are valid (opened / closed for each one, on the good order) """ only_parenthesis = '' parenthesis_char = {"(", ")", "{", "}", "[", "]"} for character in molecule: if character in parenthesis_char: only_parenthesis += character stack = [] parenthesis_opposites = {"(": ")", "{": "}", "[": "]"} for parenthese in only_parenthesis: if parenthese in parenthesis_opposites: stack.append(parenthese) elif len(stack) == 0 or parenthesis_opposites[stack.pop()] != parenthese: return False return len(stack) == 0 def get_list_molecules_elements(self, molecule: str) -> Dict[str, int]: """ This method returns the list of molecule elements. A molecule element can be : - atom_name : an atom can be composed of 1 letter uppercase, or 1 letter uppercase + 1 letter lowercase - atom_multiplier : the multiplier linked to the atom. For example : 'H(S4[SO]3)2', atom multipler of S = 4. - parenthesis : can be one of the following : "(", ")", "[", "]", "{", "}" - parenthesis_multiplier : multiplified amount of all current surrounding parenthesis :param molecule: the molecule to analyse :return: the list of molecule elements, composing the molecule """ return re.findall(r'[A-Z][a-z]?|[()\[\]{}]|[0-9]', molecule) def parse_group(self, list_molecules_elements, atoms_dict, parenthesis_multiplier=1): """ This method returns the updated dictionary of atoms for a specified molecule. Here we handle the mulitplier of atoms, defined by the parenthesis. The recursiveness of this method allows to multiply the parenthesis_multiplier at each parenthesis. We 'read' the molecule from right to left, so that we catch the multiplier first. Easier fot calculation. :param list_molecules_elements: the molecule, parsed by molecule elements :param atoms_dict: the dictionary of atoms to construct / return :param parenthesis_multiplier: the parenthesis_multiplier, which evolve at each opened/closed parenthesis :return: the dictionary of atoms, containing the amount for each atom """ _parenthesis_multiplier = parenthesis_multiplier starting_parenthesis_char = {"(", "{", "["} closing_parenthesis_char = {")", "}", "]"} for molecule_element in list_molecules_elements: # entering a parenthesis : we use the parenthesis_multiplier if molecule_element in closing_parenthesis_char: self.parse_group( list_molecules_elements=list_molecules_elements, atoms_dict=atoms_dict, parenthesis_multiplier=_parenthesis_multiplier) # exiting a parenthesis : we do not use the parenthesis_multiplier anymore elif molecule_element in starting_parenthesis_char: break elif molecule_element.isdecimal(): _parenthesis_multiplier = parenthesis_multiplier * int(molecule_element) continue elif molecule_element.isalpha(): atoms_dict[molecule_element] = atoms_dict.get(molecule_element, 0) + _parenthesis_multiplier _parenthesis_multiplier = parenthesis_multiplier return atoms_dict if __name__ == '__main__': molecule_parser = MoleculeParser() wrong_format_molecule = '(Mg3[T)]' atoms_dict = molecule_parser.parse_molecule(molecule=wrong_format_molecule) water = 'H2O' atoms_dict = molecule_parser.parse_molecule(molecule=water) magnesium_hydroxide = 'Mg(OH)2' atoms_dict = molecule_parser.parse_molecule(molecule=magnesium_hydroxide) fremy_salt = 'K4[ON(SO3)2]2' atoms_dict = molecule_parser.parse_molecule(molecule=fremy_salt)
e32c6fcb9ae8d8f9613f85ab07b69ca50d179619
owis1998/brute-force-approach
/closest_pair/closest_pair.py
847
3.796875
4
class Point: def __init__(self, x, y): self.x = x self.y = y def how_far_from(self, point): if self.x == point.x: return 0 higher_point, lower_point = (self, point) if self.y > point.y else (point, self) #Pythagorean theorem distance = ((higher_point.x - lower_point.x) ** 2 + (higher_point.y - lower_point.y) ** 2) ** 0.5 return distance def closest_point(self, points): distance = 1e9 for p in points: if self.how_far_from(p) < distance and not self is p: closestP = p distance = self.how_far_from(p) return distance, closestP def find_closest_pair(list_of_points): distance = 1e9 for i in range(0, len(list_of_points) - 1): tmp = list_of_points[i].closest_point(list_of_points) if tmp[0] < distance: distance = tmp[0] closest_pair = [list_of_points[i], tmp[1]] return closest_pair
5dfd71362ded3403b553bc743fab89bab02e2d38
BluFox2003/RockPaperScissorsGame
/RockPaperScissors.py
1,684
4.28125
4
#This is a Rock Paper Scissors game :) import random def aiChoice(): #This function generates the computers choice of Rock, Paper or Scissors x = random.randint(0,2) if x == 0: choice = "rock" if x == 1: choice = "paper" if x == 2: choice = "scissors" return choice def gameLoop(choice): #Main Game Loop playerChoice = input("Choose Rock, Paper or Scissors ") playerChoice = playerChoice.lower() if playerChoice == "rock": #If the player chooses Rock if choice == "rock": print("AI chose Rock, DRAW") elif choice == "paper": print("AI chose Paper, YOU LOSE") elif choice == "scissors": print("AI chose Scissors, YOU WIN") elif playerChoice == "paper": #If the player chooses Paper if choice == "rock": print("AI chose Rock, YOU WIN") elif choice == "paper": print("AI chose Paper, DRAW") elif choice == "scissors": print("AI chose Scissors, YOU LOSE") elif playerChoice == "scissors": #If the player chooses Scissors if choice == "rock": print("AI chose Rock, YOU LOSE") elif choice == "paper": print("AI chose Paper, YOU WIN") elif choice == "scissors": print("AI chose Scissors, DRAW") else: print("Oops you did a fuckywucky") #If the player chose none of the options repeat = input("Would you like to play again? Y/N ") #Asks the user if they wanna play again if repeat == "Y" or repeat == "y": gameLoop(choice) #Repeats the game loop elif repeat == "N" or repeat == "n": exit() #Ends the program print("Welcome to Rock, Paper, Scissors") ai = aiChoice() aiChoice() gameLoop(ai)
3fb1e727b6789e39051ecc514c29f8db0afb5c21
isrt09/Data-Visualization-using-Python
/Day01/Fill.py
188
3.5625
4
import matplotlib.pyplot as plt import numpy as np x = np.arange(0,10) y1 = 0.08*x**2 y2 = 0.03*x**2 plt.fill_between(x,y1,y2, 'r-') plt.plot(x,y1, 'r-') plt.plot(x,y2, 'b-') plt.show()
119737821e287b38e186754ab8124f02b745c50d
windanger/Exercise-after-class
/Desktop/Exercise after class/密碼設置強度檢測.py
1,708
3.984375
4
#寫一个密码安全性检查的脚本代码 #低级密码要求: #1. 密码由单纯的数字或字母组成 #2. 密码长度小于等于8位 #中级密码要求: #1. 密码必须由数字、字母或特殊字符(仅限:~!@#$%^&*()_=-/,.?<>;:[]{}|\)任意两种组合 #2. 密码长度不能低于8位 #高级密码要求: #1.密码必须由数字、字母及特殊字符(仅限:~!@#$%^&*()_=-/,.?<>;:[]{}|\)三种组合 #2.密码只能由字母开头 #3.密码长度不能低于16位 symbols = '~!@#$%^&*()_=-/,.?<>;:[]{}\|' number = '123456789' character = 'abcdefghijklmnopqrstuvwxyz' password = input('請輸要入要設置的密碼 : ') def check_len(passwoard) : if 0<len(password) <= 8 : return 0 elif 8<len(password)<=16 : return 1 else : return 2 def char(password) : result = 0 for each in password : if each in character : result =1 return result def num(password) : result = 0 for each in number : if each in number : result =1 return result def sym(password) : result = 0 for each in password : if each in symbols : result =1 return result def letter(password) : if password[0] in character : return True else : return False if check_len(password) == 0 and char(password)+num(password) >1 and sym(password) == 0 : print('Low') elif check_len(password) == 1 and char(password)+num(password)+sym(password) >= 2 : print('MID') elif check_len(password) == 2 and char(password)+num(password)+sym(password) ==3 and letter(password) == True : print('HIGH') else : print('輸入錯誤請重新輸入')
a5aeeb2e8f0bf153e0ebaa4aaae06ce71ac0539b
windanger/Exercise-after-class
/Desktop/Exercise after class/最大公因數.py
249
3.609375
4
#编写一个函数,利用欧几里得算法(脑补链接)求最大公约数,例如gcd(x, y) #返回值为参数x和参数y的最大公约数。 def gcd(a,b) : t = 1 while t==1 : t = a % b a , b = b , t return t
e8b613da719dfd651e84ce34b2c1c8ab41849656
tapatio-123/python-challenge
/PyBank/main.py
1,776
3.796875
4
import os import csv #importing file budget_csv = os.path.join('..', 'PyBank', 'Resources', 'budget_data.csv') #read into file with open(budget_csv) as csvfile: csvreader = csv.reader(csvfile, delimiter= ",") csv_header = next(csvreader) #setting variablbes total = 0 total_months = 0 total_change = 0 datelist = [] pl_list = [] #creating for loop to create list from csv data for row in csvreader: datelist.append(row[0]) #list for dates pl_list.append(int(row[1])) #profit loss list total = total + float (row[1]) #summing profit loss column delta = [] total_months = len(datelist) #for loop of differneces between profit/losses column for i in range(1,total_months): delta.append(pl_list[i]-pl_list[i-1]) #finding greatest increase/decrease in profits inc_pl = max(delta) dec_pl = min(delta) #matching the above variables to column in csv file to get corresponding date inc_date = datelist[delta.index(max(delta))+1] dec_date = datelist[delta.index(min(delta))+1] average = sum(delta)/(total_months-1) average = '${:.2f}'.format(average) #writing out print statements print (f"Total Months: {total_months}") print (f"Total: ${total}") print (f"Average Change: {average}") print (f"Greatest Increase in Profits: {inc_date} (${inc_pl})") print (f"Greatest Decrease in Profits: {dec_date} (${dec_pl})") #creating text file with open("output.txt", "w") as txt_file: txt_file.write(f"Total months: {total_months}\n") txt_file.write(f"Total: ${total}\n") txt_file.write(f"Average Change: {average}\n") txt_file.write(f"Greatest Increase in Profits: {inc_date} (${inc_pl})\n") txt_file.write(f"Greatest Decrease in Profits: {dec_date} (${dec_pl})")
b0d07a7552b88785387c63cc677186fbe47c9c2c
SebastianColorado/DylansBot
/Main.py
1,329
3.5625
4
"""Tweets out a random city name + the phrase.""" import csv import twitter import os import random import time numRows = 15633 cities = [] with open('cities.csv', 'rt') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: cities.append(row[0]) # Authenticate the twitter bot by passing the twitter api keys retrieved from # environment variables consumer_key = os.environ['CONSUMER_KEY'] consumer_secret = os.environ['CONSUMER_SECRET'] access_token_key = os.environ['ACCESS_TOKEN'] access_token_secret = os.environ['ACCESS_TOKEN_SECRET'] print(consumer_key + " " + consumer_secret + " " + access_token_key + " " + access_token_secret) twitterApi = twitter.Api(consumer_key, consumer_secret, access_token_key, access_token_secret) def postTweet(city): """Post tweet with given parameters.""" try: status = twitterApi.PostUpdate(city + " niggas? They trained to go.") except twitter.error.TwitterError as e: print('There was an error: ' + e.message[0]['message']) else: print("%s just posted: %s" % (status.user.name, status.text)) return def getCity(): """Get a random city from the array.""" return cities[random.randrange(numRows)] while True: currentCity = getCity() postTweet(currentCity) time.sleep(17280)
690c1fc35fdd3444d8e27876d9acb99e471b296b
gridl/cracking-the-coding-interview-4th-ed
/chapter-1/1-8-rotated-substring.py
686
4.34375
4
# Assume you have a method isSubstring which checks if one # word is a substring of another. Given two strings, s1 and # s2, write code to check if s2 is a rotation of s1 using only # one call to isSubstring (i.e., "waterbottle" is a rotation of # "erbottlewat"). # # What is the minimum size of both strings? # 1 # Does space complexity matter? # Not initially # Time complexity is the priority? # Yes def rotated_substr(word, rotat): if len(word) != len(rotat): return False rotat_conc = rotat + rotat return word in rotat_conc if __name__ == "__main__": print(rotated_substr("thisis", "isthis")) print(rotated_substr("hihiho", "hihole"))
bad07562893a7508a001f4be69af6936d9760762
gridl/cracking-the-coding-interview-4th-ed
/chapter-2/2_1_remove_duplicates.py
1,113
3.765625
4
from linked_list import LinkedList class ExtLinkedList(LinkedList): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def remove_dup(self): curr = self.head if not (curr and curr.next): return prev = None elems = set() while curr: if curr.data in elems: prev.next = curr.next else: elems.add(curr.data) prev = curr curr = curr.next def remove_dup_no_mem(self): i = self.head while i and i.next: j = i.next p = i while j: if i.data == j.data: p.next = j.next else: p = j j = j.next i = i.next if __name__ == "__main__": ell = ExtLinkedList() ell.append("hi") ell.append("hello") ell.append("hi") print(ell) ell.remove_dup() print(ell) ell.append("hi") ell.append("hello") ell.append("hi") print(ell) ell.remove_dup_no_mem() print(ell)
c381e6e7782819eacd08c3ce44ebc2080c301da3
kevin-j-chan/cogs18project
/actors.py
11,648
3.546875
4
# coding: utf-8 # In[4]: import random from items import * from math import floor # In[5]: class Player(): def __init__(self, level=1, health=50, strength=5, speed=5): self.is_alive = True # Player inventory self.e_sword = Sword(name="none", value=0, strength=0) self.e_armor = Armor(name="none", value=0, strength=0, weight=1) self.backpack = dict() self.wealth = 0 # Player level values self.level = level self.exp_value = 0 # Player stat values self.max_health = health self.curr_health = health self.strength = strength self.speed = speed def gain_experience(self, value): """ Calculate experience value. """ stat_points = 0 self.exp_value = self.exp_value + value exp_requirement = 25 * self.level while self.exp_value >= exp_requirement: print("You leveled up!") self.level = self.level + 1 self.exp_value = self.exp_value - exp_requirement exp_requirement = 25 * self.level stat_points = stat_points + 10 if stat_points > 0: self.allocate_stats(stat_points) print("Current experience:\t" + str(self.exp_value)) print("Experience required for the next level:\t" + str(exp_requirement)) def show_stats(self): """ Print out the stats for a player. """ print("Your current stats are (+equipment): " + "\n\t Health: " + "\t" + str(self.max_health) + "(+" + str(self.e_armor.strength) + ")" "\n\t Strength: " + "\t" + str(self.strength) + "(+" + str(self.e_sword.strength) + ")" "\n\t Speed: " + "\t" + str(self.speed) + "(*" + str(self.e_armor.weight) + ")") def allocate_stats(self, points): self.show_stats() print() while points != 0: print("You have " + str(points) + " points to put into your stats.") stat_name = input("Which stat would you like to increase? \t") if stat_name.lower() == "health": stat_value = int(input("How much would you like to add?\t")) if stat_value > points: print("Invalid amount.") else: points = points - stat_value self.max_health = self.max_health + stat_value elif stat_name.lower() == "strength": stat_value = int(input("How much would you like to add?\t")) if stat_value > points: print("Invalid amount.") else: points = points - stat_value self.strength = self.strength + stat_value elif stat_name.lower() == "speed": stat_value = int(input("How much would you like to add?\t")) if stat_value > points: print("Invalid amount.") else: points = points - stat_value self.speed = self.speed + stat_value else: print("Stat name entered incorrectly, try again.") print() self.show_stats() def calculated_health(self): return self.max_health + self.e_armor.strength def calculated_strength(self): return self.strength + self.e_sword.strength def calculated_speed(self): return self.speed * self.e_armor.weight def display_items(self): if self.backpack: print("Contents of your backpack: ") for item in self.backpack.values(): item.print() def add_item(self, item): if item.name in self.backpack.keys(): item_in_backpack = self.backpack[item.name] item.value += item_in_backpack.value if(type(item) != Etc): item.strength += item_in_backpack.strength self.backpack.update({ item.name : item}) def remove_item(self, item_name): if item_name.lower() in self.backpack.keys(): del self.backpack[item_name] def equip_item(self, item_name): if item_name.lower() in self.backpack.keys(): item_name = item_name.lower() item = self.backpack[item_name] if type(item) == Sword: if self.e_sword.name == "none": self.e_sword = item self.remove_item(item_name) else: self.add_item(self.e_sword) self.e_sword = item self.remove_item(item_name) elif type(item) == Armor: if self.e_armor.name == "none": self.e_armor = item self.remove_item(item_name) else: self.add_item(self.e_armor) self.e_armor = item self.remove_item(item_name) else: print(item.name + " is not equippable.") else: print("You do not have " + item_name) def use_item(self, item_name): if item_name.lower() in self.backpack.keys(): item_name = item_name.lower() item = self.backpack[item_name] if type(item) == Potion: self.curr_health = self.curr_health + item.strength if self.curr_health > self.calculated_health(): self.curr_health = self.calculated_health() self.remove_item(item_name) elif type(item) == Sword or type(item) == Armor: self.equip_item(item_name) else: print("You cannot use this item!") else: print("You do not have " + item_name) def attack(self, mob): damage = random.randint(self.calculated_strength() - 2,self.calculated_strength() + 2) if random.random() < 0.05: damage = damage ** 2 print("\tCRITICAL STRIKE - You dealt " + str(damage) + " damage.") else: print("\tYou attacked the monster and dealt " + str(damage) + " damage.") mob.health = mob.health - damage def fight(self, mob): if self.calculated_speed() > mob.speed: self.attack(mob) if(mob.status()): mob.attack(self) elif self.calculated_speed() < mob.speed: mob.attack(self) if(self.status()): self.attack(mob) else: if random.random() < .5: self.attack(mob) if(mob.status()): mob.attack(self) else: mob.attack(self) if(self.status()): self.attack(mob) def run_from(self, mob): run_away_chance = 0.75 if self.calculated_speed() < mob.speed: run_away_chance = 0.50 return random.random() <= run_away_chance def status(self): return self.curr_health > 0 # In[7]: class Mob(): common_loot = [ Sword(), Potion(strength=5), Armor(strength=5, weight=0.75)] rare_loot = [ Sword(name="scimitar",value=10,strength=7), Sword(name="two-handed sword",value=5,strength=10), Potion(name="poison",value=5,strength=-15), Potion(name="elixir",value=10, strength=20), Armor(name="chainmail", value=7)] super_loot = [ Sword(name="slayer",value=99,strength=99), Armor(name="impenetrable defense",value=99,strength=99,weight=0.10), Armor(name="ungodly boots", value=99, strength=-5, weight=2)] def __init__(self, name, health, strength, speed, d): self.name = name self.health = floor(health * d) self.strength = floor(strength * d) self.speed = floor(speed * d) self.difficulty = d def drop_loot(self, base_rate=0.25): num = random.random() item = None if num < base_rate: num = random.random() if num < 0.05: item = random.choice(self.super_loot) elif num < 0.25: item = random.choice(self.rare_loot) elif num < 0.75: item = random.choice(self.common_loot) else: item = Etc(value=random.randint(0,5)) return item def attack(self, player): upper_bound = self.strength + 2 lower_bound = self.strength - 2 if lower_bound < 0: lower_bound = 0 damage = random.randint(lower_bound, upper_bound) if random.random() < 0.05: damage = damage ** 2 print("\tCRITICAL STRIKE - It dealt " + str(damage) + " damage.") else: print("\tIt attacked you and dealt " + str(damage) + " damage.") player.curr_health = player.curr_health - damage def print_undiscovered(self): print("\t"+self.name + " can be heard somewhere in the distance...") print("\t\t| health\t?") print("\t\t| strength\t?") print("\t\t| speed \t?") def print_encountered(self): print("\t"+self.name + " has appeared.") print("\t\t| health\t" + str(self.health)) print("\t\t| strength\t" + str(self.strength)) print("\t\t| speed \t" + str(self.speed)) class Heavy(Mob): def __init__(self, health=50, strength=5, speed=1, d = 1): super().__init__("a large beast", health, strength, speed, d) self.exp_value = floor(20 * d) def status(self): if self.health <= 0: return False else: return True class Normal(Mob): def __init__(self, health=20, strength=3, speed=5, d = 1): super().__init__("an animal", health, strength, speed, d) self.exp_value = floor(15 * d) def status(self): if self.health <= 0: return False else: return True class Quick(Mob): def __init__(self, health=5, strength=1, speed=10, d = 1): super().__init__("many small creatures", health, strength, speed, d) self.base_health = health self.exp_value = floor(10 * d) self.lives = 5 def status(self): if self.health <= 0: if self.lives == 0: return False else: print("\tOne has died, but many more fill its place") self.lives = self.lives - 1 self.health = self.base_health return True def print_encountered(self): print("\t"+self.name + " have appeared.") print("\t\t| health\t" + str(self.health)) print("\t\t| strength\t" + str(self.strength)) print("\t\t| speed \t" + str(self.speed)) class Aberrant(Mob): def __init__(self, d = 1): r = random health = r.randint(10,30) strength = r.randint(8, 15) speed = r.randint(1, 10) super().__init__("an abberant", health, strength, speed, d) self.exp_value = floor(99 * d) def status(self): if self.health <= 0: return False else: return True
41cf652afee3550d58f74cd28d7e896513cea42f
hanajhg/pylesson
/pybasic/pybasic_15_fun.py
14,282
4.15625
4
''' 函数 ''' #!/usr/bin/python3 # 计算面积函数 import functools from urllib import request def area(width, height): return width * height def print_welcome(name): print("Welcome", name) print_welcome("Runoob") w = 4 h = 5 print("width =", w, " height =", h, " area =", area(w, h)) ''' 函数调用 ''' # 定义函数 def printme(str): # 打印任何传入的字符串 print(str) return # 调用函数 printme("我要调用用户自定义函数!") printme("再次调用同一函数") ''' 参数传递 ''' # python传不可变对象实例 def ChangeInt(a): a = 10 b = 2 ChangeInt(b) print(b) # 结果是 2 # 实例中有int对象2,指向它的变量是b,在传递给ChangeInt函数时, # 按传值的方式复制了变量b,a和b都指向了同一个Int对象, # 在a = 10时,则新生成一个int值对象10,并让a指向它。 # 传可变对象实例可变对象在函数里修改了参数,那么在调用这个函数的函数里,原始的参数也被改变了。 # 可写函数说明 def changeme(mylist): "修改传入的列表" mylist.append([1, 2, 3, 4]) print("函数内取值: ", mylist) return # 调用changeme函数 mylist = [10, 20, 30] changeme(mylist) print("函数外取值: ", mylist) # 必需参数 # 必需参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。 # 调用printme()函数,你必须传入一个参数,不然会出现语法错误: # 可写函数说明 def printme(str): "打印任何传入的字符串" print(str) return # 调用 printme 函数,不加参数会报错 # printme() # 关键字参数 # 关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值。 # 使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为Python解释器能够用参数名匹配参数值。 # 可写函数说明 def printme(str): "打印任何传入的字符串" print(str) return # 调用printme函数 printme(str="南高职python教程") # 以下实例中演示了函数参数的使用不需要使用指定顺序: # 可写函数说明 def printinfo(name, age): "打印任何传入的字符串" print("名字: ", name) print("年龄: ", age) return # 调用printinfo函数 printinfo(age=50, name="runoob") # 默认参数 # 调用函数时,如果没有传递参数,则会使用默认参数。 # 以下实例中如果没有传入age参数,则使用默认值: # 可写函数说明 def printinfo(name, age=35): "打印任何传入的字符串" print("名字: ", name) print("年龄: ", age) return # 调用printinfo函数 printinfo(age=50, name="runoob") print("------------------------") printinfo(name="runoob") # 不定长参数 # 你可能需要一个函数能处理比当初声明时更多的参数。 # 这些参数叫做不定长参数,和上述2种参数不同,声明时不会命名。基本语法如下: # # def functionname([formal_args, ] * var_args_tuple): # "函数_文档字符串" # function_suite # return [expression] # 加了星号 * 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数。 # 可写函数说明 def printinfo(arg1, *vartuple): "打印任何传入的参数" print("输出: ") print(arg1) print(vartuple) # 调用printinfo 函数 printinfo(70, 60, 50) # 如果在函数调用时没有指定参数,它就是一个空元组。我们也可以不向函数传递未命名的变量。如下实例: # 可写函数说明 def printinfo(arg1, *vartuple): "打印任何传入的参数" print("输出: ") print(arg1) for var in vartuple: print(var) return # 调用printinfo 函数 printinfo(10) printinfo(70, 60, 50) # 还有一种就是参数带两个星号 ** 基本语法如下: # # def functionname([formal_args, ] ** var_args_dict): # "函数_文档字符串" # function_suite # return [expression] # 加了两个星号 ** 的参数会以字典的形式导入。 # 可写函数说明 def printinfo(arg1, **vardict): "打印任何传入的参数" print("输出: ") print(arg1) print(vardict) # 调用printinfo 函数 printinfo(1, a=2, b=3) # 声明函数时,参数中星号 * 可以单独出现,例如: def f(a, b, *, c): return a + b + c # 如果单独出现星号 * 后的参数必须用关键字传入。 # >> > def f(a, b, *, c): # ... # return a + b + c # >> > f(1, 2, 3) # 报错 # # >> > f(1, 2, c=3) # 正常 ''' 匿名函数 ''' # 可写函数说明 sum = lambda arg1, arg2: arg1 + arg2 # 调用sum函数 print("相加后的值为 : ", sum(10, 20)) print("相加后的值为 : ", sum(20, 20)) # return语句 # return [表达式] # 语句用于退出函数,选择性地向调用方返回一个表达式。不带参数值的return语句返回None。之前的例子都没有示范如何返回数值,以下实例演示了 # 可写函数说明 def sum(arg1, arg2): # 返回2个参数的和." total = arg1 + arg2 print("函数内 : ", total) return total # 调用sum函数 total = sum(10, 20) print("函数外 : ", total) ''' map&reduce ''' def f(x): return x * x r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) print(list(r)) # [1, 4, 9, 16, 25, 36, 49, 64, 81] # map()传入的第一个参数是f,即函数对象本身。由于结果r是一个Iterator,Iterator是惰性序列, # 因此通过list()函数让它把整个序列都计算出来并返回一个list。 # 你可能会想,不需要map()函数,写一个循环,也可以计算出结果: L = [] for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]: L.append(f(n)) print(L) # 的确可以,但是,从上面的循环代码,能一眼看明白“把f(x)作用在list的每一个元素并把结果生成一个新的list”吗? # 所以,map()作为高阶函数,事实上它把运算规则抽象了, # 因此,我们不但可以计算简单的f(x)=x2,还可以计算任意复杂的函数, # 比如,把这个list所有数字转为字符串: print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))) # ['1', '2', '3', '4', '5', '6', '7', '8', '9'] # 只需要一行代码。 # 再看reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数, # reduce把结果继续和序列的下一个元素做累积计算,其效果就是: # reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) # 比方说对一个序列求和,就可以用reduce实现: from functools import reduce def add(x, y): return x + y reduce(add, [1, 3, 5, 7, 9]) # 25 # 当然求和运算可以直接用Python内建函数sum(),没必要动用reduce。 # 但是如果要把序列[1, 3, 5, 7, 9]变换成整数13579,reduce就可以派上用场: def fn(x, y): return x * 10 + y reduce(fn, [1, 3, 5, 7, 9]) # 13579 # 这个例子本身没多大用处,但是,如果考虑到字符串str也是一个序列,对上面的例子稍加改动,配合map(), # 我们就可以写出把str转换为int的函数: def fn(x, y): return x * 10 + y def char2num(s): digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} return digits[s] reduce(fn, map(char2num, '13579')) # 13579 # 整理成一个str2int的函数就是: DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def str2int(s): def fn(x, y): return x * 10 + y def char2num(s): return DIGITS[s] return reduce(fn, map(char2num, s)) # 还可以用lambda函数进一步简化成: DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def char2num(s): return DIGITS[s] def str2int(s): return reduce(lambda x, y: x * 10 + y, map(char2num, s)) # 也就是说,假设Python没有提供int()函数,你完全可以自己写一个把字符串转化为整数的函数,而且只需要几行代码! ''' filter ''' # Python内建的filter()函数用于过滤序列。 # 和map()类似,filter()也接收一个函数和一个序列。 # 和map()不同的是,filter()把传入的函数依次作用于每个元素, # 然后根据返回值是True还是False决定保留还是丢弃该元素。 # 例如,在一个list中,删掉偶数,只保留奇数,可以这么写: def is_odd(n): return n % 2 == 1 list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])) # 结果: [1, 5, 9, 15] # 把一个序列中的空字符串删掉,可以这么写: def not_empty(s): return s and s.strip() list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])) # 结果: ['A', 'B', 'C'] # 可见用filter()这个高阶函数,关键在于正确实现一个“筛选”函数。 # 注意到filter()函数返回的是一个Iterator,也就是一个惰性序列, # 所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list。 # 用filter求素数 # 计算素数的一个方法是埃氏筛法,它的算法理解起来非常简单: # 首先,列出从2开始的所有自然数,构造一个序列: # 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... # 取序列的第一个数2,它一定是素数,然后用2把序列的2的倍数筛掉: # 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... # 取新序列的第一个数3,它一定是素数,然后用3把序列的3的倍数筛掉: # 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... # 取新序列的第一个数5,然后用5把序列的5的倍数筛掉: # 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... # 不断筛下去,就可以得到所有的素数。 # 用Python来实现这个算法,可以先构造一个从3开始的奇数序列: def _odd_iter(): n = 1 while True: n = n + 2 yield n # 注意这是一个生成器,并且是一个无限序列。 # 然后定义一个筛选函数: def _not_divisible(n): return lambda x: x % n > 0 # 最后,定义一个生成器,不断返回下一个素数: def primes(): yield 2 it = _odd_iter() # 初始序列 while True: n = next(it) # 返回序列的第一个数 yield n it = filter(_not_divisible(n), it) # 构造新序列 # 这个生成器先返回第一个素数2,然后,利用filter()不断产生筛选后的新的序列。 # 由于primes()也是一个无限序列,所以调用时需要设置一个退出循环的条件: # 打印1000以内的素数: for n in primes(): if n < 1000: print(n) else: break # 注意到Iterator是惰性计算的序列,所以我们可以用Python表示“全体自然数”,“全体素数”这样的序列,而代码非常简洁。 ''' 返回函数 ''' # 函数作为返回值 # 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。 # 我们来实现一个可变参数的求和。通常情况下,求和的函数是这样定义的: def calc_sum(*args): ax = 0 for n in args: ax = ax + n return ax # 但是,如果不需要立刻求和,而是在后面的代码中,根据需要再计算怎么办?可以不返回求和的结果,而是返回求和的函数: def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum # 当我们调用lazy_sum()时,返回的并不是求和结果,而是求和函数: f = lazy_sum(1, 3, 5, 7, 9) # >>> f # <function lazy_sum.<locals>.sum at 0x101c6ed90> # 调用函数f时,才真正计算求和的结果: f() # 25 # 在这个例子中,我们在函数lazy_sum中又定义了函数sum, # 并且,内部函数sum可以引用外部函数lazy_sum的参数和局部变量, # 当lazy_sum返回函数sum时,相关参数和变量都保存在返回的函数中 # ,这种称为“闭包(Closure)”的程序结构拥有极大的威力。 # 请再注意一点,当我们调用lazy_sum()时,每次调用都会返回一个新的函数,即使传入相同的参数: # >>> f1 = lazy_sum(1, 3, 5, 7, 9) # >>> f2 = lazy_sum(1, 3, 5, 7, 9) # >>> f1==f2 # False # f1()和f2()的调用结果互不影响。 ''' 闭包 注意到返回的函数在其定义内部引用了局部变量args, 所以,当一个函数返回了一个函数后,其内部的局部变量还被新函数引用, 所以,闭包用起来简单,实现起来可不容易。 另一个需要注意的问题是,返回的函数并没有立刻执行,而是直到调用了f()才执行。我们来看一个例子: ''' def count(): fs = [] for i in range(1, 4): def f(): return i*i fs.append(f) return fs f1, f2, f3 = count() # 在上面的例子中,每次循环,都创建了一个新的函数,然后,把创建的3个函数都返回了。 # 你可能认为调用f1(),f2()和f3()结果应该是1,4,9,但实际结果是: f1() # 9 f2() # 9 f3() # 9 # 全部都是9!原因就在于返回的函数引用了变量i,但它并非立刻执行。 # 等到3个函数都返回时,它们所引用的变量i已经变成了3,因此最终结果为9。 # 返回闭包时牢记一点:返回函数不要引用任何循环变量,或者后续会发生变化的变量。 # 如果一定要引用循环变量怎么办?方法是再创建一个函数,用该函数的参数绑定循环变量当前的值, # 无论该循环变量后续如何更改,已绑定到函数参数的值不变: def count(): def f(j): def g(): return j*j return g fs = [] for i in range(1, 4): fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f() return fs # 再看看结果: f1, f2, f3 = count() f1() # 1 f2() # 4 # f3() # 9 # 缺点是代码较长,可利用lambda函数缩短代码。 ''' 练习 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。 输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']: ''' def normalize(name): pass L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2)
22b2b61964f77e9e343650e16309c0d99df48845
hanajhg/pylesson
/pybasic/pybasic_6_number.py
2,607
3.796875
4
# Python 数字数据类型用于存储数值。 # 数据类型是不允许改变的,这就意味着如果改变数字数据类型的值,将重新分配内存空间。 # 以下实例在变量赋值时 Number 对象将被创建: # var1 = 1 # var2 = 10 # 您也可以使用del语句删除一些数字对象的引用。 # del语句的语法是: # del var1[,var2[,var3[....,varN]]] # 您可以通过使用del语句删除单个或多个对象的引用,例如: # del var # del var_a, var_b # >>> number = 0xA0F # 十六进制 # >>> number # 2575 # # >>> number=0o37 # 八进制 # >>> number # 31 # 以下实例将浮点数变量 a 转换为整数: # >>> a = 1.0 # >>> int(a) # 1 # Python 数字运算 # Python 解释器可以作为一个简单的计算器,您可以在解释器里输入一个表达式,它将输出表达式的值。 # 表达式的语法很直白: +, -, * 和 /, 和其它语言(如Pascal或C)里一样。例如: # >>> 2 + 2 # 4 # >>> 50 - 5*6 # 20 # >>> (50 - 5*6) / 4 # 5.0 # >>> 8 / 5 # 总是返回一个浮点数 # 1.6 # 注意:在不同的机器上浮点运算的结果可能会不一样。 # 在整数除法中,除法 / 总是返回一个浮点数,如果只想得到整数的结果,丢弃可能的分数部分,可以使用运算符 // : # >>> 17 / 3 # 整数除法返回浮点型 # 5.666666666666667 # >>> # >>> 17 // 3 # 整数除法返回向下取整后的结果 # 5 # >>> 17 % 3 # %操作符返回除法的余数 # 2 # >>> 5 * 3 + 2 # 17 # 注意:// 得到的并不一定是整数类型的数,它与分母分子的数据类型有关系。 # >>> 7//2 # 3 # >>> 7.0//2 # 3.0 # >>> 7//2.0 # 3.0 # >>> # 等号 = 用于给变量赋值。赋值之后,除了下一个提示符,解释器不会显示任何结果。 # >>> width = 20 # >>> height = 5*9 # >>> width * height # 900 # Python 可以使用 ** 操作来进行幂运算: # >>> 5 ** 2 # 5 的平方 # 25 # >>> 2 ** 7 # 2的7次方 # 128 # 变量在使用前必须先"定义"(即赋予变量一个值),否则会出现错误: # >>> n # 尝试访问一个未定义的变量 # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # NameError: name 'n' is not defined # 不同类型的数混合运算时会将整数转换为浮点数: # >>> 3 * 3.75 / 1.5 # 7.5 # >>> 7.0 / 2 # 3.5 # 在交互模式中,最后被输出的表达式结果被赋值给变量 _ 。例如: # >>> tax = 12.5 / 100 # >>> price = 100.50 # >>> price * tax # 12.5625 # >>> price + _ # 113.0625 # >>> round(_, 2) # 113.06 # 此处, _ 变量应被用户视为只读变量。
861695369e0b660989b3c8629f8073747d4d83a0
18616703217/Ibchariot
/xiaoma/lesson1.py
645
3.9375
4
print("判断密码强度:") import string #password =input("请输入密码:") password_strong = 0 strpun = "" while True: password =input("请输入密码:") if len(password) >= 6 : password_strong += 1 for i in password: if i.isalnum(): strpun += "1" elif i in string.punctuation: strpun += "2" if "1" in strpun and "2" in strpun: password_strong += 1 if password_strong == 1: print("密码强度为低") elif password_strong == 2: print("密码强度为强") else: print("您输入的密码不符合要求") break
837f039ae933a39754aec263ccf6dc194a2fdca0
nadjetfekir/jeu_allumette
/jeu.py
2,749
3.5625
4
def jeu_ordi(nb_allum, prise_max): prise=0 s = prise_max + 1 t = (nb_allum - s) % (prise_max + 1) while (t != 0): s -= 1 t = (nb_allum - s) % (prise_max + 1) prise = s - 1 if (prise == 0): prise = 1 print("l'ordi en prend : ", prise) return prise #le nombre d'allumettes que je prend def jeu_moi(nb_allu_max,nb_allu_rest): prise = 0 if(nb_allu_max>nb_allu_rest):#si le nombre d'allumete restante est inférieure au nombre max on pourra pas tirer le nombre max nbr=nb_allu_rest else: nbr=nb_allu_max while (prise <= 0 or prise > nb_allu_max or prise>nb_allu_rest): try: print("Vous pouvez tirer entre 1 et ",nbr," allumettes") prise = int(input("combien d'allumette voulez-vous tirer ?")) except: print("saisie incorrecte") return prise # afficher n allumettes def afficher_allumettes(n): a = n print("il reste ",n," allumettes") while (a != 0): a -= 1 if a == 0: print("o") else: print("o", end=' ') a = n while (a != 0): a -= 1 print("|", end=' ') print("") #nb_allu_rest le nombre d'allumettes restantes #nb_allu_max le maximum d'allumette qu'on peut tirer #qui celui qui commence le jeu def jeu(nb_allu_rest,nb_allu_max,qui): while (nb_allu_rest != 0): if(qui==0): qui = 1 nb_allu_rest-=jeu_moi(nb_allu_max,nb_allu_rest) if(nb_allu_rest==0): print("le pc a gangé") else: afficher_allumettes(nb_allu_rest) else: qui = 0 nb_allu_rest -= jeu_ordi(nb_allu_rest, nb_allu_max) if (nb_allu_rest == 0): print("j'ai gangé") else: afficher_allumettes(nb_allu_rest) def main(): nb_max_d = 0 nb_allu_max = 0 nb_allu_rest = 0 prise = 0 qui = -1 while (nb_max_d < 10 or nb_max_d > 60): try: nb_max_d = int(input("Entrez un nombre max d'allumette au depart entre 10 et 50.")) except: print("saisie incorrecte") nb_allu_rest = nb_max_d while (nb_allu_max <= 0 or nb_allu_max > nb_max_d): try: print("nombre d'allumettes max doit etre entre 1 et ",nb_max_d, "allumettes") nb_allu_max = int(input("Entrez un nombre max d'allumette que l'on peut tirer dans un tours")) except: print("saisie incorrecte") print("") qui = int(input("Qui commence? 1=PC 0=moi")) print("") afficher_allumettes(nb_allu_rest) jeu(nb_allu_rest,nb_allu_max,qui) if __name__ == "__main__": main()
bbe48bd24e69fef525cef8fb2b2281eb87e8fb4a
renowncoder/bcherry
/oldstuff/python/learning/ex3/tfe.py
815
3.75
4
class textfile: ntfiles = 0 # count of number of textfile objects def __init__(self,fname): textfile.ntfiles += 1 self.name = fname #name self.fh = open(fname) #handle for the file self.lines = self.fh.readlines() self.nlines = len(self.lines) #number of lines self.nwords = 0 #number of words self.wordcount() def wordcount(self): "finds the number of words in the file" for l in self.lines: w = l.split() self.nwords += len(w) def grep(self,target): "prints out all lines containing target" for l in self.lines: if l.find(target) >= 0: print l a = textfile('x') b = textfile('y') print "the number of text files open is", textfile.ntfiles print "here is some information about them (name, lines, words):" for f in [a,b]: print f.name,f.nlines,f.nwords a.grep('example')
5ffc8cd2a282b9ed5337721bde7b6cfa7117f6c1
zhaozhekey/Python-
/Day09/代码/07-filter内置类的使用.py
610
3.921875
4
# filter对可迭代对象进行过滤,得到的是一个filter对象 # Python2的时候是内置函数,Python3修改成一个内置类 ages = [12, 23, 30, 17, 16, 22, 19] # filter可以给定两个参数,第一个参数是函数,第二个参数是可迭代对象 # filter结果是一个filter类型的对象,filter对象也是一个可迭代对象 x = filter(lambda ele: ele > 18, ages) # print(x) # <filter object at 0x00000288AD545708> # # for ele in x: # # print(ele) print(list(x)) # [23, 30, 22, 19] m = map(lambda ele: ele + 2, ages) print(list(m)) #[14, 25, 32, 19, 18, 24, 21]
a4527e71036008aeca6ffbc4ef2ddca952cf91f4
zhaozhekey/Python-
/Day04/代码/05-break和continue.py
334
3.890625
4
# # i = 0 # while i < 10: # if i == 5: # i += 1 # continue # print(i,end="") # i += 1 username = input("用户名") password = input("密码") while (username !="zz" or password != "123"): # while not(username =="zz" or password == "123"): username = input("用户名") password = input("密码")
2c4516304358639cea17f4862257cfaa2b748461
zhaozhekey/Python-
/Day07/代码/05-字典练习二.py
815
4.0625
4
# 输入用户姓名,如果姓名已经存在,提示用户;如果姓名不存在,继续输入年龄,并存入列表中 persons = [ {"name": "zhangsan", "age": 18, "gender": "female"}, {"name": "lisi", "age": 20, "gender": "male"}, {"name": "jack", "age": 30, "gender": "unknow"}, {"name": "kevin", "age": 29, "gender": "female"} ] # name_input = input("请输入姓名") # # for person in persons: # if name_input == person['name']: # print("该姓名已经存在") # break # else: # new_person = {'name': name_input} # age = int(input("请输入年龄")) # new_person['age'] = age # persons.append(new_person) # # print(persons) #删除性别不明的人 new_person = [person for person in persons if person['gender'] != "unknow"] print(new_person)
ea0dd9a0ac67f205dd8852d29b2db061457d4c6a
zhaozhekey/Python-
/Day09/代码/06-sort方法的使用.py
971
3.828125
4
students = [ {"name": "zhangsan", "age": 18, "score": 98, "height": 180}, {"name": "lisi", "age": 25, "score": 93, "height": 170}, {"name": "jerry", "age": 30, "score": 90, "height": 173}, {"name": "kevin", "age": 30, "score": 90, "height": 176}, {"name": "poter", "age": 27, "score": 88, "height": 170}, ] # # 字典和字典之间不能进行比较运算,缺少比较规则 # students.sort() #直接报错 # print(students) # # 可行的方法 # def foo(ele): # return ele['age'] #通过返回值告诉sort方法,按照元素的哪个属性进行排序 # # # 需要传递参数key 指定比较规则 # # key需要的是一个函数,即key的参数类型是个函数 # # 在sort内部实现的时候,调用了foo方法,并且传入了一个参数,参数就是列表里的元素 # students.sort(key = foo) # print(students) # 简便上述方法,使用lambda表达式 students.sort(key=lambda ele: ele['age']) print(students)
ac828af4ad1b05b9073f125edb56d5d7bb1cc707
zhaozhekey/Python-
/Day04/代码/04-循环.py
424
3.671875
4
# # num = 0 # sum = 0 # while num <= 100: # if num %2 != 0: # sum += num # num += 1 # print(sum) # 内置类range用于生成制定区间的整数序列 # 注意:in的后面必须是一个可迭代对象!!! # 目前接触的可迭代对象: 字符串、列表、字典、元组、集合、range # for num in range(0,5): # print(num) sum = 0 for num in range(1,101): sum += num print(sum)
b8ef42374e8612fc63201fb35dcfabff91999c7d
zhaozhekey/Python-
/Day11/代码/05-魔法方法.py
2,086
3.828125
4
# 魔法方法也叫魔术方法,是类里的特殊方法 # 特点 # 1.无需手动调用,会在合适的时机自动调用 # 2.这些方法,都是使用__开始,使用__结束 # 3.方法名都是系统规定好的,在何时的时机自己调用 class Person(object): def __init__(self, name, age): # 在创建对象时,会自动调用这个方法 print("__init__方法被调用了") self.name = name self.age = age def __del__(self): # 当对象被销毁时,会自动调用这个方法 print("__del__方法被调用了") def __repr__(self): return "hello" def __str__(self): # return "good" return "姓名是{},年龄是{}".format(self.name, self.age) def __call__(self, *args, **kwargs): # print("__call__方法被调用了") #args 是一个元组,保存(1,2) # kwargs 是一个字典 {'fn': <function <lambda> at 0x000001B3F9F48708>} print("args = {},kwargs = {}".format(args,kwargs)) x = args[0] y = args[1] test = kwargs['fn'] return test(x,y) p = Person("张三", 18) # 如果不做任何的修改,直接打印一个对象,是文件的__name.__类型 内存地址 # print(p) #<__main__.Person object at 0x0000017E6CF3BE48> # 当打印一个对象的时候,会调用这个对象的__str__ 或者__repr__方法 # 如果两个方法都写了,选择__str__方法 # 使用__str__和__repr__方法,都会修改一个对象转换成字符串的结果。一般来说,__str__方法的结果 # 更加在意可读性,而__repr__方法的结果更加在意正确性 print(p) # good print(repr(p)) # 调用内置函数repr 会触发对象的__repr__方法 print(p.__repr__()) # 魔法方法,一般不会手动调用 # 如果定义类的时候没有定义 __call__方法,调用p()时会报错 TypeError: 'Person' object is not callable # p() #对象名()==> 调用这个对象的__call__方法,还可以进行传参,传参如下: x = p(1, 2, fn=lambda x, y: x + y) print(x)
c98b4be5ebfaccb676aec4a12ef1c248a14b61c9
sreehari333/pdf-no-4
/finding the second largest number.py
366
3.734375
4
list1 = [10, 20, 4, 45, 99] mx = max(list1[0], list1[1]) secondmax = min(list1[0], list1[1]) n = len(list1) for i in range(2, n): if list1[i] > mx: secondmax = mx mx = list1[i] elif list1[i] > secondmax and \ mx != list1[i]: secondmax = list1[i] print("Second highest number is : ", \ str(secondmax))
439517c3044f848c3d3cdc13b9f60548bb49b4d4
LasTshaMAN/poetry_scrapper
/processing.py
515
3.765625
4
from collections import Counter import nltk from nltk.corpus import stopwords def text_to_word_count(text): text = text.lower() words = nltk.word_tokenize(text) words = filter_stop_words(words) return dict(Counter(words).most_common()) def filter_stop_words(words): # Might use custom list of stop-words (e.g. taken from here - https://www.ranks.nl/stopwords) stop_words = set(stopwords.words("english")) return [word for word in words if word not in stop_words and word.isalpha()]
2de3e99808500542d25e10bd61fefe9a8f9703d8
juanfdg/JuanFreireCES22
/Aula3/Problem_14_11_1_e.py
777
3.59375
4
def bagdiff(xs, ys): """ bagdiff for the first list.""" result = [] xi = 0 yi = 0 while True: if xi >= len(xs): # If xs list is finished, we're done return result if yi >= len(ys): # If ys list is finished result.extend(xs[xi:]) # Add the last elements of xs return result # And we're done # Both lists still have items, copy smaller item to result. if xs[xi] < ys[yi]: result.append(xs[xi]) xi += 1 elif xs[xi] > ys[yi]: yi += 1 else: xi += 1 yi += 1 print(bagdiff([1, 2, 5, 7], [1, 3, 5, 6])) print(bagdiff([5, 7, 11, 11, 11, 12, 13], [7, 8, 11])) print(bagdiff([7, 8, 11], [5, 7, 11, 11, 11, 12, 13]))
d89d76b57a914617374ae2be28918b6019c91b82
juanfdg/JuanFreireCES22
/Aula3/Problem15_12_4.py
369
3.84375
4
class Point(): def __init__(self, x, y): self.x = x self.y = y # Method wont work when other_point.x - self.x = 0 def get_line_to(self, other_point): slope = (other_point.y-self.y)/(other_point.x-self.x) linear_coef = self.y - slope*self.x return (slope, linear_coef) print(Point(4, 11).get_line_to(Point(6, 15)))
fae94561b78158c49e3aece7739ee839b330e237
juanfdg/JuanFreireCES22
/Aula7/ConsumerProducer.py
1,462
3.65625
4
from threading import Thread, Lock import time import random shared_item = 0 itens_done = 0 available = False class Producer(Thread): global shared_item global available def __init__(self, lock): Thread.__init__(self) self.lock = lock self.produced = False def run(self): for i in range(10): item = random.randint(0, 256) self.lock.acquire() if self.produced == False: shared_item = item self.produced = True available = True print('Producer notify: item Nº%d added by %s\n' % (item, self.name)) time.sleep(1) self.lock.release() class Consumer(Thread): global shared_item global itens_done global available def __init__(self, lock): Thread.__init__(self) self.lock = lock def run(self): global available while itens_done < 10: self.lock.acquire() if available: item = shared_item available = False print('Consumer notify: %d consumed by %s' % (item, self.name)) self.lock.release() if __name__ == '__main__': lock = Lock() t1 = Producer(lock) t2 = Consumer(lock) t3 = Consumer(lock) t4 = Consumer(lock) t1.start() t2.start() t3.start() t4.start() t1.join() t2.join() t3.join() t4.join()
28e2a37dc3851d46de39dff79db94ffdc81b4d42
juanfdg/JuanFreireCES22
/Aula2/Problem4_9_10.py
325
3.640625
4
import turtle def star(t): for i in range(5): t.forward(100) t.right(144) wn = turtle.Screen() wn.bgcolor('lightgreen') pen = turtle.Pen() pen.color('purple') for i in range(5): star(pen) pen.forward(100) pen.penup() pen.forward(350) pen.pendown() pen.right(144) wn.mainloop()
dde161338c0e9cd80a6a883fb86abb5cf20c666c
Antares2k16/python_learning
/employee_info.py
394
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 23 14:49:13 2018 @author: aliao """ class Employee(): def __init__(self, first_name, last_name, salary): self.first_name = first_name self.last_name = last_name self.salary = salary def give_raise(self, boost=5000): self.boost = boost self.salary += self.boost
b842b9cfcc54bd719dd8ff1c113a879d81645030
HANICA/MachineLearningP3
/ud120-projects-master/datasets_questions/explore_enron_data_6_25_jk.py
1,337
3.703125
4
#!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that person. You should explore features_dict as part of the mini-project, but here's an example to get you started: enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000 Of these three individuals (Lay, Skilling and Fastow), who took home the most money (largest value of total_payments feature)? """ import pickle #fileLines = tuple(open('../final_project/poi_names.txt', 'r')) personsOfInterest = 0 file = open('../final_project/final_project_dataset.pkl', 'rb') enron_data = pickle.load(file) #numItems = len(enron_data["SKILLING JEFFREY K"]) poi_lastnames = ["Lay", "Skilling", "Fastow"] lookingFor = "total_payments" for person in enron_data: for poi in poi_lastnames: if person.find(poi.upper()) >= 0: print("Found: " + person) #print(enron_data[person]) print("Query result: " + str(enron_data[person][lookingFor])) #print(str(enron_data[person]["total_stock_value"])) #print(fileLines) #print("Number of features: " + str(personsOfInterest))
94a64d991e2bb98e76d3e27c4162982cded2d731
HANICA/MachineLearningP3
/ud120-projects-master/svm/svm_author_id_subset_rbf_c_items_37_jk.py
1,972
3.546875
4
#!/usr/bin/python """ This is the code to accompany the Lesson 2 (SVM) mini-project. Use a SVM to identify emails from the Enron corpus by their authors: Sara has label 0 Chris has label 1 J.A. Korten Sept 2018 See: http://scikit-learn.org/stable/modules/svm.html Excercise 3.47 There are over 1700 test events-- how many are predicted to be in the “Chris” (1) class? (Use the RBF kernel, C=10000., and the full training set.) """ import sys from time import time sys.path.append("../tools/") from email_preprocess import preprocess #added: import numpy ### features_train and features_test are the features for the training ### and testing datasets, respectively ### labels_train and labels_test are the corresponding item labels features_train, features_test, labels_train, labels_test = preprocess() ######################################################### ### your code goes here ### ### J.A. Korten Sept 2018 from sklearn import svm clf = svm.SVC(C=10000.0, kernel='rbf', gamma='auto') print("Fit (training)...") t0 = time() # Making it a lot faster but using less features / labels: (ignore 100% now!) #features_train = features_train[:int(len(features_train)/100)] #labels_train = labels_train[:int(len(labels_train)/100)] clf.fit(features_train, labels_train) timing_str = "training time: " + str(round(time()-t0, 3)) + "s" print(timing_str) t1 = time() print("Predict...") predict = clf.predict(features_test) timing_str = "prediction time: " + str(round(time()-t1, 3)) + "s" print(timing_str) print("Accuracy...") accuracy = clf.score(features_test, labels_test) print("accuracy: " + str(round(accuracy, 4))) # answers: print("Finding an answer...") numChris = 0 # Chris is a 1 actually ;) for i in range(len(predict)): if (predict[i] == 1): numChris += 1 print(str(numChris) + " emails are predicted to be from Chris...") #########################################################
36d891f703683a78d93e518e080c5964d3756384
HANICA/MachineLearningP3
/ud120-projects-master/tools/rescaler_jk.py
423
3.765625
4
#!/usr/bin/python import numpy import sys def featureScaling(arr): minF = 0 maxF = 0 feature = 0 if len(arr) == 3: minF = min(arr) maxF = max(arr) for item in arr: if (item != minF) and (item != maxF): feature = item rescaledFeature = (feature - minF) / (maxF - minF) return (feature - minF) / (maxF - minF) else: return 0.0
7d58552ddee2fb969005b372aed4bc75c453d666
jeffsilverm/GaryCrane
/Jeffs_Phylo_tree.py
15,161
4.09375
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 7 17:19:25 2017 @author: Crane Modified Tue Feb 7th 20:10 2017 @author: Jeff Silverman, HMC '80 ======================================================================== Created on Wed Jul 6 17:55:31 2016 C:\Python34\PhylogeneticTrees.py @author: Crane """ # This is from https://www.cs.hmc.edu/twiki/bin/view/CFB/PhylogeneticTrees from __future__ import print_function # Makes the code work equally well on python 2 or python 3 import sys import pprint import pdb """ leafCount(Tree) >>> leafCount(Groodies) 4 >>> leafCount((5,(3,("A", (), ()),("B", (), ())),("C", (), ()))) 3 find(node, Tree) This function returns True if the given node is in the given Tree and returns False otherwise. Some examples of find: >>> find('W',Groodies) True >>> find('A',Groodies) False >>> find('E',Groodies) True subtree(node, Tree) Returns the subtree of the given Tree rooted at the given node. Said another way, this function returns the tree beginning at node. This function can be very short, and may have as few as four lines in its body. It will be recursive, but can also call the find function for help. In particular, if the root of the Tree matches node then we just return that Tree. If not, we can use find to determine whether the species is in the left subtree or the right subtree, and then proceed from there. You can assume that node is present in Tree. Here are some examples: >>> subtree("W", Groodies) ('W', (), ()) >>> subtree("Y", Groodies) ('Y', ('W', (), ()), ('Z', ('E', (), ()), ('L', (), ()))) >>> subtree("Z", Groodies) ('Z', ('E', (), ()), ('L', (), ())) nodeList(Tree) Takes a Tree as input and returns a list of all of the nodes in that tree (including both leaves and ancestral nodes). This function can be done in three lines of code, but you are welcome to make it longer if you like. Here is an example: >>> nodeList(Groodies) ['X', 'Y', 'W', 'Z', 'E', 'L', 'C'] descendantNodes(node, Tree) Returns the list of all descendant nodes of the given node in the Tree. This function will not be recursive itself, but it will call the nodeList and subtree functions for help. This function can be written in two lines of code (not counting the def line and the docstring). Here are some examples of descendantNodes: >>> descendantNodes("X", Groodies) ['Y', 'W', 'Z', 'E', 'L', 'C'] >>> descendantNodes("Y", Groodies) ['W', 'Z', 'E', 'L'] >>> descendantNodes("Z", Groodies) ['E', 'L'] parent(node, Tree) returns the parent of the given node in the Tree. If the node has no parent in the tree, the function should return the special value None. >>> parent("Y", Groodies) 'X' >>> parent("W", Groodies) 'Y' >>> parent("Z", Groodies) 'Y' >>> parent("E", Groodies) 'Z' >>> parent("X", Groodies) >>> parent("X", Groodies) == None True scale(Tree,scaleFactor) As we've discussed, internal nodes represent the most recent common ancestor of the species which descend from them. In the example tree above, we've labelled these nodes using letters, the same way we've labeled the leaf nodes. However sometimes biologists like to include other kinds of information at these nodes, for example, information on when that most recent common ancestor lived. Here is a tree where the internal nodes are labeled with numbers. Tree = (4.3, ('C', (), () ), (3.2, ('A',(), ()), ('B',(),())) ) Perhaps we're measuring time in millions of years before present. In that case, this tree would tell us that species A and B had a most recent common ancestor which lived 3.2 million years ago, and that all three species (A, B and C) had a most recent common ancestor that lived 4.3 million years ago. Your task now is to write a function scale which takes a Tree as input, and multiplies the numbers at its internal nodes by scaleFactor and returns a new tree with those values. Here are some examples: >>> Tree = (4.3, ('C', (), () ),(3.2, ('A',(), ()), ('B',(),())) ) >>> scale(Tree,2.0) (8.6, ('C', (), ()), (6.4, ('A', (), ()), ('B', (), ()))) We will later use this function to calibrate trees so we can better estimate dates in human evolution. """ # Set this flag to True for debugging purposes. Clear this flag for production. DEBUG_FLAG=True Groodies = ( "X", ("Y", ("W", (), ()), ("Z", ("E", (), ()), ("L", (), ()) ) ), ( "C", (), () ) ) def leafCount ( tree ): """This counts the number of leaves in Tree tree. A tree is a leaf if and only if both children are empty tuples""" if DEBUG_FLAG : # See https://docs.python.org/3.6/library/string.html#custom-string-formatting for more information on the format method print( "In leaf count at {}".format( tree[0] ), file=sys.stderr ) # This is a test to make sure that I haven't done something stupid. In general, when I find a bug, I fix it, and then # I add a test to make sure that it stays fixed. assert len(tree) == 3, "In leafCount, at {}: the length of tree is {} but should be 3. tree is {}".format( tree[0], len(tree), \ str( tree ) ) if tree[1] != () and tree[2] != () : return leafCount ( tree[1]) + leafCount ( tree[2]) elif tree[1] != () : return leafCount ( tree[1]) elif tree[2] != () : return leafCount ( tree[2]) else : # This tree is a leaf, both children are empty return 1 def find ( target, tree ): """This function returns True if the given node is in the given Tree and returns False otherwise. """ if DEBUG_FLAG : print( "In find, at {}. ".format(tree[0]), file=sys.stderr ) assert len(tree) == 3, "In find, at {}: the length of tree is {} but should be 3".format( tree[0], len(tree) ) # If this tree is what we're looking for, then we're done. if tree[0] == target : return True # if this tree is not the tree we're looking for and this tree has no children, then it is hopeless. elif tree[1] == () and tree[2] == () : return False # If this tree is not the tree we're lookikng for AND it has children, then maybe one of its descendents is the # tree we're looking for. else : if tree[1] != () and tree[2] != () : return find ( target, tree[1]) or find ( target, tree[2]) elif tree[1] != () : return find ( target, tree[1]) elif tree[2] != () : return find ( target, tree[2]) else : # raise AssertionError does the same thing as the assert statement, but without the test. We know that if we got here, # Then something is wrong with the program because an earlier test dealt with the case where both tree[1] and tree[2] # are both empty tuples. raise AssertionError ("At {}: for some reason, we're here".format(tree[0]) ) def nodeList(tree): '''returns the list of nodes in a given tree''' nodes = [tree[0]] if len(tree[1]) > 1: nodes = nodes + nodeList(tree[1]) if len(tree[2]) > 1: nodes = nodes + nodeList(tree[2]) return nodes def subtree(node_name, tree): """ Returns the subtree of the given Tree rooted at the given node. Said another way, this function returns the tree beginning at node. This function can be very short, and may have as few as four lines in its body. It will be recursive, but can also call the find function for help. In particular, if the root of the Tree matches node then we just return that Tree. If not, we can use find to determine whether the species is in the left subtree or the right subtree, and then proceed from there. You can assume that node is present in Tree. Here are some examples: >>> subtree("W", Groodies) ('W', (), ()) >>> subtree("Y", Groodies) ('Y', ('W', (), ()), ('Z', ('E', (), ()), ('L', (), ()))) >>> subtree("Z", Groodies) ('Z', ('E', (), ()), ('L', (), ())) """ # Verify that were given a tuple assert type(tree) == type( () ), "In subtree: the type of tree should be tuple, but is {}".format(str(type(tree))) # If we're given an empty tree, then return an empty tree if len(tree) == 0 : return ( () ) # This is a test to make sure that I haven't done something stupid. In general, when I find a bug, I fix it, and then # I add a test to make sure that it stays fixed. assert len(tree) == 3, "In subtree, at {}: the length of tree is {} but should be 3. tree is {}".format(tree[0], len(tree), str(tree) ) if DEBUG_FLAG : print("node_name=", node_name, "tree is ", tree, file=sys.stderr ) if tree[1] != () and tree[2] != () : print ( "In subtree at node {}. One of the children is {} and the other child is {}".format \ ( tree[0], tree[1][0], tree[2][0] ), file=sys.stderr ) elif tree[1] != () : print ( "In subtree at node {}. Child 1 is {} and there is no child 2".format \ ( tree[0], tree[1][0] ), file=sys.stderr) elif tree[2] != () : print ( "In subtree at node {}. There is no child 1 and child 2 is {} ".format \ ( tree[0], tree[2][0] ), file=sys.stderr) else : print ( "In subtree at node {}. There are no children ".format ( tree[0] ), file=sys.stderr ) # THIS IS HORRENDOUS DEBUG CODE if tree[0] == "Ben" : print("in subtree at Ben. Hitting a breakpoint. HORRENDOUS DEBUG CODE") print("node_name=", node_name, file=sys.stderr ) pp.pprint(tree) pdb.set_trace() try: # This block of code should be refactored to test to see if we found what we are looking first. if tree[1] == () and tree[2] == (): # this node has no children, so it has no subtrees, this tree is a leaf. The node_name # is in tree[0]. If this node is not the node we are looking for, then return an empty # tuple, because the node_name was not found if tree[0] != node_name : print("At {}: there are no children and did not find {} so can not search further".format(tree[0], \ node_name), file=sys.stderr) # Construct a leaf node return ( ( tree[0], (), () ) ) elif tree[1] != () and tree[2] != (): if tree[0] == node_name : # We found our node. Both tree[1] and tree[2] are both subtrees return ( tree[0], subtree(node_name,tree[1]), subtree(node_name,tree[2]) ) else : return ( (subtree(node_name, tree[1]), subtree(node_name, tree[2]) ) ) elif tree[1] != () : # tree[1] is a subtree, tree[2] is a leaf if tree[0] == node_name : # Here, we are building a new node, with the name of the node, the subtree in child 1, an empty subtree in child 2 return ( tree[0], subtree(node_name, tree[1], ()) ) else : # Return a subtree, which is a tree, but do not create a new node return subtree(node_name, tree[1] ) # tree[2] is a subtree, tree[1] is a leaf elif tree[2] != () : if tree[0] == node_name : return ( tree[0], (), subtree(node_name, tree[2] ) ) else : return subtree(node_name, tree[2] ) else : print("About to raise AssertionError", file=sys.stderr ) except AssertionError as a: print("in subtree at {}: one of the children raised AssertionError. Child 1 is {}. Child 2 is {}" ).format(\ tree[0], tree[1][0], tree[2][0] ) # Raise the AssertionException. This will force the caller to run its AssertionError handler and output the values at # its level raise raise AssertionError("Not sure how we got here, in subtree, but we did.\n Tree is {}".format(str(tree))) # This is a unit test. If this module is imported into another module, then this test will fail and the following software # will not be executed. But if this module is NOT imported, the __name__ will be "__main__" and the software below will be # executed if __name__ == "__main__" : # Do some unit testing pp = pprint.PrettyPrinter() # Define my own test tree, which is different from but similar to Groodies # Note that there are 4 test cases: no children, #1 child, #2 child, 2 children fred = ("Fred", (), () ) # Fred has no childer george = ("George", (), () ) # George has no children eric = ("Eric", fred, () ) # Fred is Eric's son (first child) david = ("David", (), eric ) # Eric is David's son (second child. I know this is strange, but I need it for debugging charles = ( "Charles", (), () ) # Charles has no children ben = ( "Ben", charles, david) # Ben has 2 children alice = ( "Alice", ben, george ) jeffs_tree = alice # Note that this is not a copy! 2 identifiers pointing to the same object # jeffs_tree = ( "Alice", # Alace's children are Ben and George # ("Ben", # Ben has 2 children, Charles and David # ( "Charles", (), () # Charles has no children # ), \ # ( "David", (), # David has 1 son, Eric # ("Eric", (), # Eric has a son, Fred. Fred a second son, not because that means anything but it is a test case # ("Fred", (), ()) # Fred has no children # ), # () \ # ), \ # ), \ # ( 'George', (), () ) # George is the son of Alice # ) pp.pprint( jeffs_tree ) def my_test ( actual, nominal, label): """This is a generic test subroutine. actual is the result of the function. nominal is the "correct" answer label is a message to print """ if actual == nominal : print( "CORRECT: {}".format(label) ) else : if type(nominal) == type( () ) : print("ERROR at {} is a tuple. Nominal is:".format(label) ) pp.pprint(nominal) print("Actual is:") pp.pprint(actual) else : print ( "ERROR at {}: {} should be {}".format( label, actual, nominal ) ) return ( actual, nominal ) my_test ( leafCount(Groodies), 4, "Groodies" ) my_test ( leafCount((5,(3,("A", (), ()),("B", (), ())),("C", (), ()))), 3, "Instructor provided" ) my_test ( leafCount ( jeffs_tree ), nominal=3, label="Jeff's tree" ) my_test ( find('W',Groodies), True, "W in Groodies" ) my_test ( find('A',Groodies), False, "A in Groodies" ) my_test ( find('E',Groodies), True, "E in Groodies" ) my_test ( subtree( node_name='W', tree=(('W', (), () )) ), nominal=('W', (), () ), label="Testing subtree with W" ) my_test ( subtree( node_name="David", tree=jeffs_tree), david, "Testing subtree with david" ) my_test ( subtree( node_name="Ben", tree=jeffs_tree), ben, "Testing subtree with ben" )
5c88f6ac529ce9c0c3255805ebaa7743f222bacc
leebecker/InterAnnotatorAgreement
/stats/Agreement.py
4,324
4
4
import math import unittest from collections import defaultdict class Agreement: """ Class for computing inter-rater reliability """ def __init__(self, rater_responses): """ Arguments: rater_responses -- a list of maps of item labels. ex. [{'item1':1, 'item2':5}, {'item1':2}] """ if len(rater_responses) < 2: raise InputError("Rater responses should have ratings for at least two raters.") self.ratings = rater_responses pass def krippendorffAlpha(self, metric=None): """ Krippendorff's alpha coefficient is a statistical measure of the agreement achieved when coding a set of units of analysis in terms of the values of a variable. For more info refer to: http://en.wikipedia.org/wiki/Krippendorff's_Alpha metric -- the difference function to use when computing alpha """ if metric is None: metric = Agreement.differenceNominal items = set([k for r in self.ratings for k in r.keys()]) valueCounts, coincidence = self.computeCoincidenceMatrix(items, self.ratings) n = sum(valueCounts.values()) numeratorItems = [coincidence[c][k] * metric(c,k, valueCounts) \ for (c, nc) in valueCounts.iteritems() for (k, nk) in valueCounts.iteritems()] denominatorItems = [nc * nk * metric(c,k, valueCounts) for (c, nc) in valueCounts.iteritems() for (k, nk) in valueCounts.iteritems()] Do = (n-1) * sum(numeratorItems) De = sum(denominatorItems) alpha = 1 - Do / De return alpha def computeCoincidenceMatrix(self, items, ratings): """ From Wikipedia: A coincidence matrix cross tabulates the n pairable values from the canonical form of the reliability data into a v-by-v square matrix, where v is the number of values available in a variable. Unlike contingency matrices, familiar in association and correlation statistics, which tabulate pairs of values (Cross tabulation), a coincidence matrix tabulates all pairable values. A coincidence matrix omits references to coders and is symmetrical around its diagonal, which contains all perfect matches, c = k. The matrix of observed coincidences contains frequencies: o_ck = sum(# of c-k pairs in u (ratings) / m_u -1) ratings - list[dict[item] => label] returns - dict[label] => int = valueCounts -- a lookup table for value frequencies dict[(label,label)] => double coincidence value, -- a lookup table for value-value frequencies """ coincidence = defaultdict(lambda: defaultdict(int)) valueCounts = defaultdict(int) for item in items: itemRatings = [r[item] for r in ratings if item in r] numRaters = len(itemRatings) if numRaters < 2: continue fractionalCount = 1.0 / (numRaters-1) # m_u = numRaters - 1 for i, ri in enumerate(itemRatings): valueCounts[ri] += 1 for j, rj in enumerate(itemRatings): if i == j: continue coincidence[ri][rj] += fractionalCount return valueCounts, coincidence @classmethod def differenceNominal(cls, c, k, valueCounts): return int (c != k) @classmethod def differenceOrdinal(cls, c, k, valueCounts): if c >= k: return 0 diff = sum([valueCounts[g] for g in xrange(c+1, k) if g in valueCounts]) diff += (valueCounts[c] + valueCounts[k]) / 2.0 return math.pow(diff, 2) @classmethod def differenceInterval(cls, c, k, valueCounts): return math.pow(c-k, 2) @classmethod def differenceRatio(cls, c, k, valueCounts): return math.pow(float(c-k)/(c+k), 2) class Error(Exception): """Base class for exceptions in this module.""" pass class InputError(Error): """Exception raised for errors in the input. Attributes: expr -- input expression in which the error occurred msg -- explanation of the error """ def __init__(self, expr, msg): self.expr = expr self.msg = msg
1cf8cfebd1827f1120c0b23107aa34831b4d63d5
nadiavdleer/prograil
/code/classes/trajectory.py
2,116
3.609375
4
class Trajectory: def __init__(self, start): """ trajectory object is a collection of connections """ self.start = start self.end = start self.connections = [] self.itinerary = [start.name] self.total_time = 0 self.score = 0 def add_connection(self, connection): """ add a connection to a trajectory """ self.connections.append(connection) self.total_time += connection.time if self.end == connection.station1: self.end = connection.station2 self.itinerary.append(self.end.name) elif self.end == connection.station2: self.end = connection.station1 self.itinerary.append(self.end.name) def remove_connection(self, connection): """ remove a connection from a trajectory """ self.connections.remove(connection) self.total_time -= connection.time # end remove if self.end == connection.station1: self.end = connection.station2 del self.itinerary[-1] elif self.end == connection.station2: self.end = connection.station1 del self.itinerary[-1] # remove from start elif self.start == connection.station1: self.start = connection.station2 self.itinerary.remove(connection.station1.name) elif self.start == connection.station2: self.start = connection.station1 self.itinerary.remove(connection.station2.name) def quality(self, connections): """ return quality score of a trajectory """ p = 0 total_connections = 0 for connection in connections: total_connections += 1 if connection in self.connections: p += 1 p = p / total_connections T = 1 Min = self.total_time K = p*10000 - (T*100 + Min) return K def __str__(self): return f"start: {self.start} end: {self.end}"
fa2d7a1cf84df832521281ad836c686b6bb78fe3
qingyuannk/phoenix
/dp/jumpgame.py
2,117
3.78125
4
""" 递归动态规划 """ class Solution(object): def canJump(self,nums): if len(nums) == 1: return True for i in range(1,nums[0]+1): if i <= len(nums): if self.canJump(nums[i:]): return True else: return True return False """ 备忘录递归动态规划 """ class Solution(object): def canJump(self,nums): n = len(nums) if n == 1: return True a = [0] * n a[n-1] = 1 position = 0 return self.canJumps(nums,a,position) def canJumps(self,nums,a,position): print(nums[position]) if a[position] != 0: print(1) if a[position] == 1: return True else: return False print(position) furjump = min(nums[position]+position,len(nums)-1) for i in range(position+1,furjump+1): if i <= len(nums): if self.canJumps(nums,a,i): a[i] = 1 return True else: return True a[position]=-1 return False """ 自底向上动态规划 """ class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) if n == 1: return True memo = [0] * n memo[n-1] = 1 m = n - 2 while m>= 0: furjump = min(m+nums[m],n) print(m,furjump) for j in range(m+1,furjump+1): if (memo[j] == 1): memo[m]= 1 break m = m -1 print(memo) return memo[0] == 1 """ 贪心算法 """ class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) - 2 lasted = len(nums)- 1 while n >= 0: if (n + nums[n]>= lasted): lasted= n n = n - 1 return lasted== 0
331c08ad9a30921c2e24477263065e8d5ee584ef
qingyuannk/phoenix
/sliding_windows/Permutation_in_Sring.py
1,575
3.796875
4
""" Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string. Example1: Input: s1 = "ab" s2 = "eidbaooo" Output: True Explanation: s2 contains one permutation of s1 ("ba"). """ class Solution(object): def checkInclusion(self, s1, s2): """ :type s1: str :type s2: str :rtype: bool """ if(len(s1)>len(s2) or len(s2) == 0): return False a = [0]*26 sums = 0 L = 0 n = len(s1) R = n-1 for s in s1: sums +=ord(s) index = ord(s)-ord('a') a[index] +=1 sums1 = 0 for i in range(L,n): sums1 += ord(s2[i]) while(R<len(s2)): if sums1 != sums: if(R == len(s2)-1): break sums1 = sums1 - ord(s2[L]) L = L + 1 R = R + 1 sums1 = sums1 + ord(s2[R]) else: b = [0]*26 for i in range(L,R+1): index = ord(s2[i])-ord('a') b[index] +=1 if(a == b): return True else: if(R == len(s2)-1): break sums1 = sums1 - ord(s2[L]) L = L + 1 R = R + 1 sums1 = sums1 + ord(s2[R]) return False
db95e99f20fe9d18b38bff2fbff889fe0671d6c1
nandy23/python-belajar
/jamkedetik.py
307
3.78125
4
print("Konversi jam ke detik") jam = int(input("Masukan Jam : ")) menit = int(input("Masukan Menit : ")) detik = int(input("Masukan Detik : ")) total_detik = ((jam * 3600) + (menit * 60) + detik) print(str(jam) + ":" + str(menit) + ":" + str(detik) + " Sama dengan " + str(total_detik) + " detik")
9cd8f12a70e688213149f89dfd4e86e5dff5338f
Zackno23/taskC
/c_2.py
1,080
3.78125
4
import csv class Customer: def __init__(self, first_name, family_name, age): self.first_name = first_name self.family_name = family_name self.age = age def full_name(self): return f"{self.first_name} {self.family_name}" def age(self): return self.age def entry_fee(self): if self.age <= 3: return 0 elif self.age < 20: return 1000 elif self.age >= 75: return 500 elif self.age >= 65: return 1200 else: return 1500 def info_csv(self): name = f"{self.first_name} {self.family_name}" return '|'.join([name, str(self.age), str(self.entry_fee())]) ken = Customer(first_name="Ken", family_name="Tanaka", age=75) print(ken.info_csv() ) # 1000 という値を返す tom = Customer(first_name="Tom", family_name="Ford", age= 57) print(tom.info_csv()) # 1500 という値を返す ieyasu = Customer(first_name="Ieyasu", family_name="Tokugawa", age=73) print(ieyasu.info_csv()) # 1200 という値を返す
22a3d1c71ccdeabae5060cdd52ab9cf2cc147c90
Carlosterre/Pythonchallenge
/10.py
2,628
3.515625
4
# "len(a[30]) = ?" # Clickando la vaca: "a = [1, 11, 21, 1211, 111221, ". Es la "Look-and-say sequence" # 1.- Solucion simple a = '1' b = '' for i in range(0, 30): j = 0 k = 0 while j < len(a): while k < len(a) and a[k] == a[j]: k += 1 b += str(k - j) + a[j] j = k print(b) a = b b = '' print(len(a)) # 2.- Usando Python import re print(re.findall(r"(\d)(\1*)", "111221")) # Expresion regular para encontrar las parejas de (numeros, length). El patron es un string fila (r"..."), lo que significa que no necesita '\' # Equivalente a 're.findall("(\\d)(\\1*)", "111221")' # Tuplas: (Primera aparicion, siguiente aparicion) -> de la primera se extrae el numero, de la segunda la length-1 -> length+1 x = '1' print("".join([str(len(i+j))+i for i,j in re.findall(r"(\d)(\1*)", x)])) print("".join([str(len(i+j))+i for i,j in re.findall(r"(\d)(\1*)", "1")])) print("".join([str(len(i+j))+i for i,j in re.findall(r"(\d)(\1*)", "11")])) print( "".join([str(len(i+j))+i for i,j in re.findall(r"(\d)(\1*)", "21")])) print("".join([str(len(i+j))+i for i,j in re.findall(r"(\d)(\1*)", "1211")])) for n in range(30): # Corriendo el bucle 30 veces x="".join([str(len(j) + 1)+i for i, j in re.findall(r"(\d)(\1*)", x)]) print(len(x)) # 3.- Utilizando 'itertools.groupby()' en vez de expresiones regulares para encontrar las parejas (numeros, length) import itertools print("".join([str(len(list(j))) + i for i,j in itertools.groupby("1211")])) print([(i, list(j)) for i,j in itertools.groupby("1211")]) # No es necesario el '+1' x = "1" for n in range(30): x = "".join([str(len(list(j))) + i for i,j in itertools.groupby(x)]) print(len(x)) # 4.- En una sola linea # 2 'reduce()'anidados. El exterior simplemente corre 30 veces, y establece el valor inicial 1 para la x. El interior hace lo mismo que la solucion 3.- from itertools import groupby from functools import reduce print(len(reduce(lambda x, n:reduce(lambda a, b: a + str(len(list(b[1]))) + b[0], groupby(x), ""), range(30), "1"))) solution = len(x) print(solution) # cambiar la URL por http://www.pythonchallenge.com/pc/return/5808.html
79e0416290c99d0225d011e206d5e5d3269ac28b
jeremy-y-walker/nlc-classifier
/NLC.py
1,953
3.515625
4
######################################################################## # # # Nearest Local Centroid Classifier # # Author: Jeremy Walker # # Author Affiliation: San Jose State University College of Science # # Date Last Modified: 6/21/2021 # # E-mail: [email protected] # # # ######################################################################## import numpy as np from sklearn.neighbors import NearestNeighbors from scipy.spatial import distance #X_train should be the numeric training data in a numpy matrix, with each row corresponding #to a data point #y_train should be a 1-dimensional numpy array of integers to code for each class #query_vec should be a 1-dimensional (row) numpy array to be classified based on training data #k is the number of nearest neighbors to be considered when calculating the local class centroids def NLC(X_train, y_train, query_vec, k): centroidDists = []; n_classes = len(set(y_train)) for j in range(n_classes): classSubset = X_train[y_train == j,:] neighbors = NearestNeighbors(n_neighbors = k) neighbors.fit(classSubset) distances, indices = neighbors.kneighbors(np.reshape(query_vec,(1,-1))) centroid = np.mean(classSubset[indices,:], axis = 1) dist = distance.euclidean(centroid, query_vec) centroidDists.append(dist) return np.argmin(centroidDists) #this function will return the classification of a single query vector; included below is an #example implementation to apply NLC to a matrix of multiple data points for classification y_pred = [NLC(X_train, y_train, query_vec = i, k = 9) for i in X_test]
26df2cc6b32fe2cb664cd80e0efff6d71995071d
SzymanskiKrzysztof/TicTacToe
/TicTacToeGame.py
3,330
3.921875
4
def start(): print('Welcome to Tic Tac Toe!') def clear_board(): for i in range(1, 10): board_map[i] = '' def display_board(board): print(f' {board[7]} | {board[8]} | {board[9]} ') print(f'---------------') print(f' {board[4]} | {board[5]} | {board[6]} ') print(f'---------------') print(f' {board[1]} | {board[2]} | {board[3]} ') def player_mark(player): while True: position = int(input('Choose you position: (1-9) ')) if position in range(1, 10) and board_map[position] == "": board_map[position] = player break else: print('Wrong position. Please try again.') def first_player(): while True: first_mark = input('Player 1: Do you want to be X or 0? ').upper() if first_mark == "X" or first_mark == "0": print('Player 1 will go first.') return first_mark else: print("Wrong mark. Please try again.") def ready_to_play(): while True: ready = input('Are You ready to play? Enter YES or NO. ').upper() if ready == 'YES': return True elif ready == 'NO': print('Thanks for You game') return False else: print('Unkown answer. Please try again.') def play_again(): while True: again = input('Do You want play again? Enter: Yes or No. ').upper() if again == 'YES': clear_board() return True elif again == 'NO': print('Thanks for You game') return False else: print('Unkown answer. Please try again.') def check(board): if board_map[7] == board[8] == board[9] != "": print('You win game') return True elif board[4] == board[5] == board[6] != "": print('You win game') return True elif board[1] == board[2] == board[3] != "": print('You win game') return True elif board[7] == board[4] == board[1] != "": print('You win game') return True elif board[8] == board[5] == board[2] != "": print('You win game') return True elif board[9] == board[6] == board[3] != "": print('You win game') return True elif board[7] == board[5] == board[3] != "": print('You win game') return True elif board_map[1] == board[5] == board[9] != "": print('You win game') return True else: if "" in board.values(): return False else: print('DRAW!') return True while True: board_map = {7: "", 8: "", 9: "", 4: "", 5: "", 6: "", 1: "", 2: "", 3: ""} start() player_1 = first_player() if player_1 == "X": player_2 = "0" else: player_2 = 'X' play = ready_to_play() display_board(board_map) while play: player_mark(player_1) display_board(board_map) if check(board_map): break player_mark(player_2) display_board(board_map) if check(board_map): break if not play_again(): break
6cc71c99bec4e3da9a9a61cf65d04af95f4cdf4b
ALuqueM/Trabajo-final-Python
/Trabajo Final/Modulo 1/Scripts/Problema 1.py
150
4.03125
4
y = input('Ingrese por favor su Nombre:') print('hello, {}.'.format(y)) x = input('Ingrese por favor su Nombre:') print('hello, {}.'.format(x))
6d4ef25c5d3bb2f2225eca4ef1ed864adc896b7d
ZainabMehdee/Separate-Numbers-and-Add-Them-Together
/main.py
321
3.859375
4
# 🚨 Don't change the code below 👇 two_digit_number = input("Type a two digit number: ") # 🚨 Don't change the code above 👆 #################################### #Write your code below this line 👇 print(type(two_digit_number)) a = int(two_digit_number [0]) b = int(two_digit_number [1]) print (a + b)
4cf7bed9b1dabd9b8a0963294fcf5019bb8cdd49
AlbertGithubHome/Bella
/python/datetime_test.py
1,074
3.6875
4
# datetime test from datetime import datetime print(datetime.now()) dt = datetime(2000, 8, 8, 13, 45, 6) print('dt =',dt) time_stamp = dt.timestamp() print('dt.timestamp =', time_stamp) print('now.timestamp =', datetime.now().timestamp()) now_timestamp = datetime.now().timestamp(); print('now_timestamp =', now_timestamp) print(datetime.fromtimestamp(now_timestamp)) print(datetime.utcfromtimestamp(now_timestamp)) # str and datetime print() print(datetime.strptime('2016-12-21 15:59:32', '%Y-%m-%d %H:%M:%S')) print(datetime.now().strftime('%a, %b %d %H:%M:%S')) from datetime import timedelta print(datetime.now() + timedelta(hours = 1)) print(datetime.now() + timedelta(days = 1)) #set time zone from datetime import timezone tz_utc_8 = timezone(timedelta(hours=8)) print(datetime.now().replace(tzinfo =tz_utc_8)) #timezone change print() utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc) print(utc_dt) bj_dt = utc_dt.astimezone(timezone(timedelta(hours = 8))) print(bj_dt) tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours = 9))) print(tokyo_dt)
f4890c20a78d87556d0136d38d1a1a40ac18c087
AlbertGithubHome/Bella
/python/list_test.py
898
4.15625
4
#list test print() print('list test...') classmates = ['Michael','Bob', 'Tracy'] print('classmates =', classmates) print('len(classmates) =', len(classmates)) print('classmates[1] =', classmates[1]) print('classmates[-1] =', classmates[-1]) print(classmates.append('Alert'), classmates) print(classmates.insert(2,'Bella'), classmates) print(classmates.pop(), classmates) #list 内容可以不一致 classmates[3] = 100 print(classmates) subclassmates = ['zhuzhu', 'xiaoshandian'] classmates[2] = subclassmates print(classmates) print('len(classmates) =', len(classmates)) #tuple test # the elements can not change print() print('tuple test...') numbers = (1, 2, 3) print(numbers) new_num = (1) print(new_num) new_num2 = (1,) print(new_num2) print('len(new_num2) =',len(new_num2)) #if the element of tuple is list, you can change the list elemnet #but you can not change tuple pointer