text stringlengths 37 1.41M |
|---|
## def binary(s,e):
## last = s[-1]
## first = s[0]
## if len(s) == 2 and (s[0] == e or s[1] == e):
## return True
## else:
## mid = int(first+last+1)/2
## if e<= mid:
## last = mid
## else:
## first = mid
def selection_sort(l):
for i in range(0,len(l)):
min_value = l[i]
min_index = i
for j in range(i+1,len(l)):
if min_value > l[j]:
min_value = l[j]
min_index = j
temp = l[i]
l[i] = l[min_index]
l[min_index] = temp
print ('partially sorted list = ' , l)
l = [21,6,45,87,12,1,37]
selection_sort(l)
print ('Sorted list =', l)
|
# Finding if a given year is a leap year or not
##
##y = 1600
##if y%4 == 0:
## if y%100 == 0:
## if y%400 == 0:
## print ('Leap year')
## else:
## print ('Not a leap year')
## else:
## print ('Leap year')
##else:
## print ('Not a leap year')
y = 1664
if y%4 == 0 and y%100 != 0:
print ('Leap year')
elif y%4 == 0 and y%100 == 0 and y%400 == 0:
print ('Leap year')
else:
print ('Not a leap year')
|
# This program gives nth prime number.
# For example here n=1000
def prime(x):
i = 2 # loop variable - divisor
if x < 2 or isinstance (x,float):
return False
elif x==2 or x==3:
return True
else:
while i <= (x**0.5):
if x%i == 0:
return False
break
i=i+1
else:
return True
pc = 1
y = 3
while pc < 1000:
if prime(y) == True:
pc = pc + 1
y = y + 1
if pc == 1000:
print (y-1)
|
# University Grading system
A=75
B=45
if A>=55 and B>=45:
print ('Passed with good grades')
elif A>=45 and B>=65:
print ('Passed')
elif A>=65 and B<=45:
print ('Reappear for B')
else:
print ('Fail')
|
# Each new term in the Fibonaccisequence is generated by adding the previous
# two terms. By starting with 1 and 2, the first 10 terms will be:
# 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
# write a program to generate nth term of fibbonacci series using recursion.
def fib(n):
if n == 1 or n == 0 :
return 1
else:
return fib(n-1) + fib(n-2)
|
def partirLista(lista):
if isinstance(lista,list):
return PL_aux(lista,[],[])
def PL_aux(lista,sublista,resultado):
if lista==[]:
return resultado + [sublista]
elif lista[0]>=0:
return PL_aux(lista[1:],sublista+[lista[0]],resultado)
else:
return PL_aux(lista[1:],[],resultado+[sublista])
|
"""csvFilter
Filters out unneccsary rows from large csv files.
"""
import csv, itertools
import sys, os
def sortcsv(path, sortkey):
directory = os.path.dirname(path)
filename = os.path.basename(path)
outpath = os.path.join(directory, "SORTED_" + filename)
with open(path,'r') as fin, open(outpath,'w', newline='') as fout:
reader = csv.DictReader(fin, delimiter=',')
data = list(reader)
data.sort(key=sortkey)
writer = csv.DictWriter(fout, fieldnames=reader.fieldnames, delimiter=',')
writer.writeheader()
writer.writerows(data)
def main():
path = sys.argv[1]
specialCases = ["Global", "Developing", "Developed", "High-income Asia Pacific","Western Europe","Andean Latin America","Central Latin America","Southern Latin America","Tropical Latin America","North Africa and Middle East","High-income North America","Oceania","Central Sub-Saharan Africa","Eastern Sub-Saharan Africa","Central Asia","Southern Sub-Saharan Africa","Western Sub-Saharan Africa","East Asia","South Asia","Southeast Asia","Australasia","Caribbean","Central Europe","Eastern Europe","Central Europe, Eastern Europe, and Central Asia","Sub-Saharan Africa","North Africa and Middle East","South Asia","Southeast Asia, East Asia, and Oceania","Latin America and Caribbean"]
def sortkey(d):
result = d["location_name"]
if result in specialCases:
numzeroes = len(str(len(specialCases)))
result = str(specialCases.index(result)).zfill(numzeroes) + result
return result
filter = lambda row : row['age_group_id'] == "38" and row['metric'] == "obese"
sortcsv(path, sortkey)
if __name__ == '__main__':
main() |
import cv2
import numpy as np
def view_face_frame(face, frame):
"""
View face frame.
:param face: face from faces
:param frame: frame you want to view face to
"""
x, y = face.left(), face.top()
x1, y1 = face.right(), face.bottom()
cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2)
def midpoint(p1, p2):
"""
Finds midpoint of two numbers.
:param p1: first number
:param p2: second number
:return: midpoint
"""
return int((p1.x + p2.x)/2), int((p1.y + p2.y)/2)
def draw_point(number, landmarks, frame):
"""
Draws points that shows face structures in Dlib.
:param number: number of landmark
:param landmarks: landmarks from predictor_dlib(gray, face)
:param frame: frame you want to draw points in
"""
x = landmarks.part(number).x
y = landmarks.part(number).y
cv2.line(frame, (x, y), (x, y), (0, 0, 255), 2, 1)
def eye_center_dlib(eye, position_for_eye):
"""
Gets center of eye in eye frame and in frame.
:param eye: eye array in gray
:param position_for_eye: position [0, 0] of eye frame
:return: [center, center_in_frame] center is center in whole array, center_in_frame is center in eye frame
"""
height, width = eye.shape
center = [int(width/2) + position_for_eye[0], int(height/2) + position_for_eye[1]]
center_in_frame = [int(width/2), int(height/2)]
return center, center_in_frame
def landmarks_array(number1, number2, number3, number4, number5, number6, landmarks, frame, lines):
"""
Saves landmarks into array. Can print lines in eye if lines = 1.
:param number1 - number6: number of landmarks from landmark map
:param landmarks: output from function predictor_dlib
:param frame: image in gray
:param lines: lines = 0 -> dont draw lines, lines = 1 -> draw lines
:return: array of landmarks number1 - number6 in int32
"""
l_array = np.array([(landmarks.part(number1).x, landmarks.part(number1).y),
(landmarks.part(number2).x, landmarks.part(number2).y),
(landmarks.part(number3).x, landmarks.part(number3).y),
(landmarks.part(number4).x, landmarks.part(number4).y),
(landmarks.part(number5).x, landmarks.part(number5).y),
(landmarks.part(number6).x, landmarks.part(number6).y)], np.int32)
if lines == 1: # draw horizontal and vertical lines
cv2.line(frame, (landmarks.part(number1).x, landmarks.part(number1).y),
(landmarks.part(number4).x, landmarks.part(number4).y),
(0, 255, 0), 1) # horizontal line
cv2.line(frame, midpoint(landmarks.part(number2), landmarks.part(number3)),
midpoint(landmarks.part(number6), landmarks.part(number5)), (0, 255, 0), 1) # vertical line
return l_array
def fill_frame(img, left_array, right_array):
"""
Get eye from image
:param img: image in gray
:param left_array: array of left eye landmarks
:param right_array: array of right eye landmarks
:return: image in gray
"""
height, width = img.shape
mask = np.zeros((height, width), np.uint8)
cv2.polylines(mask, [left_array], True, 255, 2)
cv2.polylines(mask, [right_array], True, 255, 2)
cv2.fillPoly(mask, [left_array], 255)
cv2.fillPoly(mask, [right_array], 255)
# eye_filling = cv2.bitwise_and(img, img, mask, mask)
return img
def crop_eyes(eye_fill, eye_array):
"""
Crop eye region from frame
:param eye_fill: img in gray
:param eye_array: array of eye landmarks
:return: croped eye in gray, corner of image (coordinate of eye crop in frame)
"""
min_x = np.min(eye_array[:, 0])
max_x = np.max(eye_array[:, 0])
min_y = np.min(eye_array[:, 1])
max_y = np.max(eye_array[:, 1])
eye_crop = eye_fill[min_y:max_y, min_x: max_x]
corner = [min_x, min_y]
return eye_crop, corner
|
r=5
h=10
Vwtr=15
t=eval(input('enter the time'))
Vc=3.14*r**2*h
Vwtr= 15*t
if Vwtr > Vc:
print('overflow')
elif Vwtr==Vc:
print('tank is full')
else:
print('underflow')
|
#03 - Utilizando estruturas de repetição com teste lógico, faça um programa que peça uma senha para iniciar seu processamento, só deixe o usuário continuar se a senha estiver correta, após entrar dê boas vindas a seu usuário e apresente a ele o jogo da advinhação, onde o computador vai “pensar” em um número entre 0 e 10. O jogador vai tentar adivinhar qual número foi escolhido até acertar, a cada palpite do usuário diga a ele se o número escolhido pelo computador é maior ou menor ao que ele palpitou, no final mostre quantos palpites foram necessários para vencer.
from random import randrange, vonmisesvariate
print('-='*30)
user = str(input("Digite a Senha: "))
senha = 'blue'
while user != senha:
print('-='*30)
print('Dica de senha: Melhor escola de tecnologia')
print('-='*30)
user = str(input("Digite a senha novamente: "))
print(' Bem vindo(a)\n Vamos brincar!')
print('-='*30)
print('''
Esse é o jogo da adivinhação.
O computador vai pensar um numero
e vc tem que adivinhar qual foi!
''')
print('-='*30)
print(("Qual o numero que o computador pensou?: "))
numSort = randrange(12)
n = -1
c = 0
t = 1
while n != numSort:
n = int(input(f"{t}ª tentativa: "))
if n > numSort:
print('O computador pensou em numero MENOR!')
elif n == numSort:
print('-='*30)
print(' '*8,'=Acertou!=')
else:
print('O computador pensou em numero MAIOR')
c += 1
t += 1
print(f'''
O computador pensou em {numSort}
Parabens acertou com {c} tentativas
''')
print('-='*30) |
vowels1 = ['a', 'e', 'i', 'o', 'u']
print(vowels1) # ['a', 'e', 'i', 'o', 'u']
print(type(vowels1)) # class list
vowels2 = ('a', 'e', 'i', 'o', 'u')
print(vowels2) # ('a', 'e', 'i', 'o', 'u')
print(type(vowels2)) # class tuple
# vowels2[2] = 'I' # tuple is immutable type, we can't change tuple
user = ("User", 23) # для створення кортежу використовуються круглі дужки, в які поміщаються його значення, розділені комами
user1 = "User1", 23 # також для визначення кортежу ми можемо просто перерахувати значення через кому без застосування дужок
user2 = ("User2",) # якщо раптом кортеж складається з одного елемента, то після нього необхідно поставити кому
users = ("Tom", "Bob", "Sam", "Kate")
users_tuple = tuple(users) # для створення кортежу зі списку можна передати список в функцію tuple(), яка поверне кортеж
print(users[0]) # звернення до елементів кортежу відбувається по індексу
print(users[1:4]) # ("Bob", "Sam", "Kate")
# users[1] = "Tim" # але так як кортеж - незмінний тип (immutable), то ми не зможемо змінити його елементи
# при необхідності ми можемо розкласти кортеж на окремі змінні:
user3 = ("User3", 22, False)
name, age, isMarried = user3
print(name) # Tom
print(age) # 22
print(isMarried) # False
# особливо зручно використовувати кортежі, коли необхідно повернути з функції відразу кілька значень. Коли функція повертає кілька значень, фактично вона повертає в кортеж:
def get_user():
name = "User5"
age = 26
is_married = False
return name, age, is_married
user5 = get_user()
print(type(user5)) # <class 'tuple'>
print(user5[0]) # Tom
print(user5[1]) # 22
print(user5[2]) # False
# ==============
len(users) # за допомогою вбудованої функції len() можна отримати довжину кортежу
for item in user5: # ітерація по кортежу, так само, як в list, set and dict
print(item)
# ===================Складні кортежі. Один кортеж може містити інші кортежі у вигляді елементів. наприклад:
countries = (
("Germany", 80.2, (("Berlin", 3.326), ("Hamburg", 1.718))),
("France", 66, (("Paris", 2.2), ("Marsel", 1.6)))
)
for country in countries:
countryName, countryPopulation, cities = country
print("\nCountry: {} population: {}".format(countryName, countryPopulation))
for city in cities:
cityName, cityPopulation = city
print("City: {} population: {}".format(cityName, cityPopulation)) |
for number in range(5):
print(number)
#####################################
b = list(range(1, 10, 2))
print(b) # [1, 3, 5, 7, 9]
for number in [0, 1, 2, 3, 4]:
print(number)
#####################################
my_list = [1, 2, 3, 4, 5]
for i in my_list:
if i == 6:
print("Item found!")
break
print(i)
else:
print("Item not found!")
#####################################
i = 90
while i < 100:
print(i)
i = i + 1
#####################################
i = 0
while i < 10:
if i == 3:
i += 1
continue
print(i)
if i == 5:
break
i += 1
|
def outer():
def inner():
print('This is inner.')
print('This is outer, invoking inner.')
# Функцію inner можно викликати лише з тіла функції outer, тому що inner знаходиться в області видимості outer
inner()
outer()
|
def ordered_sequential_search(alist, item):
pos = 0
found = False
stop = False
while pos < len(alist) and not found and not stop:
if alist[pos] == item:
found = True
else:
# check if item searched is greater than item at a particiular index
# stop if true means item searched for is not in the list
if alist[pos] > item:
stop = True
else:
pos = pos+1
return found
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(ordered_sequential_search(testlist, 3))
print(ordered_sequential_search(testlist, 13))
|
def binary_search(input_array, value):
first = 0
last = len(input_array) - 1
while first <= last:
mid = (first + last)//2
if input_array[mid] == value:
return input_array.index(value)
elif input_array[mid] < value:
first = mid + 1
elif input_array[mid] > value:
last = mid - 1
return -1
test_list = [1,3,9,11,15,19,29]
test_val1 = 25
test_val2 = 15
print (binary_search(test_list, test_val1))
print (binary_search(test_list, test_val2))
|
from tkinter import *
from tkinter import ttk, messagebox
import csv
from datetime import datetime
##########
import sqlite3
# create data base
conn = sqlite3.connect('Expense.db')
# create operater
c = conn.cursor()
# create table
'''
'Details(details)'
'Rate(rate)'
'Quantity(quantity)'
'Discount(discount)'
'Total(amount)'
'Timestamp(now)'
'Transaction ID(transactionID)'
'''
c.execute("""CREATE TABLE IF NOT EXISTS ExpenseList(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
details TEXT,
rate REAL,
quantity REAL,
discount REAL,
amount REAL,
now TEXT,
transactionID TEXT
)""")
def insert_expense(details, rate, quantity, discount, amount, now, transactionID):
ID = None
with conn:
c.execute("""INSERT INTO expenseList VALUES (?,?,?,?,?,?,?,?)""",
(ID, details, rate, quantity, discount, amount, now, transactionID))
conn.commit() # record data to database
#print("Insert succeed")
def show_expense():
with conn:
c.execute("SELECT * FROM expenseList")
expense = c.fetchall()
#print(expense)
return expense
def update_expense(details, rate, quantity, discount, amount, transactionID):
with conn:
c.execute("""UPDATE expenseList SET details = ?, rate = ?, quantity = ?, discount = ?, amount = ? WHERE transactionID=(?)""",
([details, rate, quantity, discount, amount, transactionID]))
conn.commit()
#print("Data updated")
def delete_expense():
with conn:
c.execute("DELETE FROM expenseList WHERE transactionID = ?", ([transactionID]))
conn.commit()
#print("Data deleted")
#update_expense()
#delete_expense('202106122035757646')
show_expense()
##########
GUI = Tk()
GUI.title('Expense Record')
#GUI.geometry('1200x650+0+30')
#GUI.geometry('650x750+1000+100')
w = 1200
h = 650
ws = GUI.winfo_screenwidth() #screen width
hs = GUI.winfo_screenheight() #screen height
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
GUI.geometry(f'{w}x{h}+{x:.0f}+{y:.0f}')
############MENU##############
menubar = Menu(GUI)
GUI.config(menu=menubar)
file_menu = Menu(menubar, tearoff=0)
menubar.add_cascade(label='file', menu=file_menu)
file_menu.add_command(label='Import CSV')
file_menu.add_command(label='Export to Google Sheets')
help_menu = Menu(menubar, tearoff=0)
menubar.add_cascade(label='help', menu=help_menu)
help_menu.add_command(label='About')
##############################
Tab = ttk.Notebook(GUI)
T1 = Frame(Tab)
T2 = Frame(Tab)
Tab.pack(fill=BOTH, expand=1)
icon_T1 = PhotoImage(file='Images/Add-icon.png')
icon_T2 = PhotoImage(file='Images/Wallet-icon.png')
Tab.add(T1, text=f'{"Add Expense":^{15}}',image=icon_T1,compound='top')
Tab.add(T2, text=f'{"Expense List":^{15}}',image=icon_T2,compound='top')
#################################Tab 1#################################
F1 = Frame(T1)
#F1.place(x=100,y=50)
F1.pack()
days = {"Mon":"จันทร์",
"Tue":"อังคาร",
"Wed":"พุธ",
"Thu":"พฤหัส",
"Fri":"ศุกร์",
"Sat":"เสาว์",
"Sun":"อาทิตย์"}
def Save(event=None):
details = v_details.get()
rate = v_rate.get()
quantity = v_quantity.get()
discount = v_discount.get()
if details == "":
#print("No data")
messagebox.showerror("ERROR","Please enter details!")
return
if rate == "":
messagebox.showerror("ERROR","You typed wrong, please enter rate again!")
return
if quantity == "":
quantity = 1
if discount == "":
discount = 0
try:
amount = float(rate)*float(quantity)-float(discount)
now = datetime.now().strftime('%b %d, %Y %H:%M:%S')
stamp = datetime.now()
transactionID = stamp.strftime('%Y%m%d%H%M%f')
compound_rt_text = ' Details: {}\n Rate: {} ฿\n Quantity: {}\n Discount: {} ฿\n__________\n Amount: {} ฿\nTimestamp: {}\n'.format(details,str(rate),str(quantity),str(discount),str(amount),now)
compound_lt_text = 'Details: {}\nRate: {} ฿\nQuantity {}\nDiscount {} ฿\n__________\nAmount: {} ฿\nTimestamp: {}\n'.format(details,str(rate),str(quantity),str(discount),str(amount),now)
print(compound_rt_text)
v_result.set(compound_lt_text)
v_details.set('')
v_rate.set('')
v_quantity.set('')
v_discount.set('')
insert_expense(details,rate,quantity,discount,amount,now,transactionID)
with open('Expense.csv','a',encoding='utf-8',newline='') as f:
fw = csv.writer(f)
data = [details,float(rate),float(quantity),float(discount),amount,now,transactionID]
fw.writerow(data)
E1.focus()
update_table()
except Exception as e:
print("ERROR", e)
messagebox.showerror("ERROR","Please enter again.")
#messagebox.showwarning("ERROR","Please enter again.")
#messagebox.showinfo("ERROR","Please enter again.")
v_details.set('')
v_rate.set('')
v_quantity.set('')
v_discount.set('')
E1.focus()
GUI.bind('<Return>',Save)
FONT1 = (None,15)
center_img = PhotoImage(file='Images/list-icon.png')
logo = ttk.Label(F1,image=center_img)
logo.pack()
# ---Text 1---
L = ttk.Label(F1,text='Details',font=FONT1).pack()
v_details = StringVar()
E1 = ttk.Entry(F1,textvariable=v_details,font=FONT1)
E1.pack()
# ------------
# ---Text 2---
L = ttk.Label(F1,text='Rate',font=FONT1).pack()
v_rate = StringVar()
E2 = ttk.Entry(F1,textvariable=v_rate,font=FONT1)
E2.pack()
# ------------
# ---Text 3---
L = ttk.Label(F1,text='Quantity',font=FONT1).pack()
v_quantity = StringVar()
E3 = ttk.Entry(F1,textvariable=v_quantity,font=FONT1)
E3.pack()
# ------------
# ---Text 4---
L = ttk.Label(F1,text='Discount',font=FONT1).pack()
v_discount = StringVar()
E4 = ttk.Entry(F1,textvariable=v_discount,font=FONT1)
E4.pack()
# ------------
submit_icon = PhotoImage(file='Images/save-icon.png')
B1 = ttk.Button(F1,text=f'{"Submit": >{5}}',command=Save,image=submit_icon,compound='left')
B1.pack(padx=0,pady=30)
v_result = StringVar()
#v_result.set("-----------------------------------")
result = ttk.Label(F1, textvariable=v_result,font=FONT1,foreground="green")
result.pack(pady=20)
###########################Tab 2###############################
rs = []
def read_csv():
with open('Expense.csv', newline='', encoding='utf-8') as f:
fr = csv.reader(f) #fr = file reader
data = list(fr)
return data
#print(list(fr))
# print(data)
# print('-----------')
# print(data[0][0])
# for d in data:
# print(d[0])
# for a,b,c,d,e,f in data:
# print(c)
#rs = read_csv()
#print(rs)
# read_csv()
# print(rs)
L = ttk.Label(T2,text='Responses',font=FONT1).pack(pady=20)
header = ['Details','Rate','Quantity','Discount','Total','Timestamp','Transaction ID']
result_table = ttk.Treeview(T2, columns=header, show='headings',height=10)
result_table.pack()
# for i in range(len(header)):
# result_table.heading(header[i], text=header[i])
for h in header:
result_table.heading(h,text=h)
headerwidth = [150,90,170,170,110,190,150]
for h,w in zip(header, headerwidth):
result_table.column(h, width=w)
alltransaction = {}
def UpdateCSV():
with open('Expense.csv', 'w', newline='', encoding='utf-8') as f:
fw = csv.writer(f)
# change alltransaction to list
data = list(alltransaction.values())
fw.writerows(data) # multiple line from nested list [[],[],[]]
print("Table was updated")
update_table()
def UpdateSQL():
data = list(alltransaction.values())
#print(data[0])
for d in data:
update_expense(d[0], d[1], d[2], d[3], d[4], d[-1])
def DeleteRecord(event=None):
check = messagebox.askyesno('Conferm Delete?', 'Do you want to delete?')
print('Yes/No:',check)
if check == True:
print('Delete')
select = result_table.selection()
#print(select)
data = result_table.item(select)
data = data['values']
transactionID = data[-1]
#print(transactionID)
#print(type(transactionID))
del alltransaction[str(transactionID)]
#print(alltransaction)
#UpdateCSV()
delete_expense(str(transactionID))
update_table()
else:
print("Cancel")
BDelete = ttk.Button(T2,text='Delete',command=DeleteRecord)
BDelete.place(x=50,y=550)
result_table.bind('<Delete>', DeleteRecord)
def update_table():
result_table.delete(*result_table.get_children())
# for c in result_table.get_children():
# result_table.delete(c)
try:
data = show_expense() #read_csv()
for d in data:
# create transaction data
alltransaction[d[-1]] = d[1:]
result_table.insert('', 0, value=d[1:])
print(alltransaction)
except:
print("No file")
################Right click##################
def EditRecord():
POPUP = Toplevel()
POPUP.title('Edit Record')
#POPUP.geometry('500x500')
w = 500
h = 500
ws = POPUP.winfo_screenwidth() #screen width
hs = POPUP.winfo_screenheight() #screen height
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
POPUP.geometry(f'{w}x{h}+{x:.0f}+{y:.0f}')
# ---Text 1---
L = ttk.Label(POPUP,text='Details',font=FONT1).pack()
v_details = StringVar()
E1 = ttk.Entry(POPUP,textvariable=v_details,font=FONT1)
E1.pack()
# ------------
# ---Text 2---
L = ttk.Label(POPUP,text='Rate',font=FONT1).pack()
v_rate = StringVar()
E2 = ttk.Entry(POPUP,textvariable=v_rate,font=FONT1)
E2.pack()
# ------------
# ---Text 3---
L = ttk.Label(POPUP,text='Quantity',font=FONT1).pack()
v_quantity = StringVar()
E3 = ttk.Entry(POPUP,textvariable=v_quantity,font=FONT1)
E3.pack()
# ------------
# ---Text 4---
L = ttk.Label(POPUP,text='Discount',font=FONT1).pack()
v_discount = StringVar()
E4 = ttk.Entry(POPUP,textvariable=v_discount,font=FONT1)
E4.pack()
# ------------
def Edit(event=None):
print(transactionID)
print(alltransaction)
olddata = alltransaction[str(transactionID)]
print('OLD:', olddata)
v1 = v_details.get()
v2 = float(v_rate.get())
v3 = float(v_quantity.get())
v4 = float(v_discount.get())
amount = v2 * v3 - v4
newdata = [v1, v2, v3, v4, amount, olddata[-2], olddata[-1]]
alltransaction[str(transactionID)] = newdata
#UpdateCSV()
UpdateSQL()
update_table()
POPUP.destroy()
submit_icon = PhotoImage(file='Images/save-icon.png')
B1 = ttk.Button(POPUP,text=f'{"Submit": >{5}}',command=Edit,image=submit_icon,compound='left')
B1.pack(padx=0,pady=30)
POPUP.bind('<Return>', Edit)
# get data in selected record
select = result_table.selection()
print(select)
data = result_table.item(select)
data = data['values']
print(data)
transactionID = data[-1]
v_details.set(data[0])
v_rate.set(data[1])
v_quantity.set(data[2])
v_discount.set(data[3])
POPUP.mainloop()
rightclick = Menu(GUI, tearoff=0)
rightclick.add_command(label='Edit', command=EditRecord)
rightclick.add_command(label='Delete', command=DeleteRecord)
def menupopup(event):
#print(event.x_root, event.y_root)
rightclick.post(event.x_root, event.y_root)
GUI.bind('<Button-3>', menupopup)
update_table()
GUI.mainloop()
|
def findGCD(n1, n2):
while(n2 != 0):
if n1 > n2:
n1 , n2 = n2, n1 % n2
else:
n1, n2 = n1, n2 % n1
return n1
def modInverse(a, m):
m0 = m
y = 0
x = 1
# For (n mod 1) for any n will always be equal to zero
if (m == 1):
return 0
while (a > 1):
# q is quotient
q = a // m
t = m
# m is remainder now, process
# same as Euclid's algo
m = a % m
a = t
t = y
# Update x and y
y = x - q * y
x = t
# Make x positive
if (x < 0):
x = x + m0
return x
def encrypt(alpha, beta, plaintext):
cipher = ''
if findGCD(alpha, 26) != 1:
return "Invalid alpha"
if not(beta >= 0 and beta <= 25):
return "invalid beta"
for alphabet in plaintext:
cipher += chr((((alphabets[alphabet.upper()]* alpha) + beta) % 26) + 65)
return cipher
def decrypt(alpha, beta, cipher):
plain = ""
for alphabet in cipher:
plain += chr((((alphabets[alphabet.upper()] - beta) * modInverse(alpha, 26)) % 26) + 65)
return plain
if "__main__" == __name__:
alphabets = {}
for each in range(65, 91):
alphabets[chr(each)] = each - 65
e = encrypt(5,5,"MYNAMEISDAUD")
print(e)
d = decrypt(5, 5, e)
print(d) |
"""
dictionary comprehension
"""
numbers = [1,2,3,4,5]
names = ['a','b','c','d','e']
students = {}
for i in range(len(names)):
students[numbers[i]] = names[i]
print(students)
students2 ={numbers[i]:names[i] for i in range(len(names))}
print(students2)
# num_name = zip(numbers, names)
# print(num_name)
for x in zip(numbers, names):
print(x)
students3 = {}
for key, value in zip(numbers, names):
students3[key] = value
print(students3)
students4 = {k:v for k, v in zip(numbers, names)}
print(students4)
students5 = {k:v for k, v in zip(numbers, names) if k % 2 == 0}
print(students5) |
"""
scikit-learn 패키지를 이용한 knn(k Nearest Neighbor : 최근접이웃)
"""
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, classification_report
import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
# 1. 데이터 준비
# 1) csv파일에 헤더가 없기 때문에 컬럼 이름 정의
col_name = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class']
# 2) csv파일에서 DataFarme 생성
dataset = pd.read_csv('iris.csv', header=None, names=col_name)
# print(dataset.shape)
# print(dataset.head())
# print(dataset.info())
# print(dataset.describe())
# print(dataset.loc[0:5])
# print(dataset.iloc[0:5])
# 2. 데이터 전처리
# - 데이터 세트를 데이터(포인트)와 레이블로 구분
X = dataset.iloc[:, :-1].to_numpy()
# print(X)
y = dataset.iloc[:, 4].to_numpy()
# print(y)
# - 데이터를 training set, test set으로 나누기
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # 150 * 0.2 = 30(test_seize)
# print(len(x_train), len(x_test), len(y_train), len(y_test))
# print(x_train[:3])
# print(y_train[:3])
# 3. 거리 계산을 위해서 각 특성들을 스케일링(표준화)
# -> Z-score 표준화 : 평균0, 표준편차1로 변환
scaler = StandardScaler() # Scaler객체 생성
scaler.fit(x_train) # 스케일링(표준화)를 위한 평균과 표준편차 계산
x_train = scaler.transform(x_train) # 스케일링(표준화) 수행
x_test = scaler.transform(x_test)
for col in range(4):
print(f'train평균 : {x_train[:, col].mean()}, train표준편차 : {x_train[:, col].std()}')
print(f'test평균 : {x_test[:, col].mean()}, test표준편차 : {x_test[:, col].std()}')
print()
# 4. 학습과 예측(training / prediction)
# 분류기 생성
classifier = KNeighborsClassifier(n_neighbors=5) # 거리를 계산할 때 최단거리 5개를 뽑겠다는 의미(홀수가 좋음)
# 분류기 학습
classifier.fit(x_train, y_train)
# 예측
y_pred = classifier.predict(x_test)
print(y_pred)
# 5. 모델평가
conf_matrix = confusion_matrix(y_test, y_pred)
print(conf_matrix)
report = classification_report(y_test, y_pred)
print(report)
# 6. 모델 개선(향상) - k값을 변화시킬 때 에러가 얼마나 줄어드는가가
errors = []
for i in range(1,31):
knn = KNeighborsClassifier(n_neighbors=i)
knn.fit(x_train, y_train)
pred_i = knn.predict(x_test)
errors.append(np.mean(pred_i != y_test))
print(errors)
plt.plot(range(1,31), errors, marker='o')
plt.title('Mean Error with K-value')
plt.xlabel('k-value')
plt.ylabel('mean error')
plt.show()
|
for i in range(5):
print(i, end = ' ')
print()
for i in range(1,5):
print(i, end=' ')
print()
for i in range(1,5,2):
print(i, end=' ')
print()
for s in 'Hello, Python!':
print(s, end=' ')
print()
lang = ['pl/sql', 'r', 'python', 'java']
for l in lang:
print(l, end=' ')
print()
for i in range(len(lang)):
print(i, lang[i])
print()
alpha = {1:'a', 2:'b', 3:'c'}
print(alpha.keys())
for key in alpha.keys():
print(key, alpha[key])
print()
for key in alpha:
print(key)
for item in alpha.items():
print(item)
for key, value in alpha.items():
print(key, value)
|
# ---BIRTHYEAR EXTRACTION---
# Extracts the birthyear from the birthdate and copies it into the birthyear column
# if the latter is empty or has a different birthyear
# In CSV: birthDate is position 4, birthYear is position 5
with open('creator_data.csv', encoding = 'utf-8') as creator_input:
with open('creator_data_cleaned.csv', 'w', encoding = 'utf-8') as creator_output:
creator_output.write(creator_input.readline()) # Copy the headers to the new CSV file
for line in creator_input:
a_creator = str(line).split(',') # Transform each line into a list
birthyear_fromdate = a_creator[4].split('-')[0].strip() # Split the birthdate into a list and use the year
if ((birthyear_fromdate != 'NA') and (birthyear_fromdate != a_creator[5])): # If found birthyear is empty or different
a_creator[5] = ' ' + birthyear_fromdate # Assign the birthyear column the new birthyear
creator_output.write(','.join(a_creator)) # Write the whole list into one line of the new CSV
|
'''
Example to send file object through queue and consumer will process the file object received i.e basically a json file
'''
import json
import concurrent.futures
import logging
import queue
import random
import threading
import time
#Sample data of data2.json
'''
data = {}
data['people'] = []
data['people'].append({
'name': 'Scott',
'website': 'stackabuse.com',
'from': 'Nebraska'
})
data['people'].append({
'name': 'Larry',
'website': 'google.com',
'from': 'Michigan'
})
data['people'].append({
'name': 'Tim',
'website': 'apple.com',
'from': 'Alabama'
})
with open('data2.json', 'w') as outfile:
json.dump(data, outfile)
'''
def dataParser(need_parse):
new_data = {}
print("parsing data")
new_data[u'name'] = need_parse[u'name']
new_data[u'from'] = need_parse[u'from']
data_conv = json.dumps(new_data)
return data_conv
def producer(queue, event):
"""Pretend we're getting a number from the network."""
while not event.is_set():
f = open ('data2.json', "r")
data = json.loads(f.read())
#print(data)
message = json.dumps(data).encode("utf8")
my_tmp_file = tempfile.NamedTemporaryFile()
my_tmp_file.write(message)
my_tmp_file.seek(0)
logging.info("Producer got message:")# %s", message)
queue.put(my_tmp_file.read())
my_tmp_file.close()
# queue.put(filename)#queue.put(message)
logging.info("Producer received event. Exiting")
def consumer1(queue1, event):
"""Pretend we're saving a number in the database."""
while not event.is_set() or not queue1.empty():
message = queue1.get()
print("\ncon1: here0")
logging.info("Consumer1 storing message: %s (size=%d)", message, queue1.qsize())
print("\ncon1: here1")
with open(message, encoding='utf-8') as data_file:
data = json.loads(data_file.read())
data_json = json.dumps(message)
print("\ncon1: here2")
print(data_json)
pasredata = DataParser(data_json)
print(parsedata)
print("\ncon1: here3")
#message2 = random.randint(1, 101)
#logging.info("Consumer1 sending message:%s", message2)
#queue2.put(message2)
#print("\ncon1: here4")
logging.info("Consumer1 received event. Exiting")
def consumer2(queue, event):
"""Pretend we're saving a number in the database."""
print("\ncon2:here0")
while not event.is_set() or not queue.empty():
message = queue.get()
print("\ncon2: here1")
logging.info(
"Consumer 2 storing message: %s (size=%d)", message, queue.qsize()
)
logging.info("Consumer 2 received event. Exiting")
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
pipeline1 = queue.Queue(maxsize=10)
#pipeline2 = queue.Queue(maxsize=5)
event = threading.Event()
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
executor.submit(producer, pipeline1, event)
executor.submit(consumer1, pipeline1, event)
#executor.submit(consumer2, pipeline2, event)
time.sleep(0.1)
logging.info("Main: about to set event")
event.set()
|
# For Lists/Looping
# iterating through two lists
# m1
from collections import defaultdict, ChainMap
list_a = ['a', 'b', 'c']
list_b = [1, 2, 3, 4]
for i in range(min(len(list_a), len(list_b))):
print(list_a[i], list_b[i])
# better way of doing this is using zip.
for a, b in zip(list_a, list_b):
print(a, b)
# Both give the same output.
# Iterating until a sentinal value
class Iterable:
def __init__(self):
self.i = 0
def __call__(self, *args, **kwargs):
self.i += 1
return self.i
iter_obj = Iterable()
for el in iter(iter_obj, 3):
print(el)
"""
we get the following output
1
2
"""
# So, the basic idea behind the iter method is that it takes a callable and
# it calls that callable until some sentinal value.
# It is basically a short-hand for the object based implementation where we
# have to implement __iter__ (mostly returns self) and __next__ methods.
# for else looping
def for_else():
for el in [1, 2, 3]:
if el == 4:
print("got 4")
else:
print("unable to get 4")
for_else()
# prints 'unable to get 4'
# DICTIONARIES
# creating dictionaries using zip
my_dict = dict(zip(['a', 'b', 'c'], [1, 2, 3]))
print(my_dict)
# {'a': 1, 'b': 2, 'c': 3}
# usage of default dict and set default
# counting occurances of words
words = ['shailesh', 'sam', 'aman', 'rajesh']
counts_dict = {}
for word in words:
counts_dict.setdefault(word[0], 0)
counts_dict[word[0]] += 1
# other way
print(counts_dict)
counts_dict = {}
for word in words:
counts_dict[word[0]] = counts_dict.get(word[0], 0) + 1
print(counts_dict)
# yet another way
counts_dict = {}
counts_dict = defaultdict(int)
for word in words:
counts_dict[word[0]] = counts_dict[word[0]] + 1
print(counts_dict)
# using chainmap
d = {'a': 1, 'b': 2}
d1 = {'a': 11, 'b': 22}
d2 = {'a': 33, 'c': 44}
print("chain map is")
print(ChainMap(d, d1, d2))
# List comprehension and generator expressions.
a = (el for el in range(4)) # creates a generator
print(a)
# Output: <generator object <genexpr> at 0x100b449d0>
# python popitem
|
"""A python program that implements dutch national flag algorithm i.e sorts the arrays of 0s, 1s and 2s in single pass and
using constant space.
The algorithm which I am going to implement works as follows -
1. It makes use of three pointers namely 0's pointer, 1's pointer and Traversing pointer which traverses through the array.
2. So, Whenever we encounter 0 we add it to the start of the array.
3. Whenever we encounter a one we swap it with the element next to it and move forward the 1's pointer.
I guess this is it. And it's making use of two pointers only. Somewhat similar to pivotization in randomized quick sort algorithm."""
"""This algorithm makes use of the pivot concept in the quick sort algorithm.
Make one as a pivot.
Additional use of left pointer to group all ones.
"""
from collections import Counter
array = [2, 0, 2, 1, 1, 0]
# def sort_array(arr):
# one_ptr = 0
# # here idx behaves as the traversor.
# for idx,el in enumerate(arr):
# if el == 0:
# del arr[idx]
# arr.insert(0, el)
# if idx != 0 and one_ptr != 0:
# one_ptr += 1
# if el == 1:
# # swap with forward element and move the traversor and move the one's pointer
# print("swapping", one_ptr, idx, arr[one_ptr], arr[idx])
# arr[one_ptr], arr[idx] = arr[idx], arr[one_ptr]
# one_ptr += 1
# if el == 2:
# # do nothing just move forward
# continue
# print("current state of the array", arr)
# print("current one pointer", one_ptr)
# return arr
#
#
# print("result of sorting is ", sort_array(array))
# def sort_array_v2(array):
# ones_start = 0
# ones_end = 0
# ctr = 0
# while ctr < len(array):
# if array[ctr] ==
def pivotize(array):
pivot_ctr = 0
pivot = array[pivot_ctr]
traverser = 1
left_ctr = None
while traverser < len(array):
print("traverser", traverser)
if array[traverser] > pivot:
traverser += 1
elif array[traverser] < pivot:
print(len(array), traverser, pivot_ctr)
print("shifting", array[pivot_ctr + 1], array[traverser], "array at this point",array)
array[pivot_ctr + 1], array[traverser] = array[traverser], array[pivot_ctr + 1]
print("array after shifting", array)
print("=="*5,left_ctr)
if left_ctr is not None:
# print("=="*10)
array[left_ctr], array[pivot_ctr + 1] = array[pivot_ctr + 1], array[left_ctr]
left_ctr += 1
else:
array[pivot_ctr], array[pivot_ctr + 1] = array[pivot_ctr + 1], array[pivot_ctr]
pivot_ctr += 1
traverser += 1
elif array[traverser] == pivot:
print("equal case")
print("array before equal case", array)
array[pivot_ctr + 1], array[traverser] = array[traverser], array[pivot_ctr + 1]
print("array after", array,"pivot ctr and it's value", pivot_ctr, array[pivot_ctr])
if left_ctr is None:
left_ctr = pivot_ctr
pivot_ctr += 1
traverser += 1
print("result of pivotize is", array)
#arr = [1, 6, 5, 11, 11, 4, 1, 23, 7, 9, 6, 3, 4, 8, 10, 5, 0, 4, 11]
#arr = [1,1,0,0,0,0,2,2,2,2,2,1,0,1,1,1,2]
arr = [2,0,2,1,1,0]
print(pivotize(arr[:]))
print("count vals",Counter(arr))
|
current_level = [[A]
next_level = deque()
paths = []
while current_level:
node = current_level.pop()
if node == p or node == q:
ans.apend(current_level)
next_level.extend([node.left, node.right])
if not current_level:
if next_level:
current_level = next_level
for a,b in zip(reversed(path[0]),reversed(path[1])):
if a == b:
return a
def traverse(root, path):
if root.val == p:
return path
else:
path.append(root)
traverese(root.left)
traverse(root.right)
def time(root, step):
root.intime = step
l = time(root.left, step +1)
r = time(root.right, step + 2)
root.outtime = step
def invert(root):
l = invert(root.left)
r = invert(root.right)
root.left = r
root.right = l
return root
def ll(root, ll_root):
if root is None:
return
ll_root.next = root
ll(root.left, ll_root.next)
ll(root.right, ll_root.next)
|
class Node(object):
def __init__(self,val):
self.val = val
self.leader = None
self.finish = None
self.visited = False
def __str__(self):
return str(self.val)+","+str(self.finish)
class Edge(object):
def __init__(self,start,end):
self.start = start
self.end = end
def __str__(self):
return "from : "+str(self.start)+"to :"+ str(self.end)
class Graph(object):
def __init__(self):
self.edges = {}
def addNode(self,node):
self.edges[node] = []
def addEdge(self,edge):
start = edge.start
end = edge.end
self.edges[start]=self.edges[start]+[end]
def get_children(self,node):
return self.edges[node]
g = Graph()
nodes_list = [Node(i) for i in range(1,11)]
for node in nodes_list:
g.addNode(node)
g.addEdge(Edge(nodes_list[0],nodes_list[1]))
g.addEdge(Edge(nodes_list[1],nodes_list[2]))
g.addEdge(Edge(nodes_list[2],nodes_list[0]))
g.addEdge(Edge(nodes_list[1],nodes_list[3]))
g.addEdge(Edge(nodes_list[4],nodes_list[3]))
g.addEdge(Edge(nodes_list[4],nodes_list[5]))
g.addEdge(Edge(nodes_list[5],nodes_list[6]))
g.addEdge(Edge(nodes_list[6],nodes_list[4]))
g.addEdge(Edge(nodes_list[7],nodes_list[6]))
g.addEdge(Edge(nodes_list[7],nodes_list[8]))
g.addEdge(Edge(nodes_list[8],nodes_list[9]))
g.addEdge(Edge(nodes_list[9],nodes_list[7]))
print("the graph is :")
print(g.edges)
for k in g.edges:
for v in g.edges[k]:
print(k.val,v.val)
# dfs subroutine
def dfs(g,node):
if node is not None:
if node.visited == False:
node.visited = True
if node is not None:
for child in g.get_children(node):
if child.visited == False:
dfs(g,child)
global t_current
node.finish = t_current
t_current += 1
def dfsr(g,node):
if node is not None:
if node.visited == False:
node.visited = True
for child in g.get_children(node):
if child.visited == False:
dfsr(g,child)
global s
node.leader = s
# forward dfs pass of kosaraju's algorithm computes finishing time
t_current = 1
for node in nodes_list:
if node.visited == False:
dfs(g,node)
print('after dfs traversal')
for n in list(g.edges.values()):
print([str(x) for x in n])
# backward dfs pass of kosaraju's algorithm computes leader
s = None
nodes_list_sorted = sorted(nodes_list,key=lambda x:x.finish,reverse=True)
print('before after')
print([str(n) for n in nodes_list])
print([str(n) for n in nodes_list_sorted])
s = None # to keep track of leader
# need to reverse the graph first
# pass copy of graph here
def reverse_graph(g):
rev = {}
for k in g:
for el in g[k]:
rev[el] = rev.get(el,[]) + [k]
return rev
rev = reverse_graph(g.edges.copy())
print('original graph')
for k in g.edges:
for v in g.edges[k]:
print(k.val,v.val)
print('reversed graph')
print(rev)
for k in rev:
for v in rev[k]:
print(k.val,v.val)
g_rev = Graph()
for nodes in nodes_list:
g_rev.addNode(nodes)
g_rev.edges = rev
# lets traverse
for node in nodes_list_sorted[:]:
node.visited = False
for node in nodes_list_sorted[:]:
if node.visited == False:
s = node
dfsr(g_rev,node)
# ok lets see the strongly connected components
print('sccs')
for eld in g_rev.edges.values():
print([(el.val,str(el.leader)) for el in eld])
# yay ! it worked ! |
# implementation of topological sort using a. Vertex Deletion Algo and b. DFS implementation
class Node(object):
def __init__(self, value):
self.value = value
self.visited = None
self.order = None
def __str__(self):
return str(self.value)
class Edge(object):
def __init__(self, start, end):
self.start = start
self.end = end
def __str__(self):
return "from : " + str(self.start) + "to : " + str(self.end)
class Graph(object):
def __init__(self):
self.edges = {}
def add_node(self, node):
self.edges[node] = []
def add_edge(self, edge):
start = edge.start
end = edge.end
self.edges[start] = self.edges.get(start,[]) + [end]
def get_children(self, node):
return self.edges[node]
# topological sort function
def topological_sort(g,node,order):
# let's implement it in a recursive way
if len(g.get_children(node)) == 0:
print("node",node.value,order)
del g.edges[node]
for el in g.edges:
try:
g.edges[el].remove(node)
except:
pass
else:
try:
topological_sort(g,g.get_children(node)[0],order)
except:
pass
g = Graph()
n1 = Node('a')
n2 = Node('b')
n3 = Node('c')
n4 = Node('d')
e1 = Edge(n1, n2)
e2 = Edge(n2, n3)
e3 = Edge(n1, n4)
e4 = Edge(n4, n3)
g.add_node(n1)
g.add_node(n2)
g.add_node(n3)
g.add_node(n4)
g.add_edge(e1)
g.add_edge(e2)
g.add_edge(e3)
g.add_edge(e4)
print("graph is",g.edges)
for key in g.edges:
for el in g.edges[key]:
print(key.value,el.value)
order = 4
# while len(g.edges)>0:
# topological_sort(g,n1,order)
# order -= 1
# implementation using dfs
print('dfs implementation starts here')
n_current = 4
def dfs(graph,start,path):
if start != None:
path = path + [start]
print("exploring",start.value,start.order)
for child in graph.get_children(start):
if child not in path:
dfs(graph,child,path)
global n_current
if start.order == None:
start.order = n_current
n_current -= 1
print(start.value,start.order,n_current)
dfs(g,n1,[])
for key in g.edges:
for el in g.edges[key]:
print(key.value,el.value,key.order,"key order",el.order,'el order') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Tomada de decisoes utilizando IF, ELIF e ELSE. """
"""
Ex:
if (True):
realizar esta tarefa
elif (True):
realizar esta tarefa
else:
realizar esta tarefa / ou sair
"""
print("\n ======== Perguntando ao usuário ========")
acao = (input("Digite [1] para SIM ou [2] para NÃO: "))
if acao == "1":
print("Você disse SIM!")
elif acao == "2":
print("Você disse NÃO!")
else:
print("Você disse NÃO digitou nem [1] nem [2].")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Herança - Exemplo Eletrônicos."""
# Criando classe PAI "Eletronico"
class Eletronico:
def __init__(self):
self.ligado = "Desligada"
return False
def ligar(self):
self.ligado = "Ligada"
return True
def desligar(self):
self.ligado = "Desligada"
return False
def status(self):
return self.ligado
# Criando classe FILHA "Tv"
class Tv(Eletronico):
def __init__(self):
Eletronico.__init__(self)
self.volume = 0
def __repr__(self):
return "Sua [Tv] está {} no volume [{}]".format(
self.status(), self.volume)
def aumentar_volume(self):
if self.ligado is "Desligada":
print("Sua [Tv] está desligada!")
else:
self.volume = self.volume + 1
def diminuir_volume(self):
if self.ligado is "Desligada":
print("Sua [Tv] está desligada!")
else:
if self.volume is 0:
print(f"O volume já está é '{self.volume}'")
else:
self.volume = self.volume - 1
def obter_volume(self):
return self.volume
def imprimir_status(self):
print(self.__repr__())
# criando novo objeto tipo "Eletronico"
tv1 = Tv() # ok
tv1.ligar()
# imprimindo status atual da tv
# tv1.imprimir_status()
tv1.desligar()
# tv1.diminuir_volume() # ok
# tv1.diminuir_volume() # ok
# tv1.diminuir_volume() # ok
tv1.aumentar_volume() # ok
tv1.aumentar_volume() # ok
tv1.aumentar_volume() # ok
tv1.imprimir_status()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" FOR - Percorrendo uma lista. """
names = ["Adam", "Alex", "Mariah", "Martine", "Columbus"]
for nome in names:
print(nome)
|
# Convertendo STRING para INTEIRO
numero = int("12")
# Mostra na tela o conteudo da varial "numero"
print("O número convertido é: {}" .format(numero))
# Outra maneira utilizando (input)
valor_digitado = int(input("Digite um número inteiro: "))
print("O número inteiro digitado é: {}" .format(valor_digitado))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Função enumerate() em Python. """
# a função "enumerate()" retorna o "indice e o valor"
# contidos em uma "lista, tupla ou string"
tupla = (11, 3, 4, 55, 77)
lista = ["casa", "batata"]
for indice, valor in enumerate(tupla):
print(f"Índice {indice} - {valor}")
t1 = tuple(enumerate(tupla))[0]
print(t1)
print(tuple(lista)[1])
print(tuple(enumerate(lista[1])))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Dicionários de Dados."""
"""
Operadores de Identidade
is - avalia se ambos os lados têm a mesma identidade
is not - avalia se ambos os lados têm identidades diferentes
"""
# as chaves podem ser de qualquer tipo imutável
elementos = {
# chave: valor
# neste exemplo as chaves são "Strings"
'hidrogenio': 1,
'helio': 2,
'carbono': 6
}
# adicionando um novo item
elementos['litio'] = 3
print(elementos)
# verificando se a chave "oxigenio" está no dicionário
print('oxigenio' in elementos)
# o método "get()" procura por valores no dicionário
print(elementos.get('oxigenio'))
# imprime o valor referente a chave "helio"
print(elementos["helio"])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Dicionários de dados, listas e funções."""
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
for chave in prices:
print(f"=> {chave} <=")
print("Preço: ", prices[chave])
print("Estoque: ", str(stock[chave]))
total = 0
for key in prices:
total += prices[key] * stock[key]
print(total)
print(total)
print("=== Fazendo compras ===")
def compute_bill(food):
total = 0
for item in food:
if stock[item] > 0:
total += prices[item]
stock[item] -= 1
print(item, " - ", stock[item])
return total
shopping_list = ["banana", "orange", "apple"]
print(compute_bill(shopping_list))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Utilizando a função "enumerate()". """
print("==== Exemplo | Função enumerate() ====")
lista_numeros = [100, 200, 300, 400, 500, 600, 700, 800]
for index, item in enumerate(lista_numeros):
lista_numeros[index] += 1000
print(index, item)
print(lista_numeros)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Interagindo com usuário. """
print("==== Testando o FOR e Função range() ====")
inicio = int(input("Digite o INÍCIO: "))
fim = int(input("Digite o FIM: "))
passo = int(input("Digite o PASSO: "))
loop = [inicio, fim, passo]
for item in range(*loop):
print(item)
print(type(loop))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Funções: Parâmetros x Argumentos. """
# definindo uma função
# com "dois parâmetros"
def soma(num1, num2):
"""
Esta função soma dois numeros
e imprime o resultado
"""
resultado = num1 + num2
print(f"Soma de {num1} + {num2} = {resultado}")
# chamando a função "soma()"
# passando os argumentos "2 e 5git add ."
soma(2, 5)
|
import random
# I created this as a way to practice powers of 2 for a CS class
def powerof2():
keep_going = True
userRange = input("What range of powers of 2? ")
userRange = int(userRange)
while keep_going:
for i in range(userRange):
power = random.randint(0,10)
ans = int(input("What is 2**" + str(power) + ": "))
correct = 2**power
if ans == correct:
print("Correct!")
else:
print("Wrong!")
print(str(correct))
keep_going = input("Would you like to play again? (True or False)")
userRange = input("What range of powers of 2? ")
userRange = int(userRange)
powerof2() |
def day_month(n):
if n == 0:
print("Sunday")
elif n == 1:
print("Monday")
elif n == 2:
print("Tuesday")
elif n == 3:
print("Wednesday")
elif n == 4:
print("Thursday")
elif n == 5:
print("Friday")
else:
print("Saturday")
print(day_month(2))
|
def converter(list2):
list2 = [int(i) for i in list2] # Converts each item in the list to an integer
list3 = sum(list2) # Adds the numbers in the list
return list3
print(converter([1, 2, "3", 4, "5", 10, "12"]))
|
""" Detemine if a list is sorted using a generator defined by comprehension"""
items1 = [6, 8, 19, 20, 23, 41, 49, 53, 60, 71]
items2 = [2, 23, 34, 12, 45, 56, 78, 89, 94, 97]
def is_sorted(itemList):
return all(itemList[i] <= itemList[i+1] for i in range(len(itemList)-1))
print(is_sorted(items1))
print(is_sorted(items2)) |
"""
Given an array, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum.
Input:
The first line contains an integer 'T' denoting the total number of test cases. In each test cases, the first line contains an integer 'N' denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
In each seperate line print minimum absolute difference.
Constraints:
1<=T<=30
1<=N<=50
1<=A[I]<=50
Example:
Input:
2
4
1 6 5 11
4
36 7 46 40
Output :
1
23
Explaination :
Subset1 = {1, 5, 6}, sum of Subset1 = 12
Subset2 = {11}, sum of Subset2 = 11
"""
def minSumPartition(arr, n):
if n == 0:
return 0
# print(arr, n)
return (arr[0] + minSumPartition(arr[1:], n-1)) - minSumPartition(arr[1:], n-1)
# print("Min Val", min_val)
print(minSumPartition([36, 7, 46, 40], 4)) |
# https://www.hackerrank.com/contests/bppc14/challenges/string-and-performing-queries
s = input()
Q = int(input())
for i in range(Q):
q = [i for i in input().split()]
if q[0] == "1":
s = s[::-1] #reverse
else:
if q[1] == "1":
s = q[2] + s
elif q[1] == "2":
s = s + q[2]
print(s) |
def swap(x,i,j):
"""
交换x的i,j位置元素
"""
temp = x[i]
x[i] = x[j]
x[j] = temp
|
a = input().rstrip()
b = input().rstrip()
if a[-1] == b[0] and b[-1] != 'n':
print('OK')
else:
print('NG')
|
s = input().rstrip()
if s == 'candy' or s=='chocolate':
print('Thanks!')
else:
print('No!')
|
c1,c2 = input().split()
if c1 == 'J' and c2 =='J':
c2 = 'Q'
print(c1,c2)
|
c = int(input())
if c == 0:
c = 1
else:
c = 3*c
print(c)
|
exit = 1
while exit == 1:
summ = float(input ('Vvedite summu: '))
ostatok = summ
nominals = [500, 200, 100, 50, 20, 10, 5, 1]
nominalIndex = 0
while ostatok > 0 and nominalIndex < len (nominals):
x = ostatok // nominals[nominalIndex]
ostatok = ostatok - (x * nominals[nominalIndex])
if x > 0:
print (x, ' x ', nominals[nominalIndex], '$')
nominalIndex = nominalIndex + 1
print ('Hotite povtorit? vvedite 1')
print ('Hotite zaverchit rabatu? vvedite 2')
exit = int (input( 'Vvedite 1 and 2: '))
|
def isNatural(n):
#
lst = []
# k
k = 0
# 2 N
for i in range(2, n + 1):
# 2
for j in range(2, i):
#
if i % j == 0:
k = k + 1
# ,
if k == 0:
lst.append(i)
else:
k = 0
if n in lst:
return True
else:
return False |
def pow(x, n):
y = x
# вычисление функции x^n
for _ in range(n - 1):
y = y * x
return y
# вычисление функции x^n другим способом
def pow2(x, n):
if n == 0:
return 1
else:
return x * pow2(x, n - 1)
# вычисление функции n!
def faktorial(n):
if n == 0:
return 1
return n * faktorial(n - 1) |
# coding: utf-8
# A regular expression is a text matching pattern that is described in a
# specialized syntax. The pattern has instructions, which are executed with a
# string as an input to produce a matching subset. The Python module to perform
# regular expression is re. Typically, re is used to match or find strings.
#
# Visit the following sites to learn more
#
# http://pymotw.com/2/re/
#
# http://www.thegeekstuff.com/2014/07/python-regex-examples/
#
# http://www.diveintopython.net/regular_expressions/
#
# https://docs.python.org/2/library/re.html
# In[6]:
import re
# In[2]:
patterns = 'and'
text = 'Python is a dynamically typed language and also has a simple syntax'
print re.search(patterns, text)
if re.search(patterns, text):
print 'There is a match'
else:
print 'Found no match'
# In[ ]:
patterns = 'or'
text = 'Python is a dynamically typed language and also has a simple syntax'
print re.search(patterns, text)
if re.search(patterns, text):
print 'There is a match'
else:
print 'Found no match'
# In[ ]:
patterns = ['and', 'or']
text = 'Python is a dynamically typed language and also has a simple syntax'
for pattern in patterns:
print 'Trying to find a match for "%s" in "%s" - ' %(pattern,text)
if re.search(pattern, text):
print 'There is a match'
else:
print 'Found no match'
# In[ ]:
pattern = 'and'
text = 'Python is a dynamically typed language and also has a simple syntax'
compare = re.search(pattern,text)
s = compare.start() # start() returns the starting position of the match
e = compare.end() # end() returns the ending position of the match
print 'Found "%s" in "%s" from %d to %d ' %(pattern,text,s,e)
# In[ ]:
mynumber = 1034567810378103
pattern = 10
mynumber_str = str(mynumber)
pattern_str = str(pattern)
# findall() function finds all the substrings of the input that match the
# pattern without overlapping syntax re.findall(pattern, string)
print re.findall(pattern_str,mynumber_str)
count = len(re.findall(pattern_str,mynumber_str))
print 'In the given text, %d occured %d times' %(pattern, count)
# In[ ]:
# finditer() returns an iterator that produces match instances instead of the
# strings returned by findall
# syntax re.finditer(pattern, string)
text = '1034567810378103'
pattern = '78'
count = 0
print re.finditer(pattern,text)
for match in re.finditer(pattern,text):
s = match.start()
e = match.end()
count = count + 1
print 'The pattern "%s" starts at %d and ends at %d ' %(pattern, s, e)
print 'In the given text, "%s" occured %d times' %(pattern, count)
# The group() returns the substring that was matched by the re. Adding groups
# to a pattern lets you isolate parts of the matching text, expanding those
# capabilites to create a parser.
# In[ ]:
strval1 = 'Barack Obama, Michelle Obama, Joe Biden, Jill Biden'
list1 = strval1.split(',')
print list1
for items in list1:
firstname = re.match(r'(.*)Obama',items)
if firstname:
# command below returns every element in the list
# that has Obama in it
print firstname.group(0)
# command below returns first name of the element in the
# list that has Obama in it
print firstname.group(1)
# In[ ]:
strval = 'San Francisco, San Jose, San Carlos, Sunnyvale, Cupertino'
strval_list = strval.strip().split(',') # converting strval into a list
b = []
for items in strval_list:
allnames = re.match(r'San(.*)', items.strip())
# returns a subset of the list which starts with San
if allnames:
b.append(allnames.group(1))
print b
# re.compile() function is used to compile pattern into pattern objects,
# which have methods for various operations such as searching for pattern
# matches or performing string substitutions.
# syntax:
# ```
# re.compile(pattern)
# ```
# In[ ]:
strval = 'San Francisco, San Jose, San Carlos, Sunnyvale, Cupertino'
rec = re.compile('San')
print re.findall(rec,strval)
# In[ ]:
# Returns an iterator
for items in re.finditer(rec,strval):
print items
# In[ ]:
# Returns an iterator
for items in re.finditer(rec,strval):
print items.start(),items.end()
# First method to find and replace:
#
# The replace() function will replace substrings.
#
# syntax
# ```
# input_text.replace('pattern', 'replacement')
# ```
# In[ ]:
a = strval.replace('San','S.')
print strval
print a
# Second method to find and replace:
#
# The re.sub() function can be used to replace substrings.
#
# syntax
# ```
# re.sub(pattern, replacement, string)
# ```
# In[ ]:
strval1 = re.sub('San','S.',strval)
print strval1
# In[ ]:
t = 'It\'s a dog\n'
print t
t = r'It\'s a dog\n'
print t
# Cheat sheet for re
#
# \w - Matches characters from A-Z, a-z, 0-9 or _ also writen as A-Za-z0-9_
# \W - Matches nonword characters.
# \s - Matches whitespace. Equivalent to [ \t\n\r\f].
# \S - Matches nonwhitespace.
# \d - Matches digits. Equivalent to [0-9].
# \D - Matches nondigits.
# ^ start of string, or line
# \A Start of string
# \b Match empty string at word (\w+) boundary
# \B Match empty string not at word boundary
# \Z End of string
#
# {m} Exactly m repetitions
# {m,n} From m (default 0) to n (default infinity)
# * 0 or more. Same as {,}
# + 1 or more. Same as {1,}
# ? 0 or 1. Same as {,1}
#
# Reference
# https://github.com/tartley/python-regex-cheatsheet/blob/master/cheatsheet.rst
# In[ ]:
# in this example we want to make sure that the user enters valid email address
import re
ymail_check = re.compile(r'(\w+@\w+\.(com|net|org|edu))')
while True:
ymail = raw_input ("Please, enter your email: ")
if ymail_check.search(ymail):
print 'you entered a valid email'
breaks
else:
print "Please enter your email correctly!"
# In[ ]:
# The re.search() method takes a regular expression pattern and a string and
# searches for that pattern within the string.
# The syntax is re.search(pattern, string)
import re
name = 'Roosovelt, Eleanor'
a = re.search('(\w+), (\w+)',name)
# (\w+) matches multiple occurrances of A-Za-z0-9_
print a.group(0)
print a.group(1)
print a.group(2)
# In[4]:
name = 'Roosovelt, Eleanor'
a = re.search('(?P<lastname>\w+), (?P<firstname>\w+)',name)
'''
?P<lastname>\w+ finds pattern that has characters A-Za-z0-9_ and assigns
it to lastname
'''
print a.group(0)
print a.group('lastname')
print a.group('firstname')
# In[ ]:
# There is only one space after ,
strval = 'Elizabeth Warren, 65'
a = re.search('(?P<firstname>\w+) (?P<lastname>\w+), (?P<age>\d+)',strval)
print a.group(1)
#print a.group('age')
# In[ ]:
# What happens if there are more spaces after , ?
strval = 'Elizabeth Warren, 65'
a = re.search('(?P<firstname>\w+) (?P<lastname>\w+), \s+(?P<age>\d+)',strval)
print a#.group(0)
print a.group('age')
# In[ ]:
'''
In-class activity: In the below paragraph, find the number of occurances of
words - of, the and food.
Coral reefs are some of the most biologically rich and economically valuable
ecosystems on Earth. They provide food, jobs, income, and protection to
billions of people worldwide. However, coral reefs and the magnificent creatures
that call them home are in danger of disappearing if actions are not taken
to protect them. They are threatened by an increasing range of impacts including
pollution, invasive species, diseases, bleaching, and global climate change.
The rapid decline and loss of these valuable, ancient, and complex ecosystems
have significant social, economic, and environmental consequences in the
United States and around the world.
'''
# In[ ]:
'''
In-class activity:
In the below paragraph, there are typos. The spelling mistakes are in the
words: tping, componts, programy and binare. Create a dictionary with the key
being the incorrect word and the value is the correct word. Then replace the
incorrect word with the correct word and print the corrected text.
'''
myText = '''Python is an interpreted, object-oriented, high-level programming
language with dynamic semantics. Its high-level built in data structures,
combined with dynamic tping and dynamic binding, make it very attractive for
Rapid Application Development, as well as for use as a scripting or glue
language to connect existing componts together. Python's simple, easy to learn
syntax emphasizes readability and therefore reduces the cost of program
maintenance. Python supports modules and packages, which encourages programy
modularity and code reuse. The Python interpreter and the extensive standard
library are available in source or binare form without charge for all major
platforms, and can be freely distributed.'''
# In[12]:
# extracting year from a text file using regex
import re
pattern = re.compile("(\d+)")
for i, line in enumerate(open('modify.txt')):
#print i, line, re.finditer(pattern, line)
for m in re.finditer(pattern, line):
year = m.group(1)
print 'The year is ', year
# In[ ]:
# extracting data from a text file using regex
import re
parts = [
r'(?P<host>\S+)', # host %h
r'\S+', # indent %l (unused)
r'(?P<user>\S+)', # user %u
r'\[(?P<time>.+)\]', # time %t
r'"(?P<request>.+)"', # request "%r"
r'(?P<status>[0-9]+)', # status %>s
r'(?P<size>\S+)', # size %b (careful, can be '-')
]
pattern = re.compile(r'\s+'.join(parts)+r'\s*\Z')
status1 = []
fo = open("apache50log.txt")
for line in fo.readlines():
m = pattern.match(line)
res = m.groupdict()
print res
status1.append(res['status'])
print status1
statusdict = {}
statusset = set(status1)
for item in statusset:
statusdict[item] = status1.count(item)
print statusdict
# In[ ]:
|
# coding: utf-8
# In this notebook we will discuss:
# 1. Functions
# 2. Arguments and outputs
# 3. default argument
# 4. keyword based arguments
# In[29]:
'''
Syntax for function
def name_of_the_function(list of arguments):
statements that need to be executed
return value
'''
def increment(a):
b = a+1
print 'the increment2 value is : %d' %b
return b
print increment(20) # calling the function and passing a required argument.
# In[30]:
# Scope of variables that are is local to the function.
'''
The variable b does not exist outside the function.
So we will get NameError exception.
'''
def increment(a):
b = a+1
print 'the increment2 value is : %d' %b
return b
print increment(20) # calling the function and passing a required argument.
#print b
# In[31]:
# A function can take multiple inputs
def increment(a,incr):
c = a+incr
print 'The value of a is: %d' %a
return c
print increment(3,10) # calling the function and passing two required arguments.
# 10 will be assigned to a and
# 3 will be assigned to incr. So these are called positional arguments.
# In[32]:
def increment(a,incr):
c = a+incr
return (c,a,incr)
# returning multiple values as a tuple
print increment(10,3)
# In[33]:
# Specifying default values
def increment(a,incr=1):
a = a+incr
return a
print increment(3) # for this the incr will default to 1
print increment(3,4)
# here the incr is assigned a value of 4 which overrides the default value
# In[34]:
def increment(a=4,incr1=1):
print 'the value of a is :%d' %a
a = a+incr1
return a
print increment(a=6,incr1=2) # 2 keyword arguments
# In[35]:
print increment(incr1=2,a=3)
# Unlike positional arguments, order is not important for keyword arguments.
# In[36]:
print increment(10,incr1=5) # if you assign a value for a keyword argument
# then other arguments to its right should also be assigned values.
# In[37]:
print increment(a=10,5) # This will generate a Syntax error
# In[38]:
print increment(5,incr1=2)
# if you assign a value for a keyword argument
# then other keyword arguments to its right should also be assigned values.
# In[39]:
print type(increment)
print increment
# Pass-by-value and pass-by-reference
#
# http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference
# In[40]:
def myfunc(a):# a is an int
a = a*2
print "a = ", a
return a
b = 2
myfunc(b)
print "b = ", b
# In[41]:
def myfunc(a):# a is a TUPLE that is completely replaced
a = (4, 5, 6,)
print "a = ", a
return a
b = (1,2,3)
myfunc(b)
print "b = ", b
# In[42]:
def myfunc(a):# a is a list that is completely replaced
a = [4,5,6]
print "a = ", a
return a
b = [1,2,3]
myfunc(b)
print "b = ", b
# In[43]:
def myfunc(a):# a is a LIST that is modified inline
a.append(4)
print "a = ", a
return a
b = [1,2,3]
myfunc(b)
print "b = ", b
# In[44]:
def myfunc(a):# a is a LIST that is modified inline
a = a[:]
# Creating a deepcopy will solve the problem of pass by reference
a.append(4)
print "a = ", a
return a
b = [1,2,3]
myfunc(b)
print "b = ", b
# In[ ]:
'''
Summary of pass-by-value and pass-by-reference
'''
# <img src="http://i.stack.imgur.com/hKDcu.png = 70*70">
# In[ ]:
'''
In-class activity
Create a function called squared which takes a list called mylist and
returns another list where the elements are square of mylist. Also write
another function that takes mylist and returns a dictionary where the key
is the input and the value is the square of the input.
'''
mylist = [2, -7, 10]
# In[45]:
# args and kwargs helps to supply variable number of arguments to a
# function. Inside the function, args is of type tuple.
def take1(*args):
print args, type(args)
for i in args:
print i
take1(-10)
take1(1,2,3)
# In[46]:
# kwargs is a dictionary, with the dictionary key being the variable
# name and dictionary value is the value of that variable
def utake(**kwargs):
print kwargs, type(kwargs)
utake(a = 'abe')
utake(a = 'abe', b ='cab')
# In[47]:
def ptab(**kwargs):
# since kwargs is a dictionary, we can iterate using items() function.
for key, value in kwargs.items():
print key, value
ptab(a = 7, b = -5, c = 3, d = -10)
# In[ ]:
'''
In-class activity: define a function that takes a word and prints
characters from the word. Call the function and pass a word.
'''
# In[ ]:
'''
In-class activity: define a function that converts Fahrenheit into
Celsius. The formula is C = (F - 32)*(5.0/9). Use sys in the code and
pass the value when running the program from the command line
(if Windows) or terminal (if MAC).
'''
# In[ ]:
|
import os
from abstract import module
class resultor(module):
"""
Resultor of the network saves down resultor. The initilizer initializes the directories
for storing results.
Args:
verbose: Similar to any 3-level verbose in the toolbox.
resultor_init_args: ``resultor_params`` is a dictionary of the form
.. code-block:: none
resultor_init_args = {
"root" : "<root directory to save stuff inside>",
"results" : "<results_file_name>.txt",
"errors" : "<error_file_name>.txt",
"costs" : "<cost_file_name>.txt",
"confusion" : "<confusion_file_name>.txt",
"network" : "<network_save_file_name>.pkl"
"id" : id of the resultor
}
While the filenames are optional, ``root`` must be provided. If a particular file is
not provided, that value will not be saved.
Returns:
yann.modules.resultor: A resultor object
"""
def __init__( self, resultor_init_args, verbose = 1):
if "id" in resultor_init_args.keys():
id = resultor_init_args["id"]
else:
id = '-1'
super(resultor,self).__init__(id = id, type = 'resultor')
if verbose >= 3:
print "... Creating resultor directories"
for item, value in resultor_init_args.iteritems():
if item == "root":
self.root = value
elif item == "results":
self.results_file = value
elif item == "errors":
self.error_file = value
elif item == "costs":
self.cost_file = value
elif item == "confusion":
self.confusion_file = value
elif item == "network":
self.network_file = value
if not hasattr(self, 'root'): raise Exception('root variable has not been provided. \
Without a root folder, no save can be performed')
if not os.path.exists(self.root):
if verbose >= 3:
print "... Creating a root directory for save files"
os.makedirs(self.root)
if verbose >= 3:
print "... Resultor is initiliazed"
|
import math
n = int(input())
count = 0
for i in range(1, n + 1, 2):
divisors = 0
for j in range(1, int(math.sqrt(i)) + 1):
if i % j == 0:
if j * j == i:
divisors += 1
else:
divisors += 2
if divisors == 8:
count += 1
print(count) |
"""
1) We are going to sum each day’s sales into an accumulator/sum variable for display.
2) Make sure the user enters a valid number.
3) Step 1: Initialize input variables:
daysOfWeek[] – holds our 7 days
dailySales[] – holds our sales for each day of week
totalSales – accumulator to hold total sales
Step 2: Processing:
Loop through 7 days len(daysOfWeek)
prompt the user to enter sales for day
add sales to total (totalSales +=dailySales)
Step3: Output
Print the results
"""
# create a single dimension list for daily sales (variables)
dailySales = [0.0,0.0,0.0,0.0,0.0,0.0,0.0]
daysOfWeek = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')
totalSales = 0.0 # accumulator to sum our totals
# loop seven days and grab sales for the day
for i in range(len(dailySales)): # this is the appropriate way to code
dailySales[i] = float(input("Enter the sales for: " + daysOfWeek[i]+": "))
# accumulate the total sales from the week and display the results
totalSales += dailySales[i] # using [i] refers back to the indexed days of the week, goes through the sales for each day
print("The total sales for the week was:\t", totalSales)
# print("The average sales for the week was:\t", totalSales/len(dailySales)) IF THE AVERAGE WAS WANTED AS WELL |
import datetime
from datetime import datetime
import tkinter as tk
from tkinter import *
from re import findall
us_holidays = {'Christmas': [12,25,datetime.now().year], 'Halloween': [10,31,datetime.now().year], 'Independence Day': [7,4,datetime.now().year],
'New Year': [1,1,datetime.now().year], 'MLK Day': [1,15,datetime.now().year], 'Memorial Day': [5,28,datetime.now().year],
'Labor Day': [9,3,datetime.now().year], 'Columbus Day': [10,8,datetime.now().year], "Veteran's Day": [11,12,datetime.now().year],
'Thanksgiving': [11,22,datetime.now().year]}
# These two functions clear their corresponding entry boxes.
def clearBox1(event):
date1_entry.delete(0,'end')
return None
def clearBox2(event):
date2_entry.delete(0,'end')
return None
# Deletes the textbox before entering in the difference in dates. Also used for reset button functionality.
def delete_textbox():
t1.delete('1.0','end')
return None
def reset_fields():
date1_entry.delete(0,'end')
date2_entry.delete(0,'end')
date1_entry.insert(0,'MM-DD-YYYY')
date2_entry.insert(0,'MM-DD-YYYY')
delete_textbox()
t1.insert(END, 'Please enter two dates you would like to see the day difference between or pick your favorite holiday to see how long until it comes! \nYou may also type in "today" to use the current date.')
# Changes the date input into a datetime object
# 1 year later and I think I'm going to puke that I wrote it like this. However, it works so I won't change it.
def change_date1():
global date1
d1 = date1_entry_value.get()
if d1.lower() == 'today':
date1 = datetime.now()
else:
d1 = date1_entry_value.get()
d1_list = re.findall(r"[\w']+", d1)
d1_str = ''.join(str(i) for i in d1_list)
if (d1_str[0] != 0):
d1_str = '0' + d1_str
date1 = datetime.strptime(d1_str, "%m%d%Y")
def change_date2():
global date2
d2 = date2_entry_value.get()
if d2.lower() == 'today':
date2 = datetime.now()
else:
d2 = re.findall(r"[\w']+", d2)
d2_str = ''.join(str(i) for i in d2)
if (d2_str[0] != 0):
d2_str = '0' + d2_str
date2 = datetime.strptime(d2_str, '%m%d%Y')
# Takes dictionary values and turns them into datetime objects
def transform_holiday(holiday):
delete_textbox()
holiday_date = us_holidays[dropdown_value.get()]
holiday_str = ''.join(str(i) for i in holiday_date)
global holiday_d
holiday_d = datetime.strptime(holiday_str, '%m%d%Y')
h_diff = datetime.now() - holiday_d
if h_diff.days > 0:
t1.insert(END,'We are ' + str(365-h_diff.days) + ' days from the next ' + str(dropdown_value.get()) + '.')
else:
t1.insert(END, 'We are ' + str(-h_diff.days) + ' days from ' + str(dropdown_value.get()) + '.')
# Mathematical brains and inserts into the textbox
def diff():
delete_textbox()
while True:
try:
change_date1()
change_date2()
difference = date2 - date1
days = str(difference.days)
multiYearDays = str(int(difference.days%365.25))
negativeMultiYearDays = str(365 - int(difference.days%365.25))
negativeDays = str(-difference.days)
years = str(int((difference.days) / 365.25))
negativeYears = str(-int((difference.days) / 365.25))
if 365 > difference.days > 0:
t1.insert(END,'These dates are ' + days + ' days apart.')
elif difference.days > 365:
if (int(years) == 1):
t1.insert(END, 'These dates are ' + years + ' year and ' + multiYearDays + ' days apart.')
else:
t1.insert(END, 'These dates are ' + years + ' years and ' + multiYearDays + ' days apart.')
elif -365 < difference.days < 0:
t1.insert(END, 'These dates are ' + negativeDays + ' days apart.')
else:
if (int(negativeYears) == 1):
t1.insert(END, 'These dates are ' + negativeYears + ' year and ' + negativeMultiYearDays + ' days apart.')
else:
t1.insert(END, 'These dates are ' + negativeYears + ' years and ' + negativeMultiYearDays + ' days apart.')
except ValueError:
t1.insert(END, 'One of the values was entered improperly. Please try again.')
break
# Boots up the window
root = tk.Tk()
master = tk.Frame()
root.iconbitmap("icon.ico")
b_execution = tk.Button(master, text = 'DAYS', fg = 'green',command=diff)
b_execution.grid(row=0,column=0,padx=20, sticky=NW+NE)
b_reset = tk.Button(master, text = 'RESET', fg = 'red', command=reset_fields)
b_reset.grid(row=1,column=0,padx=20, sticky=W+E)
Label(master, text='First Date:').grid(row=0,column=1)
Label(master, text='Second Date:').grid(row=1,column=1)
# Creating the entry locations for the dates.
date1_entry_value = StringVar()
date1_entry = Entry(master, textvariable = date1_entry_value)
date1_entry.insert(0,'MM-DD-YYYY')
date1_entry.bind('<Button-1>', clearBox1)
date2_entry_value = StringVar()
date2_entry = Entry(master, textvariable = date2_entry_value)
date2_entry.insert(0,'MM-DD-YYYY')
date2_entry.bind('<Button-1>', clearBox2)
# The two binds above will clear the boxes when clicked
date1_entry.grid(row=0,column=2)
date2_entry.grid(row=1,column=2)
t1 = Text(master, height = 5, width=50, wrap = WORD)
t1.configure(font=('Arial', 11))
t1.insert(END, 'Please enter two dates you would like to see the day difference between or pick your favorite holiday to see how long until it comes! \nYou may also type in "today" to use the current date.')
t1.grid(row=3,column=0,columnspan = 4)
dropdown_value = StringVar()
w = OptionMenu(master, dropdown_value, *us_holidays.keys(), command=transform_holiday).grid(row=6, column =0,columnspan=4,sticky=S,padx=10,)
dropdown_value.set('Holidays')
root.title('Dayze 1.0')
master.pack()
root.mainloop()
|
"""
Original gumball machine (without patterns)
Author: tuanla
Date: 2018
"""
class GumballMachine:
SOLD_OUT = 0
NO_QUARTER = 1
HAS_QUARTER = 2
SOLD = 3
def __init__(self, count):
self._count = count
if count > 0:
self._state = GumballMachine.NO_QUARTER
else:
self._state = GumballMachine.SOLD_OUT
def insert_quarter(self):
if self._state == GumballMachine.HAS_QUARTER:
print "You can't insert another quarter"
elif self._state == GumballMachine.NO_QUARTER:
print "You inserted a quarter"
elif self._state == GumballMachine.SOLD_OUT:
print "You can't insert a quarter, the machine is sold out"
elif self._state == GumballMachine.SOLD:
print "Please wait, we're already giving you a gumball"
def eject_quarter(self):
if self._state == GumballMachine.HAS_QUARTER:
print "Quarter returned"
self._state = GumballMachine.NO_QUARTER
elif self._state == GumballMachine.NO_QUARTER:
print "You haven't inserted a quarter"
elif self._state == GumballMachine.SOLD:
print "Sorry, you already turned the crank"
elif self._state == GumballMachine.SOLD_OUT:
print "You can't eject, you haven't inserted a quarter yet"
def turn_crank(self):
if self._state == GumballMachine.SOLD:
print "Turning twice doesn't get you another gumball"
elif self._state == GumballMachine.NO_QUARTER:
print "You turned but there's no quarter"
elif self._state == GumballMachine.SOLD_OUT:
print "You turned, but there are no gumballs"
elif self._state == GumballMachine.HAS_QUARTER:
print "You turned..."
self._state = GumballMachine.SOLD
self.dispense()
def dispense(self):
if self._state == GumballMachine.SOLD:
print "A gumball comes rolling out the slot"
self._count -= 1
if self._count == 0:
print "Oops, out of gumballs!"
self._state = GumballMachine.SOLD_OUT
else:
self._state = GumballMachine.NO_QUARTER
elif self._state == GumballMachine.NO_QUARTER:
print "You need to pay first"
elif self._state == GumballMachine.SOLD_OUT:
print "No gumball dispensed"
elif self._state == GumballMachine.HAS_QUARTER:
print "No gumball dispensed"
def refill(self, num_gum_balls):
self._count = num_gum_balls
self._state = GumballMachine.NO_QUARTER
def __str__(self):
buff = "\nMighty Gumball, Inc."
buff +="\nJava-enabled Standing Gumball Model #2004\n"
buff += "Inventory: " + str(self._count) + " gumball"
if self._count != 1:
buff += "s"
buff += "\nMachine is "
if self._state == GumballMachine.SOLD_OUT:
buff += "sold out"
elif self._state == GumballMachine.NO_QUARTER:
buff += "waiting for quarter"
elif self._state == GumballMachine.HAS_QUARTER:
buff += "waiting for turn of crank"
elif self._state == GumballMachine.SOLD:
buff += "delivering a gumball"
buff += "\n"
return buff
if __name__ == '__main__':
gumball_machine = GumballMachine(5)
print str(gumball_machine)
gumball_machine.insert_quarter()
gumball_machine.turn_crank()
print str(gumball_machine)
gumball_machine.insert_quarter()
gumball_machine.eject_quarter()
gumball_machine.turn_crank()
print str(gumball_machine)
gumball_machine.insert_quarter()
gumball_machine.turn_crank()
gumball_machine.insert_quarter()
gumball_machine.turn_crank()
gumball_machine.eject_quarter()
print str(gumball_machine)
gumball_machine.insert_quarter()
gumball_machine.insert_quarter()
gumball_machine.turn_crank()
gumball_machine.insert_quarter()
gumball_machine.turn_crank()
gumball_machine.insert_quarter()
gumball_machine.turn_crank()
print str(gumball_machine)
|
import multiprocessing
import threading
import time
# 线程是cpu调度的最小单位,进程是操作系统分配资源和调度的最小单位
# 进程和线程都是一个时间段的描述,是CPU工作时间段的描述,不过是颗粒大小不同
class SubThread(threading.Thread):
'''
用 threading.Thread 创建进程,一种方法是传递 callable 对象,另一种是在子类中覆盖 run 方法
'''
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print("sub running")
time.sleep(2)
print("sub finish")
# 调用 start 来开始线程活动,使用 join 阻塞主线程,直到子线程完成
# 调用 setDaemon 来设置主线程为守护线程,主线程结束后子线程强制结束
class MainThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print("main running")
t = SubThread()
# t.setDaemon(True)
t.start()
# t.join()
print("main finish")
MainThread().start() |
from helpers import check_user_existence, get_user
from auth import login
username = input("Enter your username: ")
password = input("Enter your password: ")
if check_user_existence(username):
user = get_user(username)
logged_in = login(user, password)
if logged_in:
user["logged_in"] = True
print(user)
else:
print("Invalid password")
else:
print("Invalid username") |
s = input()
total=0
for x in range(len(s)):
if ((x %2) !=0):
if int(s[x])*2>9:
total+= int(s[x])*2%10+int(int(s[x])*2/10)
else:
total+=int(s[x])*2
else:
total+=int(s[x])
print(total)
if total%10 ==0:
print("Your number ID is okay!")
|
"""
Prints the internal representation of a document as a string
"""
import sys
from Element import Element
from AztexCompiler import AztexCompiler
def is_text_file(filename):
return filename.endswith('.txt')
def input_text(argv):
""" gets input text from command line args """
inputf = input_file(argv)
if inputf:
f = open(inputf, 'r')
return f.read()
else:
text = ''.join(argv[1:])
return text
def input_file(argv):
""" gets the input file from command line args """
# no input given
if len(argv) == 1:
return "input.txt"
# input file given
elif is_text_file(argv[1]):
return argv[1]
def main():
""" prints the internal representation """
md_text = input_text(sys.argv)
compiler = AztexCompiler()
print '\n'.join(map(lambda x: str(x), compiler.get_representation(md_text)))
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Find all duplicates in an array where the numbers in the array are in the
range of 0 to n-1 where n is the size of the array. For example: [1, 2, 3, 3]
is okay but [1, 2, 6, 3] is not. In this version of the challenge there can
be multiple duplicate numbers as well.
"""
# TODO
|
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Check if a string contains only balanced delimiters (eg. (), [], {}).
"""
import unittest
import sys
def is_balanced(string: str) -> bool:
"""
Time: O(n), where n=string length
Space: O(n), worst-case it consists of open delimiters only
"""
open_to_close = {
'(': ')',
'[': ']',
'{': '}',
}
expected_close = []
for char in string:
if char in open_to_close:
expected_close.append(open_to_close[char])
elif (len(expected_close) > 0) and (expected_close[-1] == char):
expected_close.pop()
else:
return False
return len(expected_close) == 0
class Test (unittest.TestCase):
def test_balanced(self):
cases = [
'([])([])',
'()[]{}',
'([]{})',
'([{}])',
'(()[{}])',
]
for case in cases:
self.assertTrue(is_balanced(case))
def test_unbalanced(self):
cases = [
'([)]',
'([]',
'[])',
'([})',
]
for case in cases:
self.assertFalse(is_balanced(case))
if __name__ == '__main__':
if sys.stdin.isatty():
unittest.main(verbosity=2)
else:
for line in sys.stdin:
if line[0] in '(){}[]':
if is_balanced(line.strip()):
print('YES')
else:
print('NO')
|
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
List all permutations of `string`.
Time: O(n^2) where n = len(string)
"""
import unittest
def permutate(string):
if string == '':
return ['']
permutations = []
for i, char in enumerate(string):
for permutation in permutate(string[:i] + string[i + 1:]):
permutations.append(char + permutation)
return permutations
class Test (unittest.TestCase):
def test_empty_string(self):
self.assertEqual(permutate(''), [''])
def test_single_char_string(self):
self.assertEqual(permutate('a'), ['a'])
def test_unique_chars_string(self):
self.assertCountEqual(permutate('abc'), [
'abc',
'acb',
'bac',
'bca',
'cab',
'cba',
])
def test_repeated_chars_string(self):
self.assertCountEqual(permutate('aab'), [
'aab',
'aba',
'aab',
'aba',
'baa',
'baa',
])
if __name__ == '__main__':
unittest.main(verbosity = 2)
|
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Insert and delete a node from a linked list.
"""
from typing import List, Optional
import unittest
class Node:
def __init__(self, value, next: Optional['Node'] = None):
self.value = value
self.next = next
def to_array(self) -> List:
node: Optional[Node] = self
values = []
while node is not None:
values.append(node.value)
node = node.next
return values
def insert(node: Node, position: int, value) -> Optional[Node]:
"""
Time: O(n), where n=number of nodes
Space: O(1)
"""
if position < 0:
return None
previous: Optional[Node] = None
current: Optional[Node] = node
i = 0
while (i < position) and (current is not None):
previous = current
current = current.next
i += 1
if i != position:
return None
if previous is None:
return Node(value, next=node)
previous.next = Node(value, next=current)
return node
def delete(node: Node, position: int) -> Optional[Node]:
"""
Time: O(n), where n=number of nodes
Space: O(1)
"""
if position < 0:
return None
previous: Optional[Node] = None
current: Optional[Node] = node
i = 0
while (i < position) and (current is not None):
previous = current
current = current.next
i += 1
if i != position:
return None
if previous is None:
return current.next
previous.next = current.next
return node
class Test (unittest.TestCase):
def test_insert_start(self):
lst = insert(Node(1, Node(2, Node(3))), 0, 4)
self.assertListEqual(lst.to_array(), [4, 1, 2, 3])
def test_insert_middle(self):
lst = insert(Node(1, Node(2, Node(3))), 1, 4)
self.assertListEqual(lst.to_array(), [1, 4, 2, 3])
def test_insert_end(self):
lst = insert(Node(1, Node(2, Node(3))), 3, 4)
self.assertListEqual(lst.to_array(), [1, 2, 3, 4])
def test_delete_start(self):
lst = delete(Node(1, Node(2, Node(3))), 0)
self.assertListEqual(lst.to_array(), [2, 3])
def test_delete_end(self):
lst = delete(Node(1, Node(2, Node(3))), 2)
self.assertListEqual(lst.to_array(), [1, 2])
def test_delete_middle(self):
lst = delete(Node(1, Node(2, Node(3))), 1)
self.assertListEqual(lst.to_array(), [1, 3])
if __name__ == '__main__':
unittest.main(verbosity=2)
|
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Calculate the `n`-th value of the Fibonacci sequence.
Time: O(n)
Memory: O(1)
"""
import sys
import unittest
def calculate(n, result = 0, nxt = 1):
if n == 0:
return result
else:
return calculate(n - 1, nxt, nxt + result)
class Test (unittest.TestCase):
def test_for_0(self):
self.assertEqual(calculate(0), 0)
def test_for_1(self):
self.assertEqual(calculate(1), 1)
def test_for_4(self):
self.assertEqual(calculate(4), 3)
def test_for_12(self):
self.assertEqual(calculate(12), 144)
def test_for_30(self):
self.assertEqual(calculate(30), 832040)
if __name__ == '__main__':
if sys.stdin.isatty():
unittest.main(verbosity = 2)
else:
print(calculate(int(sys.stdin.readline())))
|
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Pick `count` randomly selected items from `array`.
(Uses Fisher-Yates shuffle algorithm.)
Time: O(count)
"""
import random
import unittest
def pick_random(array, count):
shuffled_by_pos = {}
elems = []
for i in range(0, len(array)):
if len(elems) == count:
return elems
j = random.randint(i, len(array) - 1)
elem_i = shuffled_by_pos.get(i, array[i])
elem_j = shuffled_by_pos.get(j, array[j])
shuffled_by_pos[i] = elem_j
shuffled_by_pos[j] = elem_i
elems.append(shuffled_by_pos.pop(i))
return elems
class Test (unittest.TestCase):
def test_empty_array(self):
self.assertEqual(
pick_random([], 3),
[])
def test_no_elements(self):
self.assertEqual(
pick_random(list('example'), 0),
[])
def test_all_elements(self):
self.assertCountEqual(
pick_random(list('hello world'), 11),
'hello world')
def test_more_elements_than_array(self):
self.assertCountEqual(
pick_random(list('example'), 100),
'example')
def test_some_elements(self):
array = list('marcio')
elements = pick_random(array, 3)
self.assertEqual(len(elements), 3)
self.assertCountEqual(set(elements), elements)
for element in elements:
self.assertIn(element, array)
if __name__ == '__main__':
unittest.main(verbosity = 2)
|
arsenal = input().split(":")
commands = input().split()
the_deck = []
while not commands[0] == "Ready":
command = commands[0]
card = commands[1]
if command == "Add":
if card in arsenal:
the_deck.append(card)
else:
print("Card not found.")
elif command == "Insert":
index = int(commands[2])
if (card in arsenal) and (index in range(0, len(the_deck))):
the_deck.insert(index, card)
else:
print("Error!")
elif command == "Remove":
if card in the_deck:
the_deck.remove(card)
else:
print("Card not found.")
elif command == "Swap":
card_1_index = the_deck.index(card)
card_2_index = the_deck.index(commands[2])
the_deck[card_1_index], the_deck[card_2_index] = the_deck[card_2_index], the_deck[card_1_index]
elif command == "Shuffle":
the_deck.reverse()
commands = input().split()
print(f"{' '.join(the_deck)}") |
# nai barzoto reshenie
# divizor = int(input())
# bound = int(input())
# res = int(bound / divizor) * divizor
# print(res)
divizor = int(input())
bound = int(input())
for num in range(bound, 0, -1):
if num % divizor == 0:
print(num)
break
|
class Zoo:
__animals = 0
def __int__(self, name):
self.name = name
self.mammals = []
self.fishes = []
self.birds = []
def add_animal(self, species, names):
if species == 'mammal':
self.mammals.append(names)
elif species == 'fish':
self.fishes.append(names)
elif species == 'birds':
self.birds.append(names)
Zoo.__animals += 1
def get_info(self, species):
result = ''
if species == 'mammal':
result += f"{species} in {self.name}: {', '.join(self.mammals)}"
elif species == 'fish':
result += f"{species} in {self.name}: {', '.join(self.fishes)}"
elif species == 'birds':
result += f"{species} in {self.name}: {', '.join(self.birds)}"
return result
zoo_name = input()
zoo = Zoo(zoo_name)
count = int(input())
for i in range(count):
animal = input().split()
species = animal[0]
name = animal[1]
zoo.add_animal(species, name)
info = input()
print(zoo.get_info(info))
|
text = input()
if text == 'Johnny':
print(f'Hello, my love!')
elif text == text:
print(f'Hello, {text}!')
|
number_1 = int(input())
number_2 = int(input())
number_3 = int(input())
def sum_numbers(num_1, num_2):
return num_1 + num_2
def subtract(sum, three_num):
return sum - three_num
def add_and_subtract(one, two, three):
sum = sum_numbers(one, two, )
res = subtract(sum, number_3)
print(res)
add_and_subtract(number_1, number_2, number_3)
|
string = input()
digits = []
letters = []
other = []
for char in string:
if char.isalpha():
letters.append(char)
elif char.isdigit():
digits.append(char)
else:
other.append(char)
print(''.join(digits))
print(''.join(letters))
print(''.join(other)) |
budget = float(input())
flour = float(input())
cozunak_count = 0
eggs_count = 0
praice_eggs = flour * 0.75
praice_milk = (flour * 0.25) + flour
milk_needet = praice_milk *0.25
cozunak_praice = praice_eggs + milk_needet + flour
while budget > cozunak_praice:
cozunak_count +=1
eggs_count += 3
budget -= cozunak_praice
if cozunak_count % 3 == 0:
eggs_lost = cozunak_count - 2
eggs_count -= eggs_lost
print(f'You made {cozunak_count} cozonacs! Now you have {eggs_count} eggs and {budget:.2f}BGN left.')
|
num_wagons = int(input())
list_wagons = [0] * num_wagons
command = input()
while command != 'End':
token = command.split()
if token[0] == 'add':
number_of_people = int(token[1])
list_wagons[-1] += number_of_people
elif token[0] == 'insert':
index = int(token[1])
number_of_people = int(token[2])
list_wagons[index] += number_of_people
elif token[0] == 'leave':
index = int(token[1])
number_of_people = int(token[2])
list_wagons[index] -= number_of_people
command = input()
print(list_wagons)
|
n = int(input())
for row in range(1, n + 1):
print("*" * row)
for negative_row in range(n-1, 0, -1):
print('*' * negative_row)
|
text = input()
result = text.split()
test = []
for num in result:
num = int(num)
num *= -1
test.append(num)
print(test) |
number_1 = int(input())
number_2 = int(input())
number_3 = int(input())
#
#
# def smallest_num(num_1, num_2, num_3):
# smolest = 0
# if num_1 < num_2 and num_1 < num_3:
# smolest = num_1
# if num_2 < num_1 and num_2 < num_3:
# smolest = num_2
# if num_3 < num_1 and num_3 < num_2:
# smolest = num_3
# return smolest
#
#
# smallest_num(number_1, number_2, number_3)
# print(smallest_num(number_1, number_2, number_3))
# def smallest_num( a, b, c):
# print(min(a, b, c))
#
#
#
#
# smallest_num(number_1, number_2, number_3) |
#wap to print first three elements of list
list=[1,2,3,4]
print(list[0:3])
#wap to print last 3 elements from list
list=[1,2,3,4]
print(list[-3:])
#wap to print only even position elements from the list -index-0,2,4
list=[1,2,3,4]
print(list[0::2])
#wap to print only odd position from list
list=[1,2,3,4]
print(list[1::2])
#wap to print the list in reverse order
list=[1,2,3,4]
print(list[::-1])
#Tuple -It is a collection of different data elements separated by comma within in round brackets
#it is immutable
print("Demo for tuple")
print("tuples are used to store the data items/elements of any type")
print("tuple are immutable")
tup=(1,2,2,3,4,5)
print("the tuple members are",tup)
tup1=("one","two","three","four")
print("Tthe tuple of string",tup1)
tup2=(1,2,3,"one","two","three")
print("tuple of mixed ",tup2)
print("type of tuple",type(tup2))
print("we can print the tuple using for loop")
for i in tup:
print(i,end=' ')
print("code to check whether an element is present in tuple or not")
if 1 in tup2:
print("present")
else:
print("absent")
if 6 in tup:
print("present")
else:
print("absent")
print("trying to delete the elements")
del tup2[2]
print(tup2)#it will give error because we cannot delete items in tuple
#we can delete tuple as a whole
del tup2 #It deletes the whole tuple.
#slice a tuple from 3rd index to last index
tup=(1,2,3,4,5)
print(tup[2:])
#slice a tuple from second last index to first
tup=(1,2,3,4,5)
print(tup[:-1])
#slice a tuple in reverse order
tup=(1,2,3,4,5)
print(tup[::-1])
#slice a tuple printing even elements
tup=(1,2,3,4,5)
print(tup[0::2])
#slice a tuple to print only last element
tup=(1,2,3,4,5)
print(tup[-1])
#slice a tuple to print 2nd last element
tup=(1,2,3,4,5)
print(tup[-2])
#some functions under tuple
#sorted() function used to sort the tuple, ascending by default
tup=(5,6,7,1,3,2,9,12,14,23,12)
print(sorted(tup)) #returns a list of sorted elements
tup2=("nashik","pune","nagpur","kolhapur")
print(sorted(tup2))
#tuple concatenation
tup=("nashik","pune","aurangabad","kolhapur")
tup1=(1,2,3,4)
print("tuple 1 values ",tup)
print("the 2nd tuple is ",tup2)
tup3=tup+tup1
print("concatenated tuple is ",tup3)
#find the index of an element in tuple
tup1=(1,2,3,4)
idx=tup1.index(2)
print("the index of position 2 is ",idx)
#counting no of occurrence of an element
tup=(11,12,13,15,11)
n=tup.count(11)
print("no of occurences of 11 is ",n)
#length of tuple
tup=(1,2,3,4)
length=len(tup)
print("the length of given tuple is ",length)
print("prints the minimum element in tuple ",min(tup))
print(" prints the maximum number of element in tuple ",max(tup))
tup1=("Aniket","ABC","A")
print(min(tup1)) #prints string of minimum length
#sets
'''
1.unordered collection of various items enclosed within curly braces
2.the elemetns of the set cannot be duplicate
3.the elements of the python set must mutable
4.no index attachd to the element of the set
5.directly access any element of the set by ht index.
'''
print("demo for python set")
print("creating the set of days")
days={"monday","tuesday","wednesday","thursday","friday","saturday","sunday"}
print("the original set is ",days)
print("the type of set is ",type(days))
#looping in the set
for i in days:
print(i,end=' ')#same memory area is referred
#converting a list into set
print("converting list to set")
list=["ANiket","homosapiens","ottman"]
print("the original element is ",list)
number =set(list)
print("the converted list is ",number)
print("printing the set using for loop ",number)
for i in number:
print(i,end=' ')
#adding element to the set
number={1,2,3,4,5}
number.add(6)
number.add(7)
print("the modified list is ",number)
#adding multiple elements to set
number={1,2,3,4,5,6}
number.update([6,7,8,9])
print(number)
print("removing the elements using the discard()")
number={1,2,3,4,5}
number.discard(2)
print(number)
print("removing the elements using the remove()")
number={1,2,3,4,5}
number.remove(2)
print(number)
#remove all the elements from set
tup={1,2,3,4}
tup.clear()
print(tup)
day1={"Sunday","monday","tuesday"}
day2={"wednesday","thursday","friday"}
print("The day1 is ",day1)
print("day2 is here",day2)
#union
print("union of day1 and day2",day1.union(day2))
print("union of day1 and day2",day1|day2) #using pipe symbol
#intersection
day1={"Sunday","monday","tuesday","thursday"}
day2={"wednesday","thursday","friday"}
print("intersection between two sets is ",day1.intersection(day2))
print("intersection between two sets is ",day1&day2)
#Dictionary:collection of different elements in key value pairs enclosed in curly brackets
print("demo for dictionary in python")
d1={'id':101,'name':"rohan",'marks':75,'city':"pune"}
#key:value key/value number/string
print("the dict is",d1)
d1={1:"nashik",2:"pune",3:"khalapur"}
print("the dict is :",d1)
d1['Nsk']=103 #adding element d1[key]=value
d1['aug']=104
print(d1[1]) #accessing the element using key
print(d1[3])
d2={} #empty dict
d2[0]=101
d2[1]=102
print("the dict is ",d2)
a=d2.get(1) #using get() to print the element for the key
print("the element is ",a)
#deleting the element from dict.
print("removing the element using pop() from dict")
print("the dict is ",d1)
#d1.pop() #error-atleast one argument is required
print("the dict is ",d1)
d1.pop(2) #key
print("the dict is ",d1)
d1.pop('Nsk') #removing the element using pop()
print(d1)
#delete a dictionary/clear a dictionary
d1={"nashik":1,"pune":1,"goa":3}
print("the dict is ",d1)
d1.clear() #deleting all the elements from dict
print("after clear function")
print("the dict is ",d1)
#deletes the dictionary completely
d3={"nashik":1,"pune":1,"goa":3}
del d3 #
#iterate a dictionary
d1={1:"nashik",2:"pune",3:"khalapur","nsk":103,"aug":105,"pun":106}
print("printing only the keys from dict")
for x in d1: #printing the key
print("the key is",x)
print("***********************")
print("printing only the values from dict")
for x in d1: #printing the value
print("the value is ",d1[x])
print("************************")
print("printing the values from dict")
for x in d1.values(): #printing the values
print("the value is",x)
print("*************************")
print("printing the keys and values using items form dict")
for x,y in d1.items(): #printing keys and values
print("the key is ",x," the value is ",y)
#length of dictionary
d1={1:"Nashik",2:"Pune"}
print("length is ",len(d1))
#sort the dict
d1={1:"Nashik",2:"Pune"}
print("length is ",sorted(d1))
d1={1:"Nashik",2:"Pune"}
for x,y in d1.items(): #printing keys and values
if x==1:
print("it is present")
#converting tuple to dictionary
tup=((1,"one"),(2,"two"),(3,"three"))
print("the tup is ",tup)
print("converting a tuple to dictionary")
print(dict(tup))
#converting list to dictionary
lst=[[1,"one"],[2,"two"]]
print(dict(lst))
#create a dictionary student with student details
stud={1:{"name":"Aniket","std":"TE","Div":"B"},2:{"name":"Somesh","std":"TE","Div":"B"},3:{"name":"Gitesh","std":"TE","div":"A"}}
print(stud)
#adding elements to student dictionary
stud[3]["name"]="Pushkar"
stud[3]["std"]="TE"
stud[3]["div"]="B"
print(stud)
#delete one element from student dictionary
del stud[3]["name"]
print(stud)
#return an element with key 2 from student dictionary
del stud[1]
print(stud)
#print only the keys from student dictionary
stud={1:{"name":"Aniket","std":"TE","Div":"B"},2:{"name":"Somesh","std":"TE","Div":"B"},3:{"name":"Gitesh","std":"TE","div":"A"}}
for i in stud:
print(i)
#print the values of dict
for i in stud.values():
print(i)
#Create employee dictionary
emp={1:{"ename":"ABC","salary":-1000},2:{"ename":"PQR","salary":1000}}
#print the emp dict
print(emp)
for i in emp:
if emp[i]["salary"]==-1000:
del emp[i]["salary"]
print(emp) |
"""
LeetCode 791. Custom Sort String
S and T are strings composed of lowercase letters. In S, no letter occurs more than once.
S was sorted in some custom order previously. We want to permute the characters of T so
that they match the order that S was sorted. More specifically, if x occurs before y in S,
then x should occur before y in the returned string.
Return any permutation of T (as a string) that satisfies this property.
Example :
Input:
S = "cba"
T = "abcd"
Output: "cbad"
Explanation:
"a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are
also valid outputs.
Note:
S has length at most 26, and no character is repeated in S.
T has length at most 200.
S and T consist of lowercase letters only.
"""
from collections import Counter
def custom_string_sorting(s, t):
"""
:param s: String 1
:param t: String 2
:return: Output string computed from given conditions
"""
output = ''
dict_s = Counter(s)
dict_t = Counter(t)
for key in dict_s:
if dict_t.get(key):
count = dict_t.pop(key)
output += key * count
for key in dict_t:
count = dict_t[key]
output += key * count
return output
|
"""
LeetCode 434. Number of Segments in a String
Count the number of segments in a string, where a segment is defined to be a
contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:
Input: "Hello, my name is John"
Output: 5
"""
def no_of_segments_in_a_string(input_string):
"""
:param input_string: Input string
:return: Number of segments separated by a space
"""
# input_string = input_string.strip()
# if len(input_string) == 0:
# return 0
# string.split() handles extra spaces by itself
return len(input_string.split())
|
"""
LeetCode 461. Hamming Distance
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
"""
def hamming_distance(x, y):
"""
:param x: First Integer
:param y: Second Integer
:return: Returns hamming distance between two integers
"""
binary_x = list(map(lambda bit: int(bit), format(x, 'b')))
binary_y = list(map(lambda bit: int(bit), format(y, 'b')))
len_diff = abs(len(binary_y) - len(binary_x))
count = 0
if len(binary_x) < len(binary_y):
temp_x = [0 for _ in range(0, len_diff)]
temp_x.extend(binary_x)
binary_x = temp_x
else:
temp_y = [0 for _ in range(0, len_diff)]
temp_y.extend(binary_y)
binary_y = temp_y
for i in range(0, len(binary_x)):
if binary_x[i] ^ binary_y[i]:
count += 1
return count
def hamming_distance(x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
x = x ^ y
y = 0
while x:
y += 1
x = x & (x - 1)
return y
|
"""
LeetCode 922. Sort Array By Parity II
Given an array A of non-negative integers, half of the integers in A are odd,
and half of the integers are even.
Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.
You may return any answer array that satisfies this condition.
Example 1:
Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
Note:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
"""
def sort_array(a):
"""
:param a: Input Array
:return: Sorted Array
"""
output = []
even_index = 0
odd_index = 1
for ele in a:
if ele % 2 == 0:
output.insert(even_index, ele)
even_index += 2
else:
output.insert(odd_index, ele)
odd_index += 2
return output
def sort_array_second(a):
"""
:param a: Input Array
:return: Sorted Array
"""
even_index = 0
odd_index = 1
size = len(a)
while even_index < size and odd_index < size:
if a[even_index] % 2 == 0:
even_index += 2
elif a[odd_index] % 2 == 1:
odd_index += 2
else:
a[even_index], a[odd_index] = a[odd_index], a[even_index]
even_index += 2
odd_index += 2
return a
|
"""
LeetCode 345. Reverse Vowels of a String
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello"
Output: "holle"
Example 2:
Input: "leetcode"
Output: "leotcede"
Note:
The vowels does not include the letter "y".
"""
def reverse_vowels_of_a_string(str):
"""
:param str: Input String
:return: Reversed string
"""
low = 0
high = len(str) - 1
vowels = ["a", "e", "i", "o", "u"]
str_list = list(str)
while low < high:
if str_list[low].lower() not in vowels:
low += 1
elif str_list[high].lower() not in vowels:
high -= 1
else:
str_list[low], str_list[high] = str_list[high], str_list[low]
low += 1
high -= 1
return "".join(str_list)
|
# Data inspection
# Variables can be inspected in the VARIABLES section of the Run view or by hovering over their source in the editor
# Variables and expressions can also be evaluated and watched in the Run view's WATCH section.
# By using the Call Stack window, you can view the function or procedure calls that are currently on the stack. The Call Stack window shows the order in which methods and functions are getting called. The call stack is a good way to examine and understand the execution flow of an app.
def foo():
bar()
def bar():
pass
foo()
# TODO: https://www.sqlshack.com/how-to-debug-python-scripts-in-visual-studio-code/
# Variables Pane – Using the variables pane you can easily inspect the data elements within your program. When you start debugging a lot of system-defined variables are initiated along with the user-defined variables. During the debugging session, you can verify the values of each of those variables from this pane.
# Watch Pane – Sometimes you may write a program with hundreds of variables within it. It is not possible to monitor the values of all those variables from the Variables pane as mentioned above. In such a case, you might want to monitor only one or two variables of your choice leaving the worry about the rest. You can add those variables to your watch list, and you can easily monitor the status and the values for those particular variables within this pane.
# Call Stack(Frames) Pane – This is helpful when your code has a lot of inner methods and you navigate deep inside a stack and then you might lose track of your stack. When there is any error in your program you can easily know from which stack is the error has occurred and then debug it accordingly.
|
# WORKING WITH STRINGS
# Printing a string
# print("Giraffe Academy")
# Create a new line in string
# print("Giraffe\nAcademy")
# Putting a quotation mark inside a string
# print("Giraffe\"Academy")
# String variable
# phrase = "Giraffe Academy"
# print(phrase)
# Concatenation
# phrase = "Giraffe Academy"
# print(phrase + " is awesome")
# Functions in string:
# ~Turn the entire string to lower case
# phrase = "Giraffe Academy"
# print(phrase.lower())
# ~Turn the entire string to upper case
# phrase = "Giraffe Academy"
# print(phrase.upper())
# ~Check if the entire string is in upper case
# phrase = "Giraffe Academy"
# print(phrase.isupper())
# ~Turn the entire string to upper case then check if the entire string is in upper case
# phrase = "Giraffe Academy"
# print(phrase.upper().isupper())
# ~Figure out how many characters are inside the string
# phrase = "Giraffe Academy"
# print(len(phrase))
# ~Grab an individual character in a string
# phrase = "Giraffe Academy"
# 0123456789.....
# print(phrase[0])
# print(phrase[3])
# ~Tell where a specific character is located in a string
# phrase = "Giraffe Academy"
# print(phrase.index("G"))
# print(phrase.index("a"))
# print(phrase.index("Acad"))
# print(phrase.index("z"))
# ~Replace function
# phrase = "Giraffe Academy"
# print(phrase.replace("Giraffe", "Elephant"))
|
import sys
def fixSentance(aString):
x = 0
while (x != 1):
temp = aString
temp.split('.')
print temp.split('.')
temp = temp.replace('_',' ').strip().lower().capitalize()
if ((temp[-1] != '.') & (temp[-1] != '!') & (temp[-1] != '?')):
temp = temp + '.'
return temp
stringToFix = str(sys.argv[1])
print fixSentance(stringToFix)
# fixSentance
|
import re
def camel_to_lowdash(word):
word=word.group(0)
res=''+word[0].lower()
for letter in word[1:]:
if letter.isupper():
res+='_'+letter.lower()
else:
res+=letter
return res
def remove_camel(text_string):
camel=re.compile(r"([a-z]+([A-Z][a-z]+)+)|([A-Z][a-z]+){2,}")
return re.sub(camel, camel_to_lowdash, text_string)
|
#Sort the list alphabetically:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
#Sort the list numerically:
thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)
#Sort the list descending:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)
#Sort the list based on how close the number is to 50:
def myfunc(n):
return abs(n - 50)
thislist = [100, 50, 65, 82, 23]
thislist.sort(key = myfunc)
print(thislist)
#Perform a case-insensitive sort of the list:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)
#Reverse the order of the list items:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)
|
n1 = input("Enter the no 1")
n2 = input("Enter the no 2")
n3 = input("Enter the no 3")
if (n1<n2 and n1<n3):
l1 = n1
elif (n2<n1 and n2<n3):
l1 = n2
elif (n3<n1 and n3<n2):
l1 = n3
print ("Small est Number", l1) |
class Animal(object):
def __init__(self, species):
self.species = species
def display(self):
print(self.species)
obj = Animal(species="Lion")
obj.display()
class Parent(object):
def __init__(self):
print("Parent")
def parentfunc(self):
print("Parent Fun")
class Child(Parent):
def __init__(self):
print("You Are In child")
objp = Parent()
objc = Child()
objc.parentfunc()
print(type(objc))
print(type(objp))
print(type(Parent))
class Parent(object):
color = input("Enter color")
def __init__(self, height,color):
self.height = height
self.color = color
def display(self):
print("Color:" +self.color)
print("Height:" + self.height)
objp =Parent(5.6)
objp.display()
|
# -*- coding: utf-8 -*-
"""Demonstrate high quality docstrings."""
from random import randint
def quickselect(arr, k):
"""Doc String."""
pivot = randint(0, len(arr))
sub_min = [i for i in arr if i < arr[pivot]]
sub_pls = [i for i in arr if i > arr[pivot]]
v = len(sub_min) + 1
if v == k:
return arr[pivot]
else:
if v > k:
return(quickselect(sub_min, k))
else:
return(quickselect(sub_pls, k - v))
arr = [65, 28, 59, 33, 21, 56, 22, 95, 50, 12, 90, 53, 28, 77, 39]
print(quickselect(arr, 8))
|
# This function finds the square root of a number to within 0.0001
# This does not use anything imported from math
import sys
def toBRooted():
"""
This function takes the number to be square rooted from the user
Input: None
Output: User defined number and whether it is positive or negative
"""
try:
number = float(raw_input("What number do you want the square root of? "))
except ValueError:
print("That is not a valid input. Bye. ")
sys.exit()
if number < 0:
return number, "neg"
return number, "pos"
def root(number, epsilon):
"""
This function finds the square root of a number
Input: Number whose square root is to be found and tolerance
Output: Square root correct to 0.0001
"""
lowerLimit = 0
upperLimit = number
root = float(0.5*(lowerLimit+upperLimit)) # root starts off as midway point
while True: # True is used here because this method always converges
square = root*root
if square >= number:
if square - number < epsilon:
return round(root, 4) # Rounds it to desired accuracy
else:
upperLimit = root
root = float(0.5*(lowerLimit+upperLimit)) # Find new midway
else:
if number - square < epsilon:
return round(root, 4)
else:
lowerLimit = root
root = float(0.5*(lowerLimit+upperLimit)) # Find new midway
def main():
epsilon = 0.000001 # This determines convergence condition
number = toBRooted()
# If the number is positive, find the square root of the positive part
# Then tack on a '0i' as the imaginary part is 0
if number[1] == "pos":
sroot = root(number[0], epsilon)
print("The answer is: " + str(sroot) + " + 0 i" + "\n... Bye")
# If the number is negative, strip the positive part and find its squareroot
# Then tack on an 'i' for imaginary with the real part being 0
else:
sroot = root(-1*number[0], epsilon)
print("The answer is: " + "0 + " + str(sroot) + " i" + "\n... Bye")
if __name__ == "__main__":
main() |
from tkinter import *
ventana =Tk()
ventana.title("Calculadora")
ventana.configure(bg="grey")
#recursos
mensaje = StringVar()
#Funciones a usar para las cuatro operaciones aritmentias
def sumar():
a=int(e_texto.get())
b=int(e_texto2.get())
print(a," + ",b)
print('la suma es: ',a+b)
mensaje.set(a+b)
e_texto.delete(0, END)
e_texto2.delete(0, END)
def restar():
a=int(e_texto.get())
b=int(e_texto2.get())
print(a, " - ", b)
print('la resta es: ',a-b)
mensaje.set(a-b)
e_texto.delete(0, END)
e_texto2.delete(0, END)
def mult():
a=int(e_texto.get())
b=int(e_texto2.get())
print(a, " * ", b)
print('la multiplicacion es: ',a*b)
mensaje.set(a*b)
e_texto.delete(0, END)
e_texto2.delete(0, END)
def div():
a=int(e_texto.get())
b=int(e_texto2.get())
print(a, " / ", b)
print('la divicion es: ',a/b)
mensaje.set(a/b)
e_texto.delete(0, END)
e_texto2.delete(0, END)
#Entrada de texto
e_texto=Entry(ventana,bg="black",fg="white",justify='center')
e_texto2=Entry(ventana,bg="black",fg="white",justify='center')
salida=Label(ventana,textvariable=mensaje,justify='center',bg='grey')
msj=Label(ventana,text="Respuesta:",justify='center',bg='grey')
e_texto.grid(row=0,column=0,columnspan=2,padx=5,pady=5)
e_texto2.grid(row=0,column=2,columnspan=2,padx=5,pady=5)
salida.grid(row=4,column=1,columnspan=2,padx=5,pady=5)
msj.grid(row=4,column=0,columnspan=2,padx=5,pady=5)
#botones
btn_sum=Button(ventana,bg="grey",bd=5, text="+", width=5,height=2,command = lambda: sumar())
btn_rest=Button(ventana,bg="grey",bd=5, text="-", width=5,height=2,command = lambda: restar())
btn_mult=Button(ventana,bg="grey",bd=5, text="*", width=5,height=2,command = lambda: mult())
btn_div=Button(ventana,bg="grey",bd=5, text="/", width=5,height=2,command = lambda: div())
#agregamos los botones a la pantalla
btn_sum.grid(row=2,column=0,padx=5,pady=5)
btn_rest.grid(row=2,column=1,padx=5,pady=5)
btn_mult.grid(row=2,column=2,padx=5,pady=5)
btn_div.grid(row=2,column=3,padx=5,pady=5)
#fin del programa
ventana.mainloop()
print('***GRACIAS POR USAR EL PROGRAMA') |
# Scrape the NASA Web Page
# and collect the latest News Title and Paragraph Text.
# Assign the text to variables that you can reference later.
def init_browser():
executable_path = {"executable_path": "mission_to_mars\chromedriver"}
return Browser("chrome", **executable_path, headless=False)
def scrape_info():
browser = init_browser()
# Visit https://mars.nasa.gov/news/
url = "https://mars.nasa.gov/news/"
browser.visit(url)
time.sleep(1)
# Scrape page into Soup
html = browser.html
soup = bs(html, "html.parser")
# Find the article title
article_title = soup.find('div', id='content_title').text
# Get the article paragraph
article_teaser = soup.find('div', id='article_teaser_body').text
# Store data in a dictionary
article_data = {
"news_title": article_title,
"news_teaser": article_teaser
}
# Close the browser after scraping
browser.quit()
# Return results
return article_data
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the bonAppetit function below.
def bonAppetit(bill, k, b):
total=0
i=0
while i<(len(bill)):
if(i!=k):
total=total+int( bill[i])
i+=1
else:
i+=1
if((total//2)-b==0):
return('Bon Appetit')
else:
return abs((total//2)-b)
if __name__ == '__main__':
nk = input().rstrip().split()
n = int(nk[0])
k = int(nk[1])
bill = list(map(int, input().rstrip().split()))
b = int(input().strip())
result=bonAppetit(bill, k, b)
print(result)
|
########################################
# PROJECT XXX - Min Heap and Sort
# Author:
# PID:
########################################
class Heap:
# DO NOT MODIFY THIS CLASS #
def __init__(self, size=0):
"""
Creates an empty hash table with a fixed capacity
:param capacity: Initial size of the hash table.
"""
self.array = []
def __str__(self):
"""
Prints the elements in the hash table
:return: string
"""
return str(self.array)
def __repr__(self):
"""
Returns the string representation
:return: string representation of self
"""
return str(self)
###### COMPLETE THE FUNCTIONS BELOW ######
def get_size(self):
pass
def parent(self, i):
pass
def left(self, i):
pass
def right(self, i):
pass
def has_left(self, i):
pass
def has_right(self, i):
pass
def insert(self, value):
pass
def remove(self, value):
pass
def swap(self, i, j):
pass
def upheap(self, i):
pass
def downheap(self, i):
pass
def remove_min(self):
pass
def heapSort(unsorted):
pass
def getStats(unsorted):
pass
|
def init(data):
data['first'] = {}
data['middle'] = {}
data['last'] = {}
def lookup(data, label, name):
return data[label].get(name)
def store(data, *full_names):
for full_name in full_names:
names = full_name.split()
if len(names) == 2:
names.insert(1, '')
labels = 'first', 'middle', 'last'
for label, name in zip(labels, names):
people = lookup(data, label, name)
if people:
people.append(full_name)
else:
data[label][name] = [full_name]
d = {}#初始化data数据
init(d)
store(d, 'Mary HongSh', 'Bob HongSh')
print lookup(d, 'last', 'HongSh')
|
print("Hello World")
print("Amorcito")
print("teamo mas que tu ami")
print(type("Amorcito"))
# El simbolo mas puede servir para contactenar o sumar
# va depender si son numeros o texto
print("Bye" + "World")
# Numeros enteros o Integer
print (30)
print (30.5)
# Numeros decimales o FLOAT
print(type(30.5))
Print(type(30))
# Boolean Tipo de estado ()
False
True
#List
# Lista de varios elementos de varios tipo de datos
Print([10, 20, 30, 44])
Print(["Hello", 25, True, 10,1])
print(myStr.isnumeric())
#tuples
#Igual a una lista pero no se puede cambiar (inmutable)
print((10, 20, 30, 40))
()
{}
# Dictoriniones
print({
"name":"ryan",
"lastname":"ray",
"nickname":"fazt",
}
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.