text
stringlengths 37
1.41M
|
---|
class Planet:
def __init__(self,name,size,color):
self.name = name
self.size = size # big middle small
self.color = color
self.humanity = True
self.oxygen = True
self.water = False
self.population = True
self.temp = 0
def set_humanity(self):
if self.humanity:
self.humanity = False
self.oxygen = False
else:
self.humanity = True
def set_population(self,quantity):
if self.population:
self.humanity = True
self.population = True
self.population += quantity
else:
self.humanity = False
def set_water(self):
if self.size == 'middle' or self.size == 'great':
self.water = True
else:
self.water = False
if self.water:
self.burger = True
else:
self.burger = False
planet = Planet('Maxim','middle','black')
print(planet.name,planet.color)
planet.set_humanity()
print(planet.humanity)
planet.set_humanity()
print(planet.humanity)
planet.set_water()
print(planet.water)
planet.set_population(50)
print(planet.population) |
class Cat:
def __init__(self,size,weight):
self.size = size
self.weight = weight
self.position = 0
self.power = 0
self.damage = 0
self.exp = 0
print('кот успешно создан')
def description(self):
print(f"размер:{self.size},вес:{self.weight},позиция:{self.position},сила:{self.power},урон:{self.damage}")
def set_weight(self,weight):
if weight == 'available':
self.power += 1
self.exp += 1
print('кот летит')
elif weight == "not available":
print("вес не позволяет кошке взлететь")
def move(self):
self.position += 1
def run(self):
self.position = self.position + 10
print("побежал")
cat1 = Cat('s',14)
cat1.set_weight("not available")
cat1.run()
cat1.description()
|
"""
This is an abstract class that can be used as the basis for the
creation of new views. The only two views of the program -
ViewBraille and ViewCLI - are both inheritors of this class.
"""
import abc
class ViewType(metaclass=abc.ABCMeta):
@abc.abstractmethod
def option_select(self):
"""Given a list of strings, prints the list and waits for an integer in.
"""
pass
@abc.abstractmethod
def str_print(self):
"""Prints a provided string
This is the most basic type of printing in this program.
Replaces `print()`.
"""
pass
@abc.abstractmethod
def str_input(self):
"""Gets and then returns a string from the user.
The returned string should always be in alphabetical, not braille.
This is because the program may need to logically understand the input.
This is the most basic type of inputting in this program.
Replaces `input()`.
"""
pass
|
def largest_factor(n):
"""Return the largest factor of n that is smaller than n.
>>> largest_factor(15) # factors are 1, 3, 5
5
>>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40
40
>>> largest_factor(13) # factor is 1 since 13 is prime
1
"""
"*** YOUR CODE HERE ***"
# we want a loop to decrement f until it reaches n%f == 0
while True:
f = n-1
if(n%f == 0):
return f
f-= 1 |
class Student:
def __init__(self,name,lastname,department,year_of_entrance):
self.name = name
self.lastname = lastname
self.department = department
self.year_of_entrance = year_of_entrance
get_student_info = Student('Mary','Black',
'software engineering','2019')
print(get_student_info.name +' '+ get_student_info.lastname +' '+
'entered the department' +' '+ get_student_info.department + ' ' +
'of the NYU in year' + get_student_info.year_of_entrance)
# print(get_student_info.name,get_student_info.lastname
# 'entered the department', get_student_info.department
# 'of the NYU in year',get_student_info.year_of_entrance) |
#here is a little snippet showing the basics of variable usage
#declare a variable and initialize it
f=0
print (f)
#redeclaring a variable also works
f="abc"
g="defg"
print (f)
#you can't directly concatenate variables of different types, for instance here "this is a string" and "123" by using print("this is a string+123")
#instead use the "str" function for the conversion
print("this is a long string "+str(123))
#local vs. global variables
def someFunction ():
f="f in the function is a local variable"
print(f)
global g
g="g in the function is a global var."
print(g)
someFunction() #the local var. f and the global var. g are printed
print(f) #the var. defined line 8 is printed (ie abc)
print(g) #the global var. is printed not the one defined line 9
del f #f is undefined / deleted -> print f would now return an error |
#!/bin/python3
'''
Problem Approach :-
Fibonacci sequence F(n) = F(n-1) + F(n-2)
The target is to filter out all the non-even numbers in the sequence and then find the sum of all remaining even numbers.
1. Observe the sequence; and find a pattern
We see that every third number is an even number
2. Now, figure out a formula that fits this pattern.
Since we already have an existing formula we can decompose it as per our needs;
F(n) = F(n-1) + F(n-2)
F(n) = F(n-2) + F(n-3) + F(n-2)
F(n) = 2F(n-2) + F(n-3) ------- (1) We see that the 3rd number in the pattern of
n-2, n-1, n can be even if F(n-3) is even and since we know 2F(n-2) is always even.
This will work but we still pick every number in the Fibonacci series; hence it is
no different than the brute force algorithm. We should decompose the equation in
such a way that we can jump to the conclusion using only even numbers in the
sequence.
F(n) = 3F(n-3) + 2F(n-4)
F(n) = 3F(n-3) + 2F(n-5) + 2F(n-6)
From eq(1); F(n-3) = 2F(n-5) + F(n-6) ---> 2F(n-5) = F(n-3) - F(n-6)
F(n) = 4F(n-3) + F(n-6)
This equation gives us every 3rd number in the sequence; hence we can run through
all the even numbers.
'''
import sys
t = int(input().strip())
def summer(num_1,num_2):
return 4*num_2 + num_1
for a0 in range(t):
n = int(input().strip())
num_1 = num_3 = 0
num_2 = 2
total_1 = 2
i = 1
while(i):
total_1 += num_3
num_3 = summer(num_1,num_2)
num_1 = num_2
num_2 = num_3
if num_3 <= n:
pass
else:
print(total_1)
i = 0
|
https://stepik.org/lesson/58180/step/4?thread=solutions&unit=35865
Task:
Количество столбцов
Прочитайте изображение из файла img.png и выведите количество столбцов этого изображения на стандартный вывод.
В примере входа указана ссылка на файл. Это сделано для вашего удобства. Вы можете скачать этот файл, сохранить как img.png и протестировать решение на своем компьютере.
Sample Input:
https://stepik.org/media/attachments/lesson/58180/img.png
Sample Output:
419
Code:
from skimage.io import imread, imshow, imsave
#img = imread("https://stepik.org/media/attachments/lesson/58180/img.png")
img = imread('img.png')
print(img.shape[1])
|
Напишите программу, на вход которой подаётся список чисел одной строкой.
Программа должна для каждого элемента этого списка вывести сумму двух его
соседей. Для элементов списка, являющихся крайними, одним из соседей
считается элемент, находящий на противоположном конце этого списка.
Например, если на вход подаётся список "1 3 5 6 10", то на выход
ожидается список "13 6 9 15 7" (без кавычек).
Если на вход пришло только одно число, надо вывести его же.
Вывод должен содержать одну строку с числами нового списка, разделёнными пробелом.
s = [ int(i) for i in input().split()]
t = []
l = len(s)-1
k = 0
i = 0
if len(s)==0:
print(str(0))
else:
for st in s:
if len(s)>1:
if i==0:
k = s[i+1] + s[-1]
t.append(k)
elif i>0 and i<l:
k=s[i-1]+s[i+1]
t.append(k)
elif i==l:
k = s[i-1]+s[0]
t.append(k)
elif len(s)==1:
k = s[i]
t.append(k)
i +=1
j = 0
for st2 in t:
print(str(t[j])+' ',end='')
j +=1
|
from tkinter import *
from tkinter.messagebox import *
import math as m
#some usefull variabble
font = ('Verdana',20,'bold')
# working functions
def clear():
ex=textfield.get()
ex = ex[0:len(ex)-1]
textfield.delete(0,END)
textfield.insert(0,ex)
def all_clear():
textfield.delete(0,END)
def click_btn_function(event):
print("btn clicked")
b = event.widget
text = b['text']
print(text)
if text=='x':
textfield.insert(END,"*")
return
if text=='=':
try:
ex = textfield.get()
anser = eval(ex)
textfield.delete(0,END)
textfield.insert(0,anser)
except Exception as e:
print("Error..")
showerror("Error",e)
return
textfield.insert(END,text)
window=Tk()
window.title("Calculator")
window.geometry("480x570")
#picture lable
pic = PhotoImage(file='calulator.png')
headinglable = Label(window,image=pic)
headinglable.pack(side=TOP,pady=15)
# heading level
heading =Label(window,text='My Calculator',font=font)
heading.pack(side=TOP)
# text field
textfield = Entry(window,font = font,justify = CENTER)
textfield.pack(side = TOP,pady =10,fill=X,padx =10)
# button
buttonFrame=Frame(window)
buttonFrame.pack(side =TOP,pady = 5)
# adding button
temp=1
for i in range(0,3):
for j in range(0,3):
btn=Button(buttonFrame,text=str(temp),font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
btn.grid(row=i,column=j,padx = 2, pady = 2)
temp = temp+1
btn.bind('<Button-1>',click_btn_function)
zeroBtn = Button(buttonFrame,text='0',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
zeroBtn.grid(row=3,column=1,padx = 2, pady = 2)
dotBtn = Button(buttonFrame,text='.',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
dotBtn.grid(row=3,column=0,padx = 2, pady = 2)
equalBtn = Button(buttonFrame,text='=',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
equalBtn.grid(row=3,column=2,padx = 2, pady = 2)
plusbtn = Button(buttonFrame,text='+',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
plusbtn.grid(row=0,column=3,padx = 2, pady = 2)
minusbtn = Button(buttonFrame,text='-',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
minusbtn.grid(row=1,column=3,padx = 2, pady = 2)
multbtn = Button(buttonFrame,text='x',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
multbtn.grid(row=2,column=3,padx = 2, pady = 2)
divbtn = Button(buttonFrame,text='/',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
divbtn.grid(row=3,column=3,padx = 2, pady = 2)
clearbtn = Button(buttonFrame,text='CLEAR',font = font,width = 11,relief = 'ridge',activebackground = 'orange',activeforeground = 'white',command = clear)
clearbtn.grid(row=4,column=2,padx = 2, pady = 2,columnspan=2)
allbtn = Button(buttonFrame,text='AC',font = font,width = 11,relief = 'ridge',activebackground = 'orange',activeforeground = 'white',command = all_clear)
allbtn.grid(row=4,column=0,padx = 2, pady = 2,columnspan=2)
#binding all buttons
zeroBtn.bind('<Button-1>',click_btn_function)
equalBtn.bind('<Button-1>',click_btn_function)
divbtn.bind('<Button-1>',click_btn_function)
multbtn.bind('<Button-1>',click_btn_function)
dotBtn.bind('<Button-1>',click_btn_function)
plusbtn.bind('<Button-1>',click_btn_function)
minusbtn.bind('<Button-1>',click_btn_function)
def enterclick(event):
print(':hiiiii')
e = Event()
e.widget = equalBtn
click_btn_function(e)
textfield.bind('<Return>',enterclick)
#########################################################################################
# functions
sc_frame = Frame(window)
sqrtbtn = Button(sc_frame,text='sqrt',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
sqrtbtn.grid(row=0,column=0,padx = 3, pady = 3)
powbtn = Button(sc_frame,text='^',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
powbtn.grid(row=0,column=1,padx = 3, pady = 3)
factbtn = Button(sc_frame,text='!',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
factbtn.grid(row=0,column=2,padx = 3, pady = 3)
radbtn = Button(sc_frame,text='Rad',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
radbtn.grid(row=0,column=3,padx = 3, pady = 3)
sinbtn = Button(sc_frame,text='sin',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
sinbtn.grid(row=1,column=0,padx = 3, pady = 3)
cosbtn = Button(sc_frame,text='cos',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
cosbtn.grid(row=1,column=1,padx = 3, pady = 2)
tanbtn = Button(sc_frame,text='tan',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
tanbtn.grid(row=1,column=2,padx = 3, pady = 3)
degbtn = Button(sc_frame,text='Deg',font = font,width = 5,relief = 'ridge',activebackground = 'orange',activeforeground = 'white')
degbtn.grid(row=1,column=3,padx = 3, pady = 3)
normal_calc=True
def cal_sc(event):
print("btn...")
btn=event.widget
text = btn['text']
print(text)
ex = textfield.get()
answer = ''
if text == 'Rad':
print("radian")
answer=str(m.degrees(float(ex)))
elif text == "Deg":
print("degree")
answer = str(m.radians(float(ex)))
elif text=="sin":
print("sin")
answer = str(m.sin(m.radians(float(ex))))
elif text=="cos":
print("cos")
answer= str(m.cos(m.radians(int(ex))))
elif text=="tan":
print("tan")
answer = str(m.tan(m.radians(int(ex))))
elif text =="!":
print("factorial")
answer = str(m.factorial(int(ex)))
elif text == "sqrt":
print('squaroot')
answer = str(m.sqrt(int(ex)))
elif text=='^':
print("power")
base,pow = ex.split("^")
print('base')
print("power")
answer=m.pow(int(base),int(pow))
textfield.delete(0,END)
textfield.insert(0,answer)
def sc_click():
global normal_calc
if (normal_calc):
buttonFrame.pack_forget()
sc_frame.pack(side=TOP,pady = 5)
buttonFrame.pack(side=TOP)
window.geometry("480x700")
print("Show scientific")
normal_calc = False
else:
print("Show normal")
sc_frame.pack_forget()
window.geometry("480x570")
normal_calc = True
# binding sc button
powbtn.bind('<Button-1>',cal_sc)
sinbtn.bind('<Button-1>',cal_sc)
cosbtn.bind('<Button-1>',cal_sc)
tanbtn.bind('<Button-1>',cal_sc)
factbtn.bind('<Button-1>',cal_sc)
sqrtbtn.bind('<Button-1>',cal_sc)
degbtn.bind('<Button-1>',cal_sc)
radbtn.bind('<Button-1>',cal_sc)
fontMenu = ('',12,'bold')
menubar = Menu(window)
mode = Menu(menubar,font= fontMenu,tearoff=0)
mode.add_checkbutton(label="Scientific Mode",command=sc_click)
menubar.add_cascade(label="Mode",menu=mode)
window.config(menu=menubar)
window.mainloop() |
"""
This module illustrates how to retrieve the k-nearest neighbors of an item. The
same can be done for users with minor changes. There's a lot of boilerplate
because of the id conversions, but it all boils down to the use of
algo.get_neighbors().
"""
# needed because of weird encoding of u.item file
import io # noqa
from surprise import Dataset, get_dataset_dir, KNNBaseline
def read_item_names():
"""Read the u.item file from MovieLens 100-k dataset and return two
mappings to convert raw ids into movie names and movie names into raw ids.
"""
file_name = get_dataset_dir() + "/ml-100k/ml-100k/u.item"
rid_to_name = {}
name_to_rid = {}
with open(file_name, encoding="ISO-8859-1") as f:
for line in f:
line = line.split("|")
rid_to_name[line[0]] = line[1]
name_to_rid[line[1]] = line[0]
return rid_to_name, name_to_rid
# First, train the algorithm to compute the similarities between items
data = Dataset.load_builtin("ml-100k")
trainset = data.build_full_trainset()
sim_options = {"name": "pearson_baseline", "user_based": False}
algo = KNNBaseline(sim_options=sim_options)
algo.fit(trainset)
# Read the mappings raw id <-> movie name
rid_to_name, name_to_rid = read_item_names()
# Retrieve inner id of the movie Toy Story
toy_story_raw_id = name_to_rid["Toy Story (1995)"]
toy_story_inner_id = algo.trainset.to_inner_iid(toy_story_raw_id)
# Retrieve inner ids of the nearest neighbors of Toy Story.
toy_story_neighbors = algo.get_neighbors(toy_story_inner_id, k=10)
# Convert inner ids of the neighbors into names.
toy_story_neighbors = (
algo.trainset.to_raw_iid(inner_id) for inner_id in toy_story_neighbors
)
toy_story_neighbors = (rid_to_name[rid] for rid in toy_story_neighbors)
print()
print("The 10 nearest neighbors of Toy Story are:")
for movie in toy_story_neighbors:
print(movie)
|
""" Algorithm predicting a random rating.
"""
import numpy as np
from .algo_base import AlgoBase
class NormalPredictor(AlgoBase):
"""Algorithm predicting a random rating based on the distribution of the
training set, which is assumed to be normal.
The prediction :math:`\\hat{r}_{ui}` is generated from a normal distribution
:math:`\\mathcal{N}(\\hat{\\mu}, \\hat{\\sigma}^2)` where :math:`\\hat{\\mu}` and
:math:`\\hat{\\sigma}` are estimated from the training data using Maximum
Likelihood Estimation:
.. math::
\\hat{\\mu} &= \\frac{1}{|R_{train}|} \\sum_{r_{ui} \\in R_{train}}
r_{ui}\\\\\\\\\
\\hat{\\sigma} &= \\sqrt{\\sum_{r_{ui} \\in R_{train}}
\\frac{(r_{ui} - \\hat{\\mu})^2}{|R_{train}|}}
"""
def __init__(self):
AlgoBase.__init__(self)
def fit(self, trainset):
AlgoBase.fit(self, trainset)
num = sum(
(r - self.trainset.global_mean) ** 2
for (_, _, r) in self.trainset.all_ratings()
)
denum = self.trainset.n_ratings
self.sigma = np.sqrt(num / denum)
return self
def estimate(self, *_):
return np.random.normal(self.trainset.global_mean, self.sigma)
|
from helper import *
def main_options():
while True:
print "Please select one of the following:"
print "'l': Get all departments: score and classifier by Most Positive to Most Negative"
print "'d': Department Specific: get all children score and classifer by Most Positive to Most Negative"
print "'c': Compare 2 departments positivity classifier"
print "'p': Get Most Positive Department"
print "'n': Get Most Negative Department"
print "'s': Search for a query"
print "'q': Quit program"
choices = ('a', 's', 'd', 'c', 'p', 'n', 'q', 's')
user_choice = raw_input("Please select the letter:")
if user_choice in choices:
return user_choice
if __name__ == '__main__':
cls()
while True:
m = main_options()
cls()
if m == 'q':
quit()
elif m == 'l':
print_departments_score_classifier()
elif m == 'd':
dep_choice = get_dep_choice()
print_score_classifier_for(dep_choice)
elif m == 'c':
dep_choice1 = get_dep_choice()
dep_choice2 = get_dep_choice()
compare_positivity(dep_choice1, dep_choice2)
elif m == 'p':
name, v = get_most_positive()
print "Most positive department:", name, "score:", v[0]
elif m == 'n':
name, v = get_most_negative()
print "Most negative department:", name, "score:", v[0]
elif m == 's':
search()
print "========================================"
|
from os import system
import random
# Global Variables
null = 0
compWins = 0
playerWins = 0
# Display Function
def choise():
print('Choose One :\n\n\t1) Rock\n\t2) Paper\n\t3) Scissors\n')
# Random Conputer Choise Function
def conputerChoise():
return random.randint(1, 3)
# Verification Player Choise Function
def verifPlayerChoise(x):
if x == '1' or x == '2' or x == '3' or x == 'R' or x == 'P' or x == 'S' or x == 'ROCK' or x == 'PAPER' or x == 'SCISSORS':
return True
else:
return False
# int Player Choise Function
def intInput(x):
if x == '1' or x == 'R' or x == 'ROCK':
return 1
elif x == '2' or x == 'P' or x == 'PAPER':
return 2
else:
return 3
# Player Choise Function
def PlayerChoise():
x = input('Your Choose : ')
while(not(verifPlayerChoise(x.upper()))):
x = input('Your Choose : ')
return intInput(x.upper())
# Computer Or Player Win
def win(c, p):
if c == p:
return 'null'
elif (c == 1 and p == 3) or (c == 2 and p == 3) or (c ==3 and p == 2):
return 'c'
else:
return 'p'
# Str Player & Computer Choise Function
def strInput(x):
if x == 1:
return 'ROCK'
if x == 2:
return 'PAPER'
if x == 3:
return 'SCISSORS'
# verif test function
def varifTest(t):
if t == '':
return True
else:
return False
# Start Player Function
def play():
test = True
while test:
system('cls')
choise()
compChoice = conputerChoise()
playerChoice = PlayerChoise()
print('Your Choise : ' + strInput(playerChoice) + ' | Computer Choise : ' + strInput(compChoice))
w = win(compChoice, playerChoice)
if w == 'null':
print('*** Null ***')
global null
null += 1
if w == 'c':
print('*** Computer Win ***')
global compWins
compWins += 1
if w == 'p':
print('*** Player Win ***')
global playerWins
playerWins += 1
test = varifTest(str(input('\nPress enter to continue... ')))
print('\nComputer :', compWins, ' Player :', playerWins, ' Null :', null)
play()
|
def largest_num(arr):
finalarr = []
index = 0
for subarr in arr:
#print(subarr)
for i in subarr:
if i > index:
index = i
finalarr.append(index)
print(finalarr)
largest_num([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) |
def repeat_a_string(str, num):
final = []
i = 0
while i < num:
final.append(str)
rpt = "".join(final)
i = i + 1
print(rpt)
repeat_a_string("abc", 3)
def repeatString(str, num):
final = ""
i = 0
while i < num:
final = final + str
i = i+1
print(final)
repeatString("abc", 3) |
# navigable string objects
from bs4 import BeautifulSoup as bs
soup = bs("<h2 id='message'>Hello, Tanish op!</h2>","html.parser")
content = soup.string
print(content)
print(type(content)) # <class 'bs4.element.NavigableString'>
# important points ---- The navigable string object is used to represent the contents of a tag. here for eg- "Hello, Tanish op!" To access the contents, ".string" is used with the tags.
|
# .descendants is used to iterate over all of the children and indirect children
from bs4 import BeautifulSoup as bs
html_doc = """
<html><head><title>Tutorials Point</title></head>
<body>
<p class="title"><b>The Biggest Online Tutorials Library, It's all Free</b></p>
<p class="prog">Top 5 most used Programming Languages are:
<a href="https://www.tutorialspoint.com/java/java_overview.htm" class="prog" id="link1">Java</a>,
<a href="https://www.tutorialspoint.com/cprogramming/index.htm" class="prog" id="link2">C</a>,
<a href="https://www.tutorialspoint.com/python/index.htm" class="prog" id="link3">Python</a>,
<a href="https://www.tutorialspoint.com/javascript/javascript_overview.htm" class="prog" id="link4">JavaScript</a> and
<a href="https://www.tutorialspoint.com/ruby/index.htm" class="prog" id="link5">C</a>;
as per online survey.</p>
<p class="prog">Programming Languages</p>
"""
soup = bs(html_doc,'html.parser')
print(len(soup.contents)) # has only two children namely - html tag and \n
print(len(list(soup.descendants))) #33
# print(list(soup.descendants)) gives a list of all indirect and direct children
# .string
# if the tag has only one child and if its a navigable string , then the .string can be used to get that string
some_tag = soup.head.title
for i in some_tag.children:
print(i) # Tutorials Point
print(some_tag.string) # Tutorials Point
# If a tag's only child is another tag, and that tag has a .string, then the parent tag is considered to have the same .string as its child −
parent_tag = soup.head
print(ony_Child:=parent_tag.contents[0])
print(ony_Child.string) # Tutorials Point
print(parent_tag.string)
# if the tag contains more than one thing then .string will return None
print(soup.html.string)
|
def ALIGNW_ODD(size):
return 3 if (size) < 3 else (size) + (((size) % 2) ^ 0x01)
def align_size(size):
WSIZE = 4
return (ALIGNW_ODD(((size) + WSIZE - 1)/WSIZE)) * WSIZE
def calc_min_bits(size):
bits = 0;
while (size >> bits) > 0:
bits += 1
return bits
def alignment_test(bits):
for i in range(1, 32):
print(str(i) + " = " + str(align_size(i)))
def printbits(bits):
print "Calc min bits(%u):" %(bits)
print str(calc_min_bits(bits))
if __name__ == '__main__':
# print 'Running alignment test . . .'
# alignment_test()
print "Aligning 56"
print str(align_size(56))
printbits(4048)
printbits(4072)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost","root","","db_demo" )
def test_create_table():
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 如果数据表已经存在使用 execute() 方法删除表。
cursor.execute("DROP TABLE IF EXISTS employee")
# 创建数据表SQL语句
sql = """CREATE TABLE employee (
name varchar(20) NOT NULL,
age int,
sex char(1)
)"""
cursor.execute(sql)
def test_insert():
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 插入语句
sql = """INSERT INTO employee (name, age, sex)
VALUES ('Mac', 20, 'M')"""
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# 关闭数据库连接
db.close()
def test_select():
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("select * from employee")
# 使用 fetchone() 方法获取一条数据库。
data = cursor.fetchone()
print "data: ", data
# 关闭数据库连接
db.close()
if __name__ == '__main__':
# test_create_table()
# test_insert();
test_select()
|
from .constants import RED, GREY, SQUARE_SIZE, CROWN
import pygame
class Piece:
PADDING = 20
OUTLINE = 5
def __init__(self, row, col, color):
self.row = row
self.col = col
self.color = color
self.king = False
self.x = 0
self.y = 0
self.calc_pos()
def calc_pos(self):
"""
Calculate the position of the piece
:return:
"""
self.x = SQUARE_SIZE * self.col + SQUARE_SIZE // 2
self.y = SQUARE_SIZE * self.row + SQUARE_SIZE // 2
def make_king(self):
self.king = True
def draw(self, win):
"""
Draw the piece on the game window.
:param win:
:return:
"""
radius = SQUARE_SIZE // 2 - self.PADDING
pygame.draw.circle(win, GREY, (self.x, self.y), radius + self.OUTLINE)
pygame.draw.circle(win, self.color, (self.x, self.y), radius)
if self.king:
win.blit(CROWN, (self.x - CROWN.get_width() // 2, self.y - CROWN.get_height() // 2))
def move(self, row, col):
"""
Move the piece to the desired row and col
:param row:
:param col:
:return:
"""
self.row = row
self.col = col
self.calc_pos()
def __repr__(self):
return f'<({self.color})({self.row}, {self.col})>'
|
# CLASSES & OBJECTS
"""
Double underscore means private property in Python Classes
which cannot be accessed from outside property
"""
'''Below is the Person Class with Getters and Setters'''
class Person:
__name = ''
__email = ''
def __init__(self, name, email):
self.__name= name
self.__email = email
def set_name(self,name):
self._name = name
def get_name(self):
return self.__name
def set_email(self,email):
self._email = email
def get_email(self):
return self.__email
def toString(self):
return '{} can be contacted at {}'.format(self.__name,self.__email)
nitendra = Person('Nitendra','[email protected]')
print(nitendra.get_name())
print(nitendra.get_email())
nitendra.set_name('Nitendra')
nitendra.set_email('[email protected]')
print(nitendra.toString())
#Inheritance
class Customer(Person):
__balance = 0
def __init__(self, name, email, balance):
self.__name = name
self.__email = email
self.__balance = balance
super(Customer, self).__init__(name, email)
#Calling the constructor of Person
def set_balance(self,balance):
self.__balance = balance
def toString(self):
return '{} has a balance of {} and can be contacted at {}'.format(self.__name,self.__balance,self.__email)
john = Customer(nitendra,'John Doe','[email protected]' ,100)
print(john.toString())
|
#!/usr/local/bin/python
num1 = 20
num2 =23
sum_two_numbers = num1+num2
print("Sum of Two Numbers is: {0}".format(sum_two_numbers))
def sum_two_numbers(num1,num2):
return num1+num2
print("Sum of Two Numbers Using Function is is: {0}".format(sum_two_numbers(2,5))) |
#==========================
# Dictionaries in Python
#=========================
"""
A dictionary is a type of collection in which we store unordered,changeable and index value.
Dictionaries have multiple values written with curly braces in which each item has keys and values.
"""
## A Simple dictionaries of Person Information
"""
We can define a dictionary using a curly Bracket and Key-Value Pairs.
We can store both String and Numeric Values in the Dictionaries key-value pairs.
"""
person_info ={'first_name':'Nitendra',
'last_name':'Gautam',
'location':'Dallas',
'website':'https://www.nitendratech.com',
'zipcode':75060}
## Accessing the Value from a Dictionary
"""
We use the dictionary key to access the value for that particular key.
"""
print("First Name is {0}".format(person_info['first_name']))
## Adding a new Key Value Pair to dictionary
person_info['new_zipcode'] =76066
print("Updated Dictionary ",person_info)
## Looping through Key-value pairs
print("Printing Key-Value pairs of ")
for keys,values in person_info.items():
print(keys + str(values))
## Looping through all keys in a Python dictionary
for key in person_info.keys():
print("Person Info Dictionary Key {0}".format(key))
## Looping through All the values in the dictionary
for values in person_info.values():
print("Person Info Dictionary Value {0}".format(values))
|
#Complete the function to return the tens digit and the ones digit of any interger.
def two_digits(a):
quotient = a // 10
remainder = a % 10
return quotient, remainder
#Invoke the function with any interger as its argument.
print(two_digits(79))
|
'''
Ship.py
implements the Ship class, which defines the player controllable ship
Lukas Peraza, 2015 for 15-112 Pygame Lecture
'''
import pygame
import math
from GameObject import GameObject
class Ship(GameObject):
# we only need to load the image once, not for every ship we make!
# granted, there's probably only one ship...
@staticmethod
def init(x=0,y=0):
Ship.shipImage = pygame.transform.rotate(pygame.transform.scale(
pygame.image.load('images/redcircle.png').convert_alpha(),
(90+x,90+y)), -90)
def __init__(self, x, y):
super(Ship, self).__init__(x, y, Ship.shipImage, 30)
self.power = 1
self.drag = 0.9
self.angleSpeed = 5
self.angle = 0 # starts pointing straight up
self.maxSpeed = 20
self.invincibleTime = 1500
self.timeAlive = 0
def update(self, dt, keysDown, screenWidth, screenHeight):
self.timeAlive += dt
def update2(self,x,y):
Ship.shipImage = pygame.transform.rotate(pygame.transform.scale(
pygame.image.load('images/redcircle.png').convert_alpha(),
(90+x,90+y)), -90)
'''
x,y=pygame.mouse.get_pos()
dx,dy=x-self.width/2,y-self.height/2
#print(dx,dy)
pi=math.pi
print(pygame.mouse.get_focused())
if dx>0 and dy<0:
print('0')
self.angle=math.degrees(pi/2-math.atan(dx/-dy))
self.thrust(self.power)
print(self.angle)
elif dx<0 and dy<0:
print('1')
self.angle=math.degrees(pi/2+math.atan(dx/dy))
self.thrust(self.power)
print(self.angle)
elif dx>0 and dy>0:
print('2')
self.angle=math.degrees(2*pi-math.atan(dy/dx))
self.thrust(self.power)
print(self.angle)
elif dx<0 and dy>0:
print('3')
self.angle=math.degrees((3/2)*pi+math.atan(dx/dy))
print(self.angle)
self.thrust(self.power)
elif dx==0 and dy<0:
self.angle=math.degrees(pi/2)
self.thrust(self.power)
elif dx==0 and dy>0:
self.angle=math.degrees((3/2)*pi)
self.thrust(self.power)
elif dx >0 and dy==0:
self.angle=0
self.thrust(self.power)
elif dx<0 and dy==0:
self.angle=math.degrees(pi)
self.thrust(self.power)
elif keysDown(pygame.K_LEFT):
self.angle =180
self.thrust(self.power)
elif keysDown(pygame.K_RIGHT):
# not elif! if we're holding left and right, don't turn
self.angle = 0
self.thrust(self.power)
elif keysDown(pygame.K_UP):
self.angle=90
self.thrust(self.power)
elif keysDown(pygame.K_DOWN):
self.angle=270
self.thrust(self.power)
else:
vx, vy = self.velocity
self.velocity = self.drag * vx, self.drag * vy
super(Ship, self).update(screenWidth, screenHeight)
'''
'''
x,y=pygame.mouse.get_pos()
print(x,y)
dx,dy=x-self.width/2,y-self.height/2
pi=math.pi
if dx>0 and dy<0:
self.angle=pi/2-math.atan(dx/dy)
self.thrust(self.power)
elif dx<0 and dy<0:
self.angle=pi/2+math.atan(dx/dy)
self.thrust(self.power)
elif dx>0 and dy>0:
self.angle=2*pi-math.atan(dy/dx)
self.thrust(self.power)
elif dx<0 and dy>0:
self.angle=(3/2)*pi+math.atan(dx/dy)
self.thrust(self.power)
elif dx==0 and dy<0:
self.angle=pi/2
self.thrust(self.power)
elif dx==0 and dy>0:
self.angle=(3/2)*pi
self.thrust(self.power)
elif dx >0 and dy==0:
self.angle=0
self.thrust(self.power)
elif dx<0 and dy==0:
self.angle=pi
self.thrust(self.power)
'''
def thrust(self, power):
angle = math.radians(self.angle)
vx, vy = self.velocity
# distribute the thrust in x and y directions based on angle
vx += power * math.cos(angle)
vy -= power * math.sin(angle)
speed = math.sqrt(vx ** 2 + vy ** 2)
if speed > self.maxSpeed:
factor = self.maxSpeed / speed
vx *= factor
vy *= factor
self.velocity = (vx, vy)
def isInvincible(self):
return self.timeAlive < self.invincibleTime |
# genetic_alg.py
# authors: Megan Olsen, based on C code by Jessa Laspesa and Ned Taylor
# purpose: all functions necessary for running the genetic algorithm.
import individual
import random
import sys
# purpose: mutate genes in each individual based on mutation rate, uniformally at random
# parameters: the population list (modified by this function), the list of range values,
# the mutation rate, the number at the end to not mutate
# return: none
def mutate(pop, ranges, mutate_rate, num_ignore):
#count = 0 #for testing purposes
# go through each individual in the population, but not those chosen via elitism (last num_ignore number of individuals)
for i in range(len(pop)-num_ignore):
for param in ranges:
r = random.randrange(0, 100) #need randrange to ensure 100 isn't included in numbers
# only mutate if the random value is less than the given rate
if r < mutate_rate:
# make sure new random value isn't outside the allowed range
min = param.minimum
max = param.maximum
#count+=1
if param.type == "i":
pop[i].genes[param.name] = random.randint(min, max)
else:
the_float = random.uniform(min, max)
round_by = len(value.increment.split(".")[1])
pop[i].genes[param.name] = round(the_float,round_by)
#print(count,"genes were mutated")
# Purpose: Save keep number of individuals with highest fitnesses to new population
# Parameters: the old population list, the new (mutable) population list, and the number of individuals to keep
# Return: none. Assumes ret_pop is mutable, and modifies it.
def elitism(pop, ret_pop, keep):
# Check that anything can be done
if keep <= 0 or len(pop)==0:
return
sorted_list = [] # each item is fitness followed by the index of that individual in pop
for index in range(len(pop)):
sorted_list.append([pop[index].fitness, index])
sorted_list.sort(reverse=True) #sort to descending order
#add the first keep number of items to the returned population
for i in range(keep):
ret_pop.append(pop[sorted_list[i][1]]) #only care about saving index from original list
# purpose: goes through the current population, selects two random individuals,
# and crosses over their values at a certain point in the genes list
# parameters: the old population, the ranges list, the number of top inviduals to keep from the prior generation,
# number of individuals to compare against in choosing each parent
# return: the new population
def crossover(pop, ranges, keep, tournament_size):
# Choose the parent pairs
ret_pop = [] # this will hold the new population
number_of_pairs = int((len(pop) - keep)/2)
pairs_for_crossover = choose_individuals(pop, "tournament", number_of_pairs, tournament_size) # holds indices of individuals as a list of pairs
# ensures choose_individuals can't break this function
if len(pairs_for_crossover) != int(number_of_pairs):
print("Error. Incorrect number of pairs for crossover chosen:",len(pairs_for_crossover),number_of_pairs)
sys.exit(-1)
# crosses over two individuals at a time from the pair list
for i in range(len(pairs_for_crossover)):
# random point to cross over
cross_point = random.randint(1, len(ranges) - 1) # forces crosspoint to not be before or after end
#print("Crossoverpoint:", cross_point)
# get the random individuals
individual_1 = pop[pairs_for_crossover[i][0]]
individual_2 = pop[pairs_for_crossover[i][1]]
#print(individual_1,individual_2)
# send over individuals and crossover point. ret_pop will be modified to hold two new individuals
individual.crossover(individual_1, individual_2, ret_pop, ranges, cross_point)
#add elitism individuals to the new population
elitism(pop,ret_pop,keep)
assert (len(pop) == len(ret_pop)), "new population is not the correct size!"
return ret_pop
# Purpose: Run a tournament to determine the parent for crossover
# Parameters: pop, the population; size, the number of individuals to have in the tournament
# Return: the index of the chosen individual who should be a parent
def tournament(pop,size):
best_fitness = -1
best_index = -1
# Choose size number of individuals, keeping and returning the top one only
for i in range(size):
random_index = random.randrange(len(pop))
if pop[random_index].fitness > best_fitness:
best_fitness = pop[random_index].fitness
best_index = random_index
return best_index
# Purpose: Select individuals for crossover
# Parameters: pop, the population;
# type, the type of individual choice (random,tournament);
# paircount, the number of pairs to create;
# tournament_size, the number of individuals to run within a tournament
# Return: two indices of individuals
def choose_individuals(pop, type, paircount, tournament_size):
pairs = [] # a list of lists, each sublist has 2 indices in it to act as parents
# allows an individual to be paired with itself
for i in range(paircount):
if type == "random": #note: same as tournament of size 1
index_1 = random.randrange(len(pop))
index_2 = random.randrange(len(pop))
elif type == "tournament":
index_1 = tournament(pop,tournament_size)
index_2 = tournament(pop,tournament_size)
else:
print("Invalid choice for approach to choosing parents. Aborting.")
sys.exit(-1)
pairs.append([index_1, index_2])
return pairs
# Purpose: Compute fitness for all individuals, write them to a file, and return the highest value
# Parameters: the current population as a list (mutable), prefix of names, common part of what the files are named
# Return: the highest fitness value of the current individuals in the population
def compute_all_fitness(new_pop, prefix,common_filename):
best = -1
for i in range(len(new_pop)):
new_pop[i] = individual.compute_fitness(new_pop[i], prefix+str(i)+common_filename)
if new_pop[i].fitness > best:
best = new_pop[i].fitness
return best
# Purpose: Compute fitness for all individuals, write them to a file, and return the highest value
# Parameters: the current population as a list (mutable), prefix of names, common part of what the files are named,
# number of instances of each individual, the seeds used, the fitness function to use, the max steps for fitness
# function to use in its calculation, and other fitness function parameters
# Return: the highest fitness value of the current individuals in the population
def compute_all_fitness_seeded(new_pop, prefix,common_filename, num_seeds, seeds,function,maxsteps,fit_parameters):
best = -1
best_genes = {}
# Calculate fitness for each individual, and determine the best one
for i in range(len(new_pop)):
new_pop[i] = individual.compute_fitness_seeds(new_pop[i], prefix+str(i),common_filename,num_seeds,seeds,function,maxsteps,fit_parameters)
if new_pop[i].fitness > best:
best = new_pop[i].fitness
for key in new_pop[i].genes:
best_genes[key] = new_pop[i].genes[key]
return best,best_genes
|
from guizero import App, Text, PushButton, TextBox
app = App(title="Hello world")
welcome_message = Text(app, text="Smart Butler", size=20, color="green")
my_name= TextBox(app)
def forward():
welcome_message.value = my_name.value
PushButton(app,command=forward, text ="Butler FORWARD")
app.display()
|
player_details=[]
def create_player(id,name,matches_played,runs_scored,playing_zone):
player_d={}
zone=["north","south","east","west"]
if(len(id)==6 and id[:3] == "ICC" and id[3:].isnumeric()):
if playing_zone.lower() in zone:
player_d['Id']=id
player_d['Name']=name
player_d['Matches_Played']=matches_played
player_d['Run_Scored']=runs_scored
player_d['Playing_Zone']=playing_zone
player_details.append(player_d)
return "Player details are created successfully"
else:
return "Invalid Data"
else:
return "Invalid Data"
def display_player(player_details):
if len(player_details)==0:
print("No player details have been stored");
else:
for i in range(len(player_details)):
print("Player {}:".format(i+1))
print("Player Id:",player_details[i]['Id'])
print("Player Name:",player_details[i]['Name'])
print("No. of Matches Played:",player_details[i]['Matches_Played'])
print("Total Runs Scored:",player_details[i]['Run_Scored'])
print("Playing Zone:",player_details[i]['Playing_Zone'])
flag=True
while flag:
print("1.Create Player\n2.Display Player Details\n3.Exit")
n = int(input())
if n == 1:
print("Enter the player Id")
id = input()
print("Enter the player name")
name = input()
print("Enter the number of matches played")
match = int(input())
print("Enter the total runs scored")
runs = int(input())
print("Enter the playing zone")
zone = input()
print(create_player(id,name,match,runs,zone))
elif n==2:
print("PLAYER DETAILS:")
display_player(player_details);
else:
flag=False
print("Thank you for using the SBCC application")
|
from tkinter import *
def click():
for i in range(len(labels)):
labels[i].config(text=str(i)+" Replaced", fg="yellow", bg="green")
def close_window():
window.destroy()
exit()
window = Tk()
window.title("Label Change Test")
window.configure(background="black")
labels = []
Label(window, text="Basic Array of Labels Test", bg="black", fg="white", font="none 12 bold").grid(row=1, column=0, sticky=W)
for i in range(3):
label = "This is label #"+str(i)
labelPtr = Label(window, text=label,bg="black",fg="white", font="none 12 bold")
labelPtr.grid(row=2+i, column=0, sticky=W)
labels.append(labelPtr)
print(labels)
Button(window, text='Change Text Values', width=20, command=click).grid(row=5, column=0, sticky=W)
#exit label
Label(window, text="click to exit", bg="black", fg="white", font="none 12 bold").grid(row=6, column=0, sticky=W)
Button(window, text="Exit", width=14, command=close_window).grid(row=7, column=0, sticky=W)
window.mainloop()
|
import matplotlib.pyplot as plt
import seaborn as sb
from pandas.plotting import scatter_matrix
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
# Draw 2D scatter
def scatter_2d(data_frame, col_x, col_y):
"""
:param data_frame: The data frame of your file
:param col_x: The first column signed as Ox line
:param col_y: The second column signed as Oy line
"""
Ox = data_frame.iloc[:, col_x]
Oy = data_frame.iloc[:, col_y]
plt.scatter(Ox, Oy, marker='x', color='r', alpha=0.5)
# Get names of columns
label = list(data_frame)
plt.xlabel(label[col_x])
plt.ylabel(label[col_y])
plt.show()
# Draw 3D scatter
def scatter_3d(data_frame, col_x, col_y, col_z):
"""
:param data_frame: The data frame of your file
:param col_x: the first column signed as Ox line
:param col_y: the second column signed as Oy line
:param col_z: the third column signed as Oz line
"""
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
Ox = data_frame.iloc[:, col_x]
Oy = data_frame.iloc[:, col_y]
Oz = data_frame.iloc[:, col_z]
ax.scatter(Ox, Oy, Oz, marker='x', alpha=0.5, color='r')
# Get names of columns
label = list(data_frame)
ax.set_xlabel(label[col_x])
ax.set_ylabel(label[col_y])
ax.set_zlabel(label[col_z])
plt.show()
# Draw x*y plot in one figure, contain scatter plots and histogram plots (if col_x and col_y are the same)
def scatter_matrix(data_frame, cols_x, cols_y, kind='reg', diag_kind='hist', hue=None):
"""
:param data_frame: the data frame of your file
:param cols_{x, y} : lists of variable names, optional
Variables within data to use separately for the rows and columns of the figure;
i.e. to make a non-square plot.
:param kind: {scatter, reg}, optional
Kind of plot for the non-identity relationships.
:param diag_kind: {auto, hist, kde}, optional
Kind of plot for the diagonal subplots. The default depends on whether "hue" is used or not.
:param hue: string (variable name), optional
Variable in data to map plot aspects to different colors.
:return: None
"""
head = data_frame.columns.values
sb.set()
sb.pairplot(data_frame, hue=hue, x_vars=head[cols_x], y_vars=head[cols_y],
kind=kind, diag_kind=diag_kind, markers='x')
plt.show()
# A map draws different Frequency areas, are separated by border lines
def frequency_map(data_frame, col_x, col_y, kind="kde"):
"""
:param data_frame: The data frame of your file
:param col_x: col you want to display in your chart by label x:
:param col_y: col you want to display in your chart by label y:
:param kind: {scatter, reg}, optional
Kind of plot for the non-identity relationships.
"""
head = data_frame.columns.values
sb.set()
sb.jointplot(data=data_frame, x=head[col_x], y=head[col_y], kind=kind)
plt.show()
# A scatter plot with a curly line represent for linear relationship between cols_x and cols_y
def curly_line(data_frame, col_x, col_y, hue=None):
"""
:param data_frame: The data frame of your file
:param col_x: col you want to display in your chart by label x:
:param col_y: col you want to display in your chart by label y:
:param hue: string (variable name), optional
Variable in data to map plot aspects to different colors.
"""
head = data_frame.columns.values
sb.set()
sb.lmplot(data=data_frame, x=head[col_x], y=head[col_y], hue=hue, order=2)
plt.show()
|
# Every piece has a type, value, and belongs to a player
class Piece():
def __init__(self, player, type, value):
self.player = player
self.type = type
self.value = value
# String representation of each piece
def __str__(self):
return f"{self.type} ({self.player[0]})"
class Pawn(Piece):
def __init__(self, player):
super().__init__(player, "Pawn ", 1)
class Rook(Piece):
def __init__(self, player):
super().__init__(player, "Rook ", 5)
class Knight(Piece):
def __init__(self, player):
super().__init__(player, "Knight", 3)
class Bishop(Piece):
def __init__(self, player):
super().__init__(player, "Bishop", 3)
class Queen(Piece):
def __init__(self, player):
super().__init__(player, "Queen ", 9)
class King(Piece):
def __init__(self, player):
super().__init__(player, "King ", 1000)
|
import pandas as pd
# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is',
'portal', 'for', 'Geeks']
# Calling DataFrame constructor on list
df = pd.DataFrame(lst)
print(df)
csvdata=pd.read_csv("file.csv",index-col="name")
#single row loc
#df.loc
first=csvdata.loc["vedavyas"]
#==== iloc - retrive row and column by position
df.iloc[3]
#using isnull() function
df.isnull()
|
# print("Hell o")
# x1=(lambda x,y,z: (x+y)*z)(1,2,7)
# print(x1)
# y1=(lambda x,y,z: (x+y) if (z==0) else (x*y))(1,2,0)
# print(y1)
# print(type(y1))
# nums=[99,22,33,141,112,134,189,312,54,89]
# def Key(x):
# return x%2
# print(nums)
# print(sorted(nums ,key=Key))
# x1=(lambda x: "one" if x==1 else ("Two" if x==2 else "three"))(2)
# print(x1)
# #1
# a= ["vedavyas","p","Burli"]
# print(" ".join(a))
# #2 in place swapping
# x,y=20,30
# print(x,y)
# x,y=y,x
# print(x,y)
# #3 reversing a string
# b="Lord Darth Vader"
# print(b[::-1])
# def multiply(a, b):
# return a * b
# p=multiply(1,2)
# print(p)
# list1=[1,2,3,4]
# print(list1)
# list1.append(2)
# print(list1)
# def unique_in_order(iterable):
# list1=[]
# for i in range(len(iterable)-1):
# print(i,iterable[i])
# if iterable[i] != iterable[i+1]:
# print(iterable[i])
# list1.append(iterable[i])
# print(list1)
# unique_in_order("AAAABBBCCDAABBB")
from flask import Flask
from flask_restful import Resourse,Api
print("imported")
app=Flask(__name__)
api=Api(app)
#class TestApi(Resource):
@app.route("/")
@app.route("/login")
def hello():
return ("Hello world")
if __name__=="__manin__":
app.run(port=5000,debug=True)
print("flask imported") |
'''Welcome to python 101'''
##a,e
a=2
b="vedavyas"
c=3.1423456789
d=True
print(a)
print(type(a))
print(type(b))
print(type(c))
print(type(d))
##b
p=q=r=s=t=45
print(p)
print(q)
print(r)
print(s)
print(t)
##c
'''import keyword
print(keyword.kwlist)
True False break class continue def elif finally for while
and return'''
##d
print(id(p))
print(id(a))
print(id(b))
##f
a=2
b=3
print(a+b)
print(a-b)
print(a*b)
print(a**b)
print(a%b)
'''Types of format
positinal - {1} {0} {2}.format("c","b","a")
keyword - {c} {a} {b}.format(a='apple',b='ball',c='cat')
'''
#format()
str="This is NIA automation {}"
print (str.format("Team"))
##multiple format()
my_string = "{1}, or {0} there is No {2}"
print (my_string.format("Do", "Dont", "Try"))
#concatinate string
str3="ved"
str4="vyas"
print(str3+str4)
print(str3*3)
print(str3+3) #error
print(str3+str(3)) #error
#List
#create a list and tuple print it
list1=[12,23,45,67,12]
tuple1=("Pune","Mumbai","Chennai")
#print the list and tuple
print(list1)
print(tuple1)
#count of list and tuple
print(list1.count(12))
print(tuple1.count("Mumbai"))
#length of tuple and list
print("\nprinting the length of list and tuple: ")
print(len(list1))
print(len(tuple1))
#copy of both and print the copy
print("\ncreating copy of list & tuple and printing the copy")
list1_copy=list1
tuple1_copy=tuple1
print(list1_copy)
print(tuple1_copy)
list1=[12,23,45,67,12]
tuple1=("Pune","Mumbai","Chennai")
#append the value to list1
list1.append(97)
print(list1)
#insert the value to list1
list1.insert(2,34)
print(list1)
#pop the value to list1
list1.pop(3)
print(list1)
#Removal of First Element
print("\nRemoval of First Element: ")
print(tuple1[1:])
#delete tuple
print("\nDelete tuple")
del tuple1
print(tuple1)
list1=[12,23,45,67,12]
tuple1=("Pune","Mumbai","Chennai")
#print the list and tuple
print(list1)
print(tuple1)
print(list1[2])
print(tuple1[1])
list1.sort()
#tuples are immutable in nature
#tuple1[0]=13
#list is mutable in nature
list1[1]=13
print(list1)
print(tuple1)
#append on list
list1.append(78)
print(list1)
#extend on list
list1.extend([20,30,40])
print(list1)
#insert to add element on particular position
list1.insert(3,'bengaluru')
print(list1)
#find and fetch the particular value
list1[1]
list1=[12,23,45,67,12]
tuple1=("Pune","Mumbai","Chennai")
print(list1)
print("count of number 12 in list1:")
print(list1.count(12))
print("Remove number 23 in list1:")
list1.remove(23)
print(list1)
print("POP number from position 2 in list1:")
list1.pop(2)
print(list1)
print("del value from list1:")
del list1[1]
print(list1)
# Hello World program in Python
#Dictionary
#create and perfrom function
dict1={8:'New Delhi',2:'Bengaluru',3:'Pune',4:'Kolkata'}
print(dict1)
#display value of particular key
print(dict1[2])
print(dict1[3])
print(dict1.get(9,"no-keyfound"))
#in operator
print(1 in dict1)
print(8 in dict1)
#add new key value pair
dict1[5]='Chennai'
print(dict1)
dict1.update({6:'Surat', 7:'Hydrabad'})
print("\nadded new key value pair:")
print(dict1)
#modify existing key value pair
print("\nUpdatednew key value pair:")
dict1[7]='Jaipur'
print(dict1)
#delete key value pair from dict1 --we can clear also
print("\nDelete key value pair:")
del dict1[6]
dict1.pop(7)
print(dict1)
#Sort items in the dict1
print("\nSorted list of key value pair:")
print(sorted(dict1))
print(dict1.keys())
print(dict1.values())
print(sorted(dict1.keys()))
print(sorted(dict1.values()))
print(sorted(dict1.items()))
#1.Functions - do nothing print something
def do_nothing():
print("I was told to do nothing :D")
do_nothing()
#arbitary number of args
def arbitary_args(*args):
for i in args:
print(i)
print(arbitary_args(1,2,3,4))
#recursive function factiorial function
def rec_function(x):
if x==1:
return 1
else:
fact=x*rec_function(x-1)
return fact
print(rec_function(5))
# write function assign to variable and use it
def var_func(x):
if x==1:
return 1
elif x%2==0:
print("Its even")
else:
print("Its Odd")
y=var_func(78)
print(y)
'''
1.Classes with field and method
2.Instantite the class and use the object to call the method.
3.Define a class which has asatleast 2 metyhods.getstring:to get
a string from console input printstring :to print string in upper
case.also include simple function to test class method.
4.Write constructr for Class both default and parameterized.
5.Create new class and inherit the class cerated earlier in the class.
'''
class Person:
def __init__(self,name):
self.name=name
def say_my_name(self):
print("Hello, My name is ",self.name)
p = Person('Vedavyas')
p.say_my_name()
if name = "ved" or name = "vyas":
print("name is vedavyas")
elif var == 0:
print "Help - elif"
#calculate the area of circle
#pi*r**2
#instantite the class and use the object to call the method
# Example for parameterized constructor
import math
class Area_of_object():
def __init__(self,radius):
self.radius = radius
def area_of_circle(self):
return (math.pi * (self.radius ** 2))
def area_of_sphere(self):
return (4 * math.pi * (self.radius ** 2))
def getString(self,str1):
self.str1 = input("Enter the string: ")
circle= Area_of_object(4)
sphere = Area_of_object(4)
print(circle.area_of_circle())
print(sphere.area_of_sphere())
#getString to get the string from console
#printString to print the string in uppercase
#example for default constructor
class strings1:
def getString(self):
self.str1 = input("Enter the string: \n")
def printString(self):
return self.str1.upper()
def __init__(self):
pass
one = strings1()
one.getString()
print("printstring fun",one.printString())
#create class and inherit the class
class Football:
#League player details
def __init__(self,jersey):
self.jersey = jersey
def player_details(self):
if (self.jersey == 10):
print("Leo Messi - Barcelona - Spain")
elif(self.jersey == 11):
print("Mo Salah - Liverpool - England")
elif(self.jersey == 7):
print("Cristiano Ronaldo - Juventus - Italy")
else:
print("Try numbers like 7 or 11 or 10")
#inherit the class Fotball in to childclass League
class League(Football):
def __init__(self):
Football.__init__(self,10)
def goalscored(self):
if (self.jersey == 10):
print("Scored 15 goals")
elif(self.jersey == 11):
print("Scored 10 goals")
elif(self.jersey == 7):
print("Scored 14 goals")
else:
print("NO goals ")
c = League()
c.player_details()
c.goalscored()
#divisible by seven but not multiple of 5
from functools import lru_cache
@lru_cache(maxsize=5000)
def div_seven():
for num in range(2000,3200):
if (num%7 == 0):
if(num%5 != 0):
print(num," = Value is divisible by 7 but not multiple of 5")
else:
print(num,"= Divisible by 7 & multiple of 5")
else:
print(num," = NOT divisible by 7")
div_seven()
#Dictionary that contains (i,i*i)
dict1={}
num = int(input("Enterthe value: \n"))
#num=8
if(num <= 0):
print("please enter the integer greater than 0")
for i in range(1,num+1):
dict1[i] = i*i
print(dict1)
#accept sequence of line as inputs and capitalize each word
new = input("Enter the lines \n")
print(new.upper())
#accept the word print words remove duplicates and sort them alphanumerically
#accept the wor9d print8 words remove d7uplicates and so6rt them alphanumerically4
string1 = "apple pineapple kiwi orange kiwi apple chickoo"
#print(jwords)
list1=[]
def rem_dup(val):
for i in val:
if i not in list1:
list1.append(i)
print(list1)
rem_dup(string1.split())
v=" ".join(list1)
print(sorted(v))
#calculate number of integer and lettrs in sentence
value = input("PLEASE PROVIDE THE INPUT: \n")
print(value)
digit=0
letter=0
space=0
for i in value:
if (i.isalpha()):
digit+=1
elif(i.isnumeric()):
letter+=1
elif(i.isspace()):
space+=1
print(digit)
print(letter)
print(space)
#list comprehension square each odd value in the list
list2=[1,2,3,4,5,6,7,8,9]
val = [i*i for i in list2 if (i%2 != 0)]
print(val)
#create & open a file write 5 sentence into it
#sentence should contain specia; char
#then write func in same program t read the containt of file
#handle the execption
new = open("new1.txt","w")
new.write("one two three four five")
new.close()
try:
new = open("new4.txt","r")
print(new.read())
except IOError:
print ("Error: File does not appear to exist.")
finally:
new.close()
|
from ..utils.vector import Vector, Vector2
from .constants import G
from simulator.graphics import Screen
def gravitational_force(pos1, mass1, pos2, mass2):
""" Return the force applied to a body in pos1 with mass1
by a body in pos2 with mass2
"""
F=-(G*mass2/(Vector.norm(pos1-pos2)**3))*(pos1-pos2)
return F
class IEngine:
def __init__(self, world):
self.world = world
def derivatives(self, t0, y0):
""" This is the method that will be fed to the solver
it does not use it's first argument t0,
its second argument y0 is a vector containing the positions
and velocities of the bodies, it is laid out as follow
[x1, y1, x2, y2, ..., xn, yn, vx1, vy1, vx2, vy2, ..., vxn, vyn]
where xi, yi are the positions and vxi, vyi are the velocities.
Return the derivative of the state, it is laid out as follow
[vx1, vy1, vx2, vy2, ..., vxn, vyn, ax1, ay1, ax2, ay2, ..., axn, ayn]
where vxi, vyi are the velocities and axi, ayi are the accelerations.
"""
def make_solver_state(self):
""" Returns the state given to the solver, it is the vector y in
y' = f(t, y)
In our case, it is the vector containing the
positions and speeds of all our bodies:
[x1, y1, x2, y2, ..., xn, yn, vx1, vy1, vx2, vy2, ..., vxn, vyn]
where xi, yi are the positions and vxi, vyi are the velocities.
"""
raise NotImplementedError
class DummyEngine(IEngine):
def derivatives (self, t0, y0):
# input()
# n = int(len(y1)/4)
# if (n!=len(self.world)):
# y2=Vector (len(self.world)*4)
# for k in range (len(self.world)*4):
# y2[k]=y1[k+len(self.world)*4]
# y0=y2
# else:
# y0=y1
# print(y0)
# print (y0)
# input()
n = int(len(y0)/4)
y = Vector(4*n)
for i in range (n):
y[2*i]=y0[len(self.world)*2+2*i]
y[2*i+1]= y0[2*len(self.world)+2*i+1]
F = Vector2(0,0)
for k in range (n):
if (k!=i): #on vérifie que ce ne sont pas les mêmes corps
F += (gravitational_force(Vector2(y0[2*i],y0[2*i+1]), self.world._bodies[i].mass, Vector2(y0[k*2],y0[k*2+1]), self.world._bodies[k].mass))
y[2*(len(self.world)+i)] = F.get_x()
y[2*(len(self.world)+i)+1] = F.get_y()
y=list(y)
return y
def make_solver_state (self):
y0=[]
for body in self.world.bodies():
y0.append(body.position.get_x())
y0.append(body.position.get_y())
for body in self.world.bodies():
y0.append(body.velocity.get_x())
y0.append(body.velocity.get_y())
return y0
|
# The following file is meant to show how to work with various math functions in Python, as well as properly including numerical results in a string
print("5 + 3 = " + str(5+3))
print("4 * 2 = "+ str(4*2))
print("16 / 2 = "+str(16/2))
print("2^3 = "+ str(2**3))
favorite_number = 33
message= "My favorite number is: "+ str(favorite_number) + " pretty neat huh?"
print(message) |
#Make a list of the multiples of 3 from 3 to 30. Use a for loop to print the numbers in your list.
numbers = [value *3 for value in range (3,31)]
for number in numbers:
print(number)
|
#Simple hello message
message = "Oh Hello there! "
print (message)
message2 = "This is concatenation"
print(message + message2) |
# 2_3 Practice Personal Message
message_name = "matthew compton"
message = "Hello " + message_name.title() + ". How are you doing today?\nWould you like to learn some Python?"
print(message)
second_name = "Jeremy Simpson"
# 2_4 Practice Famous Quote
print(second_name.upper())
print(second_name.lower())
print(second_name.title())
# 2_5 Practice
quote = 'Winson Churchill once said, "A joke is a very serious thing."\n'
print(quote)
# 2_6 Practice Famous Quote 2
famous_person = "winston churchill "
famous_quote = famous_person.title() + 'once said, "A joke is a very serious thing."\n'
print(famous_quote)
# 2_7 Practice Stripping Names
end_name = " \t hallie Fowler \n"
print(end_name.lstrip())
print(end_name.rstrip())
print(end_name.strip())
|
my_pizzas = ['pepperoni','cheese','sausage']
friend_pizzas = ['pepperoni','cheese','sausage']
my_pizzas.append('hawaiian')
friend_pizzas.append('bacon')
print('My favorite pizzas are: ')
for pizza in my_pizzas:
print(pizza.title())
print("My friend's favorite pizzas are: ")
for pizza in friend_pizzas:
print(pizza.title()) |
ordinal_numbers = [1,2,3,4,5,6,7,8,9]
for place in ordinal_numbers:
if place == 1:
print(str(place) +'st')
elif place == 2:
print(str(place)+'nd')
elif place == 3:
print(str(place)+'rd')
else:
print(str(place)+'th')
print() |
languages = ['english','german','french','spanish'] #Creates original list of languages
languages.append('russian') #appends or adds to end of list
print(languages)
languages.insert(2,'swahili') #inserting at place 2 in list swahili
print(languages)
languages.remove('english') #removes data = english
print(languages)
print(languages.pop())#removes and returns last item in list
print(languages)
del languages[2] #deletes language at second spot
print(languages)
languages.append('english') #adds back english
languages.append('mandarin') #adds mandarin
print(languages)
print(sorted(languages)) #temporarily sorts alphabetically
languages.reverse() #reverses order of languages
print(sorted(languages)) #temporarily alphabetically sorts again
languages.reverse() #reverses back to original
print(languages)
languages.sort() #perm sorts alphabetically
print(languages)
languages.sort(reverse=True) #reverses alphabetical sort
print(languages)
print('The list is now ' + str(len(languages)) +' languages long.')
|
friends = ['cody','josh','chase','preston']
print("Why hello there " + friends[0].title() + " how are you doing?")
print("Why hello there " + friends[1].title() + " how are you doing?")
print("Why hello there " + friends[2].title() + " how are you doing?")
print("Why hello there " + friends[3].title() + " how are you doing?") |
#Make a list of the first 10 cubes and use a for loop to print out the value of each cube
numbers = []
for number in range(1,11):
numbers.append(number **3)
print(number**3)
print(numbers) |
###################################
# Build 2 stacks, 1 to keep track of the max value and 1 to keep track of actual values. Print from max value from max_stack.
N = int(input())
stack = []
max_stack = [0]
for _ in range(N):
item = [int(x) for x in input().split()]
if item[0] == 1:
stack.append(item[1])
max_stack.append(max(item[1], max_stack[-1]))
elif item[0] == 2:
if stack.pop() <= max_stack[-1]:
max_stack.pop()
elif item[0] == 3:
print(max_stack[-1])
###################################
# max() is terribly slow, O(n**2), so bad solution, although short
# import sys
#
# N = int(input())
#
# stack = [0]
#
# for i in range(N):
# item = [int(x) for x in input().split()]
# if item[0] == 1:
# stack.append(item[1])
# elif item[0] == 2:
# stack.pop()
# elif item[0] == 3:
# print(max(stack))
###################################
# # LOCAL
# import sys
#
# sys.stdin = open('data/input.txt', 'r')
#
# N = int(input())
# stack = []
# max_stack = [0]
#
# for _ in range(N):
# item = [int(x) for x in input().split()]
#
# if item[0] == 1:
# stack.append(item[1])
# max_stack.append(max(item[1], max_stack[-1]))
#
# elif item[0] == 2:
# if stack.pop() <= max_stack[-1]:
# max_stack.pop()
#
# elif item[0] == 3:
# print(max_stack[-1])
#
# sys.stdin.close() |
import numpy as np
import math
#Process the input and output
def main():
sys.stdin = open('data/input.txt', 'r')
N = int(input())
for _ in range(N):
input()
ratings = [float(i) for i in input().strip().split()]
corrs = [pearsonCorr(ratings, [float(i) for i in input().strip().split()]) for j in range(5)]
print(np.argmax(corrs) + 1) # + 1 for 1 indexing
# Pearson Correlation Coefficient Defined Here:
# https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
def sumSquares(x, y):
return sum(i * j for (i, j) in zip(x, y)) / len(x) - (sum(x) * sum(y)) / len(x)**2
def pearsonCorr(x, y):
try:
correlation = sumSquares(x, y) / math.sqrt(abs(sumSquares(x, x) * sumSquares(y, y)))
except Exception:
correlation = 0
return correlation
if __name__ == "__main__":
main()
####### Using sklearn
# from sklearn.linear_model import LinearRegression
# import numpy as np
# T = int(input())
# for _ in range(T):
# lr = LinearRegression()
# _ = int(input())
# y = list(map(float,input().strip().split()))
# X = []
# for _ in range(5):
# X.append(list(map(float,input().strip().split())))
# XX = np.array(X).T
# lr.fit(XX,y)
# print( np.argmax(lr.coef_)+1)
####### Using scipy.stats
# from scipy.stats import pearsonr
# import math
# def bestTest(N, gpas, test_results):
# results = []
# for scores in test_results:
# results.append((0,0) if math.isnan(pearsonr(scores, gpas)[0]) else pearsonr(scores, gpas))
# highest_test = results.index(max(results)) + 1
# return highest_test
# if __name__ == '__main__':
# T = int(input())
# for _ in range(T):
# N = int(input())
# gpas = list(map(float, input().split()))
# test_results = []
# for _ in range(5):
# test_results.append(list(map(float, input().split())))
# print(bestTest(N, gpas, test_results))
####### LOCAL
# import sys
# import numpy as np
# import math
#
# #Process the input and output
# def main():
# sys.stdin = open('data/input.txt', 'r')
# N = int(input())
# for _ in range(N):
# input()
# ratings = [float(i) for i in input().strip().split()]
# corrs = [pearsonCorr(ratings, [float(i) for i in input().strip().split()]) for j in range(5)]
# print(np.argmax(corrs) + 1) # + 1 for 1 indexing
#
# # Pearson Correlation Coefficient Defined Here:
# # https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
# def sumSquares(x, y):
# return sum(i * j for (i, j) in zip(x, y)) / len(x) - (sum(x) * sum(y)) / len(x)**2
#
# def pearsonCorr(x, y):
# try:
# correlation = sumSquares(x, y) / math.sqrt(abs(sumSquares(x, x) * sumSquares(y, y)))
# except Exception:
# correlation = 0
# return correlation
#
# if __name__ == "__main__":
# main() |
#!/bin/python3
import os
from collections import defaultdict
# Complete the bfs function below.
def generate_graph(edges):
graph = defaultdict(list)
for node1, node2 in edges:
# Bidirectional BFS (unidirectional fails)
graph[node1].append(node2)
graph[node2].append(node1)
return graph
def find_distances(s, graph):
q = [s]
distances = defaultdict(lambda: -1) # Specifies the default dictionary key returns -1
distances[s] = 0
weight = 6
# Computes edge weighted distances from starting node
while q:
node = q.pop(0)
# Process the nodes and for any adjacent nodes, calculate the distances for that node from the starting node.
for adjacent_node in graph[node]:
if distances[adjacent_node] == -1:
distances[adjacent_node] = distances[node] + weight
q.append(adjacent_node)
return distances
def bfs(n, m, edges, s):
graph = generate_graph(edges)
distances = find_distances(s, graph)
return [distances[node] for node in range(1, n + 1) if node != s]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input())
for q_itr in range(q):
nm = input().split()
n = int(nm[0])
m = int(nm[1])
edges = []
for _ in range(m):
edges.append(list(map(int, input().rstrip().split())))
s = int(input())
result = bfs(n, m, edges, s)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
####### LOCAL
# import sys
# from collections import defaultdict
#
# # Complete the bfs function below.
# def generate_graph(edges):
# graph = defaultdict(list)
# for node1, node2 in edges:
# # Bidirectional BFS (unidirectional BFS fails test cases)
# graph[node1].append(node2)
# graph[node2].append(node1)
# return graph
#
# def find_distances(s, graph):
# q = [s]
# distances = defaultdict(lambda: -1) # Specifies the default dictionary key returns -1
# distances[s] = 0
# weight = 6
#
# # Computes edge weighted distances from starting node
# while q:
# node = q.pop(0)
#
# # Process the nodes and for any adjacent nodes, calculate the distances for that node from the starting node.
# for adjacent_node in graph[node]:
# if distances[adjacent_node] == -1:
# distances[adjacent_node] = distances[node] + weight
# q.append(adjacent_node) # For computing distances of nodes > 1 adjacent node
# return distances
#
# def bfs(n, m, edges, s):
# graph = generate_graph(edges)
# distances = find_distances(s, graph)
#
# return [distances[node] for node in range(1, n + 1) if node != s]
#
#
# if __name__ == '__main__':
# sys.stdin = open('data/input.txt', 'r')
#
# q = int(sys.stdin.readline())
#
# for q_itr in range(q):
# nm = sys.stdin.readline().split()
#
# n = int(nm[0])
#
# m = int(nm[1])
#
# edges = []
#
# for _ in range(m):
# edges.append(list(map(int, sys.stdin.readline().rstrip().split())))
#
# s = int(sys.stdin.readline())
#
# result = bfs(n, m, edges, s)
#
# print(result)
|
'''s = "identifier"
for i in s:
if i.islower():
print(i,end="")
else:
print("",i,end="")'''
s = 'camelCaseProgram'
print(''.join(c if c.islower() else ' ' + c for c in s)) |
import random
def yes_no(question):
valid = False
while not valid:
response = input(question).lower()
if response == "yes" or response == "y":
response = "yes"
return response
elif response == "no" or response == "n":
response = "no"
return response
else:
print("Please answer yes / no")
def instructions():
print("**** How to Play ****")
print()
print("The rules of the game go here")
print()
return ""
def num_check(question, low, high):
error = "Please enter an whole number between 1 and 10"
vaild = False
while not vaild:
try:
response = int(input(question))
if low < response <= high:
return response
else:
print(error)
except ValueError:
print(error)
played_before = yes_no("Have you played the game before? ")
if played_before == "no":
instructions()
how_much = num_check("How much would you like to play with? ", 0, 10)
print("You will be spending ${}".format(how_much))
balance = how_much
rounds_played = 0
print()
play_again = input("Press <Enter> to play...").lower()
while play_again == "":
rounds_played += 1
print()
print("*** Round #{} ***".format(rounds_played))
chosen_num = random.randint(1, 100)
if 1 <= chosen_num <= 5:
chosen = "unicorn"
balance += 4
elif 6 <= chosen_num <= 36:
chosen = "donkey"
balance -= 1
else:
if chosen_num % 2 == 0:
chosen = "horse"
else:
chosen = "zebra"
balance -= 0.5
if balance < 1:
play_again = "xxx"
print("Sorry you have run out of money")
else:
print("You got a {}. Your balance: ${:.2f}".format(chosen, balance))
play_again = input("Press Enter to play again or 'xxx' to quit ")
print()
print("Final balance ${}".format(balance)) |
#!/usr/bin/python3
animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')
def how_many(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
res = 0
for v in aDict.values():
res += len(v)
return res
#print(how_many(animals))
#print(animals.items())
def biggest(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: The key with the largest number of values associated with it
'''
tmp_max = 0
res = ''
for e in aDict:
curr_len = len(aDict[e])
if curr_len > tmp_max:
tmp_max = curr_len
res = e
return res |
#!/usr/bin/env python3
import string
def sum_digits(s):
""" assumes s a string
Returns an int that is the sum of all of the digits in s.
If there are no digits in s it raises a ValueError exception.
"""
sum = 0
err = True
for char in s:
if char.isdigit():
sum += int(char)
err = False
if err:
raise ValueError('There are no digits in sting')
return sum
#print(sum_digits('a;35d4'), "Expected value : 12")
#print(sum_digits('a;0d0'), "Expected value : 0")
def max_val(t):
""" t, tuple or list
Each element of t is either an int, a tuple, or a list
No tuple or list is empty
Returns the maximum int in t or (recursively) in an element of t """
# Your code here
import collections
l = []
for el in t:
if isinstance(el, collections.Iterable):
l.append(max_val(el))
else:
l.append(el)
return max(l)
#print(max_val((5, (1,2), [[1],[2]])), "Expected value : 5")
#print(max_val((5, (1,2), [[1],[9]])), "Expected value : 9")
def cipher(map_from, map_to, code):
""" map_from, map_to: strings where each contain
N unique lowercase letters.
code: string (assume it only contains letters also in map_from)
Returns a tuple of (key_code, decoded).
key_code is a dictionary with N keys mapping str to str where
each key is a letter in map_from at index i and the corresponding
value is the letter in map_to at index i.
decoded is a string that contains the decoded version
of code using the key_code mapping. """
# Your code here
assert(len(map_from) == len(map_to)), 'Each string should contain N letters'
d = dict(zip(map_from, map_to))
decoded = ""
for char in code:
decoded += d.get(char, char)
return (d, decoded)
#print(cipher("abcd", "dcba", "dab"), "Expected output : ({'a':'d', 'b': 'c', 'd': 'a', 'c': 'b'}, 'adc')")
|
#!/usr/bin/env python
"""
There are code for the problems listed as tasks for week 1
"""
"""
s = 'azcbobobegghakl'
counter = 0
for c in s:
if c == 'a' or c =='e' or c == 'i' or c == 'o' or c == 'u':
counter += 1
print(counter)
"""
"""
PROBLEM 2
Assume s is a string of lower case characters.
Write a program that prints the number of times
the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl',
then your program should print
>>> Number of times bob occurs is: 2
s = 'azcbobobegghakl'
sub = 'bob'
if s.islower():
count = 0
for i in range(len(s)):
if s[i:i+3] == sub:
count += 1
print(count)
"""
"""
PROBLEM 3
Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which
the letters occur in alphabetical order. For example,
if s = 'azcbobobegghakl', then your program should print
>>>Longest substring in alphabetical order is: beggh
"""
import string
s = 'azcbobobegghakl'
long_substr = ''
current_str = ''
prev_index = 0
if s.islower() and s.isalpha():
for ch in s:
if string.ascii_lowercase.find(ch) >= prev_index:
current_str += ch
else:
current_str = ch
prev_index = string.ascii_lowercase.find(ch)
if len(current_str) > len(long_substr):
long_substr = current_str
print(long_substr)
|
import re #Library for using regular expressions.
file_name = "Book.txt"
text = open(file_name, "r") #Read text directly from file.
every_row = [] #Array with type list to store words per each row in text.
words = {} #Array with type dictionary to store unique words and their counts.
for line in text :
every_row = line.strip('\W').lower() #Trim row from text on both sides (also cropping any symbol different from
#letter at the begin and at the end of the row) and result all words in lower case.
every_row = re.split('\W+\s+|\s+\W+|\s+', every_row) #Separate each word from another using as delimiter: combination of
#any number of any symbols different from letter and any number of
#blank spaces; or combination of any number of blank spaces and any
#number of any symbols different from letter; or any number of blank spaces.
#Symbols inside words are not delimiters, so such as "we'll", "you're" etc.
#are counting as one word.
for word in every_row :
if word == '' : #There may come empty values from rows. We skip them and don't add to the dictionary.
continue;
words[word] = words.get(word, 0) + 1 #Check if the word already exists in the dictionary: if no - add to the dictionary
#with count 1; if yes - increase count by 1.
text.close()
result = open("Words and counts.txt", "w") #The result is written to the file.
for key, value in words.items() :
count = str(key) + ' ' + str(value) + '\n' #Every word and its count is written on a new line.
result.write(count)
result.close()
|
import os #Library for getting information about OS.
from stat import * #Library for getting statistical information about OS.
import time #Library to convert time.
other_dir = True #Variable to make program work repetible.
def FileSystemCreation() : #Function to check whether directory and file exist and create if not.
is_directory = os.path.isdir(fpath)
if is_directory :
print('Such directory already exists.')
else :
try :
os.makedirs(fpath)
print('Directory ' + fpath + ' was created.')
except :
print("You can't create that directory.")
is_file = os.path.isfile(fpath + '\\' + fname) #Check if there is such file in given directory.
if is_file :
print('Such file already exists.')
print('')
else :
try :
fcreate = open(fpath + '\\' + fname, 'w') #Create file in given directory (if doesn't exist.)
print('File ' + fname + ' was created.')
print('')
except :
print("You can't create that file.")
print('')
def FileSystemInformation() : #Function to get list of elements in given directory and some statistical information about them.
try :
file_list = os.listdir(fpath) #Get list of elements in given directory.
print('Information about ' + fpath)
print('')
for file in file_list :
stat = os.stat(fpath + '\\' + file) #Get statistical information about each element.
print('Element name: ' + file)
print('Element size: ' + str(stat[ST_SIZE]) + ' bytes') #Print element size.
print('Last modified: ' + str(time.ctime(stat[ST_MTIME]))) #Print last modified time after converting.
print('-------------------------------------------------')
except :
print("You can't access data in such directory. Perhaps that directory doesn't exist.")
if __name__ == '__main__' : #Main function
while other_dir :
print('')
fpath = input('Please enter a path / directory name: ')
fname = input('Please enter a file name: ')
print('')
FileSystemCreation()
FileSystemInformation() #User can create one more directory and file or get information about if wants.
other_dir = input('Do you want to create (or get information about) other directory and file? (y/n) ').lower() == 'y'
|
"""
This problem was asked by Facebook.
Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock once. You must buy before you can sell it.
For example, given [9, 11, 8, 5, 7, 10], you should return 5, since you could buy the stock at 5 dollars and sell it at 10 dollars.
"""
def maxProfit(prices):
sell_val = 0
purchase_val = float('inf')
profit = 0
for i in prices:
if i < purchase_val:
purchase_val = i
sell_val = i
if sell_val - purchase_val > profit:
profit = sell_val-purchase_val
return profit
# Time Complexity = O(n)
# Space Complexity = O(1)
|
"""
This question was asked by Apple.
Given a binary tree, find a minimum path sum from root to a leaf.
For example, the minimum path in this tree is [10, 5, 1, -1], which has sum 15.
10
/ \
5 5
\ \
2 1
/
-1
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def PathSum(root: TreeNode):
if not root:
return False
if not root.left and not root.right:
return root.val
res = root.val
res += min(PathSum(root.left), PathSum(root.right))
return res
if __name__ == '__main__':
root = TreeNode(10)
root.left = TreeNode(5)
root.left.right = TreeNode(2)
root.right = TreeNode(5)
root.right.right = TreeNode(1)
root.right.right.left = TreeNode(-1)
print(PathSum(root))
# Time Complexity = O(n) where n is the number of nodes in the tree
# Space Complexity = O(n)
|
print('Tim can bac hai cua a mod n')
print('(Tim cac x de x^2 = a mod n)')
while True:
a = int(input('Nhap a: '))
if a == 0:
break
n = int(input('Nhap n: '))
print(f'Cac can bac hai cua {a} mod {n} la: ')
for i in range(1,n):
if i**2 % n == a:
print('%8s'% i,end='')
print() |
str1 = input().split("+")
str2 = ""
str1.sort()
for str in str1:
str2+=(str+"+")
print(str2[:-1]) |
str1 = input()
list1 = list()
for str in str1 :
if str not in list1:
list1.append(str)
# print(len(list1))
if len(list1)%2==0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
|
#!/usr/bin/python
import sys
# Use Euclid's algorithm to find the GCF
# Find the difference between two numbers
# Replace the larger number with the difference
# Repeat until both parameters are equal
def gcf(a, b):
if a == b:
return a
elif a > b:
return gcf(a-b, b)
else:
return gcf(b-a, a)
def lcm(a, b):
return a * b / gcf(a,b)
print gcf(int(sys.argv[1]), int(sys.argv[2]))
print lcm(int(sys.argv[1]), int(sys.argv[2]))
|
numbers=list(range(2,21))
primes=[2,3,5,7,11,13,17,19]
count=[0]*len(primes)
for i in primes:
for j in numbers:
a=0
while j%i==0:
j /= i
a+=1
if a > count[primes.index(i)]:
count[primes.index(i)]=a
product=1
for i in range(len(primes)):
product *= primes[i]**count[i]
print(product)
|
from random import randint
class Openness:
# contruct a random player with specified number of player
def __init__(self, player):
self.player = player
#random player always returns a random number between 0 and 1
def play(self):
if self.player == 1:
return randint(1, 2)
else:
return randint(3,4)
|
# Leetcode 1162. Find Peak Element
# Time Complexity : O(log n) where n is the size of the array
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach: Condition: If both the neighbours are lesser than the current then its the min.
# If the mid element is not a peak than move in the direction of the neighbour with higher value to find the peak
# Your code here along with comments explaining your approach
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
low = 0
high = len(nums)-1
while low<= high:
mid = low + ((high-low)//2)
# if mid points to the 0th index or the element BEFORE mid is less than mid
# and if mid points to the last index or the element AFTER mid is less than mid
if ((mid==0 or nums[mid-1]<nums[mid]) and ( mid == len(nums)-1 or nums[mid+1]<nums[mid])):
return mid
# IF mid is not the peak than move in the direction of the greater neighbour
if nums[mid+1]>nums[mid]:
low = mid+1
else:
high = mid - 1
return -1 |
# coding=utf-8
from __future__ import unicode_literals, absolute_import
class Dictionary(object):
"""
A glorified set
"""
def __init__(self):
self.words = set()
def load(self, filename):
"""
Opens filename and loads each word from the file into the dictionary
:param filename: file that will be opened, should be readable
"""
with open(filename, mode='r') as dict_in:
for line in dict_in:
for word in line.strip().split(' '):
# strip removes EOL, split helps deal with multiple words
# in one line
self.add(word)
def save(self, filename):
"""
Opens filename and writes all the words in the dictionary to it
each word goes to a new line
:param filename: file to be used as output. If it exits, it should
be writeable
"""
with open(filename, mode='w+') as dict_out:
for word in self.words:
dict_out.write(word + '\n')
def add(self, word):
"""
Adds a word to the dictionary. Words will only be added if they
are not present already.
"""
return self.words.add(word)
def contains(self, word):
"""
Checks if a word is present in the dictionary
:return: True if it is, False otherwise
"""
return word in self.words
def __contains__(self, item):
return self.contains(item)
|
# The pre-order traversal of a Binary Tree is a traversal technique that starts
# at the tree's root node and visits nodes in the following order:
# Current node
# Left subtree
# Right subtree
#
# Given a non-empty array of integers representing the pre-order traversal of a
# Binary Search Tree (BST), write a function that creates the relevant BST and
# returns its root node.
#
# The input array will contain the values of BST nodes in the order in which
# these nodes would be visited with a pre-order traversal.
#
# Each BST node has an integer value, a
# left child node, and a right child node. A node is
# said to be a valid BST node if and only if it satisfies the BST
# property: its value is strictly greater than the values of every
# node to its left; its value is less than or equal to the values
# of every node to its right; and its children nodes are either valid
# BST nodes themselves or None / null.
#
# Sample Input
#
# preOrderTraversalValues = [10, 4, 2, 1, 5, 17, 19, 18]
# Sample Output
#
# 10
# / \
# 4 17
# / \ \
# 2 5 19
# / /
# 1 18
#
# Time: "O(n) | Space: O(n) - where n is the length of the input array"#
class BST:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# Sol 1
# Time O(n^2) | Space O(h)
def reconstruct(preOrderTraversalValues):
if len(preOrderTraversalValues)== 0:
return None
currentValue = preOrderTraversalValues[0]
rightSubTreeRootIdx = len(preOrderTraversalValues)
for i, value in enumerate(preOrderTraversalValues):
value = preOrderTraversalValues[i]
if value >= currentValue:
rightSubTreeRootIdx = i
break
leftSubTree = reconstruct(preOrderTraversalValues[1:rightSubTreeRootIdx])
rightSubTree = reconstruct(preOrderTraversalValues[rightSubTreeRootIdx:])
return BST(currentValue, leftSubTree, rightSubTree)
#Sol 2
class TreeInfo:
def __init(self, rootIdx):
self.rootIdx = rootIdx
def recontruct1(preOrderTraversalValues):
treeInfo = TreeInfo(0)
return reconstructBSTFromRange(float("-inf"), float("inf"), preOrderTraversalValues, treeInfo)
def reconstructBSTFromRange(lowerBound, upperBound, preOrderTraversalValues, currentTreeInfo):
if currentTreeInfo.rootIdx == len(preOrderTraversalValues):
return None
rootValue = preOrderTraversalValues[currentTreeInfo.rootIdx]
if rootValue <= lowerBound or rootValue >= upperBound:
return None
currentTreeInfo.rootIdx+=1
leftSubTree = reconstructBSTFromRange(lowerBound, rootValue, preOrderTraversalValues, currentTreeInfo)
rightSubTree = reconstructBSTFromRange(rootValue, upperBound, preOrderTraversalValues, currentTreeInfo)
return BST(rootValue, leftSubTree, rightSubTree)
|
# Write a function that takes in an n x m two-dimensional array (that can be
# square-shaped when n == m) and returns a one-dimensional array of all the
# array's elements in spiral order.
# Spiral order starts at the top left corner of the two-dimensional array, goes
# to the right, and proceeds in a spiral pattern all the way until every element
# has been visited.
# Sample Input
# array = [
# [1, 2, 3, 4],
# [12, 13, 14, 5],
# [11, 16, 15, 6],
# [10, 9, 8, 7],
# ]
#
# Sample Output
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
# Time: O(n) time | O(n) space - where n is the total number of elements in the array
def spiralTraverse(array):
res = []
startRow = 0
startCol = 0
endRow = len(array) - 1
endCol = len(array[0]) - 1
while startRow <= endRow and startCol <= endCol:
#top - right
for col in range(startCol, endCol + 1):
res.append(array[startRow][col])
# right - bottom
for row in range(startRow+1, endRow + 1):
res.append(array[row][endCol])
#bottom-right - left
for col in reversed(range(startCol, endCol)):
if startRow == endRow:
break
res.append(array[endRow][col])
#bottom-left - top
for row in reversed(range(startRow+1, endRow)):
if startCol == endCol:
break
res.append(array[row][startCol])
startCol += 1
endCol -= 1
startRow += 1
endRow -= 1
return res
|
# Write a function that takes in an array of integers and returns the length of
# the longest peak in the array.
# A peak is defined as adjacent integers in the array that are strictly
# increasing until they reach a tip (the highest value in the peak), at which
# point they become strictly decreasing. At least three integers are required to
# form a peak.
# For example, the integers 1, 4, 10, 2 form a peak, but the
# integers 4, 0, 10 don't and neither do the integers
# 1, 2, 2, 0. Similarly, the integers 1, 2, 3 don't
# form a peak because there aren't any strictly decreasing integers after the
# 3.
# Sample Input
# array = [1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]
#
# Sample Output
# 6 // 0, 10, 6, 5, -1, -3
# Time: O(n) | Space: O(1) - where n is the length of the input array
def longestPeak(array):
longestPeakLength = 0
i = 1
while i < len(array) - 1:
isPeak = array[i] > array[i - 1] and array[i] > array[i + 1]
if not isPeak:
i+=1
continue
leftIdx = i - 2
while leftIdx >= 0 and array[leftIdx] < array[leftIdx + 1]:
leftIdx-=1
rightIdx = i + 2
while rightIdx < len(array) and array[rightIdx] < array[rightIdx - 1]:
rightIdx+=1
currentPeakLength = rightIdx - leftIdx - 1
longestPeakLength = max(currentPeakLength, longestPeakLength)
i = rightIdx
return longestPeakLength |
# Write a function that takes in a Binary Search Tree (BST) and a positive
# integer k and returns the kth largest integer contained in the
# BST.
#
# You can assume that there will only be integer values in the BST and that
# k is less than or equal to the number of nodes in the tree.
#
# Also, for the purpose of this question, duplicate integers will be treated as
# distinct values. In other words, the second largest value in a BST containing
# values {5, 7, 7} will be 7 —not 5.
#
# Each BST node has an integer value, a
# left child node, and a right child node. A node is
# said to be a valid BST node if and only if it satisfies the BST
# property: its value is strictly greater than the values of every
# node to its left; its value is less than or equal to the values
# of every node to its right; and its children nodes are either valid
# BST nodes themselves or None / null.
# Sample Input
# tree = 15
# / \\
# 5 20
# / \\ / \\
# 2 5 17 22
# / \\
# 1 3
#
# k = 3
#
# Sample Output
# 17
#
# Time: O(h + k) | Space: O(h) - where h is the height of the tree and k is the input parameter
class BinaryTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
#Solution 1
#Time: O(n) | Space O(n)
def findKthLargestValueInBST(tree, k):
sortedNodeValues = []
inOrderTraverse(tree, k, sortedNodeValues)
return sortedNodeValues[len(sortedNodeValues) - k]
def inOrderTraverse(node, k, sortedNodeValues):
if node== None:
return
inOrderTraverse(node.left, k, sortedNodeValues)
sortedNodeValues.append(node.value)
inOrderTraverse(node.right, k, sortedNodeValues)
#Solution 2
#Time: O(h+k) | Space: O(h)
class TreeInfo:
def __init__(self, numberOfNodesVisited, lastVisitedNodeValue):
self.numberOfNodesVisited = numberOfNodesVisited
self.lastVisitedNodeValue = lastVisitedNodeValue
def findKthLargestValueInBST1(tree, k):
treeInfo = TreeInfo(0, -1)
reverseInOrderTraverse(tree, k, treeInfo)
return treeInfo.lastVisitedNodeValue
def reverseInOrderTraverse(node, k, treeInfo):
if node == None or treeInfo.numberOfNodesVisited >= k:
return
reverseInOrderTraverse(node.right, k, treeInfo)
if treeInfo.numberOfNodesVisited < k:
treeInfo.numberOfNodesVisited += 1
treeInfo.lastVisitedNodeValue = node.value
reverseInOrderTraverse(node.left, k, treeInfo)
|
# There's an algorithms tournament taking place in which teams of programmers
# compete against each other to solve algorithmic problems as fast as possible.
# Teams compete in a round robin, where each team faces off against all other
# teams. Only two teams compete against each other at a time, and for each
# competition, one team is designated the home team, while the other team is the
# away team. In each competition there's always one winner and one loser; there
# are no ties. A team receives 3 points if it wins and 0 points if it loses. The
# winner of the tournament is the team that receives the most amount of points.
#
# Given an array of pairs representing the teams that have competed against each
# other and an array containing the results of each competition, write a
# function that returns the winner of the tournament. The input arrays are named
# competitions and results , respectively. The
# competitions array has elements in the form of
# [homeTeam, awayTeam] , where each team is a string of at most 30
# characters representing the name of the team. The results array
# contains information about the winner of each corresponding competition in the
# competitions array.
# Specifically, results[i] denotes the winner of competitions[i] ,
# where a 1 in the results array means that the home team in the corresponding
# competition won and a 0 means that the away team won.
#
# It's guaranteed that exactly one team will win the tournament and that each
# team will compete against all other teams exactly once. It's also guaranteed
# that the tournament will always have at least two teams.
# Sample Input
# competitions = [
# ["HTML", "C#"],
# ["C#", "Python"],
# ["Python", "HTML"],
# ]
# results = [0, 0, 1]
#
# Sample Output
# Python
# //C# beats HTML, Python Beats C#, and Python Beats HTML.
# // HTML - 0 points
# // C# - 3 points
# // Python - 6 points
# Time: "O(n) | Space: O(k) - where n is the number of competitions and k is the number of teams"
#
#competitions = [home, away]
# results = 1 => home, 0 => away
#points = 3
def tournamentWinner(competitions, results):
res = {}
for i in range(0, len(competitions)):
winner = ''
loser = ''
winner = competitions[i][1] if results[i] == 0 else competitions[i][0]
loser = competitions[i][0] if results[i] == 0 else competitions[i][1]
if winner in res:
res[winner] += 3
else:
res[winner] = 3
if loser in res:
res[loser] += 0
else:
res[loser] = 0
max = 0
win = ''
for val in res:
if res[val] > max:
max = res[val]
win = val
return win
|
# You're given three nodes that are contained in the same Binary Search Tree:
# nodeOne, nodeTwo, and nodeThree. Write
# a function that returns a boolean representing whether one of
# nodeOne or nodeThree is an ancestor of
# nodeTwo and the other node is a descendant of
# nodeTwo. For example, if your function determines that
# nodeOne is an ancestor of nodeTwo, then it needs to
# see if nodeThree is a descendant of nodeTwo. If your
# function determines that nodeThree is an ancestor, then it needs
# to see if nodeOne is a descendant.
#
# A descendant of a node N is defined as a node contained in
# the tree rooted at N. A node N is an ancestor of
# another node M if M is a descendant of
# N.
#
# It isn't guaranteed that nodeOne or nodeThree will
# be ancestors or descendants of nodeTwo, but it is guaranteed that
# all three nodes will be unique and will never be None /
# null. In other words, you'll be given valid input nodes.
#
# Each BST node has an integer value, a
# left child node, and a right child node. A node is
# said to be a valid BST node if and only if it satisfies the BST
# property: its value is strictly greater than the values of every
# node to its left; its value is less than or equal to the values
# of every node to its right; and its children nodes are either valid
# BST nodes themselves or None / null.
#
# Sample Input
# tree = 5
# / \
# 2 7
# / \ / \
# 1 4 6 8
# / /
# 0 3
# // This tree won't actually be passed as an input; it's here to help you visualize the problem.
# nodeOne = 5 // The actual node with value 5.
# nodeTwo = 2 // The actual node with value 2.
# nodeThree = 3 // The actual node with value 3.
#
# Sample Output
# true // nodeOne is an ancestor of nodeTwo, and nodeThree is a descendant of nodeTwo.
#
# Time: O(h) | Space: O(1) - where h is the height of the tree
class BST:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right: right
def validateThreeNodes(nodeOne, nodeTwo, nodeThree):
if isDescendant(nodeTwo, nodeOne):
return isDescendant(nodeThree, nodeTwo)
if isDescendant(nodeTwo, nodeThree):
return isDescendant(nodeOne, nodeTwo)
def isDescendant(node, target):
while node is not None and node is not target:
node = node.left if target.value < node.value else node.right
return node == target
|
# coding=utf-8
# 通过Python编程完成一个银行ATM机模拟系统,具备如下功能:
# (1)登陆验证:用户输入用户名密码登陆,检测用户名是否存在以及用户名密码是否匹配;用户名密码各有三次输入机会,超过三次系统退出。
# (2)菜单界面:登陆成功后显示功能操作界面,输入序号选择对应功能。
# (3)用户注册:用户可以输入用户名和密码创建自己的账号,并输入电话号码等信息,如果用户名存在则让用户重新输入用户名。注册后免费赠送5000元余额。
# (4)账户管理:用户可以随时查看自己的账户余额。用户可以输入其他账户用户名,实现转账功能;用户名必须存在。用户也可以模拟实现存取款功能。
# (5)用户名和密码以及账户信息等必须永久保存。且基于命令行完成,不需要开发GUI界面。
import json
with open("custominfo.json") as f:
r = json.load(f)
print(r)
def main():
while True:
print('请输入序号选择你要进行的操作')
print('1.登录\n', '2.注册\n', '3.退出\n')
chioce = input('请输入序号:')
if chioce == '1':
login()
if chioce == '2':
register()
if chioce == '3':
return exit()
def register():
username=input('请输入用户名')
if username in r:
print('用户名已存在!')
# register()
return
password=input('请输入密码')
r[username]=[password,5000]
update()
print('注册成功,免费赠送5000余额!')
def login():
count = 3
while True:
username = str(input('请输入你的用户名:'))
if username not in r:
print('该用户名不存在,重新输入')
count -= 1
if count == 0:
print('输入次数过多,请重新输入')
return login()
else:
break
count=3
while True:
password = str(input('请输入你的密码:'))
if password == r[username][0]:
print('登录成功')
return show(username)
else:
if password not in r[username][0]:
print('密码输入错误,请重新输入')
count-=1
if count == 0:
print('输入次数过多,请重新输入')
break
def show(username):
while True:
print('请输入您要选择的操作')
print('0.回到首页\n1.查看当前余额\n2.转账\n3.存款\n4.取款\n5.退出\n')
chance = input('请输入序号:')
if chance=='0':
main()
if chance == '1':
print(r[username][1])
if chance == '2':
uid = input('请输入其他用户的用户名:')
if uid not in r:
print('用户名不存在,请重新输入!')
show(username)
else:
m = int(input('输入转账金额'))
r[username][1] = r[username][1] - m
r[uid][1] = r[uid][1] + m
update()
print('转账后余额为:', r[username][1])
if chance=='3':
m=int(input('请输入存款金额:'))
r[username][1]=r[username][1]+m
print('当前余额:',r[username][1])
update()
if chance=='4':
m=int(input('请输入取款金额:'))
r[username][1]=r[username][1]-m
print('当前余额:',r[username][1])
update()
if chance=='5':
exit()
def update():
# print(type(r[username]))
# r[username].append(money)
with open("custominfo.json", "w+") as f:
json.dump(r, f)
main() |
total = float(input(" What is your bill total? ").strip('$'))
# the above total variable is an input string into a float with a $ being taken away
fifteen = int(total) * 0.15
eightteen = int(total) * 0.18
twenty = int(total) * 0.20
# the above lines turn the total variable into an integer times the tip percentage
print(f" ${fifteen:.2f} is the suggested tip for 15%")
print(f" ${eightteen:.2f} is the suggested tip for 18%")
print(f" ${twenty:.2f} is the suggested tip for 20%")
# the above lines print the tip amount for each different tip
|
#dictionaries and lists can be inside of each other
animal_sounds = {
"cat": ['meow', 'pur'],
"dog": ['bark', 'woof'],
"fox": []
}
# above is a dictionary of lists
ant = {'name': 'Ant', 'height': 70, 'shoes': 12, 'hair': 'brown', 'eyes': 'brown'}
oscar = {'name': 'Oscar', 'height': 68, 'shoes': 11, 'hair': 'brown', 'eyes': 'brown'}
viri = {'name': 'Viri', 'height': 60, 'shoes': 7, 'hair': 'brown', 'eyes': 'brown'}
#the above lines are variables which are dictionaries
people = [ant, oscar, viri]
# above is a list of dictionaries
print(people)
for person in people:
print(person['height'])
# this prints the heights of every person from the people list
for person in people:
print(person.get('height', 'not found'))
# this 2nd block is the safer 'version' block of code to make the print to the console
# including the 'not found' default value in case some do not have a height key
|
# from https://www.reddit.com/r/dailyprogrammer/comments/3s4nyq/20151109_challenge_240_easy_typoglycemia/
from random import shuffle
import itertools
import re
text = """According to a research team at Cambridge University, it doesn't matter in what order the letters in a word are,
the only important thing is that the first and last letter be in the right place.
The rest can be a total mess and you can still read it without a problem.
This is because the human mind does not read every letter by itself, but the word as a whole.
Such a condition is appropriately called Typoglycemia."""
words = text.split()
def split_and_scramble_and_join(word):
''' Performs the typoglycemia on a word '''
if len(word) < 4:
return word
# split the first and last characters from the rest of the word
inner = word[1:-1]
first = word[0]
last = word[-1]
# scramble the inner characters
inner_list = list(inner)
shuffle(inner_list)
# join the word back together
shuffled = "".join(list(itertools.chain(first, inner_list, last)))
return shuffled
def typo(word):
''' handles punctuation and scrambling semantics for typoglycemation '''
resplitified = re.split("(\W+)", word)
return "".join([split_and_scramble_and_join(piece) for piece in resplitified])
typoed = [typo(word) for word in words]
typoed_phrase = " ".join(typoed)
print(typoed_phrase)
|
# shuffle a list in Python without using random.shuffle()
from random import shuffle
from random import randrange
values = list(range(0,10000))
def cheating_shuffle_it(values):
shuffle(values)
def shuffle_it_one(values):
# This version takes the last value from the list and
# inserts it back in to a random location. When performed
# repeatedly it will shuffle the list
for x in range(1, len(values) * 10):
item = values.pop()
pos = randrange(0, len(values))
values.insert(pos, item)
def shuffle_it(values):
# This shuffle will iterate through all items in a list and insert
# them into a new list at a random location
new_list = []
for item in values:
pos = randrange(0, len(values))
new_list.insert(pos, item)
print(new_list)
values = new_list
def shuffle_it_gen(values):
# This shuffle is a generator that will pop an items from a
# list at a random location and yield it until all
# items from the list are gone.
while len(values) > 0:
x = values.pop(randrange(0, len(values)))
yield x
#shuffle_it_one(values)
#print(values)
# Thoughts: This one seems to shuffle well given enough iterations,
# but can grow slow when dealing with large lists
#shuffle_it_two(values)
# Thoughts: This one was faster then the first, but does not
# shuffle in place. Also it seemed to be somewhat ordered
#shuffle_it_three
for item in shuffle_it_gen(values):
print(item, end=", ")
# Thoughts: This one was faster but requires an external loop
# because it also doe snto shuffle in place.
|
class Event:
def __init__(self, start, end):
"""
initializes event node with start and end time stored as Data
"""
self.data = {
'start': start,
'end': end,
}
self.next = None
return
def output(self):
"""
formats and returns start and end time
"""
start_str = 'Start: ' + str(self.data['start'])
end_str = 'End: ' + str(self.data['end'])
both = start_str + ' | ' + end_str
return(both)
class Queue:
def __init__(self):
self.front = self.rear = None
def isEmpty(self):
return self.front == None
# Method to add an item to the queue
def EnQueue(self, start, end):
temp = Event(start, end)
if self.rear == None:
self.front = self.rear = temp
return
self.rear.next = temp
self.rear = temp
# Method to remove an item from queue
def DeQueue(self):
if self.isEmpty():
return
temp = self.front
self.front = temp.next
if(self.front == None):
self.rear = None
def output_list(self):
curr_node = self.front
while curr_node is not None:
print(curr_node.output())
curr_node = curr_node.next
|
import argparse
import random
import string
def get_random_ascii_string(size=20):
return "".join(random.choices(string.ascii_lowercase, k=size))
def main():
parser = argparse.ArgumentParser(description="""Generates 2 files.\n
Format of each line of the first file:\n
<lower_case_letters> <number>\n
Format of each line of the second file:\n
<upper_case_letters> <number>\n
Letters next to the same numbers in the files will be the same
(just with different cases)""")
parser.add_argument("first_file_name")
parser.add_argument("second_file_name")
parser.add_argument("-n", "--n-lines", default=1000, type=int)
args = parser.parse_args()
with open(args.first_file_name, 'w') as f1, open(args.second_file_name, 'w') as f2:
LINES_PER_ROUND = 500000
lines_remaining = args.n_lines
current_line = 1
while lines_remaining > 0:
lines_generated = min(LINES_PER_ROUND, lines_remaining)
lines1 = []
lines2 = []
for _ in range(lines_generated):
text = get_random_ascii_string()
lines1.append(text + " " + str(current_line) + "\n")
lines2.append(text.upper() + " " + str(current_line) + "\n")
current_line += 1
random.shuffle(lines1)
random.shuffle(lines2)
f1.write("".join(lines1))
f2.write("".join(lines2))
lines_remaining -= lines_generated
if __name__ == '__main__':
main() |
from prettytable import PrettyTable
from file_reader import read_file
import unittest
import os
from collections import defaultdict
class Student:
"A class that stores all the information about students."
pt_hdr = ['CWID', 'Name', 'Completed Courses']
def __init__(self, cwid, name, major):
self.cwid = cwid
self.name = name
self.major = major
self.courses = dict() #key is course, value is grade (we're not using defaultdict because we'll always have a value for the course)
self.labels = ['cwid', 'name', 'major', 'courses']
def add_course(self, course, grade):
"""A function that assigns a value grade to the key course."""
self.courses[course] = grade
def pt_row(self):
""""A function that creates rows with student's information."""
return [self.cwid, self.name, sorted(self.courses.keys())]
class Instructor:
"""A class that stores all the information about instructors."""
pt_hdr = ['CWID', 'Name', 'Dept', 'Course', 'Students']
def __init__(self, cwid, name, department):
self.cwid = cwid
self.name = name
self.department = department
self.students = defaultdict(int) #defaultdict specifies only value type
def add_course(self, course):
self.students[course] += 1
def pt_row(self):
"""A function that creates rows with instructor's information."""
for course, num_students in self.students.items():
yield [self.cwid, self.name, self.department, course, num_students]
class Repository:
"""A class that stores information about students and instructors and generates tables of students and instructors."""
def __init__(self, path, ptables =True):
self.students = dict() #cwid is the key, Instance of class Student is the value
self.instructors = dict() #cwid is they, Instance of class Instructor is the value
self.grades = list()
self.reading_students(os.path.join(path, 'students.txt'))
self.get_instructors(os.path.join(path, 'instructors.txt'))
self.get_grades(os.path.join(path, 'grades.txt'))
if ptables:
print("\nStudent Summary")
self.student_table()
print("\nInstructor Summary")
self.instructor_table()
def student_table(self):
"""A function that creates a table with student's information."""
pt = PrettyTable(field_names = Student.pt_hdr)
for student in self.students.values():
pt.add_row(student.pt_row())
print (pt)
def instructor_table(self):
"""A function that creates a table with instructor's information."""
pt = PrettyTable(field_names = Instructor.pt_hdr)
for instructor in self.instructors.values():
for row in instructor.pt_row():
pt.add_row(row)
print (pt)
def reading_students(self, path):
"""A function that assigns student's information (cwid, name, major) to his/her cwid."""
try:
for cwid, name, major in read_file(path, 3, '\t', header=False):
self.students[cwid] = Student(cwid, name, major)
except ValueError as e:
print(e)
def get_instructors(self, path):
"""A function that assigns instructor's information (cwid, name, dept) to instructor's cwid."""
try:
for cwid, name, dept in read_file(path, 3, sep = '\t', header=False):
self.instructors[cwid] = Instructor(cwid, name, dept)
except ValueError as e:
print(e)
def get_grades(self, path):
"""A function that adds courses and grades to students and instructors."""
try:
for student_cwid, course, grade, instructor_cwid in read_file(path, 4, sep = '\t', header=False):
if student_cwid in self.students:
self.students[student_cwid].add_course(course, grade)
else:
print("unknown student")
if instructor_cwid in self.instructors:
self.instructors[instructor_cwid].add_course(course)
else:
print("instructor not found")
except ValueError as e:
print (e)
def main():
path = ('/Users/katya/Documents/GitHub/Registrar-Database')
stevens = Repository(path)
if __name__ == '__main__':
main()
|
from typing import Any, Dict, Optional
from .utils import random_string
class Publication(object):
"""Publication is a class where the attributes of each
of its objects are passed to the constructor."""
def __init__(self, attrs: Dict[str, Any]) -> None:
"""Constructs a new Publication.
:Example:
attrs = {'author': 'Fernando Pessoa', 'title': 'O Livro do Desassossego"}
Publication(**attrs)
:param attrs: a Dict of attributes
:rtype: None"""
self.attrs = attrs
@property
def attributes(self):
return self.attrs
@property
def fields(self):
return self.attrs.keys()
@property
def values(self):
"""Returns a list containing the values of every field in the object."""
return self.attrs.values()
def __getattr__(self, attr) -> Optional[Any]:
return self.attrs.get(attr)
def filename(self) -> Optional[str]:
ext = self.attrs.get('extension') # required
if ext is None:
return None
title = self.attrs.get('title') # optional
# if title is None, generate random filename
if title is None:
random_filename = random_string(15)
return f'{random_filename}.{ext}'
year = self.attrs.get('year') # optional
if year:
authors = self.attrs.get('authors') # optional
if authors:
return f'{title} ({year}) - {authors}.{ext}'
else:
return f'{title} ({year}).{ext}'
return f'{title}.{ext}'
def __repr__(self) -> str:
attrs = ', '.join([f'{a!r}: {v}' for (a, v) in self.attrs.items()])
return f'{self.__class__.__name__}({attrs})'
def __len__(self) -> int:
return len(self.attrs)
|
"""Utilities module.
Contains useful functions that don't belong to any class in particular.
"""
import random
import string
def random_string(length: int, character_set: str = string.ascii_lowercase) -> str:
"""Returns a random string of length 'length'
consisting of characters from 'character_set'."""
letters = [random.choice(character_set) for _ in range(length)]
return "".join(letters)
|
#based on :https://github.com/llSourcell/Lets_Build_a_Compiler_LIVE/blob/main/compiler.py
#regular expression library (search pattern)
import re
#Tokenizer function receives starting input
# i.e (add 2 (subtract 4 2))
def tokenizer(input_expression):
#counter variable for iterating through input array
current = 0
#array to store computed tokens
tokens = []
##use regex library to create search patterns for
#letters a,z
alphabet = re.compile(r"[a-z]", re.I);
#numbers 1-9
numbers = re.compile(r"[0-9]");
#white space
whiteSpace = re.compile(r"\s");
#iterate through input
while current < len(input_expression):
#track position
char = input_expression[current]
#If white space is detected, no token created
if re.match(whiteSpace, char):
current = current+1
continue
#create + add token to array for open parens
if char == '(':
tokens.append({
'type': 'left_paren',
'value': '('
})
#continue iterating
current = current+1
continue
#create + add token to array for closed parens
if char == ')':
tokens.append({
'type': 'right_paren',
'value': ')'
})
#continue iterating
current = current+1
continue
#create + add token to array for numbers
if re.match(numbers, char):
value = ''
#nested iteration if a number is multi-num
while re.match(numbers, char):
value += char
current = current+1
if current ==len(input_expression):
break
char = input_expression[current];
tokens.append({
'type': 'number',
'value': value
})
continue
#create + add token to array for letters
if re.match(alphabet, char):
value = ''
#nested iteration if a word is multi-char (all are in this case)
while re.match(alphabet, char):
value += char
current = current+1
if current ==len(input_expression):
break
char = input_expression[current]
tokens.append({
'type': 'text',
'value': value
})
continue
#error condition if we find an unknown value in the input
raise ValueError('what are THOSE?: ' + char);
return tokens
while(True):
i=input('input (q to quit): ')
print(tokenizer(i) ,'\n')
if(i=='q'):
break |
def solve(a, b):
sol=[0,0,0]
for i in range(3):
a[i]=int(a[i])
b[i]=int(b[i])
#a[2]=(0-a[2])
#b[2]=(0-b[2])
#print(a,b)
sol[0]=(a[1]*b[2])-(a[2]*b[1])
sol[1]=(a[2]*b[0])-(b[2]*a[0])
sol[2]=(b[1]*a[0])-(a[1]*b[0])
#print(sol)
final=[0,0]
final[0]=int((sol[0]/sol[2]))
final[1]=int((sol[1]/sol[2]))
print(final)
return None
#for i in range(0,3):
a=str(input())
#for i in range(0,3):
b=str(input())
a=a.split(' ')
b=b.split(" ")
solve(a,b) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 18 21:07:18 2017
@author: louiemceliberti
"""
def numbers(*args):
sum = 0
for x in args:
sum += x
print(sum)
numbers(39)
numbers(5,9238,85)
numbers(4207,45486689)
numbers(2,683,461) |
import time
def merge(left, right):
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(data):
if len(data) <= 1:
return data
half = len(data) // 2
left = merge_sort(data[:half])
right = merge_sort(data[half:])
return merge(left, right)
|
import sqlite3
dbase = sqlite3.connect('test_01.db')
dbase.execute(""" CREATE TABLE IF NOT EXISTS employees_records(
Id INT PRIMARY KEY NOT NULL,
Name TEXT NOT NULL,
Division TEXT NOT NULL,
Stars INT NOT NULL)
""")
def insert_record(Id,Name,Division,Stars ):
dbase.execute('''INSERT INTO employees_records(Id,Name,Division,Stars)
VALUES(?,?,?,?)''',(Id,Name,Division,Stars))
dbase.commit()
print("Recorded Inserted")
def read_data():
data = dbase.execute("SELECT * FROM employees_records ")
l = 11
print('-'*40)
print("Id " + "Name".ljust(l,' ')+ 'Division'.ljust(l,' ')+ 'Stars'.ljust(l,' '))
print('-'*40)
for record in data:
print(f"{record[0]} {record[1].ljust(l,' ')} {record[2].ljust(l,' ')} {record[3]}")
print('-'*40)
insert_record(1,'Lenny','Software',3)
insert_record(2,'Cynthia','Manager',5)
insert_record(3,'Harrison','Mechanics',4)
insert_record(4, 'Joan', 'Electonics',3)
insert_record(5,'James', 'Maintenance',4)
insert_record(6,'Ramesh', 'Maintenance',4)
read_data()
def update_record():
dbase.execute(""" UPDATE employees_records SET Stars=3 WHERE ID=6 """)
dbase.commit
update_record()
read_data()
|
num = 3.75
num2 = 3.70
# print(type(num))
#print(round(num, 1))
#print(num == num2)
num3 = '100'
num4 = 200
#print(num3 + num4)
#-_-_-_Casting-_-_-
num5 = int(num3)
#print(num5 + num4)
# print(type(num5))
num6 = str(num4)
# print(type(num6))
#print(help(int))
|
"""
Option validation with exception handling.
"""
class Validator:
"""
When a given validation function returns True, given exception is raised.
"""
def __init__(self, validation_function, exception):
self.validation_function = validation_function
self.exception = exception
def validate(self, *args, **kwargs):
if self.validation_function(*args, **kwargs):
raise self.exception
|
# 007 Reverse Integer
class Solution(object):
max_int = 2**31
min_int = -2**31-1
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
# special case: last digit is 0
# special case: reversed int overflow
if str(x)[0] != "-":
return self.reviseIfOverflow(int(str(x)[::-1]))
else:
return self.reviseIfOverflow(int("-" + str(self.reverse(-x))))
def reviseIfOverflow(self, x):
if x > self.max_int or x < self.min_int:
return 0
else:
return x
def main():
sol = Solution()
print sol.reverse(-123) # -321
print sol.reverse(100) # 1
print sol.reverse(1534236469) # 0 (overflow)
if __name__ == '__main__':
main() |
# 223 Rectangle Area
class Solution(object):
def computeArea(self, A, B, C, D, E, F, G, H):
"""
:type A: int
:type B: int
:type C: int
:type D: int
:type E: int
:type F: int
:type G: int
:type H: int
:rtype: int
"""
# common part:
# x: max(A,E) ~ min(C,G)
# y: max(B,F) ~ min(D,H)
if E > C or A > G or F > D or B > H:
return (C-A)*(D-B) + (G-E)*(H-F)
return (C-A)*(D-B) + (G-E)*(H-F) - (min(C,G)-max(A,E)) * (min(D,H)-max(B,F))
def main():
sol = Solution()
print sol.computeArea(-3,0,3,4,0,-1,9,2) # 45
print sol.computeArea(0,0,0,0,-1,-1,1,1) # 4
if __name__ == '__main__':
main() |
# 028 Implement strStr()
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
k = len(needle)
if k == 0:
return 0
for i in xrange(len(haystack)-k+1):
for kk in xrange(k):
if haystack[i+kk] != needle[kk]:
break
if kk == k-1:
return i
return -1
def main():
sol = Solution()
print sol.strStr("abc", "c") # 2
print sol.strStr("", "") # 0
print sol.strStr("", "a") # -1
print sol.strStr("aabc", "abc") # 1
if __name__ == '__main__':
main() |
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
rev = 0
# neg number is NOT palindrome...
if x < 0:
return False
temp = x
while (temp != 0):
rev = rev * 10 + temp%10
temp = temp/10
return x == rev
def main():
sol = Solution()
print 2**31
print sol.isPalindrome(12) # False
print sol.isPalindrome(-12321) # True
print sol.isPalindrome(0) # True
print sol.isPalindrome(-2147447412) # False
if __name__ == '__main__':
main() |
# 202 Happy Number
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 0:
return False
n = n if n > 0 else -n
numbers = set() # a set
while 1:
if n in numbers:
return False
numbers.add(n)
if n == 1:
return True
digits = [int(s) for s in str(n)]
n = 0
for d in digits:
n += d*d
def main():
sol = Solution()
print sol.isHappy(1) # True
print sol.isHappy(3) # False
print sol.isHappy(19) # True
print sol.isHappy(5) # False
if __name__ == '__main__':
main()
|
# 171 Excel Sheet Column Number
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
base = 26
letters = {"A":1,"B":2,"C":3,"D":4,"E":5,"F":6,"G":7,"H":8,"I":9,"J":10,"K":11,"L":12,"M":13,"N":14,"O":15,"P":16,"Q":17,"R":18,"S":19,"T":20,"U":21,"V":22,"W":23,"X":24,"Y":25,"Z":26}
result = 0
v = 1
for l in s[::-1]:
result += letters[l] * v
v *= base
return result
def main():
sol = Solution()
print sol.titleToNumber("A") # 1
print sol.titleToNumber("Z") # 26
print sol.titleToNumber("AA") # 27
print sol.titleToNumber("YZ") # 676
print sol.titleToNumber("AAA") # 703
if __name__ == '__main__':
main() |
# 022 Longest Increasing Subsequence
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
if n == 0:
return []
def helper(totalL, totalR, n):
res = []
if totalL == n and totalR == n:
return [""]
if totalL < n:
res += ["(" + p for p in helper(totalL+1, totalR, n)]
if totalR < totalL:
res += [")" + p for p in helper(totalL, totalR+1, n)]
return res
return helper(0, 0, n)
def main():
sol = Solution()
print sol.generateParenthesis(1) # ["()"]
print sol.generateParenthesis(3) # ["((()))", ... , "()()()"]
print sol.generateParenthesis(0) # []
if __name__ == '__main__':
main() |
# 357 Count Numbers with Unique Digits
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
count = [1,10]
if n <= 1:
return count[n]
if n > 10:
n = 10
currCount = 9
for i in range(2, n+1):
currCount = currCount * (11-i)
count.append(count[-1] + currCount)
return count[n]
def main():
sol = Solution()
print sol.countNumbersWithUniqueDigits(0) # 1
print sol.countNumbersWithUniqueDigits(1) # 10
print sol.countNumbersWithUniqueDigits(2) # 91
print sol.countNumbersWithUniqueDigits(4) # 5275
print sol.countNumbersWithUniqueDigits(10) # 8877691
print sol.countNumbersWithUniqueDigits(11) # 8877691
if __name__ == '__main__':
main() |
from datetime import datetime
from dateutil.relativedelta import relativedelta
SATURDAY = 5
SUNDAY = 6
def getDays(dayOfMonth, holidays):
today = datetime.today()
monthsLeftInYear = 12 - (today.month - 1)
for i in range(monthsLeftInYear):
day = datetime(today.year, today.month, dayOfMonth) + relativedelta(months=i)
while day.weekday() == SATURDAY or day.weekday() == SUNDAY or day in holidays:
day -= relativedelta(days=1)
yield day
|
# You are given an integer array nums. You are initially positioned at the array's first index,
# and each element in the array represents your maximum jump length at that position.
# Return true if you can reach the last index, or false otherwise.
# Input: nums = [2,3,1,1,4]
# Output: true
#Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
#Aproach:
# 1. This problem can be solved in various ways. one takes O(n^n) time which is awful and I won't do.
# 2. Another one is done by dynamic programming. which involves in taking the possible paths you can to get to the goal
# and based on the indexes that have already been visited check if you can or can't get to the goal
# this approach takes O(n^2) time
# 3. The best approach takes O(n) time and it doesn't involve dynamic programming.
# In this approach we check whether we can get to the goal from the number at the index we are or not.
# if we can get to the goal from that number, then we update that index as the new goal.
# else we keep going checking the indexes to see if we can get to the goal.
# if after the loop has finished, the goal is not 0, then it is not possible to reach the las index
# else, it is possible and we return True
nums = [2,3,1,1,4]
# Greedy solution O(n) time, O(1) space
def jumpGame1(nums):
goal = len(nums)-1
for i in reversed(range(len(nums)-1)):
if nums[i] + i >= goal:
goal = i
if goal == 0:
return True
else:
return False
print(f"Greedy solution: array --> {nums}, result: {jumpGame1(nums)}")
|
#Enter the string,and it wll be changed by autocorrect if required
from textblob import TextBlob
text = raw_input("Enter the string:")
print "After AutoCorrect:",TextBlob(text).correct()
|
"""
Code for representing each block
"""
class Block:
color = ""
size = "small"
xloc = 0
yloc = 0
def getColor(self):
return self.color
def getSize(self):
return self.size
def getLocation(self):
return self.xloc, self.yloc
def setColor(self, newColor):
self.color = newColor
def setSize(self, newSize):
self.size = newSize
def setLocation(self, newx, newy):
self.xloc = newx
self.yloc = newy
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.