text stringlengths 37 1.41M |
|---|
#使用“!=”表示不等于,这种情况如果不等于则返回True,如果等于则返回False
requested_topping='mushrooms'
if requested_topping!='fish':
print('Hold the fish, please!')
age=18
print(age==18)
answer=42
if answer!=42:
print('That is not the correct answer. Please try again!')
else:
print('congratulations! U r right!')
age=19
print(age<21)
print(age<=21)
print(age>21)
print(age>=21)
#需要检查适合的所有条件,有可能有多个True,每个条件为True时都采取相应措施。
requested_toppings=['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
print('Adding mushroom.')
if 'pepperoni' in requested_toppings:
print('Adding peppetoni')
if 'extra cheese' in requested_toppings:
print('Adding extra cheese.')
print('\nFinished making your pizza!')
|
# ________________________________________________________________________ #
# Written by: Vy Hoang #
# Program: Practice with strings stuff #
# This program works with strings, uses regular expressions, #
# and performs input validation tasks. #
# This program requires the use of pyperclip, a module to work #
# with the clipboard. #
# ________________________________________________________________________ #
import pyinputplus as pyip
import pyperclip
import re
print("\n###### A String that includes the five Python escape characters ######")
print("My favorite\'s movies:\n\"2012\" by Roland Emmerich\\\t\"Taken\" by Olivier Megaton\\\t"
"\"Captain Phillips\" by Paul Greengrass")
print("\n###### A raw string that includes the five Python escape characters ######")
print(r"My favorite\'s movies:\n\"2012\" by Roland Emmerich\\\t\"Taken\" by Olivier Megaton\\"
r"\t\"Captain Phillips\" by Paul Greengrass")
print("\n###### Triple quotes using single and double quote ######")
print('''My favorite\'s movies:
2012
Taken
Captain \"Phillips\"''')
print("\n###### An example of multiline comments in code ######")
"""Vy Hoang are practicing Python script.
This is example of multiline comments.
"""
print("\n\nAssign a string to a list and print characters in string")
my_string = 'Beautiful life!'
print("\nMy string: ", my_string)
print("\nA single indexed character at 0:", my_string[0])
print("\nThe character 5 index places from the end:", my_string[-5])
print("\nThe characters starting at 3 until the end:", my_string[3:])
print("\nThe characters from the beginning up to but not including character 7:", my_string[0:7])
print("\n\nDemonstrate the in and not in operators.")
print("\n\'Beautiful\' in my string:", 'Beautiful' in my_string)
print("\n\'Beautiful\' not in my string:", 'Beautiful' not in my_string)
print("\n\nDemonstrate including two strings inside another string")
first_name = 'Vy'
last_name = 'Hoang'
print("\nMy full name using \'+\' operator:", first_name + ' ' + last_name)
print("\nMy full name using string interpolation: {} {}".format(first_name, last_name))
print(f"\nMy full name using f-strings: {first_name} {last_name}")
print("\n\nDemonstrate: isalpha(), isalnum(), isdecimal(), isspace(), and istitle()")
print("\n\'life\' with string method isalpha():\t", 'life'.isalpha())
print("\n\'life123\' with string method isalpha():\t", 'life123'.isalpha())
print("\n\'life123\' with string method isalnum():\t", 'life123'.isalnum())
print("\n\'life\' with string method isalnum():\t", 'life'.isalnum())
print("\n\'123\' with string method isdecimal():\t", '123'.isdecimal())
print("\n\' \' with string method isspace():\t", ' '.isspace())
print("\n\'Life Is Beautiful!\' with string method istitle():\t\t",
'Life Is Beautiful!'.istitle())
print("\n\'Life 123 Is Beautiful!\' with string method istitle():\t",
'Life 123 Is Beautiful!'.istitle())
print("\n\'Life is NOT Beautiful!\' with string method istitle():\t",
'Life is NOT Beautiful!'.istitle())
print("\n\nUse two isX() methods in two loops (one per loop) for input validation")
while True:
user_name = input("\nEnter username: ")
if not user_name.isalnum():
print("\nUsername can only have letters (a-z), numbers (0-9) and no spaces")
else:
break
while True:
phone_num = input("\nEnter phone number: ")
if not phone_num.isdecimal():
print("\nPlease input only numbers (0-9) and no spaces")
else:
break
print("\n\nConvert a list of strings into one string using join()")
list_fruits = ['orange', 'lemon', 'apple']
string_fruits = 'Juice, '.join(list_fruits)
print("\nConvert a list of strings into one string:", string_fruits)
print("\n\nConvert one string into a list of strings using split()")
print("\nConvert one string into a list of strings", string_fruits.split('Juice, '))
print("\n\nDemonstrate the following string methods")
print("\n\'Life is so beautiful\' with string method partition():",
'Life is so beautiful'.partition('is'))
print("\n\' Life \' with string method center(25):", ' Life '.center(25))
print("\n\'BadLife\' with string method strip('adB'):", 'BadLife'.strip('adB'))
print("\nReturn an integer \'65\' with string method ord('A'):", ord('A'))
print("\nReturn a character \'A\' with string method chr(65):", chr(65))
print("\n\nDemonstrate the following using pyperclip copy() and paste()")
my_text = 'The days are long but the years are short!'
pyperclip.copy(my_text.upper().join('""'))
print("\nNew replacement pasted from clipboard:", pyperclip.paste())
print("\n\nUse regular expressions to verify the user id "
"supplied by the user meets format")
ID = input("\nEnter user ID in format AAAA-####: ")
idRegex = re.compile(r'^[a-zA-Z]{4}([-][0-9]{4})')
while True:
matchID = idRegex.search(ID)
if not matchID:
print("\nIncorrect user ID.")
ID = input("\nRe-Enter user ID in format AAAA-####: ")
else:
break
print("\n\nVerify that one of the user ids in the list has been entered.")
accepted_IDs = ["gdrt-8493", "DBTF-6253", "UyHt-8326", "YYrv-5329", "qzrb-8264"]
print("The id list: ", accepted_IDs)
# Display a message the id match in the list
if matchID.group() in accepted_IDs:
print("\nThank you for entering your user ID.")
print("\n\nUse regular expressions to verify the phone number"
" supplied by the user meets format")
phoneNum = input("Enter your phone number in format ###-###-###-####: ")
phoneRegex = re.compile(r'(\d{3})-(\d{3})-(\d{3})-(\d{4})')
while True:
matchPhone = phoneRegex.search(phoneNum)
if not matchPhone:
print("\nIncorrect phone number.")
phoneNum = input("\nRe-Enter phone number in format ###-###-###-####: ")
else:
break
print("\n\nVerifying the phone number meets the format,"
" verify the call is being placed to one of the countries below")
accepted_calls = {"Andorra": "376", "Bolivia": "591", "Djibouti": "253",
"Georgia": "995", "Lithuania": "370"}
print("The placed call list: ", accepted_calls)
# Display a message after successful entry
for index in accepted_calls:
if matchPhone.group(1) == accepted_calls[index]:
print("\nYour call has been placed. Thank you for calling", index.join(' .'), sep="")
# Demonstrate five PyInputPlus functions to validate input
print("\n######### Validate inputNum() ########")
print(pyip.inputNum("\nEnter a number: "))
print("\n######### Validate inputDate() ########")
print(pyip.inputDate("\nEnter a date : "))
print("\n######### Validate inputYesNo() ########")
print(pyip.inputYesNo("\nDo you like Python? (y/n): "))
print("\n######### Validate inputChoice() ########")
fruits = ['apple', 'banana', 'orange']
print("\nYour choice:", pyip.inputChoice(fruits))
print("\n######### Validate inputMenu() ########")
print("\nYour fruit:", pyip.inputMenu(fruits, numbered=True))
# Demonstrate the following PyInputPlus keyword arguments
print("\n######### Keyword arguments min, max ########")
print(pyip.inputInt("\nEnter a number (min=70, max=100): ", min=70, max=100))
print("\n######### Keyword arguments greaterThan, lessThan ########")
print(pyip.inputNum("\nEnter a number (3<num<5): ", lessThan=5, greaterThan=3))
print("\n######### Keyword arguments limit, timeout, default ########")
print(pyip.inputEmail("\nEnter your email1(limit=3): ", limit=3, default='\nFailed Input!'))
print(pyip.inputEmail("\nEnter your email2(timeout=10): ", timeout=10, default='\nTime Out!'))
print("\n######### Keyword arguments allowRegexes and block Regexes ########")
print(pyip.inputNum("\nEnter a positive number: ", blockRegexes=[r'-[\d]']))
print(pyip.inputNum("\nEnter a number with spaces: ", allowRegexes=[r'\s']))
|
# DS 212 Homework 2 Python3 Edition
# TJ Liggett
import pandas as pd
import numpy as np
Player = ['Liggett', 'Theis', 'Balliette', 'Kujawa', 'Schwartz', 'Baker', 'Gubbrud', 'Wickersham', 'Hoops', 'Wallace', 'Herding', 'Boike', 'Witter']
#Position: Vector of player positions
Position = ['Will', 'Will', 'Mike', 'Sam', 'Mike', 'Sam', 'Will', 'Sam', 'Will', 'Mike', 'Sam', 'Will', 'Mike']
#Hometown: Hometown of each player
Hometown = ['Rosemount', 'Germantown', 'Bradenton', 'Waukesha', 'Mankato', 'Apple Valley', 'St. Paul', 'Brandon', 'Storm Lake', 'Kansas City', 'Mankato', 'Dawson', 'Miramar']
#State: Vector of the home states of players
State = ['Minnesota', 'Wisconsin', 'Florida', 'Wisconsin', 'Minnesota', 'California', 'Minnesota', 'South Dakota', 'Iowa', 'Missouri', 'Minnesota', 'Minnesota', 'Florida']
#Year: Year of eligibility for each player
Year = ['Sophomore', 'Senior', 'Junior', 'Senior', 'Junior', 'Freshman', 'Junior', 'Sophomore', 'Freshman', 'Redshirt', 'Redshirt', 'Redshirt', 'Sophomore']
#Number: Roster number for each player
Number = [43, 47, 33, 35, 57, 29, 37, 41, 46, 51, 50, 48, 16]
#Using the six vectors, create a dataframe
d = {'Player':Player, 'Position': Position, 'Hometown': Hometown, 'State':State, 'Year':Year, 'Number':Number}
df = pd.DataFrame(d)
#print the dataframe and summary
print(df)
print(df.describe())
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from utils import time_it, assert_sort
@assert_sort
@time_it
def radix_sort(sort_list: list) -> list:
def counting_sort(sort_list: list, exp: int) -> list:
k = 10
counting_list = [0] * k
result = [0] * len(sort_list)
for num in sort_list:
counting_list[(num // exp) % 10] += 1
for i in range(1, k):
counting_list[i] += counting_list[i - 1]
for j in range(len(sort_list) - 1, -1, -1):
result[counting_list[(sort_list[j] // exp) % 10] - 1] = sort_list[j]
counting_list[(sort_list[j] // exp) % 10] -= 1
return result
max_num = max(sort_list)
exp = 1
while max_num//exp > 0:
sort_list = counting_sort(sort_list, exp)
exp *= 10
return sort_list
if __name__ == '__main__':
raw_list = [15, 489, 45, 4, 28, 16, 73, 45, 85, 96, 26, 87, 26, 51, 32] * 100
print(radix_sort(raw_list))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from utils import time_it, assert_sort
@assert_sort
@time_it
def merge_sort(sort_list: list) -> list:
"""
归并排序
1、divide: 拆分为两部分
2、conquer: 对每一部分进行排序,调用自己
3、combine: 将排序好的两部分,merge到一起
:param sort_list:
:return: sorted list
"""
if len(sort_list) < 2:
return sort_list
left_list = sort_list[:len(sort_list)//2]
right_list = sort_list[len(sort_list)//2:]
sorted_list = []
sorted_left = merge_sort(left_list)
sorted_right = merge_sort(right_list)
while len(sorted_left) and len(sorted_right):
if sorted_left[0] <= sorted_right[0]:
sorted_list.append(sorted_left.pop(0))
else:
sorted_list.append(sorted_right.pop(0))
if not len(sorted_left):
sorted_list.extend(sorted_right)
if not len(sorted_right):
sorted_list.extend(sorted_left)
return sorted_list
if __name__ == '__main__':
raw_list = [15, 489, 45, 4, 28, 16, 73, 45, 85, 96, 26, 87, 26, 51, 32] * 100
print(merge_sort(raw_list))
|
from tkinter import messagebox
import tkinter
from tkinter import *
root = Tk()
root.title('Math')
root.resizable(0,0)
class application(Frame):
def __init__(self,master,*args,**kwargs):
Frame.__init__(self,master,*args,**kwargs)
global hit
self.hit = False
global ans
self.ans = '0'
self.create_display(25,'Pocket Calculator')
# ------
# ------
def create_display(self,font_size,font_family):
self.display = Entry(self, font=(font_family, font_size), borderwidth=10, relief=RAISED, justify=RIGHT,width=15,bg='black',fg='white')
self.display.insert(0, '0')
self.display.grid(row='0', column='0', columnspan=4)
self.create_buttons(15, 'Verdana',1,1,'#282830','#ECF0F1')
def get_buttons_text(self, txt):
self.entry_text = self.display.get()
self.last_index = len(self.entry_text)
if self.entry_text == '0':
self.display.delete(0,END)
#self.display.insert(0,txt)
if self.hit == True:
self.display.delete(0, END)
self.display.insert(self.last_index, txt)
self.hit = False
else:
self.display.insert(self.last_index, txt)
# ------ get value
def evaluation(self):
try:
self.entry_text = self.display.get()
self.ans= self.display.get()
self.display.delete(0, END)
self.display.insert(0,eval(self.entry_text))
self.hit=True
except:
messagebox.showerror("Error", "Typing Error")
# ------ init buttons
def create_buttons(self,font_size, font_family,w,h,b,f):
# ------ / * - C Buttons
self.btn = Button(self, height=h,width=w, font=(font_family, font_size),bg=b,fg=f, borderwidth=0, text='C',command=lambda : self.display.delete(0, END))
self.btn.grid(row=1, column=0, sticky='NWNESWSE')
self.btn = Button(self, font=(font_family, font_size), text='/',borderwidth=0, bg=b, fg=f, command=lambda: self.get_buttons_text('/'))
self.btn.grid(row=1, column=1, sticky='NWNESWSE')
self.btn = Button(self, font=(font_family, font_size), text='*', borderwidth=0, bg=b, fg=f, command=lambda: self.get_buttons_text('*'))
self.btn.grid(row=1, column=2, sticky='NWNESWSE')
self.btn = Button(self, font=(font_family, font_size), text='-', borderwidth=0, bg=b, fg=f, command=lambda: self.get_buttons_text('-'))
self.btn.grid(row=1, column=3, sticky='NWNESWSE')
# ------ 7 8 9 + Buttons
self.btn = Button(self, height=h, width=w, font=(font_family, font_size),text='7', bg=b, fg=f, borderwidth=0, command=lambda: self.get_buttons_text('7'))
self.btn.grid(row=2,column=0, sticky='NWNESWSE')
self.btn = Button(self, font=(font_family, font_size), text='8', borderwidth=0, bg=b, fg=f, command=lambda: self.get_buttons_text('8'))
self.btn.grid(row=2, column=1,sticky='NWNESWSE')
self.btn = Button(self, font=(font_family, font_size), text='9', borderwidth=0, bg=b, fg=f, command=lambda: self.get_buttons_text('9'))
self.btn.grid(row=2, column=2, sticky='NWNESWSE')
self.btn = Button(self, font=(font_family, font_size), text='+', borderwidth=0, bg=b, fg=f, command=lambda: self.get_buttons_text('+'))
self.btn.grid(row=2, column=3, sticky='NWNESWSE',rowspan=2)
# ------ 4 5 6
self.btn = Button(self, height=h, width=w, font=(font_family, font_size), text='4', bg=b, fg=f, borderwidth=0, command=lambda: self.get_buttons_text('4'))
self.btn.grid(row=3, column=0, sticky='NWNESWSE')
self.btn = Button(self, font=(font_family, font_size), text='5', borderwidth=0, bg=b, fg=f, command=lambda: self.get_buttons_text('5'))
self.btn.grid(row=3, column=1, sticky='NWNESWSE')
self.btn = Button(self, font=(font_family, font_size), text='6', borderwidth=0, bg=b, fg=f, command=lambda: self.get_buttons_text('6'))
self.btn.grid(row=3, column=2, sticky='NWNESWSE')
# ----- 1 2 3 =
self.btn = Button(self, height=h, width=w, font=(font_family, font_size), text='1', bg=b, fg=f, borderwidth=0, command=lambda: self.get_buttons_text('1'))
self.btn.grid(row=4, column=0, sticky='NWNESWSE')
self.btn = Button(self, font=(font_family, font_size), text='2', borderwidth=0, bg=b, fg=f, command=lambda: self.get_buttons_text('2'))
self.btn.grid(row=4, column=1, sticky='NWNESWSE')
self.btn = Button(self, font=(font_family, font_size), text='3', borderwidth=0, bg=b, fg=f, command=lambda: self.get_buttons_text('3'))
self.btn.grid(row=4, column=2, sticky='NWNESWSE')
self.btn = Button(self, font=(font_family, font_size), text='=', borderwidth=0, bg=b, fg=f, command=lambda: self.evaluation())
self.btn.grid(row=4, column=3, sticky='NWNESWSE', rowspan=2)
# ------ 0 .
self.btn = Button(self, height=h, width=w, font=(font_family, font_size), text='0', bg=b, fg=f, borderwidth=0, command=lambda: self.get_buttons_text('0'))
self.btn.grid(row=5, column=0, columnspan=2, sticky='NWNESWSE')
self.btn = Button(self, font=(font_family, font_size), text='.', borderwidth=0, bg=b, fg=f, command=lambda: self.get_buttons_text('.'))
self.btn.grid(row=5, column=2, sticky='NWNESWSE')
# ------ ans
self.btn = Button(self, font=(font_family, font_size), text='Ans', borderwidth=1, bg=b, fg=f, command=lambda: self.display.insert( 0, eval(self.ans)))
self.btn.grid(row=6, column=0, sticky='NWNESWSE',columnspan=4)
app = application(root).grid()
root.mainloop() |
#!/usr/bin/python3
"""
function that writes a string to a text file (UTF8)
and returns the number of characters written:
Prototype: def write_file(filename="", text=""):
You must use the with statement
You don’t need to manage file permission exceptions.
Your function should create the file if doesn’t exist.
Your function should overwrite the content of the file
if it already exists.
"""
def write_file(filename="", text=""):
""" write string to a file """
with open(filename, mode="w", encoding='utf-8') as file:
return (file.write(text))
|
#!/usr/bin/python3
"""
function that returns True if the object is an
instance of a class that inherited (directly or indirectly)
from the specified class ; otherwise False.
"""
def inherits_from(obj, a_class):
""" true if obj inherits from a_class """
return issubclass(type(obj), a_class) and (type(obj) != a_class)
|
#!/usr/bin/python3
"""
function that returns an object
(Python data structure) represented by a JSON string:
Prototype: def from_json_string(my_str):
You don’t need to manage exceptions if the
JSON string doesn’t represent an object.
"""
import json
def from_json_string(my_str):
""" take json str and gives a python object """
return json.loads(my_str)
|
#!/usr/bin/python3
"""
function that reads n lines of a text file (UTF8)
and prints it to stdout:
Prototype: def read_lines(filename="", nb_lines=0):
Read the entire file if nb_lines is lower or equal
to 0 OR greater or equal to the total number of lines
of the file
You must use the with statement
You don’t need to manage file permission or file doesn't
exist exceptions.
"""
def read_lines(filename="", nb_lines=0):
""" read nb_lines of a text """
with open(filename, encoding='utf-8') as f:
if (nb_lines <= 0):
print(f.read(), end="")
else:
cont = 0
while (cont < nb_lines):
print(f.readline(), end="")
cont += 1
|
#!/usr/bin/python3
"""
function that creates an Object from a “JSON file”:
Prototype: def load_from_json_file(filename):
You must use the with statement
You don’t need to manage exceptions if the JSON string
doesn’t represent an object.
You don’t need to manage file permissions / exceptions.
"""
import json
def load_from_json_file(filename):
""" creates a pythonobject from json file """
with open(filename, encoding='utf-8') as file:
return json.load(file)
|
#!/usr/bin/python3
"""
Write a function that prints a square with
the character #.
Prototype: def print_square(size):
size is the size length of the square
size must be an integer, otherwise raise a TypeError
exception with the message size must be an integer
if size is less than 0, raise a ValueError exception
with the message size must be >= 0
if size is a float and is less than 0,
raise a TypeError exception with the message size
must be an integer
"""
def print_square(size):
""" print a square """
int_error = "size must be an integer"
neg_error = "size must be >= 0"
if type(size) is not int:
raise TypeError(int_error)
if size < 0:
raise ValueError(neg_error)
for i in range(size):
print("#" * size, end="")
print()
|
'''
1. Leer dataset "clase_6_dataset"
2. Aplicar Logistic Regresion
3. Hacer fit con y = w2 *x1 + w1 * x2 + 1
4. Graficar el resultado
'''
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import KFold
from sklearn.linear_model import LogisticRegression
class Data(object):
def __init__(self, path):
self.dataset = self._build_dataset(path)
def _build_dataset(self, path):
# usar numpy esctructurado
data = np.genfromtxt(path, delimiter=',')
return data
# np.fromiter
def shape(self):
return self.dataset.shape
def add(self, offset):
self.dataset += offset
def split(self, percentage):
# retornar train y test segun el %
dim = self.dataset.ndim
X = self.dataset[:,0:dim]
y = self.dataset[:,dim]
#train_test_split(X, y, test_size=(1-percentage))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=(1-percentage))
return X_train, X_test, y_train, y_test
class CsvData(Data):
def _build_dataset(self, path):
# usar numpy esctructurado
data = np.genfromtxt(path, delimiter=',')
data = data[1:,1:]
return data
# np.fromiter
class BaseModel(object):
def __init__(self):
self.model = None
def fit(self, X, Y):
# train model
return NotImplemented
def predict(self, X):
# retorna y hat
return NotImplemented
class ConstantModel(BaseModel):
def fit(self, X, Y):
# Calcular los W y guadarlos en el modelo
W = Y.mean()
self.model = W
def predict(self, X):
# usar el modelo (self.model) y predecir
# y hat a partir de X e W
return np.ones(len(X)) * self.model
class LinearRegresion(BaseModel):
def fit(self, X, Y):
# Calcular los W y guadarlos en el modelo
if X.ndim == 1:
W = X.T.dot(Y) / X.T.dot(X)
else:
W = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Y)
self.model = W
def predict(self, X):
# usar el modelo (self.model) y predecir
# y_hat a partir de X e W
if X.ndim == 1:
return self.model * X
else:
return np.matmul(X, self.model)
class Metric(object):
def __call__(self, target, prediction):
# target --> Y
# prediction --> Y hat
return NotImplemented
class MSE(Metric):
def __call__(self, target, prediction):
# Implementar el error cuadratico medio MSE
return np.square(target-prediction).mean()
def gradient_descent(X_train, y_train, lr=0.01, amt_epochs=100):
"""
shapes:
X_t = nxm
y_t = nx1
W = mx1
"""
n = X_train.shape[0]
m = X_train.shape[1]
# initialize random weights
W = np.random.randn(m).reshape(m, 1)
for i in range(amt_epochs):
prediction = np.matmul(X_train, W) # nx1
error = y_train - prediction # nx1
grad_sum = np.sum(error * X_train, axis=0)
grad_mul = -2/n * grad_sum # 1xm
gradient = np.transpose(grad_mul).reshape(-1, 1) # mx1
W = W - (lr * gradient)
return W
def stochastic_gradient_descent(X_train, y_train, lr=0.01, amt_epochs=100):
"""
shapes:
X_t = nxm
y_t = nx1
W = mx1
"""
n = X_train.shape[0]
m = X_train.shape[1]
# initialize random weights
W = np.random.randn(m).reshape(m, 1)
for i in range(amt_epochs):
idx = np.random.permutation(X_train.shape[0])
X_train = X_train[idx]
y_train = y_train[idx]
for j in range(n):
prediction = np.matmul(X_train[j].reshape(1, -1), W) # 1x1
error = y_train[j] - prediction # 1x1
grad_sum = error * X_train[j]
grad_mul = -2/n * grad_sum # 2x1
gradient = np.transpose(grad_mul).reshape(-1, 1) # 2x1
W = W - (lr * gradient)
return W
def mini_batch_gradient_descent(X_train, y_train, lr=0.01, amt_epochs=100):
"""
shapes:
X_t = nxm
y_t = nx1
W = mx1
"""
b = 16
n = X_train.shape[0]
m = X_train.shape[1]
# initialize random weights
W = np.random.randn(m).reshape(m, 1)
for i in range(amt_epochs):
idx = np.random.permutation(X_train.shape[0])
X_train = X_train[idx]
y_train = y_train[idx]
batch_size = int(len(X_train) / b)
for i in range(0, len(X_train), batch_size):
end = i + batch_size if i + batch_size <= len(X_train) else len(X_train)
batch_X = X_train[i: end]
batch_y = y_train[i: end]
prediction = np.matmul(batch_X, W) # nx1
error = batch_y - prediction # nx1
grad_sum = np.sum(error * batch_X, axis=0)
grad_mul = -2/n * grad_sum # 1xm
gradient = np.transpose(grad_mul).reshape(-1, 1) # mx1
W = W - (lr * gradient)
return W
def mini_batch_logistic_regression(X_train, y_train, lr=0.01, amt_epochs=100):
"""
shapes:
X_t = nxm
y_t = nx1
W = mx1
"""
b = 16
m = X_train.shape[1]
# initialize random weights
W = np.random.randn(m).reshape(m, 1)
for i in range(amt_epochs):
idx = np.random.permutation(X_train.shape[0])
X_train = X_train[idx]
y_train = y_train[idx]
batch_size = int(len(X_train) / b)
for i in range(0, len(X_train), batch_size):
end = i + batch_size if i + batch_size <= len(X_train) else len(X_train)
batch_X = X_train[i: end]
batch_y = y_train[i: end]
exponent = np.sum(np.transpose(W) * batch_X, axis=1)
prediction = 1/(1 + np.exp(-exponent))
error = prediction.reshape(-1, 1) - batch_y.reshape(-1, 1)
grad_mul = (1/b) * np.matmul(batch_X.T, error) # 1xm
gradient = np.transpose(grad_mul).reshape(-1, 1) # mx1
W = W - (lr * gradient)
return W
def predict(X, W):
wx1 = np.matmul(X, W)
wx = np.concatenate(wx1, axis=0 )
sigmoid = 1/(1 + np.exp(-wx))
#sigmoid = [1 if x >= 0.5 else 0 for x in sigmoid]
sigmoid = np.where(sigmoid >= 0.5, 1.0, 0.0)
return sigmoid
if __name__ == '__main__':
dataset = Data('clase_6_dataset.txt')
X_train, X_test, y_train, y_test = dataset.split(0.8)
X_train_expanded = np.vstack((X_train[:, 0], X_train[:, 1], np.ones(len(X_train)))).T
X_test_expanded = np.vstack((X_test[:, 0], X_test[:, 1], np.ones(len(X_test)))).T
lr = 0.001
epochs = 50000
W = mini_batch_logistic_regression(X_train_expanded, y_train.reshape(-1, 1), lr=lr, amt_epochs=epochs)
y_hat = predict(X_test_expanded, W)
print('Predicted (y_hat)')
print(y_hat)
print('Real (y_test)')
print(y_test)
# y_hat = w0 * x1 + w1 * x2 + w3(b)
# 0 = w0 * x1 + w1 * x2 + w3(b) = w0 * x + w1 * y + w3(b)
# y = ( -w0 *x - w3) / w1
x_regression = np.linspace(30, 100, 70)
y_regression = (-x_regression*W[0] - W[2])/W[1]
zeros = y_train < 0.5
ones = y_train >= 0.5
X_train_zeros = X_train[zeros]
y_train_zeros = y_train[zeros]
X_train_ones = X_train[ones]
y_train_ones = y_train[ones]
plt.scatter(X_train_zeros[:,0], X_train_zeros[:,1], marker='*')
plt.scatter(X_train_ones[:,0], X_train_ones[:,1], marker='+')
plt.plot(x_regression, y_regression, c='r')
plt.show()
|
import re
def test_pfe_2(research):
matches = '[A-Z]+[a-z]+$'
if re.search(matches, research):
return "Found"
else:
return "Not Found"
#TEST
print(test_pfe_2("Alcindor"))
print(test_pfe_2("Lourdvic"))
print(test_pfe_2("Kaissens-Data"))
print(test_pfe_2("test"))
print(test_pfe_2("DaTaScience")) |
#Determine the sum of all elements in the sequence, ending with the number 0.
sum = 0
i=int(input())
while i!=0:
sum+=i
i = int(input())
print(sum) |
#Given a string. Delete from it all the characters whose indices are divisible by 3.
s = input()
t=''
for i in range(len(s)):
if i%3!=0:
t += s[i]
print(t) |
#Input Format
# The first line contains the integer,
# the total number of plants.
# The second line contains the
# space separated heights of the plants.
# Constraints
# Output Format
# Output the average height value on a single line.
def average(array):
avg=sum(set(array))/len(set(array))
return avg
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
result = average(arr)
print(result)
|
#Given a list of integers. Determine how many distinct numbers there are.
print(len(set(input().split()))) |
#Given a string that may or may not contain a letter of interest. Print the index location of the first
# and last appearance of f. If the letter f occurs only once, then output its index. If the letter f does not occur, then do not print anything.
s=input()
if s.count('f')==1:
print(s.find('f'))
elif s.count('f')>1:
print(s.find('f'),s.rfind('f')) |
# H hours, M minutes and S seconds are passed since the midnight (0 ≤ H < 12, 0 ≤ M < 60, 0 ≤ S < 60).
# Determine the angle (in degrees) of the hour hand on the clock face right now.
h = int(input())
m = int(input())
s = int(input())
ha = 30*h
ma = 0.5*m
sa = 0.00833333*s
ta = ha + ma + sa
print(ta) |
r1 = int(input())
c1 = int(input())
r2 = int(input())
c2 = int(input())
if abs(r1-r2)%2!=0:
if abs(c1-c2)%2!=0:
print("YES")
else:
print("NO")
else:
if abs(c1-c2)%2==0:
print("YES")
else:
print("NO") |
n = int(input())
count = 0
#calculate no of zeros entered by user
for i in range(n):
if(int(input())==0):
count = count +1
print(count) |
#As a future athlete you just started your practice for an upcoming event. Given that on the first day you run x miles, and by the event you must be able to run y miles.
#Calculate the number of days required for you to finally reach the required distance for the event, if you increases your distance each day by 10% from the previous day.
#Print one integer representing the number of days to reach the required distance.
x = int(input())
y = int(input())
days=1
while(x<y):
x=x+0.1*x
days+=1
print(days) |
#Given a list of countries and cities of each country. Then given the names of the cities. For each city specify
# the country in which it is located.
n=int(input())
land = {}
for i in range(n):
country, *cities = input().split()
for city in cities:
land[city] = country
n2=int(input())
for i in range(n2):
print(land[input()]) |
#!/usr/bin/env python
# coding: utf-8
# (time)=
# # Time Series / Dates
# Key ways of thinking about time in python:
#
# - **Timestamp**: An instant in time
# - **Period**: Some established interval of time, usually a month, year. Special case of interval
# - **Interval**: An arbitrary interval of time.
# - **Experimental / Elapsed time**: Represents elapsed time from some chosen start point.
# Important Native-Python Packages concering date:
#
# - [`datetime`](https://docs.python.org/3/library/datetime.html)
# - [`dateutil`](https://dateutil.readthedocs.io/en/stable/)
# In[1]:
from datetime import datetime
print(f'datetime.now() : {datetime.now()}')
print(f'datetime.now().year : {datetime.now().year}')
# In[2]:
from dateutil import parser
date = parser.parse("4th of July, 2015")
date
# Types available in the datetime module:
#
# - `date` - Date object (only concerned with calendar type dates)
# - `time` - Time object concerned with time of a date
# - `datetime` - Combo of both
# - `timedelta` - Differences between to datetime objects
# - `tzinfo` - Time zone things
# (timestr)=
# ## Strings and strftime
# Once you have a datetime object or some date ready to be converted into one, it is easy to convert and format into a string
# In[3]:
stamp = datetime.now()
print(str(stamp))
# In[4]:
stamp.strftime('%Y-%m')
# (strf)=
# ### Strftime
#
# **strftime** allows you to select certain parts of the datetime object with using the special formatting codes. Here is a list of common ones: (ISO C89 compatible)
#
# - `%Y` : 4 digit year
# - `%y` : 2 digit year
# - `%m` : 2 digit month
# - `%d` : 2 digit day
# - `%H` : military time hour
# - `%h` : 12 hour [01,12]
# - `%M` : 2 digit minute [00,59]
# - `%S` : seconds [00,61]
# - `%w` : weekday as an integer
# - `%F` : shortcut for `%Y-%m-%d`
# - `%D` : shortcut for `%d/%m/%y`
#
# Here is a list of useful locale-specific **strftime** codes:
#
# - `%a` : abbreviated day name
# - `%A` : Full-length day name
# - `%b` : abbreviated month name
# - `%B` : Full month name
# - `%c` : full date-time (Tue 01 May 2012 04:20:57 PM’)
# - `%p` : locale equivalent of a.m./p.m.
# - `%x` : locale-appropriate formatted date (%c)
# - `%X` : locale-appropriate time
# (datetime64)=
# ## Numpy [datetime64](https://numpy.org/doc/stable/reference/arrays.datetime.html)
# Like most native python objects and and processes - problems with efficiency and speed arise when dealing with large quantities and loops.
#
# The dypte **datetime64** was developed in order to address these problems.
# The `datetime64` datatype encodes dates as 64 bit integers (which allows dates to be represented compactly)
# In[5]:
import numpy as np
date = np.array('2020-07-04', dtype='datetime64[D]')
date
# Dates in this format allow for vectorized operations.
# ````{margin}
# ```{note}
# Recall that alot of the speed attainable in `numpy` is due to the uniformity
# of dtype in numpy arrays
# ```
# ````
# In[6]:
date + np.arange(6)
# `datetime64` and `timedelta` are both built upon a **fundamental time unit** and so the range of encodable dates =
#
# $$ 2^{64} \cdot (t_{u}) $$
#
# where $t_{u}$ is the smallest unit of time measured **(time resolution)** and the product above is the **max time span**
#
# $ns = 10^{-9}$ (nanoseconds) are the default ftu. but there are quite a few codes that can be used.
# In[7]:
np.datetime64('2020-08-11', 'ns')
# Here are the various codes for `datetime64`:
#
# - `Y` : year
# - `M` : month
# - `W` : ...
# - `D` :
# - `h` :
# - `m` :
# - `s` :
# - `ms` : millisecond
# - `us` : microsecond $10^{-6}$ one millionth of a second
# - `ns` : nanosecond
# - `ps` : picosecond $10^{-12}$ one trillionth of a second
# - `fs` : femtosecond
# - `as` : attosecond $10^{-18}$ one quintillionth of a second
# (pandasdate)=
# ## Dates and Times in Pandas
# Pandas builds upon `datetime`, `dateutils`, and `datetime64` to provide objects such as `Timestamp` that takes the best part of each:
#
# The flexibility and ease of use of native `python3` packages, and the efficient storage and vectorized interface of `numpy`
# In[8]:
import pandas as pd
date = pd.to_datetime('11 of August, 2020')
date
# In[9]:
date.strftime("%A")
# In[10]:
date + pd.to_timedelta(np.arange(5), "D")
# (timeindex)=
# ### Indexing by Timestamp
# The power of datetime in pandas becomes apparent when we begin to index by timestamp allowing us to parse data easily w.r.t. time.
#
# We do this by constructing an a DatetimeIndex and using that as our index for our series/df. We can accomplish this explicitly by passing an array of properly formatted
# timestamps to `pd.DatetimeIndex()` or using pandas excellent `pd.to_datetime()` function:
# In[11]:
index1 = pd.DatetimeIndex(['2020-08-11', '2020-08-12', '2020-08-13'])
index1
# In[12]:
dates = ['August 11th, 2020', 'August 12th, 2020', 'August 13th, 2020']
index2 = pd.to_datetime(dates)
index2
# (datastructures)=
# ### Time Data Structures in Pandas
# `Timestamp`: essentially a replacement for native python `datetime` based on more efficient `datetime64` datatype
#
# `DatetimeIndex` : Index data structure associated with `Timestamp`
#
# ---
# `Period`: A fixed-frequency interval into which `Timestamps` either fall or do not.
#
# `PeriodIndex`: Associated Index data structure/
#
# ---
# `Timedelta`: a duration, small amount of elapsed time from some reference.
#
# `TimedeltaIndex`: Associated index data structure.
#
# ---
# `Timestamp` and `DatetimeIndex` are the fundamental date/time objects in pandas.
#
# Although they can be invoked directly it is much more common to use the `pd.to_datetime()` function, **which can parse a wide variety of formats.**
# ```{note}
# Any `DatetimeIndex` can be converted to a `PeriodIndex` with the `pd.to_period()` function with the addition of the desired
# frequency code (ex. 'D').
# ```
# (dateseq)=
# ### Functions that allow for creation of Date Sequences
# `pd.date_range()`
# `pd.period_range()`
# `pd.timedelta_range()`
# Like the native python `range()` function these calls allow for specification of start, stop and step/frequency to create a sequence of date/time objects.
# In[13]:
pd.date_range('2020-08-11', '2020-08-17')
# In[14]:
pd.date_range('2020-08-11', periods=7, freq="D")
# In[15]:
pd.period_range('2020-01', periods=6, freq="M")
# In[16]:
pd.timedelta_range(0, periods=10, freq='H')
# (freqcodes)=
# ### Frequency Codes
# #### Conventional Time
# `D` : Calendar Day
# `W` : Weekly
# `M` : Month End
# `A` : Year End
# `H` : Hourly
# `T` : Minutes
# `S` : Seconds
# `L` : Milliseconds
# `U` : Microseconds
# `N` : Nanoseconds
# #### Business Time
# `B` : Business Day
# `BM` : Business Month End
# `BQ` : Business Quarter End
# `BA` : Business Year End
# ```{important}
# Adding `S` to any monthly, quarterly or annual period will change the marker from the end of the period to the beginning.
#
# ex. `MS` or `BMS`
# ```
# #### Other Modifications to Ranges/Periods
# In addition to changing the start or ending of a period as a split point you have other flexibility.
#
# You can change the month used to mark any quarterly or annual code by adding a 3-letter suffix code to the original:
#
# `Q-JAN`, `BQS-APR`, `A-FEB`, `BAS-APR`
#
# You can also modify the split points of other periods such as week:
#
# `W-SUN`, `W-TUE`
# (offsets)=
# #### Offsets
#
# [pandas offset documentation](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#time-date-components)
#
# Pandas allows us to specify offsets which help select dates in a range based on some criterion.
# In[17]:
from pandas.tseries.offsets import BDay
pd.date_range('2020-10-04', periods=5, freq=BDay()) # selects the next 5 business days on or after intial date
# In[ ]:
|
n=float(input('Digite seu salario: '))
a=float(input('Digite a % do seu aumento: '))
s=n+(n*a/100)
print('Seu novo salario com {:.0f}% de aumento é R${:.2f}'.format(a,s)) |
n = input('digite algo ')
print('Esse valor é? ', (type)(n))
print('Ele é númerico? ', n.isnumeric())
print('Ele é alfabeto? ', n.isalpha())
print('Ele está em maiusculo? ', n.isupper())
print('Ele está em minusculo? ', n.islower())
print('Ele é um digito? ', n.isdigit())
print('Ele é um decimal? ', n.isdecimal())
print('Tchau dxzin fofolol')
|
import math
cat=float(input('Comprimento do cateto oposto: '))
cat1=float(input('Comprimento do cateto adjacente: '))
s=math.hypot(cat,cat1)
print('='*40)
print(f'Ola dxzin')
print('O comprimento da hipotenusa é {:.2f}'.format(s))
print('='*40)
|
n = int(input("Digite um numero: "))
m = n % 2
if m == 0:
print("Seu numero é par")
else:
print('Seu numero é impar') |
'''
Have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false.
The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a)
and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false.
The string will not be empty and will have at least one letter.
'''
def SimpleSymbols(str):
alph = "abcdefghijklmnopqrstuvwxyz"
x = True
if (str[0] in alph) or (str[-1] in alph):
return False
for char in str:
char = char.lower()
if char in alph:
indx_p = str.index(char)+1
indx_m = str.index(char)-1
if (str[indx_p] == '+') and (str[indx_m] == '+'):
pass
else:
x = False
return x
test = '"+d+=3=+s+"'
test2 = '+=+f++d'
print(SimpleSymbols(test2))
|
'''
Have the function AlphabetSoup(str) take the str string parameter being passed and return the string with the letters in alphabetical order
(ie. hello becomes ehllo). Assume numbers and punctuation symbols will not be included in the string.
'''
def Alphabet(str):
return ''.join(sorted(str))
|
from tkinter import *
from quiz_brain import QuizBrain
THEME_COLOR = "#375362"
class QuizInterface:
def __init__(self, quiz_brain: QuizBrain):
self.quiz = quiz_brain
self.window = Tk()
self.window.title("Quizzler")
self.window.config(padx=20, pady=20, bg=THEME_COLOR)
self.canvas = Canvas(width=300, height=250, bg="white")
self.quiz_text = self.canvas.create_text(150, 125, width=280, text="Question", fill=THEME_COLOR, font=('Arial', 20, 'italic'))
self.canvas.grid(row=1, column=0, columnspan=2, pady=50)
self.score = Label(text="Score: 0", fg='white', bg=THEME_COLOR)
self.score.grid(row=0, column=1)
self.right = PhotoImage(file="images/true.png")
self.true = Button(text='True', image=self.right, highlightthickness=0, command=self.true_pressed)
self.true.grid(row=2, column=0)
self.wrong = PhotoImage(file="images/false.png")
self.false = Button(text='False', image=self.wrong, highlightthickness=0, command=self.false_pressed)
self.false.grid(row=2, column=1)
self.get_next_question()
self.window.mainloop()
def get_next_question(self):
self.canvas.config(bg='white')
if self.quiz.still_has_questions():
self.score.config(text=f"Score: {self.quiz.score}")
q_text = self.quiz.next_question()
self.canvas.itemconfig(self.quiz_text, text=q_text)
else:
self.canvas.itemconfig(self.quiz_text, text=f"Your score : {self.quiz.score}/10")
self.true.config(state="disabled")
self.false.config(state="disabled")
def true_pressed(self):
self.give_feedback(self.quiz.check_answer('True'))
def false_pressed(self):
self.give_feedback(self.quiz.check_answer('False'))
def give_feedback(self, alert):
if alert:
self.canvas.config(bg="green")
self.window.after(1000, self.get_next_question)
else:
self.canvas.config(bg="red")
self.window.after(1000, self.get_next_question)
|
import nltk, re, pprint, sys, random
from nltk import word_tokenize
from collections import defaultdict
#note: program should always start by opening the universal dictionary
#and saving to the universal dictionary
class Player:
def __init__(self):
#a dict of win and loss words, maintained throughout every run
#of this program (i.e. saved to a file)
self._dictionary = defaultdict(list)
#a dict of keywords and their corresponding phrases
self._keys = defaultdict(list)
#a dict of keywords and the important words in their
#corresponding phrase
self._outcome_dict = defaultdict(list)
#a list of important words encountered in a playthrough
self._game_list = []
self._win_freq_dict = defaultdict(lambda: 0)
self._loss_freq_dict = defaultdict(lambda: 0)
''' Name: open_dictionary
Purpose: to open the universal dictionary and give the playerbot
access throughout the code'''
def open_dictionary(self):
try:
markers = [':', ',', '.', '']
#will always open a file specifically called 'dictionary.txt'
#since this is where it will save new vocab to as well
f = open('dictionary.txt', 'rU')
#gather raw file text
raw = ''.join([word for word in f])
#split into lines by presence of newline character
lines = raw.split('\n')
lines = [line for line in lines if line not in markers]
if lines == []:
#sends empty files to the except block
raise IndexError
for line in lines:
#split into key and value form
keys = line.split(':')
#tokenize and standardize values
values = nltk.word_tokenize(keys[1])
values = [value for value in values if value not in markers]
values = [v.lower() for v in values]
values = sorted(values)
#update program variable dictionary
self._dictionary[keys[0]] = values
#in case the file has not been created or is empty
except (FileNotFoundError, IndexError) as error:
print('Error reading file, writing new file!')
output_file = open('dictionary.txt', 'w')
print('WIN:', end='', file= output_file)
print('\n', file= output_file)
print('LOSS:', end='', file= output_file)
''' Name: parse_script
Purpose: to take a raw bit of text, tag it with parts of speech,
and return it in phrases.
Parameters: a str objects
Returns: a list object, the phrases of the raw string,
element of the list is a tuple object with the first position
containing the word and the second its part of speech'''
def parse_script(self, raw):
tokens = word_tokenize(raw)
tagged = nltk.pos_tag(tokens)
phrases = []
line = []
for word in tagged:
#the word, not the pos tag
if word[0].isalnum():
line.append(word)
else:
phrases.append(line)
line = []
return(phrases)
''' Name: develop_dict
Purpose: to take in phrases and separate the keyword (the word
the player would input) from the actual phrase, developing
the self._keys dictionary
Parameters: a list of tuples, each obj is a word and its pos tag
Returns: a dict object with phrase keywords as the keys and phrases
as the values'''
def develop_dict(self, phrases):
#default dictionary in case a nonexistent key is entered
inputs = defaultdict(lambda: 'NO KEY')
for phrase in phrases:
#set key as 'no key' until a key is found
key = 'NO KEY'
for word in phrase:
#this relies on the assumption that keywords will always
#be all uppercase
if word[0].isupper():
key = word[0]
inputs[key] = phrase
return inputs
''' Name: gather_word_data
Purpose: to add important words (nouns, adj, verb, adverb) to a
univeral dictionary to be accessed by the playerbot, and to
link keywords with their respective phrases in a separate dictionary.
Parameters: a dict object
Return: a dict containing keywords as the keys and their respective
sentences as the values
'''
def gather_word_data(self, inputs):
for key in inputs:
for word in inputs[key]:
#ignores data from the phrases lacking a key word
if key == 'NO KEY':
None
else:
self._keys[key].append(word[0].lower())
if word[1].startswith('NN'):
self._outcome_dict[key].append(word[0].lower())
elif word[1].startswith('JJ'):
self._outcome_dict[key].append(word[0].lower())
elif word[1].startswith('VB'):
self._outcome_dict[key].append(word[0].lower())
elif word[1].startswith('RB'):
self._outcome_dict[key].append(word[0].lower())
''' Name: save_to_dictionary
Purpose: to save the new and categorized vocabulary from the
text to the existing dictionary and onto the 'dictionary.txt' file
'''
def save_to_dictionary(self):
output_file = open('dictionary.txt', 'w')
for key in self._dictionary:
try:
#sort dictionary before reupload
self._dictionary[key] = sorted(self._dictionary[key])
except TypeError:
pass
print(key + ':', end='', file= output_file)
try:
for value in self._dictionary[key]:
print(value, end=',', file = output_file)
except TypeError:
print(self._dictionary[key], end='', file = output_file)
print('\n', file= output_file)
''' Name: process
Purpose: to consolidate the different methods for processing
a script into one callable method.
Parameters: Script, a bit of text to parse'''
def process(self, Script):
#clears so the same keywords cannot be selected multiple times
#by the computer.
self._keys.clear()
phrases = self.parse_script(Script)
inputs = self.develop_dict(phrases)
self.gather_word_data(inputs)
''' Name: decide
Purpose: to make a decision whether to use a semi-educated guess
or a random choice when presented with an option.
Returns: the keyword associated with the decision made, in str form'''
def decide(self):
self.gather_common_words()
self.develop_freq_dict()
decision = None
random = False
for key in self._outcome_dict:
for word in self._outcome_dict[key]:
if word in self._dictionary['CWW']:
pass
elif word in self._dictionary['CLW']:
pass
else:
print('WORD IN QUESTION: ', word)
random = True
#checks if there are at least 10 distinct words gathered in the top 50
#most common win and loss words
if len(self._dictionary['CWW']) >= 10 and len(self._dictionary['CLW']) >= 10:
#makes sure the frequencies are in float form
ww_freq = str(self._dictionary['Average WW Freq'])
ww_freq = float(ww_freq)
lw_freq = str(self._dictionary['Average LW Freq'])
lw_freq = float(lw_freq)
#checks if the average frequency for a word is >= 10
if random is True:
#print('1.WORD NOT ACCOUNTED FOR')
decision = self.random_decision()
elif ww_freq >= 10.0 and lw_freq >= 10.0:
decision = self.educated_decision()
else:
#print('ENOUGH WORDS, NOT ENOUGH TESTS.')
decision = self.random_decision()
#checks if there are over 50 examples of win and loss words
elif len(self._dictionary['WIN']) >= 50 and len(self._dictionary['LOSS']) >= 50:
if random is True:
#print('2.WORD NOT ACCOUNTED FOR')
decision = self.random_decision()
else:
#print('THE SAMPLE IS LARGE BUT NOT VARIED.')
decision = self.educated_decision()
else:
decision = self.random_decision()
return str(decision)
''' Name: educated_decision
Purpose: to make a decision based on the presence of words associated
with wins and losses in the phrases enveloping a keyword.
Returns: a decision, in str form'''
def educated_decision(self):
score_dict = defaultdict(int)
for key in self._keys:
score = 0
for word in self._keys[key]:
if word in self._dictionary['CWW'] and word in self._dictionary['CLW']:
if self._win_freq_dict[word] > 5 + self._loss_freq_dict[word]:
print(word, ' gives +1 from freq dict')
score = score + 1
elif self._loss_freq_dict[word] > 5 + self._win_freq_dict[word]:
print(word, ' gives -1 from freq dict')
score = score - 1
elif word in self._dictionary['CWW']:
print(word, ' gives +1')
score = score + 1
elif word in self._dictionary['CLW']:
score = score - 1
print(word, ' gives -1')
score_dict[key] = score
print(key, ' score is ', score)
#this is written as such to prevent the need of some arbitrary
#greatest value, since the scores could be negative or positive
if score_dict[list(score_dict)[0]] > score_dict[list(score_dict)[1]]:
decision = list(score_dict)[0]
else:
decision = list(score_dict)[1]
print('EDUCATED CHOICE IS ', str(decision))
return decision
''' Name: random_decision
Purpose: to make a random decision between the two given options
Returns: a decision, in str form'''
def random_decision(self):
keys = [str(key) for key in self._keys]
decision = random.choice(keys)
#this adds relevant words to the list of words encountered in a playthrough
for value in self._outcome_dict[decision]:
self._game_list.append(value)
return decision
''' Name: gather_common_words
Purpose: to gather data on the most common words in win and loss entries,
and create new entries for those words and the avg freq of a word in the dict.
'''
def gather_common_words(self):
win_text = nltk.Text(self._dictionary['WIN'])
fdwin = nltk.FreqDist(win_text)
#common win words
cww = []
cwwf = []
win_sum = 0
total_ww = 0
for tup in fdwin.most_common(50):
#changed to add whole tup so other methods can access freqs
cwwf.append(tup)
cww.append(tup[0])
win_sum += tup[1]
total_ww += 1
try:
avg_ww_freq = win_sum/total_ww
except ZeroDivisionError:
avg_ww_freq = 0
self._dictionary['CWW'] = cww
self._dictionary['CWWF'] = cwwf
self._dictionary['Average WW Freq'] = avg_ww_freq
loss_text = nltk.Text(self._dictionary['LOSS'])
fdloss = nltk.FreqDist(loss_text)
#common loss words
clw = []
clwf = []
loss_sum = 0
total_lw = 0
for tup in fdloss.most_common(50):
clwf.append(tup)
clw.append(tup[0])
loss_sum += tup[1]
total_lw += 1
try:
avg_lw_freq = loss_sum/total_lw
except ZeroDivisionError:
avg_lw_freq = 0
self._dictionary['CLW'] = clw
self._dictionary['CLWF'] = clwf
self._dictionary['Average LW Freq'] = avg_lw_freq
''' Name: develop_freq_dict
Purpose: to add another dictionary entry containing words and their freqs
'''
def develop_freq_dict(self):
for tup in self._dictionary['CWWF']:
self._win_freq_dict[tup[0]] = tup[1]
for tup in self._dictionary['CLWF']:
self._loss_freq_dict[tup[0]] = tup[1]
''' Name: update_game_dict
Purpose: to update the universal dictionary with all the words the player
encountered on its path to a win or loss.
Paramters: result, either a WIN or LOSS'''
def update_game_dict(self, result):
print('The computer had a ' + result)
if result == 'WIN':
#print('ADDED WIN WORDS ', str(self._game_list))
for word in self._game_list:
self._dictionary['WIN'].append(word)
if result == 'LOSS':
#print('ADDED LOSS WORDS ', str(self._game_list))
for word in self._game_list:
self._dictionary['LOSS'].append(word)
self.save_to_dictionary()
''' Name: __str__
Purpose: to return an easily readable string of the entries
in the universal dictionary.
Returns: string, the entries of the universal dictionary'''
def __str__(self):
string = 'UNIVERSAL DICTIONARY:\n'
dict_list = []
for key in self._dictionary:
try:
value = ', '.join([value for value in self._dictionary[key]])
dict_list.append(str(key) + ': ' + value)
except TypeError:
dict_list.append(str(key) + ': ' + str(self._dictionary[key]))
string = string + '\n'.join([line for line in dict_list])
return string
if __name__ == '__main__':
pass
|
class Square:
def __init__(self, a):
print(self.__class__.__bases__)
self.a = a
self.__area = self.a ** 2
@property
def area(self):
return self.__area
@area.setter
def area (self, value ):
self.__area = value
self.a = self.__area ** 0.5
def __setattr__(self, key, value):
super().__setattr__(key, value)
def __getattribute__(self, item):
print("get attribute ", item)
return super().__getattribute__(item)
s1 = Square(10)
# print(s1.a)
# s1.area = 81
#print(s1.a)
# s1.whatever
s1.new_property = 100
print(s1.new_property)
# print(s1.new_property) |
courses = ['Physics', 'Chemistry', 'Mathmetics', 'English', 'Computer Science']
courses_2 = ['Art', 'Education']
print(courses.extend(courses_2))
print(courses[0]) # First element of the list
print(courses[-1]) # Last element of the list |
#! /usr/bin/env python3
##### FOR MATH244; AUTUMN-WINTER, 2020
from sympy import *
import re # for prettifying the input equation
# import numpy as np # https://stackoverflow.com/q/60383716/12069968
# for multiple substitutions
class Substitutable(str):
def __new__(cls, *args, **kwargs):
newobj = str.__new__(cls, *args, **kwargs)
newobj.sub = lambda fro,to: Substitutable(re.sub(fro, to, newobj))
return newobj
# sin = np.sin
# get derivatives of functions
x, y = symbols('x y', real=True)
# f = Substitutable("sin(x**2)")
f = x*sin(x)
# d1 = Substitutable(diff(f, x))
# d2 = Substitutable(diff(f, y))
# prettyFunction = f.sub("^yp = ", r"y' = ").sub(r"\*\*\((\d+)\)", r"^{\1}").sub(r"\*\*", r"^").sub(r"\*", r" · ").sub(r"/", r" ÷ ")
# prettyD1 = d1.sub("^yp = ", r"y' = ").sub(r"\*\*\((\d+)\)", r"^{\1}").sub(r"\*\*", r"^").sub(r"\*", r" · ").sub(r"/", r" ÷ ")
# prettyD2 = d2.sub("^yp = ", r"y' = ").sub(r"\*\*\((\d+)\)", r"^{\1}").sub(r"\*\*", r"^").sub(r"\*", r" · ").sub(r"/", r" ÷ ")
print(r"Taking the derivative of {}".format(f), "\n")
dydx = diff(f, x); print("\tWRT x:\t {}".format(dydx))
dxdy = diff(f, y); print("\tWRT y:\t {}".format(dxdy), "\n")
print("\tSecond derivative WRT x:\t {}".format(diff(dydx, x)))
print("\tSecond derivative WRT y:\t {}".format(diff(dxdy, y)))
|
def getSum(file_string):
f = open(file_string, "r")
groups = [group.split('\n') for group in f.read().split("\n\n")]
count = 0
for group in groups:
votes = {}
for voter in group:
for vote in voter:
if vote in votes.keys():
votes[vote] += 1
else:
votes[vote] = 1
for key in votes.keys():
print(key, votes[key])
if votes[key] == len(group):
count += 1
print(len(group), '\n')
return count
sum = getSum("/Users/jakeireland/Desktop/doov_advent_of_code/06/test.txt")
print(sum)
assert sum == 6, 'test failed'
|
f = open("input.txt", "r")
def isSum(numbers, i, distance):
number = numbers[i]
for j in range(max(i-distance, 0), i):
addend_1 = numbers[j]
if addend_1 > number:
continue
else:
for k in range(max(i-distance, 0), i):
addend_2 = numbers[k]
if addend_2 > number or j == k:
continue
else:
if addend_1 + addend_2 == number:
return (addend_1, addend_2, number)
return False
def getNonSum(numbers):
for i in range(25, len(numbers)):
if not isSum(numbers, i, 25):
return numbers[i]
def getContiguousSet(numbers):
non_sum = getNonSum(numbers)
for start in range(0, len(numbers)):
if numbers[start] > non_sum:
continue
for end in range(start + 1, len(numbers)):
contiguous_set = [numbers[i] for i in range(start, end)]
contiguous_set_sum = sum(contiguous_set)
if contiguous_set_sum == non_sum:
return contiguous_set
elif contiguous_set_sum > non_sum:
break
numbers = [int(line) for line in f.readlines()]
contiguous_set = getContiguousSet(numbers)
print(max(contiguous_set) + min(contiguous_set)) |
import math
from turtle import Turtle, Screen
def turtle_set_up(colour: str) -> Turtle:
t = Turtle()
t.shape("turtle")
t.color(colour)
return t
def calc_side_len(n: int, w: int):
"""
Calculate the length of each side of a regular polygon with `n` sides of width `w`.
"""
# https://math.stackexchange.com/a/4680901/705172
return w * math.sin(math.radians(360 / (2 * n)))
def move_outwards(t: Turtle, r: int = 0, f: int = 100):
"""
Rotate turtle `t` `r` degrees clockwise, move forward `f` units, and rotate back to the original position.
"""
t.penup()
t.right(r)
t.forward(f)
t.left(r)
t.pendown()
def draw_shape(t: Turtle, n: int, w: int = 30):
"""
Draw a shape with `n` sides of width `w` using turtle `t`.
"""
side_length = calc_side_len(n, w)
for _ in range(n):
t.forward(side_length)
t.right(360 / n)
def main() -> int:
# Set up screen
wn = Screen()
wn.bgcolor("lightblue")
# Turtle set up
tess = turtle_set_up("blue")
alex = turtle_set_up("green")
bex = turtle_set_up("hotpink")
clive = turtle_set_up("orange")
# Turtles move out from centre
# They should always face to the right at the end of their move
move_outwards(tess)
move_outwards(alex, 180)
move_outwards(bex, 90)
move_outwards(clive, 270)
# Draw shapes
draw_shape(tess, 3) # triangle
draw_shape(alex, 4) # square
draw_shape(bex, 6) # hexagon
draw_shape(clive, 8) # octagon
wn.mainloop()
return 0
if __name__ == "__main__":
raise SystemExit(main())
|
def big_header(title):
print("## {}".format(title))
print()
def small_header(title):
print("### {}".format(title))
print()
def write_education(education):
big_header("Education")
for edu in education:
majors = ", ".join(list(map(lambda x: x.strip() + " Major", edu["majors"].split(","))))
minors = ", ".join(list(map(lambda x: x.strip() + " Minor", edu["minors"].split(","))))
small_header(edu["degree"] + ": " + edu["institution"])
print(majors)
print()
print(minors)
print()
def write_skills(skills):
big_header("Skills")
small_header("Proficient")
print(", ".join(skills["proficient"]))
print()
small_header("Familiar")
print(", ".join(skills["familiar"]))
print()
small_header("Technologies")
print(", ".join(skills["software"]))
print()
def write_experience(experience):
big_header("Experience")
for exp in filter(lambda exp: exp["tag"] != "other", experience):
small_header(exp["title"] + ": " + exp["institution"])
print(exp["description"].replace(" n ", " $n$ "))
print()
def write_projects(projects):
big_header("Projects")
for proj in projects:
small_header(proj["title"])
print(proj["description"])
print()
|
def deposit_calculator(total_cost, annual_salary, portion_saved, semi_annual_raise):
r = 0.04
portion_deposit = 0.20
deposit_required = total_cost * portion_deposit
current_savings = 0.0
monthly_salary = annual_salary/12
salary_savings = monthly_salary * portion_saved
months = 0
while current_savings < deposit_required:
months = months + 1
interest = (current_savings * r) / 12
current_savings = current_savings + salary_savings + interest
if months % 6 == 0:
annual_salary = annual_salary + annual_salary * semi_annual_raise
monthly_salary = annual_salary/12
salary_savings = monthly_salary * portion_saved
return months
print(deposit_calculator(1000000, 120000, 0.10, 0.02)) |
def deposit_calculator(total_cost, annual_salary, portion_saved):
r = 0.04
portion_deposit = 0.20
deposit_required = total_cost * portion_deposit
current_savings = 0.0
monthly_salary = annual_salary/12
salary_savings = monthly_salary * portion_saved
months = 0
while current_savings < deposit_required:
interest = (current_savings * r) / 12
current_savings = current_savings + salary_savings + interest
months = months + 1
return months
print(deposit_calculator(1000000, 120000, 0.10))
print("test files added") |
# -*- coding: utf-8 -*-
__author__ = 'Sergey Sobko'
from bisect import insort_left
def n_max_numbers(in_iter, n=2):
"""Get N maximal numbers from iter.
>>> n_max_numbers([])
[]
>>> n_max_numbers([1, 2, 3])
[2, 3]
>>> n_max_numbers([4, 2, 3])
[3, 4]
>>> n_max_numbers([1, 2, -1, 0], 3)
[0, 1, 2]
"""
max_numbers = list()
for number in in_iter:
insort_left(max_numbers, number)
max_numbers = max_numbers[-n:]
return max_numbers
if __name__ == '__main__':
import doctest
doctest.testmod()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 14 16:07:27 2020
@author: ritambasu
"""
import numpy as np
#import pandas as pd # Import pandas
from matplotlib import pyplot as plt
from urllib.request import urlretrieve # Import package
# Assign url of file: url
url = 'http://theory.tifr.res.in/~kulkarni/noise.txt'
#coverting data to array
sampled_data=np.loadtxt(url)
#fourier transform through dft by using numpy.fft.fft
xmin=0
dx=1
numpoints=len(sampled_data)
dft=np.fft.fft(sampled_data,n=numpoints,norm='ortho')
k=2*np.pi*np.fft.fftfreq(numpoints,d=dx)
"""Now the following process for convoluting R i.e
correlation fuction by convolution sampled data function with itself using
numpy.Though the same code can be use for conlvolution as spcified in problem 9"""
#power spectrum through convolution of R = colrelation function
#defining frequency array kq to plot dft w.r.t it
kq=np.fft.fftfreq(numpoints,d=dx)
#defining fourier transformed variable say(k) corresponding to data points say(x)
k=2*np.pi*kq
factor1=np.exp(-1j*k*xmin)
#Defining corelation function using Periodogram estimator
R=np.convolve(sampled_data,sampled_data,'same')/(2*numpoints)
#Defining power spectrum to be forier transform of the correlation function
Power=np.abs(dx*np.sqrt(numpoints/(2.0*np.pi))*factor1*np.fft.fft(R,norm='ortho'))
#plotting of sampled data
plt.plot(sampled_data)
plt.xlabel('n',fontsize=16)
plt.ylabel('sampled function value',fontsize=16)
plt.show()
#plotting of dft of sampled data
plt.plot(kq,dft)
plt.title('DFT ',fontsize=15)
plt.xlabel('kq',fontsize=16)
plt.ylabel('DFT of function value',fontsize=16)
plt.show()
#plotting of power spectrum
plt.plot(k,Power)
plt.title('Power Spectrum ',fontsize=15)
plt.xlabel(r'$k$',fontsize=16)
plt.ylabel(r'Power spectrum',fontsize=16)
plt.show()
#plotting the power spectrum bins
bins=10
plt.hist(Power,bins)
plt.title('Actual Binned power spectrum ',fontsize=15)
plt.xlabel(r'Power spectrum',fontsize=16)
plt.ylabel(r'Occurance',fontsize=16)
plt.show()
#plotting of power spectrum through ft
f_k=dx*np.sqrt(numpoints/(2.0*np.pi))*factor1*dft
p=np.abs(f_k)**2/numpoints #power spectrum using Periodogram estimator
plt.plot(k,p)
plt.title('Power Spectrum through FT ',fontsize=15)
plt.ylabel('non_stocastic power spectrum',fontsize=16)
plt.xlabel('n',fontsize=16)
plt.show()
#plotting the power spectrum bins if the process were non stocastic
bins=10
plt.hist(p,bins)
plt.title('Binned power spectrum Power Spectrum through FT',fontsize=15)
plt.xlabel(r'Power spectrum',fontsize=16)
plt.ylabel(r'Occurance',fontsize=16)
plt.show()
|
import math
def is_right_triangle(a, b, c):
'Determines whether the three side lengths form a right triangle, where C is the hypotenuse'
return (a ** 2) + (b ** 2) == c ** 2
def pyth_triplets(perimeter):
'Generates all the pythagorean triplets with the given perimeter'
for c in range(1, perimeter / 2):
for b in range(int(math.ceil((perimeter - c) / 2.0)), perimeter - c):
a = perimeter - c - b
if is_right_triangle(a, b, c):
yield (a, b, c)
print([x[0] * x[1] * x[2] for x in pyth_triplets(1000)]) |
def multiple_sum(multiple_cap, *args):
''' Calculates the sum of the multiples of the provided arguments
All multiples in [1, multiple_cap) will be considered'''
return sum(x for x in range(1, multiple_cap) if any(x % y == 0 for y in args))
print(multiple_sum(1000, 3, 5)) |
def proper_divisors(num):
'Generates all numbers less than the input which divide the input evenly'
return [x for x in range(1, num) if num % x == 0]
def is_amicable(n, divisor_sums):
return divisor_sums[n] in divisor_sums and divisor_sums[n] != n and divisor_sums[divisor_sums[n]] == n
divisor_sums = { x : sum(proper_divisors(x)) for x in range(1, 10000) }
print(sum(x for x in divisor_sums if is_amicable(x, divisor_sums))) |
my_list = [1,2,3];
your_list = [4,5,6];
print(my_list);
#indexing
print(my_list[1]);
#everything after that element
print(my_list[1:]);
#length of the array/string
print(len(my_list))
#concatonate lists
print(my_list + your_list);
#change items in the list
your_list[0] = 'four'
print(your_list)
#add new item to the end
your_list.append('seven')
print(your_list)
#remove last element of an array
popped_item = your_list.pop()
print(your_list)
print(popped_item)
all_list = your_list + my_list;
print(all_list);
#remove an element at a specific index
all_list.pop(-3);
print(all_list);
num_list = [1,5,7,4,3,6]
char_list = ['g','b','d','t','y','f','d']
#sorting a list - you've to execute sort fully before accesing
print(num_list)
num_list.sort()
print(num_list)
print(char_list)
char_list.reverse()
print(char_list)
|
import math
figure = input()
area = 0.0
if figure == "square":
side = float(input())
area = side ** 2
elif figure == "rectangle":
sideA = float(input())
sideB = float(input())
area = sideA * sideB
elif figure == "circle":
radius = float(input())
area = math.pi * radius ** 2
elif figure == "triangle":
side = float(input())
height = float(input())
area = side * height / 2
print(f"{area:.3f}")
|
text = input()
line = input()
while not line == "Finish":
data = line.split()
command = data[0]
if command == "Replace":
current_char = data[1]
new_char = data[2]
text = text.replace(current_char, new_char)
print(text)
elif command == "Cut":
start_index = int(data[1])
end_index = int(data[2])
if start_index in range(len(text)) and end_index in range(len(text)):
fist_half = text[:start_index]
second_half = text[end_index + 1:]
text = fist_half + second_half
print(text)
else:
print("Invalid indices!")
elif command == "Make":
method = data[1]
if method == "Upper":
text = text.upper()
elif method == "Lower":
text = text.lower()
print(text)
elif command == "Check":
string = data[1]
if string in text:
print(f"Message contains {string}")
else:
print(f"Message doesn't contain {string}")
elif command == "Sum":
start_index = int(data[1])
end_index = int(data[2])
if start_index in range(len(text)) and end_index in range(len(text)):
substring = text[start_index:end_index+1]
substring = sum([ord(char) for char in substring])
print(substring)
else:
print("Invalid indices!")
line = input()
|
import math
change_in_leva = float(input())
change = math.floor(change_in_leva * 100)
count_coins = 0
while change != 0:
if change >= 200:
change -= 200
count_coins += 1
elif change >= 100:
change -= 100
count_coins += 1
elif change >= 50:
change -= 50
count_coins += 1
elif change >= 20:
change -= 20
count_coins += 1
elif change >= 10:
change -= 10
count_coins += 1
elif change >= 5:
change -= 5
count_coins += 1
elif change >= 2:
change -= 2
count_coins += 1
elif change >= 1:
change -= 1
count_coins += 1
else:
print(count_coins) |
command = input()
c_counter = 0
o_counter = 0
n_counter = 0
word = ""
word_to_print = ""
while command != "End":
letter = command
if ("a" <= letter <= 'z') or ('A' <= letter <= 'Z'):
if letter == "c" and c_counter == 0:
c_counter += 1
elif letter == "o" and o_counter == 0:
o_counter += 1
elif letter == "n" and n_counter == 0:
n_counter += 1
else:
word += letter
if c_counter != 0 and o_counter != 0 and n_counter != 0:
c_counter = 0
o_counter = 0
n_counter = 0
word_to_print += word
word_to_print += " "
word = ""
command = input()
print(word_to_print)
|
height_house = float(input())
length_house = float(input())
height_roof = float(input())
side_wall_of_house = height_house * length_house
window = 1.5 * 1.5
sum_wallsides_of_house = (side_wall_of_house * 2) - (window * 2)
backside_house = height_house * height_house
entrance = 1.2 * 2
sum_backsides_house = (backside_house * 2) - entrance
total_area_house = sum_wallsides_of_house + sum_backsides_house
green_paint = total_area_house / 3.4
wallside_roof = 2 * side_wall_of_house
frontside_roof = 2 * (height_house * height_roof / 2)
total_area_roof = wallside_roof + frontside_roof
red_paint = total_area_roof / 4.3
print(f"{green_paint:.2f}")
print(f"{red_paint:.2f}") |
destination = input()
saved_money_all = 0
while destination != "End":
budget = float(input())
while saved_money_all < budget:
saved_money = float(input())
saved_money_all += saved_money
else:
print(f"Going to {destination}!")
saved_money_all = 0
destination = input() |
data = input()
cities = {}
while not data == "Sail":
city, population, gold = data.split("||")
population = int(population)
gold = int(gold)
if city not in cities:
cities[city] = {"population": population, "gold": gold}
else:
cities[city]["population"] += population
cities[city]["gold"] += gold
data = input()
line = input()
while not line == "End":
data = line.split("=>")
command = data[0]
city = data[1]
if command == "Plunder":
people = int(data[2])
gold = int(data[3])
cities[city]["population"] -= people
cities[city]["gold"] -= gold
print(f"{city} plundered! {gold} gold stolen, {people} citizens killed.")
if cities[city]["population"] == 0 or cities[city]["gold"] == 0:
del cities[city]
print(f"{city} has been wiped off the map!")
elif command == "Prosper":
gold = int(data[2])
if gold >= 0:
cities[city]["gold"] += gold
print(f"{gold} gold added to the city treasury. {city} now has {cities[city]['gold']} gold.")
else:
print("Gold added cannot be a negative number!")
line = input()
sorted_towns = sorted(cities.items(), key=lambda x: (-x[1]['gold'], x[0]))
print(f"Ahoy, Captain! There are {len(sorted_towns)} wealthy settlements to go to:")
for town, value in sorted_towns:
if sorted_towns:
print(f"{town} -> Population: {value['population']} citizens, Gold: {value['gold']} kg")
else:
print("Ahoy, Captain! All targets have been plundered and destroyed!") |
import re
def replace_special_chars(line):
return re.sub(r"[-_.,!#$%^&*()<>?/|}{~:]", "@", line)
with open("text.txt", "r") as file:
lines = file.readlines()
for row in range(len(lines)):
if row % 2 == 0:
replaced_text = replace_special_chars(lines[row]).split()
print(" ".join(replaced_text[::-1]))
|
start_letter = int(input())
end_letter = int(input())
for letter in range(start_letter, end_letter + 1):
print(chr(letter), end=" ") |
import math
days_off = int(input())
animals_food_kg = int(input())
daily_dog_food_kg = float(input())
daily_cat_food_kg = float(input())
daily_turtle_food_g = float(input())
dog_food_sum = days_off * daily_dog_food_kg
cat_food_sum = days_off * daily_cat_food_kg
turtle_food_sum = (days_off * daily_turtle_food_g) / 1000
total_food_sum = dog_food_sum + cat_food_sum + turtle_food_sum
if animals_food_kg >= total_food_sum:
food_left = animals_food_kg - total_food_sum
print(f"{math.floor(food_left)} kilos of food left.")
else:
food_need = total_food_sum - animals_food_kg
print(f"{math.ceil(food_need)} more kilos of food are needed.") |
import math
magnolias_cnt = int(input())
hyacinths_cnt = int(input())
roses_cnt = int(input())
cactus_cnt = int(input())
present_price = float(input())
magnolias_price = magnolias_cnt * 3.25
hyacinths_price = hyacinths_cnt * 4
roses_price = roses_cnt * 3.50
cactus_price = cactus_cnt * 8
total_price_with_tax = (magnolias_price + hyacinths_price + roses_price + cactus_price) * 0.95
if total_price_with_tax >= present_price:
money_left = total_price_with_tax - present_price
print(f"She is left with {math.floor(money_left)} leva.")
else:
money_need = present_price - total_price_with_tax
print(f"She will have to borrow {math.ceil(money_need)} leva.") |
message = input().split()
new_message = []
for word in message:
str_to_conv = ""
string_words = []
num_letter = [letter for letter in word if letter.isdigit()]
letter_as_num_ascii = int("".join(map(str, num_letter)))
str_to_conv += chr(letter_as_num_ascii)
for index in word:
if index.isalpha():
string_words.append(index)
string_words[0], string_words[-1] = string_words[-1], string_words[0]
string_words = str_to_conv + "".join(string_words)
new_message.append(string_words)
new_message = " ".join(new_message)
print(new_message) |
from math import floor
def is_valid(n, pot_row, pot_col):
return 0 <= pot_row < n and 0 <= pot_col < n
n = int(input())
matrix = []
player_position = []
for i in range(n):
line = [char for char in input().split()]
matrix.append(line)
if "P" in line:
player_column_index = line.index("P")
player_row_index = i
player_position = [player_row_index, player_column_index]
commands = {
'up': (-1, 0),
'down': (1, 0),
'left': (0, -1),
'right': (0, 1),
}
is_out = False
total_coins = 0
path = []
while total_coins <= 100:
command = input()
start_row, start_column = player_position
new_row, new_column = commands[command]
potential_row = start_row + new_row
potential_col = start_column + new_column
if is_valid(n, potential_row, potential_col):
if matrix[potential_row][potential_col].isdigit():
number = int(matrix[potential_row][potential_col])
total_coins += number
elif matrix[potential_row][potential_col] == "X":
total_coins = total_coins / 2
is_out = True
break
player_position = [potential_row, potential_col]
path.append(player_position)
else:
total_coins = total_coins / 2
is_out = True
break
if total_coins >= 100:
break
if is_out:
print(f"Game over! You've collected {floor(total_coins)} coins.")
else:
print(f"You won! You've collected {total_coins} coins.")
print("Your path:")
print(*[p for p in path], sep='\n')
|
import re
participants = input().split(", ")
results = {el: 0 for el in participants}
pattern_words = r"[A-Za-z+]"
nums_pattern = r"\d"
line = input()
while not line == "end of race":
name = re.findall(pattern_words, line)
name = "".join(name)
distance = re.findall(nums_pattern, line)
sum_distance = 0
for num in distance:
sum_distance += int(num)
if name in results:
if not results[name] == 0:
results[name] += sum_distance
else:
results[name] = sum_distance
line = input()
sorted_results = dict(sorted(results.items(), key=lambda x: -x[1]))
winners = []
for name in sorted_results:
winners.append(name)
print(f"1st place: {winners[0]}")
print(f"2nd place: {winners[1]}")
print(f"3rd place: {winners[2]}") |
positive_list = input().split(", ")
def palindrome_integers(numbers):
for number in positive_list:
if number[::] == number[::-1]:
print("True")
else:
print("False")
return palindrome_integers
palindrome_integers(positive_list)
|
n = int(input())
previous_pair_sum = 0
pair_difference = 0
max_difference = 0
for i in range(n):
pair_sum = int(input()) + int(input())
if i == 0:
previous_pair_sum = pair_sum
if pair_sum != previous_pair_sum:
pair_difference = abs(pair_sum - previous_pair_sum)
previous_pair_sum = pair_sum
if pair_difference > max_difference:
max_difference = pair_difference
if max_difference == 0:
print(f"Yes, value={pair_sum}")
else:
print(f"No, maxdiff={max_difference}") |
def init_matrix():
n = int(input())
matrix = [[0 for x in range(n)] for _ in range(n)]
return matrix
def plant_mines(bombs_count, matrix):
for _ in range(bombs_count):
row_index, column_index = [int(el) for el in input()[1:-1].split(", ")]
matrix[row_index][column_index] = "*"
if row_index - 1 in range(len(matrix)) and matrix[row_index - 1][column_index] != "*": # up
matrix[row_index - 1][column_index] += 1
if row_index + 1 in range(len(matrix)) and matrix[row_index + 1][column_index] != "*": # down
matrix[row_index + 1][column_index] += 1
if column_index - 1 in range(len(matrix)) and matrix[row_index][column_index - 1] != "*": # left
matrix[row_index][column_index - 1] += 1
if column_index + 1 in range(len(matrix)) and matrix[row_index][column_index + 1] != "*": # right
matrix[row_index][column_index + 1] += 1
if row_index - 1 in range(len(matrix)) and column_index - 1 in range(len(matrix)) and matrix[row_index - 1][
column_index - 1] != "*":
matrix[row_index - 1][column_index - 1] = int(
matrix[row_index - 1][column_index - 1]) + 1 # up left diagonal
if row_index - 1 in range(len(matrix)) and column_index + 1 in range(len(matrix)) and matrix[row_index - 1][
column_index + 1] != "*":
matrix[row_index - 1][column_index + 1] = int(
matrix[row_index - 1][column_index + 1]) + 1 # up right diagonal
if row_index + 1 in range(len(matrix)) and column_index - 1 in range(len(matrix)) and matrix[row_index + 1][
column_index - 1] != "*":
matrix[row_index + 1][column_index - 1] = int(
matrix[row_index + 1][column_index - 1]) + 1 # down left diagonal
if row_index + 1 in range(len(matrix)) and column_index + 1 in range(len(matrix)) and matrix[row_index + 1][
column_index + 1] != "*":
matrix[row_index + 1][column_index + 1] = int(
matrix[row_index + 1][column_index + 1]) + 1 # down right diagonal
matrix = [" ".join([str(el) for el in el]) for el in matrix]
return matrix
matrix = init_matrix()
bombs_count = int(input())
matrix = plant_mines(bombs_count, matrix)
print(*[el for el in matrix], sep='\n')
|
wide_free_space = int(input())
length_free_space = int(input())
height_free_space = int(input())
boxes_command = input()
boxes = 0
free_space = wide_free_space * length_free_space * height_free_space
while boxes_command != "Done":
boxes = int(boxes_command)
if free_space < boxes:
break
free_space -= boxes
boxes_command = input()
if boxes_command == "Done":
print(f"{free_space} Cubic meters left.")
else:
print(f"No more free space! You need {boxes - free_space} Cubic meters more.") |
budget = int(input())
season = input()
fishermen_cnt = int(input())
rent_ship = 0
if season == "Spring":
rent_ship = 3000
elif season == "Summer" or season == "Autumn":
rent_ship = 4200
elif season == "Winter":
rent_ship = 2600
if fishermen_cnt <= 6:
rent_ship *= 0.90
elif 7 <= fishermen_cnt <= 11:
rent_ship *= 0.85
elif fishermen_cnt >= 12:
rent_ship *= 0.75
if fishermen_cnt % 2 == 0 and not season == "Autumn":
rent_ship *= 0.95
if budget >= rent_ship:
money_left = budget - rent_ship
print(f"Yes! You have {money_left:.2f} leva left.")
else:
money_need = rent_ship - budget
print(f"Not enough money! You need {money_need:.2f} leva.")
|
import os
def create_file(file_name):
with open(file_name, "w") as file:
file.write("")
def add_to_file(file_name, content):
with open(file_name, "a") as file:
file.write(content + "\n")
def replace_string_to_file(file_name, content, replaced):
try:
with open(file_name, "r+") as file:
text = "".join(file.readlines())
replaced_text = text.replace(content, replaced)
file.seek(0)
file.write(replaced_text)
except FileNotFoundError:
print("An error occurred")
def delete_file(file_name):
try:
os.remove(file_name)
except FileNotFoundError:
print("An error occurred")
mapper = {"Create": create_file, "Add": add_to_file, "Replace": replace_string_to_file, "Delete": delete_file}
def start_program():
data = input().split("-")
while not data[0] == "End":
command, command_data = data[0], data[1:]
mapper[command](*command_data)
data = input().split("-")
start_program()
|
def binary_search(A, key):
left = -1
right = len(A)
while right > left + 1:
middle = (left + right) // 2
if A[middle] >= key:
right = middle
else:
left = middle
return right if A[right] == key else -1
|
from math import sqrt
class Sudoku:
puzzle = []
def __init__(self, puzzle):
self.puzzle = puzzle
def __len__(self):
return len(self.puzzle)
def __str__(self):
st = ""
for row in self.puzzle:
st = st + "\n"+str(row)
return st
def get_row(self, row):
return self.puzzle[row]
def get_col(self, col):
return [x[col] for x in self.puzzle]
def get_block(self, row, col):
x = col/3
y = row/3
size = int(sqrt(len(self)))
elms = []
for b in range(size*y, size*y+3):
for a in range(size*x, size*x+3):
elms.append(self.puzzle[b][a])
return elms
def is_valid(self, num, row, col):
return not (num in self.get_row(row) or num in self.get_col(col) or num in self.get_block(row, col))
def get_valids(self, row, col):
cands = []
for i in range(1, len(self.puzzle)+1):
if (self.is_valid(i, row, col)):
cands.append(i)
return cands
def insert(self, val, row, col):
self.puzzle[row][col] = val
|
# Python Weakref
# weakref Weak references.
# The weakref module allows the Python programmer to create weak references to objects.
#
# In the following, the term referent means the object which is referred to by a weak reference.
# A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage
# collection is free to destroy the referent and reuse its memory for something else.
# However, until the object is actually destroyed the weak reference may return the object even if there are no strong references to it.
# A primary use for weak references is to implement caches or mappings holding large objects, where its desired that a large object not be kept alive
# solely because it appears in a cache or mapping.
#
#
# If the referent no longer exists, calling the reference object returns None:
#
del o, o2
print(r())
# OUTPUT: 'None'
|
#1
# spam = 0
# while spam < 5:
# print("Hello World!")
# spam = spam +1
#2
# name = ''
# while name != 'your name':
# print('please type your name')
# name = input()
# print('Thank you!')
#3
# name = ''
# while True:
# print('please type your name')
# name = input()
# if name == 'your name':
# break #when break is executed, it jumps out of the while loop
# print('Thank you!')
#4
spam = 0
while spam < 5:
spam = spam +1
if spam == 3:
continue #When continue is executed, it returns to beginning of the while loop and evaluates the expression again
print("Spam is " + str(spam)) |
print("===== using map =======")
# what is map function?
"""
- apply same function to each element of a sequence / list
- return the modified list
"""
list_1 = [1, 2, 3, 4]
def square_up(list_1):
list_2 = []
for num in list_1:
list_2.append(num ** 2)
return list_2
print("Square up using explicit function: {}".format(square_up(list_1)))
square_map_lambda = list(map(lambda x: x ** 2, list_1))
print("Square up using map+lambda: {}".format(square_map_lambda))
from numpy import square
square_map_lambda = list(map(square, list_1))
print("Square up using map+square: {}".format(square_map_lambda))
square_map_lambda = list(n * n for n in list_1) # OR [n * n for n in list_1]
print("Square up using list comprehension: {}".format(square_map_lambda))
print("\n\n===== using filter =======")
def over_two(list_1):
list_2 = [n for n in list_1 if n > 2]
return list_2
print("Filter >2 using explicit function: {}".format(over_two(list_1)))
print("Filter >2 using filter+lambda: {}".format(list(filter(lambda x: x > 2, list_1))))
generator_with_over_two = (n for n in list_1 if n > 2)
print("generator_with_over_two from list comprehension: {}".format(generator_with_over_two))
print("generator_with_over_two from list comprehension: {}".format(type(generator_with_over_two)))
print("Filter >2 using list comprehension: {}".format(list(generator_with_over_two)))
print("\n\n===== using reduce =======")
# what is reduce function?
"""
- applies same operation to items of a sequence / list
- uses result of operation as first param of next operation
- returns an item, not a list
Example:
List = [m, n, o] and Reduce Function = f()
execution would be like this: f(f(m, n), o)
"""
def mult_list_items(list_1):
if len(list_1) < 1:
print("Input list is Empty")
return -1
result = list_1[0]
for i in range(1, len(list_1)):
result *= list_1[i]
return result
print("Multiply list items using explicit function: {}".format(mult_list_items(list_1)))
from functools import reduce
print("Multiply list items using reduce+lambda: {}".format(reduce(lambda x, y: x * y, list_1)))
|
# Loop through a List
print("-------------------Loop through a List---------------------------------")
nums = [1, 3, 5, 7]
target = 3
for num in nums:
print('item is={}'.format(num))
if num == target:
print('Found the target')
break
else:
print('Moving on')
print("---------------------Using continue------------------------------------")
for num in nums:
if num <= target:
print('continue')
continue
else:
print(num)
print("-------------------Loop through a Range--------------------------------")
for i in range(5):
print(i)
print("-----------------------------------------------------------------------")
# use a starting point in a range
for i in range(2, 5):
print(i)
print("-----------------------------------------------------------------------")
print("-----------------------------------------------------------------------")
print("-----------------------------------------------------------------------")
print("-----------------------------------------------------------------------")
|
# https://www.techbeamers.com/python-inheritance/
class Car:
def __init__(self, make, model, variant):
self._make = make
self._model = model
self._variant = variant
def getMake(self):
return self._make
def getModel(self):
return self._model
def getVariant(self):
return self._variant
def setVariant(self, variant):
self._variant = variant
class SportsCar(Car):
def __init__(self, make, model, variant, color):
super(SportsCar, self).__init__(make, model, variant)
self._color = color
def getColor(self):
return self._color
def vehicleInfo(self):
return self.getMake() + " " + self.getModel() + " " + self.getVariant() + " in " + self._color
c1 = SportsCar("Dodge", "Charger", "RT", "Tri-Quote Red")
print("c1: ", c1.vehicleInfo())
# class to create sports car with size definition
class SportsCarWithSize(SportsCar):
def __init__(self, make, model, variant, color, size):
super(SportsCarWithSize, self).__init__(make, model, variant, color)
self._size = size
# override vehicleInfo()
def vehicleInfo(self):
return self.getMake() + " " + self.getModel() + " " + self.getVariant() + "in" + self.getColor() + " and size" + self._size
c2 = SportsCarWithSize("Ford", "Mustang", "GT", "Dark Grey", "Coupe")
print("c2 vehicleInfo: ", c2.vehicleInfo())
# access base class function
print("c2 vehicleInfo without Size: ", SportsCar.vehicleInfo(c2))
|
import random
UKRAINIAN_ALPHABET_LETTERS = ['ь', 'і', 'ю', 'я', 'є', 'ї']
SYMBOLS = [' ', '!', ':', "'", '"', '`', '/', '?', '.', ',']
def all_symbols(lang: str):
letters = []
if lang == 'ukr':
common_cyrillic_letters = [chr(i) for i in range(ord('а'), ord('ъ'))]
letters = common_cyrillic_letters + UKRAINIAN_ALPHABET_LETTERS
elif lang == 'eng':
letters = [chr(i) for i in range(ord('a'), ord('z')+1)]
upper_letters = [letter.upper() for letter in letters]
#digits = [str(i) for i in range(10)]
symbols = letters + upper_letters + SYMBOLS
random.shuffle(symbols)
return symbols
def get_char(code: int, symbols: list):
return symbols[code]
def get_code(char: str, symbols: list):
return ''.join(symbols).find(char)
ALL_SYMBOLS_UKR = all_symbols('ukr')
ALL_SYMBOLS_ENG = all_symbols('eng')
|
# 1. Note the variable account_types, the list of account types.
# 2. Create a function called gatekeeper that returns the following error message strings in the following scenarios:
# For “admin”:
# program says “You have the privileges.”
# For “user”:
# program says “You have limited privileges.”
# For “guest”:
# program says “You have no privileges.”
# 3. Call your function with a string and print what it returns.
# 4. How could this code be improved? Make it better. Think about what other scenarios you should cover in your if logic.
# 5. Create a function called check_balance that takes one parameter, loan_balance.
# 6. If loan_balance is zero or more, it says “you don’t owe any money”
# 7. If loan_balance is negative, it says “you owe $X” where X is the amount
# 8. Call your function with a negative and positive number and print what it returns.
account_types = ["admin", "user", "guest"]
|
def decimal_to_binary(n):
bit_8 = 0
bit_7 = 0
bit_6 = 0
bit_5 = 0
bit_4 = 0
bit_3 = 0
bit_2 = 0
bit_1 = 0
while n > 0:
if n >= 128:
n -= 128
bit_8 = 1
elif n >= 64:
n -= 64
bit_7 = 1
elif n >= 32:
n -= 32
bit_6 = 1
elif n >= 16:
n -= 16
bit_5 = 1
elif n >= 8:
n -= 8
bit_4 = 1
elif n >= 4:
n -= 4
bit_3 = 1
elif n >= 2:
n -= 2
bit_2 = 1
elif n >= 1:
n -= 1
bit_1 = 1
print(bit_8, bit_7, bit_6, bit_5, bit_4, bit_3, bit_2, bit_1)
running = True
print("welcome to the decimal to binary converter")
while running:
num = int(input("Enter the number you wish to convert (no bigger than 255): "))
decimal_to_binary(num)
|
import numpy as np
import itertools
import timeit
import matplotlib.pyplot as plt
m = int(input('number of clauses(rows), m = '))
n = int(input('number of literals(coloumns), n = '))
matrix = []; columns = []
# initialize the number of rows
for i in range(0,m):
matrix += [0]
# initialize the matrix
for i in range (0,m):
matrix[i] = [0]*n
for i in range (0,m):
for j in range (0,n):
print ('entry in row: ',i+1,' column: ',j+1)
matrix[i][j] = int(input())
if matrix[i][j]>1 or matrix[i][j]<-1:
print("Invalid input:Enter correct input")
print ('entry in row: ',i+1,' column: ',j+1)
matrix[i][j]=int(input())
#print (matrix)
ct=0
matrix1 = np.array(matrix)
print(matrix1)
for row in matrix1:
if any(i >0 for i in row):
ct=ct+1
print(row)
#x= np.where(matrix1.any(axis=1))[0]
#print(matrix1.any(axis=1))
#print(np.where(matrix1.any(axis=1)))
#print(x)
if ct!=m:
print("Solution to the satisfiability problem doesnt exist")
else:
print("Solution to the given satisfiability probelm is true")
'''---------'''
#below code to get the samples vs time output
'''
for n in range(10,21):
matrix = []; columns = []
# initialize the number of rows
m=10
for i in range(0,m):
matrix += [0]
# initialize the matrix
for i in range (0,m):
matrix[i] = [0]*n
for i in range (0,m):
for j in range (0,n):
#print ('entry in row: ',i+1,' column: ',j+1)
#matrix[i][j] = int(input())
#if matrix[i][j]>1 or matrix[i][j]<-1:
#print("Invalid input:Enter correct input")
#print ('entry in row: ',i+1,' column: ',j+1)
matrix[i][j]=np.random.randint(-1,1)
#print (matrix)
ct=0
matrix1 = np.array(matrix)
print(matrix1)
row=[]
start=0
start = timeit.default_timer()
for row in matrix1:
if any(i >0 for i in row):
ct=ct+1
print(row)
if ct!=m:
print("Solution to the satisfiability problem is 0")
else:
print("Solution to satisfiability probelm is true")
stop=0
stop = timeit.default_timer()
print("Time required for SAT with ",n," variables is:",stop-start)
plt.plot(stop-start, n)
plt.show()
|
from sys import argv
import sys
import random
import os.path
import os
def load_items_from_file(filename = 'gimme.txt'):
if (os.path.isfile(filename)):
contents = open(filename)
return contents.readlines()
return []
def add_item(item, filename = 'gimme.txt'):
if (item in items):
return
with open(filename, "a") as item_file:
item_file.write(item + '\n')
done = []
items = load_items_from_file()
def get_items(count = 0):
print "Getting %s items" % m
i = 0
while (len(items) != len(done)) and (i < count):
item = random.choice(items)
if (item not in done):
i = i + 1
done.append(item)
print "Item %d: %s" % (i, item),
input = ''
try:
filename, count = argv
m = int(float(count))
"""
Fix this
print argv
"""
get_items(m)
sys.exit(0)
except ValueError:
print 'Did not ask for items, continuing...'
while input != 'q' and input != 'x':
input = raw_input('\nWhat do you want to do? ')
if input == 'g' or input == 'l' or input == 'ls':
print 'Getting list...'
if os.path.exists('gimme.txt'):
filename = open('gimme.txt')
print filename.read()
else:
print "No file"
if input == 'n' or input == 'a':
new_item = raw_input("\nWhat do you wana add? ")
add_item(new_item)
load_items_from_file()
if input == 'd' or input == 'r':
exit_or_not = raw_input("Are you sure you want to delete your file?(y/n): ")
if exit_or_not =='y':
os.remove('gimme.txt')
print "deleted!"
if input == '-i' or input == 'info':
print """ g, l = get list \\ n, a = add \n d, r = delete \\ y, n = yes/no
"""
print 'exiting...'
|
import random
def is_prime(num):
for i in range(2, num):
if num % i == 0:
return False
return True
def generator_prime(max_num):
for num in range(2, max_num):
if is_prime(num):
yield num
return
double = (x * 2
for x in range(10))
def initial():
print(list(map((lambda x: x * 2), range(1, 11))))
print([2 * x
for x in range(1, 11)])
print(list(filter((lambda x: x % 2 != 0), range(1, 11))))
print([x
for x in range(1, 11)
if x % 2 != 0])
print([i ** 2
for i in range(50)
if i % 8 == 0])
print([x * y
for x in range(1, 3)
for y in range(11, 16)])
print([x
for x in [i * 2
for i in range(10)]
if x % 8 == 0])
multi_list = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print([col[1]
for col in multi_list])
print([multi_list[i][i]
for i in range(len(multi_list))])
prime = generator_prime(50)
print("Prime :", next(prime))
print("Prime :", next(prime))
print("Prime :", next(prime))
print("Prime :", next(prime))
print("Prime :", next(prime))
print("Double :", next(double))
print("Double :", next(double))
print("Double :", next(double))
print("Double :", next(double))
print("Double :", next(double))
return
def test():
print([x
for x in [random.randrange(1, 1001)
for i in range(50)]
if x % 9 == 0])
return
if __name__ == "__main__":
initial()
# test()
|
import section_22_Sum as s
class Sum:
@staticmethod
def get_sum(*args):
sum_1 = 0
for i in args:
sum_1 += i
return sum_1
class Dog:
num_of_dogs = 0
def __init__(self, name="Default"):
self.name = name
Dog.num_of_dogs += 1
def __str__(self):
return "Name : {}, Total : {}".format(self.name, Dog.num_of_dogs)
if __name__ == "__main__":
print(Sum.get_sum(1, 2, 4, 8, 7, 5))
spocka = Dog("A")
print(spocka)
spockb = Dog("B")
print(spockb)
spockc = Dog("C")
print(spockc)
print(s.get_sum(1, 2, 4, 8, 7, 5)) |
def pattern_1():
l_list = (1, 1, 1, 1, 4)
i_list = (1, 1, 1, 1, 1)
f_list = (4, 1, 2, 1, 1)
e_list = (4, 1, 2, 1, 4)
choice = input(">> Choice Character : ")
for i in l_list:
print(choice * i)
print()
for i in i_list:
print(choice * i)
print()
for i in f_list:
print(choice * i)
print()
for i in e_list:
print(choice * i)
return
def pattern_2():
choice = input(">> Choice Character : ")
print(choice)
for j in range(2):
for i in range(4):
print(choice, " " * i, choice)
for i in range(4, -1, -1):
print(choice, " " * i, choice)
print(choice)
return
if __name__ == "__main__":
# pattern_1()
pattern_2()
|
def factorial_1(num):
if num <= 1:
return 1
else:
return num * factorial_1(num - 1)
def test_fibonacci_1(num):
if num == 1 or num == 0:
return num
else:
return test_fibonacci_1(num - 1) + test_fibonacci_1(num - 2)
def test2(num):
i = 1
while i <= num:
print(test_fibonacci_1(i))
i += 1
def initial():
print("factorial(7) :", factorial_1(7))
print(test_fibonacci_1(10))
print(test2(10))
return
if __name__ == "__main__":
initial()
|
import random
import numpy
from ase import Atom, Atoms
def gen_pop_box(atomlist, size, crystal=False):
"""Function to generate a random structure of atoms.
Inputs:
atomlist = List of tuples with structure of atoms and quantity
[('Sym1', int(concentration1), float(mass1), float(chempotential1)),
('Sym2', int(concentration2), float(mass2), float(chempotential2)), ...]
size = Float of length of side of cube within which to generate atoms
crystal = False/List of crystal cell shape options
list('cubic', 'orthorhombic', 'tetragonal', 'hexagonal', 'monoclinic', 'triclinic')
cell shape will be adjusted accordingly
Outputs:
Returns individual of class Atoms (see ase manual for info on Atoms class)
and if crystal list provided also outputs combined string with output information
"""
indiv = Atoms()
indiv.set_cell([size, size, size])
# Get list of atom types for all atoms in cluster
for s, c, m, u in atomlist:
if c > 0:
for i in range(c):
pos = [random.uniform(0, size) for j in range(3)]
at = Atom(symbol=str(s), position=pos)
indiv.append(at)
if not crystal:
return indiv
else:
stro = ''
natoms = sum([c for s, c, m, u in atomlist])
pos = indiv.get_scaled_positions()
structure = random.choice(crystal).lower()
cello = indiv.get_cell()
if structure == 'cubic':
# Set to cubic shape
an, bn, cn = [numpy.linalg.norm(v) for v in cello]
a = (an+bn+cn)/3.0
celln = numpy.array([[a, 0, 0], [0, a, 0], [0, 0, a]])
stro += 'Setting cell to cubic\n'
elif structure == 'orthorhombic':
# Set to orthorhombic
a = random.uniform(2, natoms**0.3333*size)
b = random.uniform(2, natoms**0.3333*size)
c = random.uniform(2, natoms**0.3333*size)
celln = numpy.array([[a, 0, 0], [0, b, 0], [0, 0, c]])
stro += 'Setting cell to orthorhombic\n'
elif structure == 'tetragonal':
# Set to tetragonal shape
an, bn, cn = [numpy.linalg.norm(v) for v in cello]
a = (an+bn)/2.0
c = cn
if c == a:
c = random.uniform(1, natoms**0.3333*size)
celln = numpy.array([[a, 0, 0], [0, a, 0], [0, 0, c]])
stro+= 'Setting cell to tetragonal\n'
elif structure == 'hexagonal':
# Set to hexagonal shape
an, bn, cn = [numpy.linalg.norm(v) for v in cello]
a = (an+bn)/2.0
c = cn
if c <= a:
c = random.uniform(a+1, natoms**0.3333*size)
trans = numpy.array([[1, 0, 0], [-0.5, (3.0**0.5)/2.0, 0], [0, 0, 1]])
trans[0] = [a*i for i in trans[0]]
trans[1] = [a*i for i in trans[1]]
trans[2] = [c*i for i in trans[2]]
celln = trans
stro += 'Setting cell to Hexagonal\n'
elif structure == 'monoclinic':
# Set to monoclinic
a, b, c = [numpy.linalg.norm(v) for v in cello]
if a == b:
b = random.uniform(1, natoms**0.3333*size)
trans = numpy.array([(1+random.random())*c, 0, (1+random.random())*c])
celln = numpy.array([[a, 0, 0], [0, b, 0], [0, 0, 0]])
celln[2] = trans
stro+= 'Setting cell to monoclinic\n'
elif structure == 'triclinic':
# Set to triclinic
a, b, c = [numpy.linalg.norm(v) for v in cello]
celln = numpy.array([[a, 0, 0], [(1+random.random())*b, (1+random.random())*b, 0], [(1+random.random())*c, 0, (1+random.random())*c]])
stro+= 'Setting cell to triclinic\n'
indiv.set_cell(celln)
indiv.set_scaled_positions(pos)
stro += repr(indiv.get_cell())+'\n'
return indiv, stro
|
from functools import lru_cache
@lru_cache(None)
def fibonacci(n):
if n < 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
for i in range(10):
print(fibonacci(i))
|
from typing import List, Dict, Tuple, Set
import math
class Node(object):
def __init__(self, order: int):
self.order = order
self.values = []
self.pointers = []
self.right = None
self.left = None
self.parent = None
self.is_leaf = False
def insert_in_leaf(self, value, pointer: int) -> None:
if self.values:
temp = self.values
for i in range(len(temp)):
if temp[i] == value: # equal
self.pointers[i].append(pointer)
break
if value < temp[i]: # less
self.pointers.insert(i, [pointer])
self.values.insert(i, value)
break
if i + 1 == len(temp): # biggest
self.pointers.append([pointer])
self.values.append(value)
break
else: # first couple
self.values.append(value)
self.pointers.append([pointer])
class BPlusTree(object):
def __init__(self, name: int, order: int = 3):
self.tree_name_m = name
self.root = Node(order)
self.root.is_leaf = True
def insert(self, value, pointer: int) -> None:
leaf = self.search(value)
leaf.insert_in_leaf(value, pointer)
if len(leaf.values) == leaf.order: # split the leaf node according to the order
new_node = Node(leaf.order)
new_node.is_leaf = True
new_node.parent = leaf.parent
mid = int(math.ceil(leaf.order / 2))
new_node.values = leaf.values[mid:]
new_node.pointers = leaf.pointers[mid:]
leaf.values = leaf.values[:mid]
leaf.pointers = leaf.pointers[:mid]
# new_node 在leaf 右边,更新左右兄弟
new_node.right = leaf.right
if leaf.right is not None:
leaf.right.left = new_node
leaf.right = new_node
new_node.left = leaf
# 插入维护
self.__insert_in_parent(leaf, new_node, new_node.values[0])
def __insert_in_parent(self, node1, node2, value):
if node1 == self.root:
rootNode = Node(node1.order)
rootNode.values = [value]
rootNode.pointers = [node1, node2]
node1.parent = rootNode
node2.parent = rootNode
self.root = rootNode
return
parentNode = node1.parent
temp = parentNode.pointers
for i in range(len(temp)):
if temp[i] == node1:
parentNode.values.insert(i, value)
parentNode.pointers.insert(i + 1, node2)
if len(parentNode.pointers) > parentNode.order:
uncle = Node(parentNode.order)
uncle.parent = parentNode.parent
mid = int(math.ceil(parentNode.order / 2))
uncle.values = parentNode.values[mid:]
uncle.pointers = parentNode.pointers[mid:]
newvalue = parentNode.values[mid - 1]
if mid == 1:
parentNode.values = parentNode.values[:mid]
else:
parentNode.values = parentNode.values[:mid - 1]
parentNode.pointers = parentNode.pointers[:mid]
for n in parentNode.pointers:
n.parent = parentNode
for n in uncle.pointers:
n.parent = uncle
self.__insert_in_parent(parentNode, uncle, newvalue)
else:
break
def search(self, value) -> Node: # get the leaf node where the value might in
current_node = self.root
while not current_node.is_leaf:
for i in range(len(current_node.values)):
if current_node.values[i] == value:
current_node = current_node.pointers[i + 1]
break
if value < current_node.values[i]:
current_node = current_node.pointers[i]
break
if i + 1 == len(current_node.values):
current_node = current_node.pointers[i + 1]
break
return current_node
def find(self, value, op: str) -> list: # get the list of pointer whose values is op(<.>,=,<=,>=) vaule
# global i, item
leaf = self.search(value)
addr = []
if not leaf.values:
return addr
for i, item in enumerate(leaf.values):
if value <= item:
break
if op == "=":
if value == item:
addr.append(leaf.pointers[i])
elif ">" in op:
addr += leaf.pointers[i:]
temp = leaf.right
while temp is not None:
addr += temp.pointers
temp = temp.right
if "=" not in op and value == item: # 大于
addr.pop(0)
elif value > item:
addr.pop(0)
elif "<" in op:
if "=" in op and value == item:
addr.append(leaf.pointers[i])
elif item < value:
addr.append(leaf.pointers[i])
addr += list(reversed(leaf.pointers[:i]))
temp = leaf.left
while temp is not None:
addr += temp.pointers[::-1]
temp = temp.left
addr = [sub for group in addr for sub in group] # flatten
return addr
def delete(self, pointer: int, value) -> int:
node = self.search(value)
temp = 0
for i, item in enumerate(node.values):
if item == value:
temp = 1
if pointer in node.pointers[i]:
if len(node.pointers[i]) > 1:
node.pointers[i].remove(pointer)
elif node == self.root:
node.values.pop(i)
node.pointers.pop(i)
else:
del node.pointers[i]
node.values.pop(i)
self.__delete_parents(node, pointer, value)
def __delete_parents(self, node, pointer, value):
if not node.is_leaf: # not leaf,then delete the pointer and value
for i, item in enumerate(node.pointers):
if item == pointer:
node.pointers.pop(i)
break
for i, item in enumerate(node.values):
if item == value:
node.values.pop(i)
break
if self.root == node and len(node.pointers) == 1:
self.root = node.pointers[0]
node.pointers[0].parent = None
del node
return
# 每个中间节点至少有ceil(m/2)个孩子,最多m个孩子;每个叶子节点至少都包含ceil(m/2)-1个元素
elif (len(node.pointers) < int(math.ceil(node.order / 2)) and node.is_leaf == False) or \
(len(node.values) < int(math.ceil(node.order / 2) - 1) and node.is_leaf == True):
is_predecessor = 0
parentNode = node.parent
PrevNode = -1 # 左兄弟结点
NextNode = -1 # 右兄弟节点
PrevK = -1 # 指针左边的数值
PostK = -1 # 指针右边的数值
for i, item in enumerate(parentNode.pointers):
if item == node:
if i > 0: # 不是父结点的第一个孩子
PrevNode = parentNode.pointers[i - 1]
PrevK = parentNode.values[i - 1]
if i < len(parentNode.pointers) - 1: # 不是父结点的最后一个孩子
NextNode = parentNode.pointers[i + 1]
PostK = parentNode.values[i]
if PrevNode == -1: # 第一个孩子
ndash = NextNode
value_ = PostK
elif NextNode == -1: # 最后一个孩子
is_predecessor = 1
ndash = PrevNode
value_ = PrevK
else: # 中间孩子
if len(node.values) + len(NextNode.values) < node.order: # 右兄弟结点不富余
ndash = NextNode
value_ = PostK
else:
is_predecessor = 1
ndash = PrevNode
value_ = PrevK
if len(node.values) + len(ndash.values) < node.order: # 兄弟结点不富余:合并处理
if is_predecessor == 0:
node, ndash = ndash, node # ndash是node的左兄弟
ndash.pointers += node.pointers # 合并两结点的pointers
if not node.is_leaf: # 内部节点
ndash.values.append(value_) # 父结点值下移
else: # 叶子结点需处理左右兄弟指针
ndash.right = node.right
if node.right is not None:
node.right.left = ndash
ndash.values += node.values # 合并左右兄弟的values
if not ndash.is_leaf: # 内部结点需将新增的pointer的父结点设为自己
for j in ndash.pointers:
j.parent = ndash
self.__delete_parents(node.parent, node, value_)
del node
else: # 兄弟结点富余
if is_predecessor == 1:
if not node.is_leaf: # 内部节点:父结点value下移,兄弟结点value上移
ndashpm = ndash.pointers.pop(-1)
ndashkm_1 = ndash.values.pop(-1)
node.pointers = [ndashpm] + node.pointers
node.values = [value_] + node.values
parentNode = node.parent
for i, item in enumerate(parentNode.values):
if item == value_:
parentNode.values[i] = ndashkm_1
break
else: # 叶子结点:
ndashpm = ndash.pointers.pop(-1)
ndashkm = ndash.values.pop(-1)
node.pointers = [ndashpm] + node.pointers
node.values = [ndashkm] + node.values
parentNode = node.parent
for i, item in enumerate(parentNode.values):
if item == value_:
parentNode.values[i] = ndashkm
break
else:
if not node.is_leaf: # 内部节点
ndashp0 = ndash.pointers.pop(0)
ndashk0 = ndash.values.pop(0)
node.pointers = node.pointers + [ndashp0]
node.values = node.values + [value_]
parentNode = node.parent
for i, item in enumerate(parentNode.values):
if item == value_:
parentNode.values[i] = ndashk0
break
else: # 叶子结点
ndashp0 = ndash.pointers.pop(0)
ndashk0 = ndash.values.pop(0)
node.pointers = node.pointers + [ndashp0]
node.values = node.values + [ndashk0]
parentNode = node.parent
for i, item in enumerate(parentNode.values):
if item == value_:
parentNode.values[i] = ndash.values[0]
break
# 把交换的结点的父结点设为当前结点
if not ndash.is_leaf:
for j in ndash.pointers:
j.parent = ndash
if not node.is_leaf:
for j in node.pointers:
j.parent = node
if not parentNode.is_leaf:
for j in parentNode.pointers:
j.parent = parentNode
def dict_structure(self, node=0):
if node == 0:
node = self.root
if node.is_leaf:
dict_set = {
"type": 'leaf',
"node_value": None,
"node_pointer": None,
'leaf_value': node.values,
'leaf_pointer': node.pointers,
'leaf_next_leaf': self.dict_structure(node.right) if node.right is not None else None
}
else:
dict_set = {
"type": 'node',
"node_value": node.values,
"node_pointer": [self.dict_structure(n) for n in node.pointers],
'leaf_value': None,
'leaf_pointer': None,
'leaf_next_leaf': None
}
return dict_set
|
def multiply(*list): # use Asterik to make it a tupple , tuples are iterable
total = 1
for number in list:
total *= number
return total
print(multiply(2, 3, 5, 6))
|
# old School
names = ["John", "Mary"]
found = False
for name in names:
if name.startswith("L"):
print("Found")
found = True
break # terminate iteration once found
if not found:
print("Not found")
# Cleaner Way with python with for else:
names = ["John", "Mary"]
for name in names:
if name.startswith("L"):
print("Found")
break # terminate iteration once found
else:
print("Not found")
|
# Local
def greet(): # define variable in local function
if True:
message = "a" # does not matter if defined in an if statement, still local to the function
print(message)
print(greet())
# Global
message = 'b'
def greet2():
global message # use to call for Global
message = "c"
print(greet2())
print(message)
# Avaoid Global its bad practice , it evil!
|
import pygame
'''
Uzupełnij klasę TextButton
Napis powinien być pozycjonowany na ekranie względem środkowych współrzędnych napisu
Przydatne funkcje:
mpx, mpy = pygame.mouse.get_post() # zwraca współrzędne kursora myszy
text.get_rect() # zwraca prostokąt otaczający wyrenderowany text
'''
class TextButton:
def __init__(self, center_x, center_y, font_name, font_size, text, color):
self.center_x = center_x
self.center_y = center_y
self.font = pygame.font.SysFont(font_name, font_size)
self.text = self.font.render(text, True, color)
self.text_rect = self.text.get_rect()
def cursor_hover(self):
# Zwraca True lub False w zależności od tego czy kursor znajduje się nad tekstem
mpx, mpy = pygame.mouse.get_pos()
if self.text_rect.left < mpx < self.text_rect.right and self.text_rect.top < mpy < self.text_rect.bottom:
return True
else:
return False
def update(self, text, color):
self.text = self.font.render(text, True, color)
self.text_rect = self.text.get_rect()
def draw(self, win):
self.text_rect.center = (self.center_x, self.center_y)
win.blit(self.text, self.text_rect) |
import pygame
from textbutton import TextButton
pygame.init()
pygame.display.set_caption("Blobby Volley")
bg = pygame.image.load("background.png")
w, h = 788, 444
win = pygame.display.set_mode((w, h))
run = True
clock = pygame.time.Clock()
button = TextButton(w/2, h/2, "comicsans", 40, "Click!", (0, 0, 0))
while run:
clock.tick(60)
button_hover = button.cursor_hover()
if button_hover:
button.update("Click!", (0, 200, 0))
else:
button.update("Click!", (0, 0, 0))
win.blit(bg, (0, 0))
button.draw(win)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
if button_hover:
run = False |
import mraa
AUTONOMOUS_SELECT_PIN = int(raw_input("Enter a pin number: "))
value = int(raw_input("Enter a value to write: either 0 or 1: "))
print ("writing a value of " + str(value) + " to pin " + str(AUTONOMOUS_SELECT_PIN))
auto_select_pin = mraa.Gpio(AUTONOMOUS_SELECT_PIN)
auto_select_pin.dir(mraa.DIR_OUT)
auto_select_pin.write(value)
|
from itertools import combinations
from functools import reduce
import sys
def findprimefactors(num):
i = 2
while i < num:
if num % i == 0:
factors = [i]
factors.extend(findprimefactors(num // i))
return factors
i += 1
return [num]
def finddivisors(num):
it = findprimefactors(num)
factors = set(it + [1, num])
for i in range(2, len(it)):
for j in combinations(it, i):
factors |= set([reduce(lambda x, y: x * y, j)])
return factors
def trinum(num):
return reduce(lambda x, y: x + y, range(1, num + 1))
def numdivisors(num):
return len(finddivisors(trinum(num)))
def findfirsttrinum(target):
start = 1
while numdivisors(start) < target:
start += 1
return trinum(start)
print(findfirsttrinum(int(sys.argv[1])))
|
##Project Euler Problems
#Problem 18: Maximum Path Sum 1
a = """75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23"""
test = """3
7 4
2 4 6
8 5 9 3"""
def createpyramid(x):
x =[row.split(" ")for row in x.split("\n")]
pyramid = []
for row in x:
pyramid.append([int(col) for col in row])
return pyramid
def findpath(x, row = 0, col = 0):
if row == len(x):
return 0
start = x[row][col]
first = findpath(x, row + 1, col)
second = findpath(x, row + 1, col + 1)
return start + max([first, second])
pyramid1 = createpyramid(test)
print(findpath(pyramid1))
pyramid2 = createpyramid(a)
print(findpath(pyramid2))
|
# Final Exam
# Name: Gunjan Pravinchandra Pandya
# Part: 3(a)
"""
3 (a). Export the contents of the User table from a SQLite table into a sequence of INSERT statements within a
file. This is very similar to what you did in Assignment 4. However, you have to add a unique ID column which
has to be a string (you cannot use any numbers). Hint: one possibility is to replace digits with letters, e.g.,
chr(ord('a')+1) gives you a 'b' and chr(ord('a')+2) returns a 'c'
-> Runtime: 12.12 seconds
"""
import sqlite3
import time
start = time.time()
# Open a connection to database
conn = sqlite3.connect("Finaldatabase.db")
# Request a cursor from the database
cursor = conn.cursor()
cursor.execute('pragma foreign_keys=ON')
results = cursor.execute('SELECT * FROM USER;').fetchall()
output = open('C:\Gunjan DePaul\CSC 455\Finals\Insert.txt', 'w', encoding='utf8')
for rows in results:
insert = 'INSERT INTO USER VALUES ('
for attr in rows:
# Convert None to NULL
if attr == None:
insert = insert + 'NULL' + ', '
else:
if isinstance(attr, (int, float)):
value = str(attr)
else:
# Escape all single quotes in the string
value = "'" + str(attr.replace("'", "''")) + "'"
insert = insert + value + ', '
#print(insert)
ID = str(rows[0])
uniqueSID = ''
for j in range( len( ID ) ):
uniqueSID = uniqueSID + chr(ord('a')+int(ID[j]))
value = "'" + uniqueSID +"'"
insert = insert + value + ', '
insert = insert[:-2] + '); \n'
#print(insert)
output.write(insert)
output.close()
end = time.time()
print ("Difference is ", (end-start), "seconds") #12.12 seconds
conn.commit()
conn.close()
|
# Final Exam
# Name: Gunjan Pravinchandra Pandya
# Part: 1(d)
"""
1 (d). Use your locally saved tweet file (created in part-b) to repeat the database population step from part-c.
That is, load 500,000 tweets into the 3-table database using your saved file with tweets (do not use the URL to
read twitter data). How does the runtime compare with part-c?
-> Runtime: 15.66 minutes
-> No of records:
Geo: 11849
User: 447304
Tweet: 499776
-> Compared to loading the data from URL (part-c) this approach of loading data from text file took less time.
"""
import json
import sqlite3
import time
import html
start = time.time()
# Open a connection to database
conn = sqlite3.connect("Finaldatabase.db")
# Request a cursor from the database
cursor = conn.cursor()
cursor.execute('pragma foreign_keys=ON')
COUNT = 0
fd = open('C:\Gunjan DePaul\CSC 455\Finals\Tweet.txt', 'r', encoding='utf8')
#tweet = fd.readlines()
for i in range(500000):
#COUNT = COUNT + 1;
#print(COUNT)
tweet = fd.readline()
try:
jsonobject = json.loads(str(tweet))
if jsonobject['geo'] != None:
geovalues = (str(jsonobject['geo']['coordinates'][1]) + str(jsonobject['geo']['coordinates'][0]), jsonobject['geo']['type'], jsonobject['geo']['coordinates'][1], jsonobject['geo']['coordinates'][0])
cursor.execute("INSERT OR IGNORE INTO GEO VALUES(?,?,?,?);",geovalues)
uservalues = (jsonobject['user']['id'], jsonobject['user']['name'], jsonobject['user']['screen_name'], jsonobject['user']['description'], jsonobject['user']['friends_count'])
cursor.execute("INSERT OR IGNORE INTO USER VALUES(?,?,?,?,?);",uservalues)
if 'retweeted_status' in jsonobject.keys():
retweetcount = jsonobject['retweeted_status']['retweet_count']
else:
retweetcount = jsonobject['retweet_count']
text = html.unescape(jsonobject['text'])
if jsonobject['geo'] != None:
tweetvalues = (jsonobject['created_at'], jsonobject['id_str'], text, jsonobject['source'],jsonobject['in_reply_to_user_id'], jsonobject['in_reply_to_screen_name'], jsonobject['in_reply_to_status_id'], retweetcount, jsonobject['contributors'], jsonobject['user']['id'], str(jsonobject['geo']['coordinates'][1]) + str(jsonobject['geo']['coordinates'][0]))
else:
tweetvalues = (jsonobject['created_at'], jsonobject['id_str'], text, jsonobject['source'],jsonobject['in_reply_to_user_id'], jsonobject['in_reply_to_screen_name'], jsonobject['in_reply_to_status_id'], retweetcount, jsonobject['contributors'], jsonobject['user']['id'], None)
cursor.execute("INSERT OR IGNORE INTO TWEET VALUES(?,?,?,?,?,?,?,?,?,?,?);",tweetvalues)
except ValueError:
None
end = time.time()
print ("Difference is ", (end-start), "seconds") #940 seconds -> 15.66 minutes
conn.commit()
print ("Loaded ", cursor.execute('SELECT COUNT(*) FROM GEO').fetchall()[0], " rows into GEO table")
print ("Loaded ", cursor.execute('SELECT COUNT(*) FROM USER').fetchall()[0], " rows into USER table")
print ("Loaded ", cursor.execute('SELECT COUNT(*) FROM TWEET').fetchall()[0], " rows into TWEET table")
conn.close()
#Geo: 11849
#User: 447304
#Tweet: 499776 |
BRACKET_PAIRS = ['()', '{}', '[]', '<>']
OPEN_BRACKETS = {a for a, _ in BRACKET_PAIRS}
CLOSE_BRACKETS = {b: a for a, b in BRACKET_PAIRS}
def checkio(data):
stack = []
for ch in data:
if ch in OPEN_BRACKETS:
stack.append(ch)
elif ch in CLOSE_BRACKETS:
if not stack or stack[-1] != CLOSE_BRACKETS[ch]:
return False
stack.pop()
return not stack
# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio("((5+3)*2+1)") == True, "Simple"
assert checkio("{[(3+1)+2]+}") == True, "Different types"
assert checkio("(3+{1-1)}") == False, ") is alone inside {}"
assert checkio("[1+1]+(2*2)-{3/3}") == True, "Different operators"
assert checkio("(({[(((1)-2)+3)-3]/3}-3)") == False, "One is redundant"
assert checkio("2+3") == True, "No brackets, no problem"
|
# flips a bit in the binary number "number" at the nth place from the right
def flip_bit(number,n):
if n > 0:
mask = (0b1 << n - 1)
return bin(number ^ mask)
else:
print "\nERROR: Must choose bit number greater than zero.\n"
return bin(0b00000)
print int(flip_bit(12341, 30), 2)
|
# 打印库存信息
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def displayInventory(inventory):
total = 0
for k,v in inventory.items():
print(str(v) + ' ' + str(k))
total += int(v)
print('Total number of items:' + str(total))
def addToInventory(inventory, addedItems):
for item in addedItems:
inventory.setdefault(item, 0)
inventory[item] += 1
addToInventory(stuff, dragonLoot)
displayInventory(stuff)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.