text
stringlengths 37
1.41M
|
---|
# Modify the code inside this loop to stop when i is greater than zero and exactly divisible by 11
# for i in range(0, 100, 11):
# if i % 11 == 0:
# break
# print(i)
for i in range(0, 100, 7):
print(i)
if i > 0 and i % 11 == 0:
break
|
vehicles = {'dream': 'Honda 250T',
# 'roadster': 'BMW R1100',
'er5': 'Kawasaki ER5',
'can-am': 'Bombardier Can-Am 250',
'virago': 'Yamaha XV250',
'tenere': 'Yamaha XT650',
'jimny': 'Suzuki Jimny 1.5',
'fiesta': 'Ford Fiesta Ghia 1.4',
'roadster': 'Triumph Street Triple',
# "starfighter": "Lockheed F-104",
# "learjet": "Bombardier Learjet 75",
# "toy": "Glider",
# "virago": "Yamaha XV535"
}
vehicles["starfighter"] = "Lockheed F-104"
vehicles["learjet"] = "Bombardier Learjet 75"
vehicles["toy"] = "Glider"
# Upgrade the Virago
vehicles["virago"] = 'Yamaha XV535'
del vehicles["starfighter"]
# This doesn't exists so cause an error
# del vehicles["f1"]
# Better way to check if a key exists.
result = vehicles.pop("f1", f"f1?! {None} You wish! Sell the LearJet and you might afford a racing car")
print(result)
# plane = vehicles.pop("learjet")
# print(plane)
bike = vehicles.pop("tenere", "not present")
print(bike)
print()
# Not an efficient way to work with Dicts
# for key in vehicles:
# print(key, vehicles[key], sep=", ")
# .items() is the better way.
for key, value in vehicles.items():
print(key, value, sep=", ")
|
def multiply(x: float, y: float) -> float:
"""
Multiply 2 numbers.
Although this function is intended to multiply 2 numbers,
you can also use it to multiply a sequence. If you pass
a string, for example, as the first argument, you'll get
the string repeated `y` times as the returned value.
:param x: The first number to multiply.
:param y: The number to multiply `x` by.
:return: The product of `x` and `y`.
"""
result = x * y
return result
def is_palindrome(string: str) -> bool:
"""
Check if a string is a palindrome.
A palindrome is a string that reads the same forwards as backwards.
:param string: The string to check.
:return: True if `string` is a palindrome, False otherwise.
"""
return string[::-1].casefold() == string.casefold()
def palindrome_sentence(sentence: str) -> bool:
"""
Check if a sentence is a palindrome.
The function ignores whitespace, capitalisation and
punctuation in the sentence.
:param sentence: The sentence to check.
:return: True if `sentence` is a palindrome, False otherwise.
"""
string = ""
for char in sentence:
if char.isalnum():
string += char
print(string)
return is_palindrome(string)
def fibonacci(n: int) -> int:
"""Return the `n` th Fibonacci number, for positive `n`."""
if 0 <= n <= 1:
return n
n_minus1, n_minus2 = 1, 0
result = None
for f in range(n-1):
result = n_minus2 + n_minus1
n_minus2 = n_minus1
n_minus1 = result
return result
for i in range(36):
print(i, fibonacci(i))
p = palindrome_sentence("Howdy do")
|
data = [4, 5, 104, 105, 110, 120, 130, 130, 150,
160, 170, 183, 185, 187, 188, 191, 350, 360]
# del data[0:2]
# print(data)
# del data[16:]
# print(data)
# del data[14:]
# print(data)
min_valid = 100
max_valid = 200
for index, value in enumerate(data):
if (value < min_valid) or (value > max_valid):
del data[index]
print(data)
# "Be very careful when changing the size of an object,
# "that you're iterating over. If you want to replace items
# "with different ones, that's normally fine, but deleting
# "items from a list, or any other mutable sequence type, while
# "iterating forwards over it will cause problems, as we've seen here.
# "So for new programmers, just remember that rule. Be very careful
# "when changing the size of an object that you're iterating over."
|
revenue = float(input("Введите выручку Вашей фирмы: "))
expenses = float(input("Введите затраты Вашей фирмы: "))
if revenue > expenses:
print("Ваша фирма прибыльная!")
profitability = (revenue - expenses) / revenue
print((f"Рентабельность Вашей фирмы - {profitability}"))
staff = int(input("Введите количество Ваших сотрудников: "))
profit_per_employee = (revenue - expenses) / staff
print(f"Средняя прибыль на сотрудника составляет {profit_per_employee} у.е.")
elif revenue < expenses:
print("Ваша фирма убыточная!")
else:
print("Ваша фирма работает в 0!") |
class Road:
def __init__(self, lenght, width, a, m):
self._lenght = lenght
self._width = width
self.a = 5 # толщина асфальта
self.m = 25 # масса асфальта для покрытия 1 кв.м
def calc(self):
print(f"{(self._lenght * self._width * self.a * self.m) / 1000}т")
total = Road(5000, 20, 5, 25)
total.calc() |
def division(a, b):
try:
return a / b
except ZeroDivisionError:
return print('Делить на ноль нельзя!')
print(division(6, 0)) |
my_list = [1, 2, 3, 2, 3, 5, 6, 5, 8, 9, 11, 123, 321, 123, 0]
new_list = [i for i in my_list if my_list.count(i) == 1]
print(new_list) |
n = int(input("Введите целое положительное число, а я найду самую большую цифру в нем: "))
max = 0
while n > 0:
a = n % 10
if a == 9:
max = a
break
elif a > max:
max = a
n = n // 10
print(max) |
from copy import deepcopy
"""
时间复杂度 n^n
"""
def maxSizeSlices(slices):
if len(slices) <= 3:
return max(slices)
maxPiza = 0
dp = []
dp.append((slices, 0))
while len(dp) > 0:
slices, currentPiza = dp.pop()
if len(slices) <= 3:
maxPiza = max(maxPiza, (max(slices) + currentPiza))
else:
for i, v in enumerate(slices):
t = deepcopy(slices)
if i == (len(slices) - 1):
del t[i-1], t[i-1], t[0]
elif i == 0:
del t[-1], t[0], t[0]
else:
del t[i-1], t[i-1], t[i-1]
dp.append((t, v+currentPiza))
maxPiza = max(maxPiza, (v+currentPiza))
return maxPiza
if __name__ == "__main__":
slices = [6,3,1,2,6,2,4,3,10,4,1,4,6,5,5,3,4,7,6,5,8]#,7,3,8,8,1,7,1,7,8]
res = maxSizeSlices(slices)
print(res) |
t=int(input())
while(t>0):
n=int(input())
print(n)
t=t-1 |
### DICTIONARIES
product = {
"name" : "Book",
"quantity" : 1,
"price" : 4.99
}
person = {
"firstName" : "Joan",
"lastName" : "Perez Alvarado"
}
## accesing keys
#print(person['firstName'])
# delete object
## del person;
## Working with keys
print(person.keys());
print(person.items());
## Clearing Object
person.clear(); |
import random
# Making A General GCD function
def gcd(num1,num2):
if num2 == 0:
return num1
else:
return gcd(num2,num1%num2)
# 1. Picking a large random integer number.
n = random.randint(1,10000)
while gcd(n,2310)!= 1:
n = random.randint(1,10000)
print("Random Number (n): "+str(n))
# 2. Picking a random integer K such that x = 2310K + n is 100-bit long
K = random.getrandbits(10000)
x = 2310*K + n
print("K: "+ str(K)+" length:"+ str(len(str(K))))
print("x: "+ str(x)+" length:"+ str(len(str(x))))
### 3. Miller Rabin's Primality Test
def MillerRabinTest(p,a):
if p == 1:
return False
if p == 2:
return True
if p % 2 == 0:
return False
m, k = p - 1, 0
while m % 2 == 0:
m, k = m // 2, k + 1
x = pow(a, m, p)
if x == 1 or x == p - 1:
return True
while k > 1:
x = pow(x, 2, p)
if x == 1:
return False
if x == p - 1:
return True
k = k - 1
return False
def isPrime(p):
a =random.randint(2,p-1)
if not MillerRabinTest(p,a):
return False
return True
flag = True
num = 1
while (flag):
if (isPrime(x)):
print("Iteration "+str(num)+": "+str(x) + " is prime " + "length:"+str(len(str(x))));
print("k: "+str(K))
flag = False
num+=1
else:
print ("Iteration "+str(num)+": "+str(x) + " is not prime")
K = random.getrandbits(10000)
x = 2310*K + n
isPrime(x)
num+=1 |
EOL = '\n' # end of line character
MAX = 1024 # maximum number of bytes to receive at a time
# The Receiver class manages receiving messages over a socket
class Receiver:
def __init__(self, sock):
# The socket instance variable stores the socket associated with
# the receiver which is passed in when the object is created and is
# presumed to be connected
self.sock = sock
# The open instance variable is used to track when the other side of
# the connection closes
self.open = True
# The buffer instance variable is used to collect chunks of data
# received over the socket and to save received data in between
# calls to recv_message()
self.buffer = []
def recv_message(self):
"""recv_message() returns all bytes received until an end of line character
is encountered. Any further bytes that have been received are held in
a buffer to be used in the next call to recv_message"""
# Initialize the msg_chunk variable to any excess bytes that were received
# on the last call to recv_message()
if len(self.buffer) == 1:
msg_chunk = self.buffer[0]
else:
msg_chunk = ""
# Initialize the end of line position based on the contents of msg_chunk
eol_pos = msg_chunk.find(EOL)
# Keep reading the socket until an end of line is encountered or the
# socket is closed
while self.open and eol_pos == -1:
# Read up to MAX characters from the socket
msg_chunk = self.sock.recv(MAX)
if not msg_chunk:
# When recv() on the socket returns the empty string, it
# indicates that the other end has closed the socket so add
# an end of line to the buffer so that the echoed message can
# be delimited
self.buffer.append(EOL)
self.open = False
else:
# Append the newest chunk of data to the buffer and look
# for an end of line in the data
self.buffer.append(msg_chunk)
eol_pos = msg_chunk.find(EOL)
# The last chunk of data in the buffer contains an end of line
# character but there may be additional bytes after the end of line
# If so, remove those characters from the buffer and save them in
# leftover temporarily
leftover = ""
if self.open:
if len(self.buffer[-1])-1 != eol_pos:
leftover = self.buffer[-1][eol_pos+1:]
last = self.buffer.pop()
self.buffer.append(last[0:eol_pos+1])
# Join all the chunks of data into a string and reset the buffer to
# either be empty or contain the leftover chunk of data
message = "".join(self.buffer)
if leftover == "":
self.buffer = []
else:
self.buffer = [leftover]
return message
|
"""
Functions for preprocessing mortgage complaints data.
"""
import pandas as pd
def encode_targets(df, target_column, target_encoding_dict):
"""
Replaces values in `df` target_column with the corresponding values
specified in the encoding_dict
Parameters
----------
df : pandas.DataFrame
DataFrame on which to operate
target_column : string
Name of the target column to replace values of
encoding_dict : string
Dictionary containing current target value to desired value mapping
Returns
-------
df : pandas.DataFrame (or indexable)
Input DataFrame, with values of target column replaced
"""
df = df.copy() # do not mutate original frame
df[target_column] = df[target_column].apply(
lambda target: target_encoding_dict[target]
)
return df
def filter_rename_mortgages(df):
"""
Filter dataset down to only mortgage products, only the complaint and issue
columns (feature and target, respectively), and rename those columns.
Parameters
----------
df : pandas.DataFrame
DataFrame on which to operate. Must contain "Product", "Issue", and
"Consumer complaint narrative" columns.
Returns
-------
df : pandas.DataFrame (or indexable)
Filtered and renamed version of input DataFrame.
"""
mortgages = (
df
[df['Product'] == 'Mortgage']
[['Consumer complaint narrative', 'Issue']]
.rename({
'Consumer complaint narrative': 'complaint',
'Issue': 'issue'
},
axis='columns')
.reset_index(drop=True)
)
return mortgages
target_encoding_dict = {
"Loan servicing, payments, escrow account": "loan_servicing",
"Loan modification,collection,foreclosure": "loan_modification",
"Trouble during payment process": "payment_process",
"Struggling to pay mortgage": "struggling_to_pay",
"Application, originator, mortgage broker": "application",
"Settlement process and costs": "settlement",
"Applying for a mortgage or refinancing an existing mortgage": "applying",
"Closing on a mortgage": "closing",
"Credit decision / Underwriting": "underwriting",
"Incorrect information on your report": "other",
"Applying for a mortgage": "applying",
"Problem with a credit reporting company's investigation into an existing problem": "other",
"Improper use of your report": "other",
"Credit monitoring or identity theft protection services": "other",
"Unable to get your credit report or credit score": "other",
"Problem with fraud alerts or security freezes": "other"
} |
import time
from turtle import Turtle
class Bullet(Turtle):
def __init__(self, position):
super().__init__()
self.shape('circle')
self.color('red')
self.bullets = []
self.hideturtle()
self.shapesize(0.5)
self.penup()
self.goto(position)
self.fired = False
def fire(self):
self.showturtle()
self.fired = True
def ready(self, position):
self.hideturtle()
self.goto(position)
self.fired = False
|
# write your code here
from random import randint, choice
import os
class Calculator:
def __init__(self):
self.difficulty = None
self.level_descriptions = ["simple operations with numbers 2-9", "integral squares of 11-29"]
self.choose_difficulty()
self.task_generator = Calculator.TaskGenerator()
self.user_answer = None
self.correct_result = None
self.correct_answers = 0
self.exam()
self.give_mark()
self.save_result()
def choose_difficulty(self):
print("Which level do you want? Enter a number:")
print(f"1 - {self.level_descriptions[0]}")
print(f"2 - {self.level_descriptions[1]}")
while True:
try:
self.difficulty = int(input())
if self.difficulty in [1, 2]:
break
else:
raise ValueError
except ValueError:
print("Incorrect format.")
continue
def get_input(self):
while True:
try:
self.user_answer = int(input())
break
except ValueError:
print("Incorrect format.")
continue
def calculate(self):
self.correct_result = eval(self.task_generator.task)
def evaluate_answer(self):
if self.user_answer == self.correct_result:
self.correct_answers += 1
print("Right!")
else:
print("Wrong!")
def exam(self):
for i in range(5):
self.task_generator.generate(self.difficulty)
self.get_input()
self.calculate()
self.evaluate_answer()
def give_mark(self):
print(f"Your mark is {self.correct_answers}/5.")
def save_result(self):
answer = input("Would you like to save your result to the file? Enter yes or no.")
if answer in ["yes", "YES", "y", "Yes"]:
user_name = input("What is your name?")
to_write = f"{user_name} {self.correct_answers}/5 in level {self.difficulty} ({self.level_descriptions[self.difficulty - 1]})"
if os.path.isfile("results.txt"):
with open("results.txt", "a") as file:
file.write(to_write)
else:
with open("results.txt", "w") as file:
file.write(to_write)
print('The results are saved in "results.txt".')
else:
exit()
class TaskGenerator:
def __init__(self):
self.operands = []
self.operator = ""
self.task = ""
def generate(self, difficulty):
if difficulty == 1:
self.task = f'{randint(2, 9)} {choice("+-*")} {randint(2, 9)}'
print(self.task)
elif difficulty == 2:
self.task = f'{randint(11, 29)} ** 2'
print(self.task[:2])
calculator = Calculator()
|
"""
Miranda Lassar and Sonia Presti and Charisma Chauhan storybook_app.py is an app for stories in the terminal
it is also used as a module in the storybook_webapp flask app
"""
def split(word):
return list(word)
def welcome(name):
newName = split(name)
for y in range(0, len(newName)):
if newName[y] == 'a' or newName[y] == 'A':
print(' _______ \n | _ | \n | |_| | \n | | \n | | \n | _ | \n |__| |__|')
if newName[y] == 'b' or newName[y] == 'B':
print(' _______ \n| |_| |\n| |\n| _ |\n| |_| |\n|_______|')
if newName[y] == 'c' or newName[y] == 'C':
print(' _______\n| |\n| |\n| |\n| _|\n| |_ \n|_______|')
if newName[y] == 'd' or newName[y] == 'D':
print(' ______ \n| | \n| _ |\n| | | |\n| |_| |\n| |\n|______|')
if newName[y] == 'e' or newName[y] == 'E':
print(' _______ \n| |\n| ___|\n| |___ \n| ___|\n| |___ \n|_______|')
if newName[y] == 'f' or newName[y] == 'F':
print(' _______ \n| |\n| ___|\n| |___ \n| ___|\n| | \n|___| ')
if newName[y] == 'g' or newName[y] == 'G':
print(' _______ \n| |\n| ___|\n| | __ \n| || |\n| |_| |\n|_______|')
if newName[y] == 'h' or newName[y] == 'H':
print(' __ __ \n| | | |\n| |_| |\n| |\n| |\n| _ |\n|__| |__|')
if newName[y] == 'i' or newName[y] == 'I':
print(' ___ \n| | \n| | \n| | \n| | \n| | \n|___| ')
if newName[y] == 'j' or newName[y] == 'J':
print(' ___ \n | |\n | |\n | |\n ___| |\n| |\n|_______|')
if newName[y] == 'k' or newName[y] == 'K':
print(' ___ _ \n| | | |\n| |_| |\n| _|\n| |_ \n| _ |\n|___| |_|')
if newName[y] == 'l' or newName[y] == 'L':
print(' ___ \n| | \n| | \n| | \n| |___ \n| |\n|_______|')
if newName[y] == 'm' or newName[y] == 'M':
print(' __ __ \n| |_| |\n| |\n| |\n| |\n| ||_|| |\n|_| |_|')
if newName[y] == 'n' or newName[y] == 'n':
print(' __ _ \n| | | |\n| |_| |\n| |\n| _ |\n| | | |\n|_| |__|')
if newName[y] == 'o' or newName[y] == 'O':
print(' _______ \n| |\n| _ |\n| | | |\n| |_| |\n| |\n|_______|')
if newName[y] == 'p' or newName[y] == 'P':
print(' _______ \n| |\n| _ |\n| |_| |\n| ___|\n| | \n|___| ')
if newName[y] == 'q' or newName[y] == 'Q':
print(' _______ \n| |\n| _ |\n| | | |\n| |_| |\n| | \n|____||_|')
if newName[y] == 'r' or newName[y] == 'R':
print(' ______ \n| _ | \n| | || \n| |_||_ \n| __ |\n| | | |\n|___| |_|')
if newName[y] == 's' or newName[y] == 'S':
print(' _______ \n| |\n| _____|\n| |_____ \n|_____ |\n _____| |\n|_______|')
if newName[y] == 't' or newName[y] == 'T':
print(' _______ \n| |\n|_ _|\n | | \n | | \n | | \n |___| ')
if newName[y] == 'u' or newName[y] == 'U':
print(' __ __ \n| | | |\n| | | |\n| |_| |\n| |\n| |\n|_______|')
if newName[y] == 'v' or newName[y] == 'V':
print(' __ __ \n| | | |\n| |_| |\n| |\n| |\n | | \n |___| ')
if newName[y] == 'w' or newName[y] == 'W':
print(' _ _ \n| | _ | |\n| || || |\n| |\n| |\n| _ |\n|__| |__|')
if newName[y] == 'x' or newName[y] == 'X':
print(' __ __ \n| |_| |\n| |\n| |\n | | \n| _ |\n|__| |__|')
if newName[y] == 'y' or newName[y] == 'Y':
print(' __ __ \n| | | |\n| |_| |\n| |\n|_ _|\n | | \n |___| ')
if newName[y] == 'z' or newName[y] == 'Z':
print(' _______ \n| |\n|____ |\n ____| |\n| ______|\n| |_____ \n|_______|')
def intro_story():
print("Hello! Welcome to your first interactive story!")
print("Before we begin, we would love to get to know a little bit about you!")
name = input("What is your name?")
welcome(name)
print('Pretty cool, right? This is called ASCII art, and this is how we are going to tell stories!')
def owl_story():
print("Ollie the Owl's Big Adventure")
ready = input('Shall we begin?')
if ready == 'yes' or ready == 'Yes' or ready == 'Y':
print("Meet Ollie the Owl!")
print(' /\ /\ \n ((ovo)) \n ():::() \n VVV')
if __name__ == "__main__":
intro_story()
owl_story()
def grab_fishing_pole():
storytext = "I just grabbed my fishing pole, now I am ready to catch some fish. Tell me when you are ready to cast the line!"
question = "Enter: ready"
opt1 = "ready"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
return [storytext, question, opt1, options3Display, options2Display, options1Display]
#the function story2_conditions returns a dictionary of the variables that will be passed to story2.html
def story2_conditions(choices):
conditions = {}
options1Display = "display:none"
options2Display = "display:none"
options3Display = "display:none"
storytext = ""
question = ""
pictureUrl = ""
audio = ""
if len(choices)==1:
if choices[0] == "get dressed":
storytext = "Okay, time to get dressed. Let's pick out a color hat to wear"
question = "Enter: black or blue or red"
opt1 = "black"
opt2 = "blue"
opt3 = "red"
options3Display = "display:inline"
options2Display = "display:none"
options1Display = "display:none"
pictureUrl = "https://s7d5.turboimg.net/t1/52388300_penguin_iceberg.jpg"
audio = "/static/GetDressedML.mp3"
elif choices[0] == "go fishing":
storytext = "I just grabbed my fishing pole and can't wait to catch some big fish. Tell me when you are ready to cast the line!"
question = "Enter: ready"
opt1 = "ready"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d5.turboimg.net/t1/52388331_penguin_iceberg_fishing.jpg"
audio = "/static/GoFishing.mp3"
elif choices[0] == "go swimming":
storytext = "I put on my snorkel, now I am ready to jump into the ocean. On the count of 3, let's jump together! 1... 2... 3... JUMP!"
question = "Enter: jump"
opt1 = "jump"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d5.turboimg.net/t1/52388333_penguin_snorkel.jpg"
audio = "/static/GoSwimming.mp3"
if len(choices)==2:
if choices[0]=="get dressed" and choices[1] == "blue":
storytext = "I love this blue hat, thanks for helping me choose to wear it today. I am now ready to go outside and fish!"
question = "Enter: start fishing"
opt1 = "start fishing"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl="https://s7d5.turboimg.net/t1/52388336_penguin_tophat_blue.jpg"
audio = "/static/BlueHat.mp3"
elif choices[0]=="get dressed" and choices[1] == "black":
storytext = "I love this black hat, thanks for helping me choose to wear it today. I am now ready to go outside and fish!"
question = "Enter: start fishing"
opt1 = "start fishing"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl="https://s7d5.turboimg.net/t1/52388335_penguin_tophat.jpg"
audio = "/static/BlackHat.mp3"
elif choices[0]=="get dressed" and choices[1] == "red":
storytext = "I love this red hat, thanks for helping me choose to wear it today. I am now ready to go outside and fish!"
question = "Enter: start fishing"
opt1 = "start fishing"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl="https://s7d5.turboimg.net/t1/52388339_penguin_tophat_red.jpg"
audio = "/static/RedHat.mp3"
elif choices[0] == "go fishing" and choices[1] == "ready":
storytext = "Wow I just caught a big orange fish! Should I cast the line again or go swimming or go to sleep?"
question = "Enter: cast line or go swimming or goodnight"
opt1 = "cast line"
opt2 = "go swimming"
opt3 = "goodnight"
options3Display = "display:inline"
options2Display = "display:none"
options1Display = "display:none"
pictureUrl="https://s7d5.turboimg.net/t1/52388332_penguin_iceberg_fishing_orange.jpg"
audio = "/static/FishingReady.mp3"
elif choices[0] == "go swimming" and choices[1]=="jump":
storytext = "SPLASH! Now we can explore underwater. Which friend do you want to visit? Willy the Whale, Fiona the Fish, or Colby the Crab"
question = "Enter: Willy or Fiona or Colby"
opt1 = "Willy"
opt2 = "Fiona"
opt3 = "Colby"
options3Display = "display:inline"
options2Display = "display:none"
options1Display = "display:none"
pictureUrl = "https://s7d5.turboimg.net/t1/52388334_penguin_swim.jpg"
audio = "/static/SwimmingJump.mp3"
if len(choices)==3:
if choices[0]=="get dressed" and choices[1] == "blue" and choices[2]=="start fishing":
storytext = "I just grabbed my fishing pole, now I am ready to catch some fish. Tell me when you are ready to cast the line!"
question = "Enter: ready"
opt1 = "ready"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl="https://s7d5.turboimg.net/t1/52388337_penguin_tophat_blue_fishing.jpg"
audio = "/static/HatFish.mp3"
elif choices[0]=="get dressed" and choices[1] == "black" and choices[2]=="start fishing":
storytext = "I just grabbed my fishing pole, now I am ready to catch some fish. Tell me when you are ready to cast the line!"
question = "Enter: ready"
opt1 = "ready"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl="https://s7d5.turboimg.net/t1/52388338_penguin_tophat_fishing.jpg"
audio = "/static/HatFish.mp3"
elif choices[0]=="get dressed" and choices[1] == "red" and choices[2]=="start fishing":
storytext = "I just grabbed my fishing pole, now I am ready to catch some fish. Tell me when you are ready to cast the line!"
question = "Enter: ready"
opt1 = "ready"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl="https://s7d5.turboimg.net/t1/52388340_penguin_tophat_red_fishing.jpg"
audio = "/static/HatFish.mp3"
elif choices[0]=="go fishing" and choices[1] == "ready" and choices[2]=="cast line":
storytext = "Wow I just caught a big blue fish! I am getting tired, I think it is time to go to sleep."
question = "Enter: goodnight"
opt1 = "goodnight"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl="https://s7d6.turboimg.net/t1/52391969_penguin_iceberg_fishing_blue.jpg"
audio = "/static/FishingReadyCastline.mp3"
elif choices[0]=="go fishing" and choices[1] == "ready" and choices[2]=="go swimming":
storytext = "I let the fish back into the ocean, put back my fishing rod, and found my snorkel. Now I am ready to swim. On the count of 3 let's jump together, 1... 2... 3... JUMP!"
question = "Enter: jump"
opt1 = "jump"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d5.turboimg.net/t1/52388333_penguin_snorkel.jpg"
audio = "/static/FishingReadySwimming.mp3"
elif choices[0] == "go swimming" and choices[1]=="jump" and choices[2]=="Willy":
storytext = "Hello Willy! Thank you for reminding me that it is Fiona's birthday today! I could either bake her a cake or buy one from Colby the Crab's bakery or go to sleep because it has been a long day."
question = "Enter: make cake or buy cake"
opt1 = "make cake"
opt2 = "buy cake"
opt3 = "goodnight"
options3Display = "display:inline"
options2Display = "display:none"
options1Display = "display:none"
pictureUrl = "https://s7d8.turboimg.net/t1/52391952_penguin_swim_whale.jpg"
audio = "/static/SwimmingJumpWilly.mp3"
elif choices[0] == "go swimming" and choices[1]=="jump" and choices[2]=="Fiona":
storytext = "Hello Fiona! Your scales look extra shiny today! Do you want to come with me and visit Willy or Colby or Tom?"
question = "Enter: Willy or Colby or Tom"
opt1 = "Willy"
opt2 = "Colby"
opt3 = "Tom"
options3Display = "display:inline"
options2Display = "display:none"
options1Display = "display:none"
pictureUrl = "https://s7d8.turboimg.net/t1/52391947_penguin_swim_fish.jpg"
audio = "/static/SwimmingJumpFiona.mp3"
elif choices[0] == "go swimming" and choices[1]=="jump" and choices[2]=="Colby":
storytext = "Hello Colby! Mmmmmm it smells really good down at the bottom of the ocean! It seems like you baked a cake for Fiona's birthday, let's go celebrate with her"
question = "Enter: celebrate"
opt1 = "celebrate"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d8.turboimg.net/t1/52391946_penguin_swim_crab_touch_botton.jpg"
audio = "/static/SwimmingJumpColby.mp3"
if len(choices)==4:
if choices[0]=="get dressed" and choices[1] == "blue" and choices[2]=="start fishing" and choices[3]=="ready":
storytext = "Wow it has been a productive day, I got dressed into a blue hat and caught a big orange fish! Now I am tired and ready to go to sleep."
question = "Enter: goodnight"
opt1 = "goodnight"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl="https://s7d2.turboimg.net/t1/52391983_penguin_tophat_blue_fishing_fish.jpg"
audio = "/static/DressedBlueTired.mp3"
elif choices[0]=="get dressed" and choices[1] == "black" and choices[2]=="start fishing" and choices[3]=="ready":
storytext = "Wow it has been a productive day, I got dressed into a black hat and caught a big orange fish! Now I am tired and ready to go to sleep."
question = "Enter: goodnight"
opt1 = "goodnight"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl="https://s7d2.turboimg.net/t1/52391984_penguin_tophat_fishing_fish.jpg"
audio = "/static/DressedBlackTired.mp3"
elif choices[0]=="get dressed" and choices[1] == "red" and choices[2]=="start fishing" and choices[3]=="ready":
storytext = "Wow it has been a productive day, I got dressed into a red hat and caught a big orange fish! Now I am tired and ready to go to sleep."
question = "Enter: goodnight"
opt1 = "goodnight"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl="https://s7d2.turboimg.net/t1/52391985_penguin_tophat_red_fishing_fish.jpg"
audio = "/static/DressedRedTired.mp3"
elif choices[0]=="go fishing" and choices[1] == "ready" and choices[2]=="go swimming" and choices[3]=="jump":
storytext = "SPLASH! Now we can explore underwater. I can either choose a friend to visit or go to sleep."
question = "Enter: Willy or Colby"
opt1 = "Willy"
opt2 = "Colby"
opt3 = "goodnight"
options3Display = "display:inline"
options2Display = "display:none"
options1Display = "display:none"
pictureUrl = "https://s7d5.turboimg.net/t1/52388334_penguin_swim.jpg"
audio = "/static/FishingReadySwimmingJump.mp3"
elif choices[0] == "go swimming" and choices[1]=="jump" and choices[2]=="Willy" and choices[3]=="make cake":
storytext = "I made the cake by mixing together flour, sugar, eggs, and butter. Now it is time to deliver the cake to Fiona and celebrate her birthday!"
question = "Enter: celebrate"
opt1 = "celebrate"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d8.turboimg.net/t1/52391942_penguin_swim_cake.jpg"
audio = "/static/MakeCake.mp3"
elif choices[0] == "go swimming" and choices[1]=="jump" and choices[2]=="Willy" and choices[3]=="buy cake":
storytext = "Thank you Colby for making this wonderful cake. Now it is time to deliver the cake to Fiona and celebrate her birthday!"
question = "Enter: celebrate"
opt1 = "celebrate"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d8.turboimg.net/t1/52391944_penguin_swim_crab_cake.jpg"
audio = "/static/ColbyCake.mp3"
elif choices[0] == "go swimming" and choices[1]=="jump" and choices[2]=="Fiona" and choices[3]=="Willy":
storytext = "Whale hello there Willy! Haha get it :) I just wanted to come say hi before I swim back home and Fiona followed along."
question = "Enter: goodnight"
opt1 = "goodnight"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d6.turboimg.net/t1/52392171_penguin_swim_whale_fish.jpg"
audio = "/static/WhaleHello.mp3"
elif choices[0] == "go swimming" and choices[1]=="jump" and choices[2]=="Fiona" and choices[3]=="Colby":
storytext = "Hi Colby, hope we didn't wake you up! We just wanted to come say hi before I swim back home."
question = "Enter: goodnight"
opt1 = "goodnight"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d8.turboimg.net/t1/52391945_penguin_swim_crab_fish.jpg"
audio = "/static/WakeColbyUp.mp3"
elif choices[0] == "go swimming" and choices[1]=="jump" and choices[2]=="Fiona" and choices[3]=="Tom":
storytext = "Hi Tom, thank you for popping your head out of your shell to say hi! It is getting late, so I must swim back home."
question = "Enter: goodnight"
opt1 = "goodnight"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d2.turboimg.net/t1/52398139_penguin_swim_crab_fish_turtle.jpg"
audio = "/static/HiTom.mp3"
elif choices[0] == "go swimming" and choices[1]=="jump" and choices[2]=="Colby" and choices[3]=="celebrate":
storytext = "Lets sing happy birthday to Fiona! All this partying has been really fun, but now I am tired and must go home to sleep."
question = "Enter: goodnight"
opt1 = "goodnight"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d7.turboimg.net/t1/52397544_penguin_swim_crab_fish_cake.jpg"
audio = "/static/HappyBirthdayFiona.mp3"
if len(choices)==5:
if choices[0]=="go fishing" and choices[1] == "ready" and choices[2]=="go swimming" and choices[3]=="jump" and choices[4]=="Willy":
storytext = "Hi Willy! I hope you have a great day swimming around in the ocean! I noticed that I am a little tired from swimming so much, so I am going to sleep now."
question = "Enter: goodnight"
opt1 = "goodnight"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d8.turboimg.net/t1/52391952_penguin_swim_whale.jpg"
audio = "/static/WillyGoodnight.mp3"
elif choices[0]=="go fishing" and choices[1] == "ready" and choices[2]=="go swimming" and choices[3]=="jump" and choices[4]=="Colby":
storytext = "Hi Colby! I never realized how soft the sand is down here. No wonder you love living on the ocean floor! Swimming took a lot of energy, so I am going to go home and sleep."
question = "Enter: goodnight"
opt1 = "goodnight"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d8.turboimg.net/t1/52391946_penguin_swim_crab_touch_botton.jpg"
audio = "/static/ColbyGoodnight.mp3"
elif choices[0] == "go swimming" and choices[1]=="jump" and choices[2]=="Willy" and choices[3]=="make cake" or choices[3]=="buy cake" and choices[4]=="celebrate":
storytext = "Hi Fiona, I made a cake for you! Should I make a banner that says happy birthday, say happy birthday, or sing happy birthday to Fiona?"
question = "Enter: make banner or say or sing"
opt1 = "make banner"
opt2 = "say"
opt3 = "sing"
options3Display = "display:inline"
options2Display = "display:none"
options1Display = "display:none"
pictureUrl = "https://s7d5.turboimg.net/t1/52392168_penguin_swim_fish_cake_bubbles.jpg"
audio = "/static/HiFiona.mp3"
if len(choices)==6:
if choices[0] == "go swimming" and choices[1]=="jump" and choices[2]=="Willy" and choices[4]=="celebrate" and choices[5]=="make banner" and choices[3]=="make cake" or choices[3]=="buy cake":
storytext = "This has been a really fun birthday party, but it is getting late so I must swim home. Enjoy your birthday banner and cake!"
question = "Enter: goodnight"
opt1 = "goodnight"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d5.turboimg.net/t1/52398144_penguin_swim_fish_cake_banner.jpg"
audio = "/static/BirthdayBanner.mp3"
if choices[0] == "go swimming" and choices[1]=="jump" and choices[2]=="Willy" and choices[4]=="celebrate" and choices[5]=="say" and choices[3]=="make cake" or choices[3]=="buy cake":
storytext = "This has been a really fun birthday party, but it is getting late so I must swim home. Enjoy your cake!"
question = "Enter: goodnight"
opt1 = "goodnight"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d8.turboimg.net/t1/52391950_penguin_swim_fish_cake_exclaim.jpg"
audio = "/static/EnjoyYourCake.mp3"
if choices[0] == "go swimming" and choices[1]=="jump" and choices[2]=="Willy" and choices[4]=="celebrate" and choices[5]=="sing" and choices[3]=="make cake" or choices[3]=="buy cake":
storytext = "This has been a really fun birthday party, but it is getting late so I must swim home. Enjoy your cake!"
question = "Enter: goodnight"
opt1 = "goodnight"
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:inline"
pictureUrl = "https://s7d8.turboimg.net/t1/52391951_penguin_swim_fish_cake_sing.jpg"
audio = "/static/HappyBirthdaySong.mp3"
if "goodnight" in choices:
storytext = "What a fun day! Now it is time to go to sleep, goodnight!"
question = ""
options3Display = "display:none"
options2Display = "display:none"
options1Display = "display:none"
pictureUrl="https://s7d5.turboimg.net/t1/52388330_penguin_goodnight.jpg"
audio = "/static/Goodnight.mp3"
if options3Display=="display:inline":
conditions.update( {"opt1": opt1} )
conditions.update( {"opt2": opt2})
conditions.update( {"opt3": opt3})
if options2Display=="display:inline":
conditions.update( {"opt1": opt1} )
conditions.update( {"opt2": opt2})
if options1Display=="display:inline":
conditions.update( {"opt1": opt1} )
conditions.update( {'storytext': storytext} )
conditions.update( {'question': question} )
conditions.update( {'pictureUrl': pictureUrl} )
conditions.update( {"options3Display": options3Display})
conditions.update( {"options2Display": options2Display})
conditions.update( {"options1Display": options1Display})
conditions.update( {"audio":audio})
return conditions
#conditions = story2_conditions(choice)
#the get functions below return the string for each of the variables that will be passed to story2.html
def get_storytext(conditions):
return conditions['storytext']
def get_question(conditions):
return conditions['question']
def get_pictureUrl(conditions):
return conditions['pictureUrl']
def get_opt1(conditions):
return conditions['opt1']
def get_opt2(conditions):
return conditions['opt2']
def get_opt3(conditions):
return conditions['opt3']
def get_options3Display(conditions):
return conditions['options3Display']
def get_options2Display(conditions):
return conditions['options2Display']
def get_options1Display(conditions):
return conditions['options1Display']
def get_audio(conditions):
return conditions['audio']
|
""" Question 2 """
class BinarySearchTreeMap:
class Item:
def __init__(self, key, value=None):
self.key = key
self.value = value
class Node:
def __init__(self, item):
self.item = item
self.parent = None
self.left = None
self.right = None
self.index = 0
self.rank = None
def num_children(self):
count = 0
if (self.left is not None):
count += 1
if (self.right is not None):
count += 1
return count
def disconnect(self):
self.item = None
self.parent = None
self.left = None
self.right = None
self.rank = None
def __init__(self):
self.root = None
self.size = 0
def __len__(self):
return self.size
def is_empty(self):
return len(self) == 0
# raises exception if not found
def __getitem__(self, key):
node = self.subtree_find(self.root, key)
if (node is None):
raise KeyError(str(key) + " not found")
else:
return node.item.value
# returns None if not found
def subtree_find(self, subtree_root, key, delete=False):
curr = subtree_root
while (curr is not None):
if (curr.item.key == key):
return curr
elif (curr.item.key > key):
curr = curr.left
else: # (curr.item.key < key)
curr = curr.right
return None
# updates value if key already exists
def __setitem__(self, key, value):
node = self.subtree_find(self.root, key)
if (node is None):
self.subtree_insert(key, value)
else:
node.item.value = value
# assumes key not in tree
def subtree_insert(self, key, value=None):
item = BinarySearchTreeMap.Item(key, value)
new_node = BinarySearchTreeMap.Node(item)
if (self.is_empty()):
self.root = new_node
self.root.rank = 1
self.size = 1
else:
parent = self.root
if(key < self.root.item.key):
parent.rank +=1
curr = self.root.left
else:
curr = self.root.right
while (curr is not None):
parent = curr
if (key < curr.item.key):
curr = curr.left
parent.rank += 1
else:
curr = curr.right
if (key < parent.item.key):
parent.left = new_node
parent.rank+=1
parent.left.rank = 1
else:
parent.right = new_node
parent.right.rank = parent.rank+1
new_node.parent = parent
self.size += 1
#raises exception if key not in tree
def __delitem__(self, key):
if (self.subtree_find(self.root, key) is None):
raise KeyError(str(key) + " is not found")
else:
self.subtree_delete(self.root, key)
#assumes key is in tree + returns value assosiated
def subtree_delete(self, node, key):
node_to_delete = self.subtree_find(node, key)
value = node_to_delete.item.value
num_children = node_to_delete.num_children()
if (node_to_delete is self.root):
if (num_children == 0):
self.root = None
node_to_delete.disconnect()
self.size -= 1
elif (num_children == 1):
if (self.root.left is not None):
self.root = self.root.left
self.root.rank = 1
else:
self.root = self.root.right
self.root.parent = None
node_to_delete.disconnect()
self.size -= 1
else: #num_children == 2
max_of_left = self.subtree_max(node_to_delete.left)
node_to_delete.item = max_of_left.item
node_to_delete.rank-=1
self.subtree_delete(node_to_delete.left, max_of_left.item.key)
else:
if (num_children == 0):
parent = node_to_delete.parent
if (node_to_delete is parent.left):
parent.left = None
else:
parent.right = None
node_to_delete.disconnect()
self.size -= 1
elif (num_children == 1):
parent = node_to_delete.parent
if(node_to_delete.left is not None):
child = node_to_delete.left
else:
child = node_to_delete.right
child.parent = parent
if (node_to_delete is parent.left):
parent.left = child
else:
parent.right = child
node_to_delete.disconnect()
self.size -= 1
else: #num_children == 2
max_of_left = self.subtree_max(node_to_delete.left)
node_to_delete.item = max_of_left.item
self.subtree_delete(node_to_delete.left, max_of_left.item.key)
return value
# assumes non empty subtree
def subtree_max(self, curr_root):
node = curr_root
while (node.right is not None):
node.rank-=1
node = node.right
return node
######################################## Question 5 ##########################################
def get_ith_smallest(self, i):
if i > self.size:
raise IndexError
lst = []
bst_sub_root = self.root
while True:
while bst_sub_root is not None:
lst.append(bst_sub_root)
bst_sub_root = bst_sub_root.left
bst_sub_root = lst.pop()
if i == 1:
return bst_sub_root.item.key
else:
i -= 1
bst_sub_root = bst_sub_root.right
def inorder(self):
for node in self.subtree_inorder(self.root):
yield node
def subtree_inorder(self, curr_root):
if(curr_root is None):
pass
else:
yield from self.subtree_inorder(curr_root.left)
yield curr_root
yield from self.subtree_inorder(curr_root.right)
def preorder(self):
for node in self.subtree_preorder(self.root):
yield node
def subtree_preorder(self, curr_root):
if(curr_root is None):
pass
else:
yield curr_root
yield from self.subtree_preorder(curr_root.left)
yield from self.subtree_preorder(curr_root.right)
def __iter__(self):
for node in self.inorder():
yield (node.item.key, node.item.value)
########################################## Question 2 ##################################################
def create_chain_bst(n):
new_bst = BinarySearchTreeMap()
for num in range(1,n+1):
new_bst.subtree_insert(num)
return new_bst
def create_complete_bst(n):
bst = BinarySearchTreeMap()
add_items(bst, 1, n)
return bst
def add_items(bst, low, high):
if low >= high:
bst.subtree_insert(low)
return
bst.subtree_insert(low+((high-low)//2))
add_items(bst, low, low+((high-low)//2)-1)
add_items(bst, low+((high-low)//2)+1, high)
########################################## Question 3 ##################################################
def restore_bst(prefix_lst):
if len(prefix_lst) == 0:
return BinarySearchTreeMap()
else:
mini = 12342343456453
for index in range(len(prefix_lst)):
if mini > prefix_lst[index]:
mini = prefix_lst[index]
mini-=1
maxi = prefix_lst[len(prefix_lst)-1]+1
restore_bst.index = 0
def restore_bst_helper(lst, mini, maxi, low, high):
if len(lst) == 1:
return BinarySearchTreeMap().Node(BinarySearchTreeMap().Item(lst[low]))
if low > high:
return
if mini < lst[low] < maxi:
subtree_root = BinarySearchTreeMap().Node(BinarySearchTreeMap().Item(lst[low]))
restore_bst.index += 1
if low + 1 < high:
subtree_root.left = restore_bst_helper(lst, mini, lst[low], restore_bst.index, high)
subtree_root.right = restore_bst_helper(lst, lst[low], maxi, restore_bst.index, high)
return subtree_root
bst = BinarySearchTreeMap()
bst.root = restore_bst_helper(prefix_lst, mini, maxi, 0, len(prefix_lst)-1)
return bst
########################################## Question 4 ##################################################
def find_min_abs_difference(bst):
lst = []
mini = 9999999999
for node in bst:
lst.append(node[0])
for index in range(len(lst)):
mini = min(mini, abs(lst[index]-lst[index-1]))
return mini
if __name__=="__main__":
bst = restore_bst([9,7,3,1,5,13,11,15])
for node in bst.preorder():
print(node.item.key, end=" ")
bst.get_ith_smallest(1)
|
""" Question 5 """
class ArrayStack:
def __init__(self):
self.data = []
def push(self, item):
self.data.append(item)
def pop(self):
return self.data.pop()
def top(self):
return self.data[-1]
def __len__(self):
return len(self.data)
def isEmpty(self):
return len(self.data) == 0
def __getitem__(self, item):
return self.data[item]
class EmptyStack(Exception):
pass
class ArrayQueue:
INITIAL_VALUE = 10
def __init__(self):
self.data = [None] * ArrayQueue.INITIAL_VALUE
self.front = 0
self.nextInsert = 0 # Duplicate information
self.count = 0
def enqueue(self, val):
if self.count >= len(self.data):
self._resize(2*len(self.data))
back = (self.front + self.count) % len(self.data)
self.data[back] = val
self.count += 1
def __len__(self):
return self.count
def dequeue(self):
if self.count == 0:
raise EmptyStack()
result = self.data[self.front]
self.data[self.front] = None
self.front = (self.front + 1) % len(self.data)
self.count -= 1
return result
def _resize(self, capacity):
old = self.data
self.data = [None] * capacity
for i in range(self.count):
self.data[i] = old[(self.front + i) % len(old)]
self.front = 0
def __str__(self):
result = ""
for i in range(self.front, len(self.data)):
if i != len(self.data)-1:
result += str(self.data[i])+ ", "
else:
result += str(self.data[i])
return "["+result+"]"
def permutations(lst):
perm_sets = ArrayQueue()
perm_nums = ArrayStack()
perm_sets.enqueue([])
# for i in range(len(perm_nums)-1, -1, -1):
for num in lst:
for i in range(len(perm_sets)):
val = perm_sets.dequeue()
for j in range(len(val)+1):
perm_nums.push(val[:j] + [num] + val[j:])
perm_sets.enqueue(perm_nums)
perm_nums = ArrayStack()
temp = perm_sets.dequeue()
for j in range(len(temp)):
print(temp.pop())
print(permutations([1,2,3]))
|
from collections import Counter, defaultdict
f=open("1661.txt","r")
def getTotalNumberOfWords():
#f=open("1661.txt","r")
f=open("1661.txt","r")
count=0
for line in f:
for word in line.split():
count+=1
print("total number of words:",count)
def getTotalUniqueWords():
#f=open("1661.txt","r")
d=defaultdict(int)
for line in f:
for word in line.split():
d[word]+=1
print("total unique numbers is",len(d))
def get20MostFrequentWords():
f=open("1661.txt","r")
dict={}
for line in f:
for word in line.split():
dict[word]=dict.get(word,0)+1
k=Counter(dict)
high=k.most_common(20)
print("Dictionary with 20 frequent words:")
print("keys: Values")
for i in high:
print('[',i[0],', ',i[1],']')
def get20MostInterestingFrequentWords():
f=open("1661.txt","r")
g=open("1-1000.txt","r")
dict={}
for line in f:
for word in line.split():
dict[word]=dict.get(word,0)+1
k=Counter(dict)
high=k.most_common(20)
# result=filter(lambda x: x%200!=0,k)
print("Dictionary with 20 Interesting frequent words:")
print("keys: Values")
for i in high:
print('[',i[0],', ',i[1],']')
getTotalNumberOfWords()
getTotalUniqueWords()
#get20MostFrequentWords()
get20MostInterestingFrequentWords()
|
s=input()
print(s)
s=input("Enter your name: ")
print(s)
i=int(input("Enter an integer:"))
print(i)
print(type(i))
lst = [int(x) for x in input("Enter 3 numbers: ").split()]
print(lst) |
import math
radius=float(input("Enter radius"))
area = math.pi*radius**2
print(area) |
a,b,c = [int(x) for x in input("Enter 3 numbers").split()]
average = (a+b+c)/3
print("Average of 3 numbers is ",average) |
x=int(input("Enter min number"))
y=int(input("Enter max number"))
i=x
if(i%2==0):
i+=1
while(i<=y):
print(i)
i+=2
|
# https://leetcode.com/problems/fizz-buzz/
def fizz_buzz(n):
# do a for loop
result = []
for i in range(1, n+1):
if i % 3 == 0 and i % 5 == 0:
result.append('FizzBuzz')
elif i % 3 == 0:
result.append('Fizz')
elif i % 5 == 0:
result.append('Buzz')
else:
result.append(str(i))
return result
print(fizz_buzz(3))
# O(n) - time complextiy
# O(n) - space complexity |
# https://leetcode.com/problems/factorial-trailing-zeroes/
# 1! = 1
# 2! = 2*1 = 2
# 3! = 3*2*1 = 6
# 4! = 4*3*2*1 = 24
# 5! = 5*4*3*2*1 = 120 - one trailing zero
# 6! = 6*5*4*3*2*1 = 720 - one trailing zero
# 7! = 7*6*5*4*3*2*1 = 5040 - two trailing zeros
# how many multiples of 5 in a given n?
import math
def trailing_zero(n):
if n < 5:
return 0
if n < 10:
return 1
return math.floor(n/5 + trailing_zero(n/5))
print(trailing_zero(100))
def trailing_zero_2(n):
result = 0
while n > 0:
result += math.floor(n/5)
n /= 5
print(trailing_zero(101)) |
# https://leetcode.com/problems/number-of-segments-in-a-string/
def count_segments(s):
return len(s.split())
print(count_segments('Hello, my name is John')) |
# https://leetcode.com/problems/defanging-an-ip-address/
def defang_ip(address):
result = []
for char in address:
if char == '.':
char = '[' + char + ']'
result.append(char)
return ''.join(result)
print(defang_ip('1.1.1.1')) |
# https://leetcode.com/problems/move-zeroes/
def move_zeros(arr):
# do it in place
i = 0
for j in range(len(arr)):
if arr[j] != 0:
arr[i], arr[j] = arr[j], arr[i]
i += 1
return arr
print(move_zeros([0, 1, 0, 3, 12]))
# O(n) - time complexity
# O(1) - space complexity |
# Given a non-empty string s, you may delete at most one character. Judge
# whether you can make it a palindrome.
# Input: "aba"
# Output: True
#
# Input: "abca"
# Output: True
# Explanation: You could delete the character 'c'.
# brute force solution is to delete each char and see if the rest of the s is a panlindrom
# time complexity is O(N^2) and space is O(N)
def validPalindrome(s):
"""
:type s: str
:rtype: bool
"""
l, r = 0, len(s) - 1
while l < r:
if s[l] == s[r]:
l += 1
r -= 1
else:
return s[l:r] == s[l:r][::-1] or s[l + 1:r + 1] == s[l + 1:r + 1][::-1]
return True
|
# https://leetcode.com/problems/implement-strstr/
def strStr(haystack, needle):
L = len(haystack)
n = len(needle)
for i in range(L):
if haystack[i:n+i] == needle:
return i
return -1
print(strStr('hello', 'll')) |
def update_path_with_transfer_count(all_paths, trips):
"""
Takes all paths list with dictionary and updates them with transfers needed from trips
"""
for paths in all_paths:
for path in paths.values():
path["transfers"] = get_transfer_count(path["path"], trips)
def get_transfer_count(path, connections):
index = 0
transfer_count = 0
if len(path) <= 2:
return 0
while True:
index += find_most_direct_stop_count(path, index, connections)
if path[index] == path[-1]:
break
else:
transfer_count += 1
return transfer_count
def find_most_direct_stop_count(path, path_index, connections):
direct_length_max = 0
for connection in connections:
connection_index = 0
while connection_index < len(connection):
if connection[connection_index] == path[path_index]:
direct_match = 1
while True:
if connection_index + direct_match >= len(connection) or path_index + direct_match >= len(path):
break
if connection[connection_index + direct_match] == path[path_index + direct_match]:
direct_match += 1
else:
break
direct_length = direct_match - 1
if direct_length > direct_length_max:
direct_length_max = direct_length
break
else:
connection_index += 1
if path_index + direct_length_max == len(path) - 1:
break # We are in the target stop
if direct_length_max == 0:
direct_length_max = 1 # This should never happen, but...
return direct_length_max
|
#deleting the repetetive characters
a = 'Biiiishwwwwa'
new_string = ''
for i in range(len(a)):
if i != len(a) -1 and a[i+1] == a[i]:
pass
else:
new_string += a[i]
print new_string
|
# 注意一定要按照这个模板格式,不然报错,特别注意冒号:和缩进问题
print('请输入一个1-100之间的数字')
str = input()
num = int(str)
if num < 60:
print("您的分数不及格")
elif num < 70:
print("合格")
elif num < 80:
print("中等")
elif num < 90:
print("良好")
else:
print("优秀")
# if x:
# print('True')
# 只要x是非零数值、非空字符串、非空list等,就判断为True,否则为False |
# print('Início')
# for num in range(0, 6):
# print(num)
# if num == 2:
# break
# print('Final')
# for c in 'Curso de Python':
# print(c)
# if c == 'o':
# break
# for c in 'Curso de Python':
# if c == 'o':
# continue
# print(c)
# for c in 'Curso de Python':
# if c in 'ory':
# continue
# print(c)
soma = 0
print('Digite apenas números entre 0 e 10.\nA soma máxima será 20.')
for num in range(0, 4):
n = int(input('Número: '))
if n >= 0 and n <= 10:
soma += n
else:
print(f'Serão somados apenas números entre 0 e 10, {n} não será somado')
if soma >= 20:
soma = 20
print('valor máximo da soma atingido')
break
print(f'Soma = {soma}') |
# n1 = 1
# n2 = 0
# soma = n1 + n2
#
# while soma > 0:
# n1 = int(input('Número 1: '))
# n2 = int(input('Número 2: '))
# soma = n1 + n2
# print(f'{n1} + {n2} = {soma}\n')
numero = 7
while numero >= 3:
print(numero)
numero = numero - 1 |
num = [1,2,3,4,5]
print(num)
#
# num.append(10)
# print(num)
#
# num.insert(0,20)
# print(num)
#
num.insert(3, 50)
num.insert(-1, 80)
print(num)
# num[1] = 'D'
# num[2] = 'p'
# print(num)
# del(num[1])
# print(num)
# del(num[2:4])
# print(num)
# num.clear()
# print(num)
# num = [1,2,3,4,5]
# print(num)
# print(num.pop(2))
# print(num)
|
import sys
import os
# https://www.geeksforgeeks.org/merge-sort/
def merge(input_array, left, middle, right):
comps = 0
N1 = middle - left + 1
N2 = right - middle
left_sub = []
right_sub = []
for i in range(0, N1):
left_sub.append(input_array[left + i])
for j in range(0, N2):
right_sub.append(input_array[middle + 1 + j])
i = j = 0
k = left
while i < N1 and j < N2:
if left_sub[i] <= right_sub[j]:
input_array[k] = left_sub[i]
i += 1
comps += 1
else:
input_array[k] = right_sub[j]
j += 1
comps += 1
k += 1
while i < N1:
input_array[k] = left_sub[i]
i += 1
k += 1
while j < N2:
input_array[k] = right_sub[j]
j += 1
k += 1
return comps
def recursive_mergesort(input_array, left, right):
comps = 0
if right > left:
mid_point = (left + right) // 2
comps += recursive_mergesort(input_array, left, mid_point)
comps += recursive_mergesort(input_array, mid_point + 1, right)
comps += merge(input_array, left, mid_point, right)
return comps
# https://www.geeksforgeeks.org/iterative-merge-sort/
def iterative_mergesort(input_array):
sz = 1
comps = 0
while sz < len(input_array) - 1:
left = 0
while left < len(input_array) - 1:
mid = left + sz - 1
if 2 * sz + left - 1 > len(input_array) - 1:
right = len(input_array) - 1
else:
right = 2 * sz + left - 1
comps += merge(input_array, left, mid, right)
left = left + sz * 2
sz = 2 * sz
return comps
def mergesort_insertion_cutoff(input_array, left, right, cutoff=7):
if right > left:
if right - left <= cutoff:
for i in range(left, right+1):
key = input_array[i]
j = i - 1
while j >= left and key < input_array[j]:
input_array[j + 1] = input_array[j]
j -= 1
input_array[j + 1] = key
else:
mid_point = (left + right) // 2
mergesort_insertion_cutoff(input_array, left, mid_point)
mergesort_insertion_cutoff(input_array, mid_point+1, right)
merge(input_array, left, mid_point, right)
def main():
try:
# https://stackoverflow.com/questions/7165749/open-file-in-a-relative-location-in-python
rel_path = sys.argv[1] # "/data/data1.1024"
cwd = os.getcwd()
abs_file_path = cwd + rel_path
input_file = open(abs_file_path)
data_array = []
for line in input_file.readlines():
data_array.append(int(line))
input_file.close()
print("Input data: {}".format(data_array))
print("Iterative mergesort called on a copy of data_array, used {} comparisons".format(iterative_mergesort(data_array[:])))
print("Recursive mergesort called on a copy of data_array, used {} comparisons".format(recursive_mergesort(data_array[:], 0, len(data_array)-1)))
except IndexError:
print("No input data file")
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 10 12:47:09 2019
@author: Saloni Rawat
"""
from numpy import random
import tictactoe
gameBoard = tictactoe.create_board()
tictactoe.print_board(gameBoard)
Players = (tictactoe.PIECE_ONE, tictactoe.PIECE_TWO)
def HumanPlayer(board, history, players):
''' Read move from human player '''
moves = 9
move = -1
while move not in range(0, moves):
move = int(input('Which square? '))
print()
print()
#Handle the exception
'''check if the value is in range'''
if move not in range(0, moves):
print ("invalid value")
else:
break;
return move
def ComputerPlayer(board, history, players):
'''selects random move for the computer'''
move = random.randint(0,8)
flag = False
while not flag:
row = move// 3
column = move%3
if tictactoe.check_piece(board, row, column):
#print("Move", move)
return move
else:
move = random.randint(0,8)
return move
|
# copy(): 深拷贝字典,创建一个新的字典对象。
name_dict = {"name": "python", "age": 26, "id": 110}
# pop():参数是键,删除指定的键值对,并返回值(第二个参数表示如果没有这个键值队,则返回这个值)
print(name_dict)
newName_dict = name_dict.copy()
print(newName_dict)
newName_dict.pop("name")
print(newName_dict)
INFO = newName_dict.pop("newName", "没有这个键") # 有这个键就删除这个键,没有就返回第二个参数的值
print(INFO)
# popitem(): 依次,从后向前 删除键值对,并返回这个键值对的 元组
name_dict1 = {"name": "python", "age": 26, "id": 110}
key, value = name_dict1.popitem() # 拆包(拆分元组, 并用变量接收)
print(key, value)
# 删除
# name_dict1.clear()
# print(name_dict1)
del name_dict1
print(name_dict1) |
# coding=utf-8
card_info_save = []
def add_card_info():
name_info = input("请输入姓名:")
age_info = input("请输入年龄:")
sex_info = input("请输入性别:")
card_info_save.append([name_info, age_info, sex_info])
print(card_info_save)
print("[INFO]:用户信息存储成功")
def del_card_info():
del_name = input("请输入要删除的用户:")
for del_info in card_info_save:
if del_name in del_info:
# card_info_save[card_info_save.index(del_info)].remove()
card_info_save.remove(del_info)
print(del_info)
print("[INFO]:用户信息删除成功")
break
else:
print("[ERROR]:系统内不存在此用户")
def update_card_info():
update_name = input("请输入要修改的用户名:")
for update_info in card_info_save:
if update_name in update_info:
new_card_name = input("请输入新用户姓名:")
new_card_age = input("请输入新用户年龄:")
new_card_sex = input(" 请输入用户新性别:")
card_info_save[card_info_save.index(update_info)] = [new_card_name, new_card_age, new_card_sex]
print("[INFO]:用户信息修改成功")
break
else:
print("[ERROR]:系统内不存在此用户")
def select_card_info():
select_name = input("请输入要查询的用户姓名:")
for select_info in card_info_save:
if select_name in select_info:
print(card_info_save[card_info_save.index(select_info)])
else:
print("[ERROR]:系统内不存在此用户")
# def save_info():
while True:
user_index = int(input("请选择要操作的功能:"))
if user_index == 1:
add_card_info()
elif user_index == 2:
del_card_info()
elif user_index == 3:
update_card_info()
elif user_index == 4:
select_card_info()
|
# 1、创建集合
"""
集合里的数据是唯一的,没有重复的数据
集合、列表、元组 可以互相转换
交集&
并集|(会去重)
差集 -
"""
num_set = set() # 集合
print(type(num_set))
num_set1 = (1, 2) # 元组
print(type(num_set1))
num_list = [10, 20, 30, -90]
print(max(num_list))
print(min(num_list)) |
# coding=utf-8
import os
file_path = os.getcwd()
file_name_list = os.listdir(file_path)
print(file_name_list)
my_file = input("请输入要查询的文件名:")
# for my_file_list in file_name_list:
if my_file not in file_name_list:
print("[ERROR:]not found the file 'my_file'")
else:
postion = my_file.rfind(".")
newfile_name = my_file[:postion] + "_backup" + my_file[postion:]
print(postion)
print(newfile_name)
source_file = open(my_file, "rb")
backup_file = open(newfile_name, "wb")
data = source_file.read(10)
# 新建一个文件,把要拷贝的文件写入到这个文件里
backup_file.write(data)
# read()会读取所有的内容,如果文件过大,会导致打开失败,
# data = source_file.read()
print(data)
backup_file.close()
source_file.close()
|
import random
number1 = random.randint(1, 1000)
counter = 1
number2 = random.randint(1, 1000)
while number1 != number2:
counter += 1
number2 = random.randint(1, 1000)
print('number 1 is:', number1)
print('number 2 is:', number2)
print('number of attempts:', counter)
|
list_noun = ['dog', 'potato', 'meal', 'icecream', 'car']
list_adj = ['dirty', 'big', 'hot', 'colorful', 'fast']
for x in list_adj:
for z in list_noun:
print(x, z) |
import random
dice_range = range(1, 6)
dice = random.choice(dice_range)
if dice == 1:
print('o')
elif dice == 2:
print('\to \no')
elif dice == 3:
print('\t\to\n\to\no')
elif dice == 4:
print('o o')
print(' ')
print('o o')
elif dice == 5:
print('o o')
print(' o ')
print('o o')
else:
print('o o')
print('o o')
print('o o')
dices = []
for i in range(5):
dices.append(random.choice(dice_range))
random.shuffle(dices)
print(dices)
|
a=int(input("enter value "))
sum=0
num=1
while a>0:
r=a%10
sum=sum+r
num=num*r
a=a//10
print("sum",sum)
print("num",num)
if sum==num:
print("twin")
else:
print("not twin")
|
a=int(input("enter value of a : "))
b=int(input("enter value of b : "))
if a>b:
print("a moto che")
else:
print("b moto che")
|
a=int(input("enter value "))
no=a
rev=0
while a>0:
r=a%10
rev=(rev*10)+r
a=a//10
print("rev",rev)
if no==rev:
print("pelindrom")
else:
print("not pelindrom")
|
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 14:38:50 2020
@author: jyoth
"""
#It is a binary classification
# Importing the datasets
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Social_Network_Ads.csv')
X = dataset.iloc[:, 2:-1].values
y = dataset.iloc[:, 4].values
# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
# Feature Scaling categorical variables should not be encoded
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
# Creating classifer object
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(random_state = 0)
classifier.fit(X_train, y_train)
# Prediciting
y_pred = classifier.predict(X_test)
# Check how many predicitons are true, false using function confusion matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
# Visualizing the Dependent variable in the dataset
import seaborn as sns
sns.countplot(x = 'Purchased', data = dataset, palette = 'hls')
# Visualising the 'Age' and 'Estimated salary' as scatterplot in Whole set
purchased = dataset.iloc[y == 1] #Filtering purchased data
not_purchased = dataset.iloc[y == 0] # Filtering Unpurchased data
plt.scatter(purchased.iloc[:, 2], purchased.iloc[:, 3], s=30, label = 'Purchased', color = 'red')
plt.scatter(not_purchased.iloc[:, 2], not_purchased.iloc[:, 3], s=30, label = 'Not_Purchased', color = 'blue')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
# Visualising the 'Age' and 'Estimated salary' as scatterplot in Training set
purchased = X_train[y_train == 1]
not_purchased = X_train[y_train == 0]
plt.scatter(purchased[:, 0], purchased[:, 1], label = 'Purchased', color = 'red')
plt.scatter(not_purchased[:, 0], not_purchased[:, 1], label = 'Not_Purchased', color = 'blue')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
# Visualising the 'Age' and 'Estimated salary' as scatterplot in Test set
purchased = X_test[y_test == 1]
not_purchased = X_test[y_test == 0]
plt.subplot(2, 2, 1)
plt.title('Test_set')
plt.scatter(purchased[:, 0], purchased[:, 1], label = 'Purchased', color = 'red')
plt.scatter(not_purchased[:, 0], not_purchased[:, 1], label = 'Not_Purchased', color = 'blue')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
#plt.legend()
plt.subplot(2, 2, 2)
plt.title('Predicted')
purchased = X_test[y_pred == 1]
not_purchased = X_test[y_pred == 0]
plt.scatter(purchased[:, 0], purchased[:, 1], label = 'Purchased', color = 'green')
plt.scatter(not_purchased[:, 0], not_purchased[:, 1], label = 'Not_Purchased', color = 'orange')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
#plt.legend()
plt.tight_layout()
plt.show()
#Visualising the Logistic Regression classifier
from matplotlib.colors import ListedColormap
X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('yellow', 'gray')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
plt.title('Logistic Regression (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
# final Visualisation of Classifier with prediction results
from matplotlib.colors import ListedColormap
X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('yellow', 'gray')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
plt.title('Predicted')
purchased = X_test[y_pred == 1]
not_purchased = X_test[y_pred == 0]
plt.scatter(purchased[:, 0], purchased[:, 1], label = 'Purchased', color = 'green')
plt.scatter(not_purchased[:, 0], not_purchased[:, 1], label = 'Not_Purchased', color = 'orange')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend(fontsize = 'x-small')
plt.show()
|
# # 1
# def acc(x):
# for y in range(x,0,-1):
# print(y)
# acc(10)
# # 2
# def printReturn(x,y):
# print(x)
# return(y)
# z=printReturn(10,5)
# print(z)
# # 3
# def length(x):
# sum=len(x)+x[0]
# return sum
# z=length([1,2,3,4,5])
# print(z)
# # 4
# def valGreat2(x):
# y=[]
# for i in range(0,len(x),1):
# if len(x)<=2:
# return False
# if x[i] > x[1]:
# y.append(x[i])
# print(len(y))
# if len(y) >=2:
# return y
# else:
# return False
# z = valGreat2([3])
# print (z)
# 5
def tltv(s,v):
x=[]
for i in range(0,s,1):
x.append(v)
return x
z=tltv(6,2)
print(z) |
import random
def randInt(min=0, max=100 ):
num= random.random() *(max-min)+min
num=round(num)
return num
print(randInt(max=50)) |
import random
while True:
choices = ["pedra","papel","tesoura"]
computer = random.choice(choices)
player = None
while player not in choices:
player = input("Pedra, papel ou tesoura?").lower()
if player == computer:
print("O computador escolheu", computer)
print("O jogador escolheu", player)
print("O jogo empatou")
elif player == "pedra":
if computer == "papel":
print("O computador escolheu", computer)
print("O jogador escolheu", player)
print("Você perdeu!")
if computer == "tesoura":
print("O computador escolheu", computer)
print("O jogador escolheu", player)
print("Você ganhou!")
elif player == "papel":
if computer == "tesoura":
print("O computador escolheu", computer)
print("O jogador escolheu", player)
print("Você perdeu!")
if computer == "pedra":
print("O computador escolheu", computer)
print("O jogador escolheu", player)
print("Você ganhou!")
elif player == "tesoura":
if computer == "pedra":
print("O computador escolheu", computer)
print("O jogador escolheu", player)
print("Você perdeu!")
if computer == "papel":
print("O computador escolheu", computer)
print("O jogador escolheu", player)
print("Você ganhou!")
play_again = input("Quer jogar novamente? (Sim/Não)").lower()
if play_again != "sim":
break
print("Adeus! \nFoi bom jogar com você!") |
__author__ = 'satish'
# We have a class defined for vehicles.
# Create two new vehicles called car1 and car2. Set car1 to be a red convertible
# worth $60,000 with a name of Fer, and car2 to be a blue van named Jump worth $10,000.
# define the Vehicle class
class Vehicle:
name = ""
kind = "car"
color = ""
value = 100.00
def description(self):
desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
return desc_str
# your code goes here
car1 = Vehicle()
car1.kind="convertible"
car1.color="read"
car1.name="Fer"
car1.value = 60000
car2=Vehicle()
car2.name="Jump"
car2.kind="van"
car2.color="blue"
car2.value=10000
# test code
print car1.description()
print car2.description()
|
import time
condition = 0
#this while loop adds one to the condition variable so it no longer meets the condition to run the loop again
#so the loop ends
while condition == 0:
print("the variable 'condition' is equal to 0")
condition += 5
print("the variable 'condition' is no longer equal to 0 so the loop is over")
time.sleep(5)
#this loop will run as long as the condition variable is not equal to 0
while condition != 0:
print("the variable 'condition' is equal to " +str(condition))
condition -= 1
print("the variable 'condition' is back to 0")
time.sleep(5)
#this loop will run forever or until you use break
while True:
condition -= 1
print("the variable 'condition' is equal to " +str(condition))
if condition == -7:
break
print("no more loop") |
snt=input()
snt=snt.lower()
x=[]
for i in snt:
if i.isalpha():
x.append(i)
x=set(x)
if len(x)==26:
print("Pangram")
else:
raise ValueError("Not a pangram")
|
"""
Assume you are given two dictionaries d1 and d2, each with integer keys and i
nteger values
1. find interesection
2. find difference
Source: MIT excercise
author: Akshit Gupta
"""
#Let's take two dictionaries
#Hard coding the dictionaries
# d1 = {1:10,2:20,3:30,5:80}
# d2 = {1:40, 2:50, 3:60, 4:40, 6:70, 7:80}
#Take the dictionaries from user
d1 = dict()
d2 = dict()
number1 = input('Enter the values for the first dictonary ')
for i in range(int(number1)):
data = input ('Enter the key, value pair seperated by : = ')
temp = data.split(':')
d1[temp[0]] = int (temp[1])
number2 = input('Enter the values for the second dictonary ')
for i in range(int(number2)):
data1 = input ('Enter the key, value pair seperated by : = ')
temp1 = data1.split(':')
d2[temp1[0]] = int (temp1[1])
intersection = {}
difference = {}
for key1 in d1:
for key2 in d2:
if key1 == key2:
intersection[key1] = (d1[key1], d2[key1])
elif key1 not in d2.keys():
difference [key1] = d1[key1]
elif key2 not in d1.keys():
difference [key2] = d2 [key2]
print (f"The value of intersections is {intersection}")
print (f"The value of difference is {difference}")
|
"""
Class Inhertiance Program
author: Akshit Gupta <[email protected]>
"""
class Coin:
def __init__(self, rare=False, clean=True, head=True, **kwargs):
for key,value in kwargs.items():
setattr(self, key, value)
self.is_rare = rare
self.is_clean = clean
self.head = head
if self.is_rare:
self.value = self.original_value * 1.25
else:
self.value = self.original_value
if self.is_clean:
self.color = self.clean_color
else:
self.color = self.rusty_color
def rust(self):
self.color = self.rusty_color
def clean(self):
self.color = self.clean_color
def __del__(self):
print ("coin spent!")
def flip(self):
head_options = [True, False]
choice = random.choice(head_options)
self.head = choice
def __str__ (self):
if self.original_value >=1:
return "{} Coin".format (int(self.original_value))
else:
return "{}p Coin". format (int(self.original_value * 100))
class Two_Rupee1(Coin):
def __init__(self):
data = { "original_value": 2.00,
"clean_color":"steel",
"rusty_color":"brownish",
"num_edges": 11,
"diameter" : 23.00,
"weight": 26,
}
super().__init__(**data)
class Two_Rupee(Coin):
def __init__(self):
data = { "original_value": 2.00,
"clean_color":"steel",
"rusty_color":"brownish",
"num_edges": 11,
"diameter" : 23.00,
"weight": 26,
}
super().__init__(True, **data)
rupee1 = Two_Rupee1()
print (rupee1.value)
rupee = Two_Rupee()
#rupee1.color
#rupee1.clean()
#rupee1.color
print (rupee.value)
|
import sys
import os
import datetime
from peewee import *
welcome = '\n***Welcome to Work Database for Python Command Line***\n'
db = SqliteDatabase('tasks.db')
class Task(Model):
employee = CharField(max_length=100)
name = CharField(max_length=100)
time = IntegerField(default=0)
date = DateField(default=datetime.date.today())
notes = TextField()
class Meta:
database = db
def initialize():
'''Create the database and the table if they don't exist.'''
db.connect()
db.create_tables([Task], safe=True)
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
def work_log():
'''stores information about tasks including name, time spent, and optional
notes. Tasks can be searched, edited, and deleted.
>>> work_log()
>>> 1
'''
menu = """\nSelect from the following options:\n
1 - Enter new task
2 - Search for existing task
3 - Quit\n
"""
print(menu)
menu_select = None
while not menu_select:
menu_select = input('>>>')
if menu_select == '1':
task_entry()
elif menu_select == '2':
task_search()
elif menu_select == '3':
sys.exit(0)
elif menu_select.lower() == 'm':
print(menu)
menu_select = None
else:
print("Please select an option from 1, 2, 3, m=menu")
menu_select = None
def task_entry():
'''Allows user to enter a task name, time spent, and optional notes'''
# define employee, name, time, and notes variables
# employee = name = time = notes = None
# get input for each of these
employee = name_input('Enter employee name (100 characters or less).')
name = name_input('Enter a name for the task (100 characters or less).')
time = number_input('Enter time spent on task in minutes.')
notes = input("Enter any notes about the task (optional).\n>>>")
if notes.isspace():
notes = None
# insert input into file
Task.create(employee=employee, name=name, time=time, notes=notes)
# Option to add another entry or return to main menu
repeat = input("The task was added. Enter another task? [Y/n]")
if repeat.lower() == 'y':
task_entry()
else:
work_log()
def task_search():
'''Allows user to search, edit, and delete task entries from file'''
menu = '''\nSelect from the following options:\n
1 - Find by date
2 - Find by time spent
3 - Find by exact search
4 - Find by employee name
5 - Return to main menu\n
'''
print(menu)
search_mode = None
while not search_mode:
search_mode = input('>>>').strip()
if search_mode == '1':
date_find()
elif search_mode == '2':
time_find()
elif search_mode == '3':
exact_find()
elif search_mode == '4':
employee_find()
elif search_mode == '5':
work_log()
else:
print("Please enter a selection from 1 to 5")
search_mode = None
def number_input(msg):
'''Takes string as argument and prints it to solicit input,
and tests that input represents an integer
'''
time = None
print(msg)
while not time:
time = input('>>>').strip()
try:
time = int(time)
except ValueError:
print('Enter a valid number.')
time = None
else:
if not time or time < 0:
print('Enter a valid time.')
time = None
return time
def name_input(msg):
'''Takes string as argument and prints it to solicit name,
then checks that input is 100 characters or less in length.
'''
name = None
print(msg)
while not name or name.isspace():
name = input('>>>').strip()
if len(name) > 100 or not name:
print('Please enter a name from 1-100 characters in length.')
name = None
return name
def date_input(date_wrapper):
'''Asks for date and validates for format YYYY-MM-DD'''
# Function takes lists rather than strings since strings are immutable
while len(date_wrapper) == 0:
try:
input_string = input('>>>')
date_wrapper.append(datetime.datetime.strptime(
input_string, '%Y-%m-%d'))
except ValueError:
print('Date must be valid and in format YYYY-MM-DD. Try again.')
def date_find():
'''Searches for all entries matching a specific date
or falling within a date range.
'''
# Dates are lists so that they can be passed into date_input and modified
search_date_1 = []
search_date_2 = []
search_mode = None
while not search_mode:
search_mode = input('Enter 1 to browse all dates '
'or 2 to search within a date range.\n>>>').strip()
if search_mode not in ['1', '2']:
print('Not a valid selection')
search_mode = None
if search_mode == '2':
print('Input start date in format YYYY-MM-DD')
date_input(search_date_1)
print('Input end date in format YYYY-MM-DD')
while not search_date_2:
date_input(search_date_2)
# make sure search_date1 is no later than search_date2
if search_date_1[0].timestamp() > search_date_2[0].timestamp():
print('First date cannot be later than second date. '
'Enter end date again.')
search_date_2 = []
# run search
search_results = []
tasks = Task.select().order_by(Task.date.desc())
if search_mode == '2':
tasks = tasks.where(Task.date >= search_date_1[0].date())
tasks = tasks.where(Task.date <= search_date_2[0].date())
if not tasks.count():
print('\nNo results found.\n')
task_search()
else:
entry_dates = []
count = 1
for task in tasks:
if task.date not in entry_dates:
entry_dates.append(task.date)
print('Pick one of the following dates to view entries from')
for date in entry_dates:
date_entries_count = Task.select().where(
Task.date == str(date)).count()
print(str(count) + ": " + str(date) + " (" +
str(date_entries_count) + " entr{})".format(
'ies' if date_entries_count > 1 else 'y'))
count += 1
selection = None
print('Enter number corresponding to the desired date.')
while not selection:
selection = input('>>>').strip()
try:
selection = int(selection)
except ValueError:
print('Please enter a valid number')
selection = None
else:
if selection > len(entry_dates) or selection < 0:
print('Please enter a valid number{}'.format(
' between 1 and {}.'.format(
len(entry_dates)) if len(entry_dates) > 1
else '.'))
selection = None
search_results = []
query = Task.select().where(
Task.date == str(entry_dates[selection - 1]))
for result in query:
search_results.append(result)
display_results(search_results)
def time_find():
search_results = []
search_time = number_input("Enter task time to the nearest minute")
query = Task.select().where(Task.time == search_time)
for result in query:
search_results.append(result)
if len(search_results) == 0:
print('\nNo results found.\n')
task_search()
else:
display_results(search_results)
def exact_find():
search_string = None
search_results = []
print('Enter text to be searched')
while search_string is None or search_string.isspace():
search_string = input('>>>')
if search_string.strip() == '':
print("Please enter some text to be searched.")
search_string = None
query = Task.select().where(
(Task.name.contains(search_string)) |
(Task.notes.contains(search_string))
)
for result in query:
search_results.append(result)
if len(search_results) == 0:
print('\nNo results found.\n')
task_search()
else:
print('Number of results = ' + str(len(search_results)))
display_results(search_results)
def employee_find():
tasks = Task.select().order_by(Task.employee.asc())
employee_names = []
count = 1
for task in tasks:
if task.employee not in employee_names:
employee_names.append(task.employee)
print('Pick one of the following employees to view entries from:')
for person in employee_names:
number_of_entries = Task.select().where(
Task.employee == person).count()
print(str(count) + ": " + person + " (" + str(number_of_entries)
+ " entr{})".format('ies' if number_of_entries > 1 else 'y'))
count += 1
selection = None
while not selection:
print('Enter number corresponding to the desired employee.')
selection = input('>>>').strip()
try:
selection = int(selection)
except ValueError:
print('Please enter a valid number')
selection = None
else:
if selection > len(employee_names):
print('Please enter a valid number{}'.format(
' between 1 and {}.'.format(
len(employee_names) if len(employee_names) > 1
else '.')))
selection = None
search_results = []
query = Task.select().where(Task.employee == employee_names[selection - 1])
for result in query:
search_results.append(result)
display_results(search_results)
def display_results(results_list):
'''Displays search results one by one,
allowing each entry to be edited or deleted.'''
count = 1
for entry in results_list:
print('''
Result {} of {}\n
Employee name: {}
Task name: {}
Work time: {}
Date: {}
Notes: {}
'''.format(count, len(results_list), entry.employee, entry.name,
entry.time, entry.date, entry.notes))
selection = None
while not selection:
selection = input('Select {}[E]dit entry, '
'[D]elete entry, [S]earch menu \n>>>'
.format('[N]ext result, ' if count <
len(results_list) else ''))
if selection.lower() == 'e':
edit_entry(entry)
elif selection.lower() == 'd':
delete_entry(entry)
elif selection.lower() == 's':
# quit display results and go back to search menu
return task_search()
elif selection.lower() != 'n':
selection = None
count += 1
print("\nEnd of search results.\n")
task_search()
def edit_entry(table_row):
'''Allows user to edit specific field of task entry'''
field_dict = {'1': 'name', '2': 'time', '3': 'date', '4': 'notes'}
field = None
while not field:
field = input('''Select field to edit: 1 - task name, 2 - time, 3 - date, 4 - notes.
Enter 5 to go back to search results, 6 to go back to search menu\n>>>''')
if field == '5':
return
if field == '6':
return task_search()
print('Enter new {}.'.format(field_dict[field]))
new_info = None
while not new_info:
new_info = input('>>>')
if new_info.isspace():
print('Please enter non-empty string.')
new_info = None
continue
if field == '2':
try:
new_info = int(new_info)
except ValueError:
print("Please enter a valid number")
new_info = None
else:
new_info = str(new_info)
if field == '3':
try:
datetime.datetime.strptime(new_info, '%Y-%m-%d')
except ValueError:
print("Dates should be valid and in format YYYY-MM-DD")
new_info = None
if field == '1':
query = Task.update(name=new_info).where(Task.id == table_row.id)
elif field == '2':
query = Task.update(time=new_info).where(Task.id == table_row.id)
elif field == '3':
query = Task.update(date=new_info).where(Task.id == table_row.id)
else:
query = Task.update(notes=new_info).where(Task.id == table_row.id)
query.execute()
print("\nEntry edited!\n")
def delete_entry(table_row):
'''Allows user to delete task entry'''
print("Confirm delete? [yN]")
confirm = input('>>>')
if confirm.lower() == 'y':
row = Task.get(Task.id == table_row.id)
row.delete_instance()
print("\nEntry deleted!\n")
else:
print("Delete cancelled!\n")
if __name__ == "__main__":
print(welcome)
initialize()
work_log() |
word="ABCDBCA"
for char in word:
print(char)
dic={}
for char in word:
if(char not in dic):
dic[char]=1
else:
print("first recursive character",char)
break |
lst=[(i,"even") if i%2==0 else (i,"odd") for i in range(1,51)]
print(lst) |
a=(input('enter string'))
print(a)
for st in a:
if st=='l':
print(st)
|
lst=[100,200,39,43,22,12,65,44,73]
print("original list is",lst)
length=len(lst)
print("length of list is",length)
i=0
j=0
for i in range(length):
for j in range(i+1,length):
if(lst[i]>lst[j]):
temp=lst[i]
lst[i]=lst[j]
lst[j]=temp
print("sorted list is",lst)
print("second largest element is:",lst[length-2]) |
class Person:
def details(self,name,age,gender):
self.name=name
self.age=age
self.gender=gender
def printdet(self):
print(self.name)
print(self.age)
print(self.gender)
class Actor(Person):
def det(self,industry,role):
self.industry=industry
self.role=role
def prints(self):
print(self.industry)
print(self.role)
per=Person()
per.details("Abhishek Bachan",40,"male")
per.printdet()
act=Actor()
act.details("Abhishek Bachan",40,"male")
act.printdet()
act.det("Bollywood","Hero")
act.prints() |
#print 1 to 50(normal method)
# lst=[]
# for i in range(1,51):
# lst.append(i)
# print(lst)
#using list comprehension
lst=[i for i in range(1,51)]
print(lst)
|
lim=int(input("enter limit:"))
i=1
while(i<=lim):
sum=i+(i+1)
i+=1
print("sum is",sum) |
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def printdet(self):
print(self.name)
print(self.age)
print(self.gender)
class Student(Person):
def __init__(self, roll_no,mark,name,age,gender):
super().__init__(name,age,gender)
self.roll_no = roll_no
self.mark=mark
def print_stud(self):
print(self.roll_no)
print(self.mark)
stu = Student(30,97,"Neha",14,"Female")
stu.printdet()
stu.print_stud() |
lst=[12,3,1,6,55,76,55]
print(lst )
lst.sort()
element=int(input("enter the element to b searched:"))
#print(lst)
flag=0
low=0
upp=len(lst)-1
while(low<=upp):
mid=(low+upp)//2
if (element>lst[mid]):
low=mid+1
elif (element<lst[mid]):
upp=mid-1
elif (element==lst[mid]):
flag=1
break
if (flag>0):
print("element found in list")
else:
print("element not found in list")
|
# Importujemy bibliotekę, która pozwoli nam generować losowe liczby
import random
# Wczytujemy od użytkownika liczbę rzutów kością, które mamy zasymulować
ile_razy = int(input("Podaj ilość rzutów kostką: "))
# Będziemy zliczać, ile razy wypadła wartość 6
# Zliczanie zaczynamy od zera
szostki = 0
# W pętli od 0 do liczby rzutów minus 1
for i in range(ile_razy):
# Symulujemy rzut kością losując liczbę całkowitą z przedziału od 1 do 6
wynik = random.randint(1, 6)
print("Kości zostały rzucone...")
# Wypisujemy wylosowaną wartość na ekranie
print("Wynik to", wynik)
# Jeżeli wylosowaliśmy wartość 6
if wynik == 6:
# To zwiększamy licznik wylosowanych szóstek
szostki += 1
# Wypisujemy, ile razy wypadła szóstka
print("Szóstka wypadła", szostki, "razy")
|
class GeometricSequence:
"""
Implementation of geometric sequence
Formula of geometric sequence:
an = a1 * r^(n-1)
an - nth element of sequence
a1 - first element
r - common ratio
You can get value of element using [] operator
Example:
seq = GeometricSequence(2, 3)
seq[1] - first element
seq[3] - third element
"""
def __init__(self, first_element: float, common_ratio: float):
self.first_element = first_element
self.common_ratio = common_ratio
def __getitem__(self, n: int) -> float:
"""Returns nth element of sequence(first index is 1 not 0!)"""
# Wrong argument
if not isinstance(n, int):
raise TypeError("index must be integer")
elif n < 1:
raise IndexError("index must be greater or equeal to 1")
return self.first_element * (self.common_ratio ** (n - 1))
def sum(self, n: int) -> float:
"""Return sum of the first n elements"""
# Wrong argument
if not isinstance(n, int):
raise TypeError("n argument must be integer")
elif n <= 0:
return 0
if self.common_ratio == 1:
# Sum = a1 * n, for r == 1
return self.first_element * n
else:
# Sum = a1 * ((1 - r^n) / (1 - r)), for r != 1
return self.first_element * (
(1 - (self.common_ratio ** n)) / (1 - self.common_ratio))
if __name__ == "__main__":
seq1 = GeometricSequence(3, 1)
seq2 = GeometricSequence(1.5, -2)
# Print first sequence
for i in range(10):
print("{} {}".format(seq1[i+1], seq1.sum(i+1)))
# Print second sequence
for i in range(10):
print("{} {}".format(seq2[i+1], seq2.sum(i+1)))
|
class Edge:
"""Represents edges of graph
Atributes
---------
start : str
beginning of edge
end : str
ending of edge
cost : float
distence between start and end
"""
def __init__(self, start: str, end: str, cost: float):
self.start = start
self.end = end
self.cost = cost
class Graph:
"""This class is used to represent Graphs
Attributes
----------
vertices : set
graph vertices
edges : list
graph edges
is_directed:
if True graph is directed if False graph is undirected
In directed graph Edge("A", "B", 2) is diffrent from Edge("B", "A", 2)
Methods
-------
get_neighbors(vertex: int)
Returns vertex neighbors(with cost)
shortest_path(source: str, target: str)
Returns shortest path from source to target using Dijkstra's algorithm
"""
def __init__(self, vertices: set, edges: list, is_directed=False):
"""
Parameters
----------
vertices : set
Set of vertices, example: set(["A", "B", "C"])
edges : list
List of edges, example: [Edge("A", "B", 3), Edge("B", "C", 2)]
is_directed : bool, optional
specify if graph is directed or undirected(default is False)
"""
self.vertices = vertices
self.edges = edges
self.is_directed = is_directed
def get_neighbors(self, vertex: int) -> list:
"""Returns list of neightbors(with distance) to the vertex
Parameters
----------
vertex : int
vertex to check
Returns
-------
list
neighbors of vertex and distance between them
Example:
edges: [Edge("A", "B", 1), Edge("A", "C", 4)]
get_neighbor("A") -> [("B", 1), ("C", 4)]
"""
neighbors = []
for edge in self.edges:
if edge.start == vertex:
# Neighbor found
neighbors.append((edge.end, edge.cost))
# if Graph is undirected check edge.end
elif (not self.is_directed) and edge.end == vertex:
# Neighbor found
neighbors.append((edge.start, edge.cost))
return neighbors
def shortest_path(self, source: str, target: str) -> list:
"""
Returns shortest path from source to target using Dijkstra's algorithm
Parameters
----------
source : str
vertex that begins the path
target : str
vertex that ends the path
Returns
-------
list
path from source to target, example: ["A", "C", "B", "D"]
"""
unvisited_vertices = set()
# Distance from source to vertex
distance = dict()
# Previous vertex in path
prev = dict()
# Default values
for i in self.vertices:
unvisited_vertices.add(i)
# Default distance for all vertices is infinity
distance[i] = float("inf")
# At the beginning all vertices don't have previous vertex
prev[i] = None
# distance from source to source is 0
distance[source] = 0
while unvisited_vertices:
# Select vertex with the shortest distance
ver = min(unvisited_vertices, key=distance.get)
# Mark selected vertex as visited
unvisited_vertices.remove(ver)
for neighbor in self.get_neighbors(ver):
# Calculate distance between neighbor and current vertex
new_distance = distance[ver] + neighbor[1]
# Check if new path to neighbor is shorter than previous one
if new_distance < distance[neighbor[0]]:
# Update distance of neighbor
distance[neighbor[0]] = new_distance
# Update neighbor previous vertex
prev[neighbor[0]] = ver
# Build path from distance dictionary
path = [target]
tmp_vertex = target
# End building path when previous element is None
while prev[tmp_vertex] is not None:
# Add vertex at the beginning of the path(building in
# reversed order: from target to source)
path.insert(0, prev[tmp_vertex])
# change tmp_vertex to it's previous vertex
tmp_vertex = prev[tmp_vertex]
return path
if __name__ == "__main__":
vertices = set([char for char in "ABCDEF"])
print("""
3 8
A------B------C
| /| |
3| 2/ |7 |20
| / | |
F--E---D------/
3 3
""")
edges = [
Edge("A", "F", 3),
Edge("A", "B", 3),
Edge("B", "E", 2),
Edge("B", "D", 7),
Edge("B", "C", 8),
Edge("C", "D", 20),
Edge("D", "E", 3),
Edge("E", "F", 3),
]
g = Graph(vertices, edges)
print("Shortest path from C to D: ")
for i in g.shortest_path("C", "D"):
print(i, end=" ")
print("\nShortest path from A to D: ")
for i in g.shortest_path("A", "D"):
print(i, end=" ")
print("")
|
for i in range(int(input("How many hello world, do you need? Please use a number:\n"))):
print("Hello World!") |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 8 20:04:37 2021
@author: User
"""
def f02_13_removeDupl2D(l):
"""
Removes duplicates from a 2-D list
Parameters
----------
l : list
2-dimensional list (list of lists)
Returns
-------
list
2-D list with the duplicated elements removed, in the original order
Implementation constraints
--------------------------
- target number of non-white characters for the code: 66
(docstring and comments are ignored when counting)
- do not use "import"
"""
k = []
for i in l:
if i not in k:
k.append(i)
return k
# Testing
a = [[1, 2], [3, 4], [5, 6], [1, 2], [1, 3]]
b = [1, 2, 3]
print(f02_13_removeDupl2D(a))
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 8 20:04:37 2021
@author: User
"""
def f02_12_evenFromList(l):
"""
Returns even numbers from the list of integers.
Parameters
----------
l : list
List of integers (can be empty)
Returns
-------
list
List of the even integers from the input list in the
original order
Implementation constraints
--------------------------
- target number of non-white characters for the code: 62
(docstring and comments are ignored when counting)
- do not use "import", "for", "while"
"""
return list(filter(lambda x: x % 2 == 0, l))
# Test
print(f02_12_evenFromList([1, 2, 3, 4, 5, 6]))
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 10:26:34 2021
@author: User
"""
def f03_14_genInterlaced(m, n):
"""
Generates an interlaced array of int chunks.
Parameters
----------
m : int
Number of integers in the chunk.
n : int
Number of chunks
Returns
-------
list
List of sublist (chunks). Each chunk is a list of m integers,
with a difference of n. The number of chunks is n.
The first number in the chunks are consecutive integers starting
from 0.
Examples
--------
2,3 -> [(0, 3), (1, 4), (2, 5)]
2,4 -> [(0, 4), (1, 5), (2, 6), (3, 7)]
3,2 -> [(0, 2, 4), (1, 3, 5)]
4,2 -> [(0, 2, 4, 6), (1, 3, 5, 7)]
Implementation constraints
--------------------------
- target number of non-white characters for the code: 81
(docstring and comments are ignored when counting)
- do not use "import"
"""
return [tuple([i+j for i in range(0, m*n, n)]) for j in range(n)]
print(f03_14_genInterlaced(2, 4))
print(f03_14_genInterlaced(4, 2))
|
# -*- coding: utf-8 -*-
# D10 (14) posortuje słownik według klucza.
def d10(dic):
return dict(sorted(dic.items()))
D = {'Olo': 23, 'Bolo': 34, 'Ala': 20, 'Ela': 15}
print(d10(D))
|
# -*- coding: utf-8 -*-
# L36 Napisać funkcję, która wyróżni kolorami czerwonym i zielonym odpowiednio największa
# i najmniejszą liczbę w danym łańcuchu. (html: x ) Zasady podobne jak w L34 Przykład:
# in: '1 dzielone przez 8 daje 0.128 a 7 dzielone przez 2 daje 3.5'
# out: '1 dzielone przez 8 daje 0.128 a 7 dzielone przez 2 daje 3.5'
def l36(string):
string = string.split()
_ = list(filter(lambda x: x.replace(".", "", 1).isdigit(), string))
min_num = min(_)
max_num = max(_)
r = []
for e in string:
if e == min_num:
r.append(f"<font color=green>{e}</font>")
elif e == max_num:
r.append(f"<font color=red>{e}</font>")
else:
r.append(e)
return " ".join(r)
test = '1 dzielone przez 8 daje 0.128 a 7 dzielone przez 2 daje 3.5'
print(l36(test)) |
# -*- coding: utf-8 -*-
# L2 (2) pomnoży wszystkie elementy na danej liście.
def l2(lst, m):
return [i * m for i in lst]
print(l2([1, 2, 3, 4], 3))
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 5 14:49:24 2021
@author: Huber Mucha
"""
def f02_02_removeDuplicates(x):
"""
Removing duplicates from the input list
Parameters
----------
x : list
list of numbers or strings (can be empty)
Returns
-------
list
list with removed duplicates
Implementation constraints
--------------------------
- target number of non-white characters for the code: 58
(docstring and comments are ignored when counting)
- do not use import
"""
return list(dict.fromkeys(x)) |
# -*- coding: utf-8 -*-
# L13 (19) zwróci w postaci listy różnicę między dwiema podanymi listami.
def l13(lst1, lst2):
return [e1 - e2 for e1, e2 in zip(lst1, lst2)]
lista1 = [1, 2, 3, 4, 5]
lista2 = [-1, 2, 3, -4, 5]
print(l13(lista1, lista2))
|
import yfinance_ez as yf
import streamlit as st
import pandas as pd
st.title("""
Stock Price app
""")
st.write("""
This app shows the closing price and the volume of a given ticker symbol
""")
ticker_symbol = 'TSLA'
# This downloads some of the data from the ticker symbol
ticker_data = yf.Ticker(ticker_symbol)
# This gets info about the ticker
st.write("""
## Info about the selected stock
""")
ticker_info = st.write(ticker_data.info)
# Historical data from the ticker
# period can be: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo
# default is 1mo
ticker_df = ticker_data.get_history(period=yf.TimePeriods.Quarter)
st.write("""
## Here are the closing value of the stock
""")
st.line_chart(ticker_df.Close)
st.write("""
## Volume of the stock
""")
st.line_chart(ticker_df.Volume)
st.write("""
## Analyst recommendations
""")
recommendations = st.write(ticker_data.recommendations)
st.write("""
## Ticker Calendar
""")
calendar = st.write(ticker_data.calendar) |
#!/usr/bin/env python
# coding: utf-8
# In[4]:
n = int(input("Enter a number: "))
sum = 0
temp = n
while temp > 0:
Number = temp % 10
sum += Number ** 3
temp //= 10
print(sum)
# In[6]:
n=int(input("Enter a no:- "))
sum=0
for i in range(0,n+1):
sum=sum+i
print(sum)
# In[7]:
n=int(input("Enter The no of terms:- "))
result = list(map(lambda x: 2 ** x, range(n)))
print("The total terms are:",n)
for i in range(n):
print("{}".format(result[i]))
# In[9]:
decimal = int(input("Enter a decimal number \n"))
binary = 0
ctr = 0
temp = decimal
#calculating binary
while(temp > 0):
binary = ((temp%2)*(10**ctr)) + binary
temp = int(temp/2)
ctr += 1
print("Binary of {} is: {}".format(decimal,binary))
# In[ ]:
print("Enter the values of the list:-1 ")
x=[]
for i in range(0,6):
b=int(input(""))
x.append(b)
y=int(input("Enter 2nd no:- "))
for i in range(0,4):
if(x[i]%y==0):
print("Numbers Divisible by another number are:- {}".format(x[i]))
else:
print("Numbers are not divisible by another No's")
break
# In[ ]:
x = int(input('Enter First Number: '))
y = int(input('Enter Second Number: '))
if x > y:
smaller = y
else:
smaller = x
for i in range (1,smaller+1):
if((x % i == 0) and (y % i == 0)):
gcd = i
print("The GCD of {} and {} is:- {} ".format(x,y,gcd))
# In[ ]:
|
def calcBMI():
h = float(input("你的身高(cm): "))
w = float(input("你的體重(kg): "))
bmi = w / ((h/100)**2)
result = "正常" if 18 < bmi <= 23 else "過高" if bmi > 23 else "過低"
print("身高: %.1f cm 體重: %.1f kg BMI: %.2f (%s)" % (h, w, bmi,result))
def menu():
print("BMI計算系統")
print("----------")
print("1. 輸入身高體重")
print("2. 離開系統")
id = int(input("請選擇: "))
if id == 1:
print("您選擇的是1")
calcBMI()
input("按下任意鍵繼續")
menu()
elif id == 2:
print("您選擇的是2")
print("感謝您的使用")
else:
print("輸入錯誤")
menu()
menu() |
import random as r
print("比骰子")
flag = input("比大還是比小(比大請輸入 1, 比小請輸入 0)")
user = r.randint(1, 6) + r.randint(1, 6) + r.randint(1, 6)
pc = r.randint(1, 6) + r.randint(1, 6) + r.randint(1, 6)
if flag == 1:
winner = "玩家" if user > pc else "電腦"
else:
winner = "玩家" if user < pc else "電腦"
result = "比{0}, 玩家點數:{1} 電腦點數{2} 贏家:{3}"\
.format("大" if flag == 1 else "小", user, pc, winner)
print(result) |
import os
import contextlib
import sys
import re
import json
def read_json(path, prefix=None):
"""
Read a Json File a returns a dict
It removes comments specified by # before parsing the file.
If the json file has a field with a string "py:..."
it assumes that it is a python statement and evaluates it
Args:
path (str) In : path to the json file to load
Returns:
dict : dict with the json file in path contents
"""
with open(path, "r") as f:
filtered = re.sub(re.compile("#.*?\n"), "", f.read())
j_file = json.loads(filtered)
if prefix != None and "name" in j_file:
j_file["name"] = "%s%s" % (prefix, j_file["name"])
# Some times the json might have python code for simplify legibility
eval_json_python(j_file)
return j_file
def eval_json_python(j_file):
"""
Evaluates all the python statements in the json file str fields
that starts by 'py:'
Args :
j_file (dict) InOut : json file contents
"""
for key in j_file:
# TODO Add strings in list support
if type(j_file[key]) is dict:
eval_json_python(j_file[key])
elif (type(j_file[key]) is str) and (j_file[key][0:3] == "py:"):
j_file[key] = eval(j_file[key][3:])
class cd:
"""
Context manager for changing the current working directory
as seen in https://stackoverflow.com/questions/431684/how-do-i-cd-in-python
"""
def __init__(self, newPath):
self.newPath = os.path.expanduser(newPath)
self.newPath = os.path.expandvars(self.newPath)
def __enter__(self):
self.savedPath = os.getcwd()
os.chdir(self.newPath)
def __exit__(self, etype, value, traceback):
os.chdir(self.savedPath)
|
def return_10():
return 10
def add(first_number, second_number):
sum = first_number + second_number
return sum
def subtract(first_number, second_number):
sum = first_number - second_number
return sum
def multiply(first_number, second_number):
sum = first_number * second_number
return sum
def divide(first_number, second_number):
sum = first_number / second_number
return sum
def length_of_string(string):
string_length = len(string)
return string_length
def join_string(string_1, string_2):
joined_string = f'{string_1}{string_2}'
return joined_string
def add_string_as_number(string_1, string_2):
add_result = int(string_1) + int(string_2)
return add_result
def number_to_full_month_name(month_number):
months_of_year = {1: "January", 3: "March", 9: "September"}
return months_of_year[month_number]
def number_to_short_month_name(month_number):
months_of_year = {1: "Jan", 4: "Apr", 10: "Oct"}
return months_of_year[month_number] |
# -*- coding: utf-8 -*-
import time
import sqlite3
from sqlite3 import Error
database = "/home/playps/bot/ps_unity.db"
def create_connection(db_file):
""" create a database connection to a SQLite database """
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
with open("log.txt", 'a') as log:
log.write(str(e))
return None
def create_table(conn, create_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
with open("log.txt", 'a') as log:
log.write(str(e))
"""##################################################################################################################"""
"""___________________________________________________Games table____________________________________________________"""
def add_new_game(conn, game):
"""
Add a new game in games
:param conn:
:param game: "name-must, description-must, genre-must, date-must, photo-must, price-must, links-variable
:return: games id
"""
sql = ''' INSERT INTO games (name, description, genre, date, photo, price, links)
VALUES(?,?,?,?,?,?,?) '''
cur = conn.cursor()
cur.execute(sql, game)
return cur.lastrowid
def update_game(conn, game):
"""
Update information about a game in games
:param conn:
:param game: name-must, description-must, genre-must, date-must, photo-must, price-must, links-variable, id
:return: None
"""
sql = ''' UPDATE games
SET name = ? ,
description = ? ,
genre = ? ,
date = ? ,
photo = ? ,
price = ? ,
links = ?
WHERE id = ?'''
cur = conn.cursor()
cur.execute(sql, game)
def delete_game(conn, game_id):
"""
Delete a game by game id
:param conn: Connection to the SQLite database
:param game_id: id of the task
:return:
"""
sql = 'DELETE FROM games WHERE id=?'
cur = conn.cursor()
cur.execute(sql, (game_id,))
def delete_games(conn):
"""
remove table top
:return:
"""
sql = "DROP TABLE games"
cur = conn.cursor()
cur.execute(sql)
def select_in_games(conn, needle):
"""
search in games name
:param conn:
:param needle:
:return:
"""
sql = "SELECT * FROM games WHERE name LIKE '%'||?||'%'"
cur = conn.cursor()
res = cur.execute(sql, (needle,))
return res
def select_all_games(conn):
"""
Return all rows from games
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
cur.execute("SELECT * FROM games")
rows = cur.fetchall()
return rows
def select_game_name_by_id(conn, game_id):
"""
Return a game by it's id in table games
:param conn: the Connection object
:param game_id:
:return: game with id = game_id
"""
cur = conn.cursor()
cur.execute("SELECT name FROM games WHERE id=?", (game_id,))
return "ggame0" + cur.fetchone()[0]
def select_game_cost_by_id(conn, game_id):
"""
Return a game's cost by it's id in table games
:param conn: the Connection object
:param game_id:
:return: game with id = game_id
"""
cur = conn.cursor()
cur.execute("SELECT price FROM games WHERE id=?", (game_id,))
return cur.fetchone()[0]
def select_all_genres_from_games(conn):
"""
Select all available genres from Base
:param conn: the Connection object
:param:
:return: all available genres
"""
cur = conn.cursor()
cur.execute("SELECT genre FROM games")
rows = cur.fetchall()
res = []
for row in rows:
if ('genres' + row[0]) not in res:
res.append('genres' + row[0])
return res
def select_games_by_genre(conn, genre):
"""
Select all games with genre="genre"
:param conn: the Connection object
:param genre:
:return: all games witch is genre-type (in list - format sequence)
"""
cur = conn.cursor()
cur.execute("SELECT name FROM games WHERE genre=?", (genre,))
rows = cur.fetchall()
res = []
for row in rows:
res.append('ggames' + row[0])
return res
def select_game_by_name(conn, name):
"""
select game from games where name == name
:param conn:
:param name:
:return res: game with name == name or None
"""
cur = conn.cursor()
cur.execute("SELECT * FROM games WHERE name=?", (name,))
res = cur.fetchall()
return res
def select_games_by_date(conn, year):
"""
Select all games with date="year"
:param conn: the Connection object
:param year:
:return: all games that released at year
"""
cur = conn.cursor()
cur.execute("SELECT * FROM games WHERE date=?", (year,))
rows = cur.fetchall()
return rows
"""##################################################################################################################"""
"""____________________________________________________Top table_____________________________________________________"""
def add_to_top(conn, rating):
"""
Add position at top-20 table
:param conn:
:param rating:
:return: None
"""
sql = ''' INSERT INTO top (games_id)
VALUES(?) '''
cur = conn.cursor()
cur.execute(sql, (rating,))
def update_top(conn, new_pos):
"""
Update top-list in table top
:param conn:
:param new_pos: games_id, id
:return: None
"""
sql = ''' UPDATE top
SET games_id = ?
WHERE id = ?'''
cur = conn.cursor()
cur.execute(sql, new_pos)
def delete_position_top(conn, top_id):
"""
Delete a game by game id
:param conn: Connection to the SQLite database
:param top_id: id of the position
:return:
"""
sql = '''DELETE FROM top WHERE id=?'''
cur = conn.cursor()
cur.execute(sql, (top_id,))
def delete_top(conn):
"""
remove table top
:return:
"""
sql = "DROP TABLE top"
cur = conn.cursor()
cur.execute(sql)
def select_all_from_top(conn):
"""
Select all games id in top
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
cur.execute("SELECT games_id FROM top")
rows = cur.fetchall()
res = []
for i in rows:
res.append(i[0])
return res
def select_from_top_by_pos(conn, pos):
"""
Select game id from top
:param conn: the Connection object
:param pos:
:return: game with id = top_id or blank list
"""
cur = conn.cursor()
cur.execute("SELECT games_id FROM top WHERE id=?", (pos,))
try:
return cur.fetchone()[0][1]
except Exception:
return []
"""##################################################################################################################"""
"""___________________________________________________Cart table_____________________________________________________"""
def add_to_cart(conn, chat_id):
"""
Add new chat_id to cart
:param conn:
:param chat_id:
:return: None
"""
sql = ''' INSERT INTO cart (chat_id, games_id, time_add)
VALUES(?, ?, ?) '''
cur = conn.cursor()
cur.execute(sql, (chat_id, "", int(time.time() * 100)))
def update_cart(conn, data):
"""
Update cart
:param conn:
:param data: chat_id, games_id, time_add
:return: None
"""
sql = ''' UPDATE cart
SET games_id = ?,
time_add = ?
WHERE chat_id = ?'''
cur = conn.cursor()
cur.execute(sql, data)
def delete_cart(conn):
"""
remove table
:return:
"""
sql = "DROP TABLE cart"
cur = conn.cursor()
cur.execute(sql)
def select_all_from_cart(conn):
"""
select all positions in cart for each customer
:param conn:
:return:
"""
cur = conn.cursor()
cur.execute("SELECT * FROM cart")
rows = cur.fetchall()
return rows
def select_cart_for_chat_id(conn, chat_id):
"""
Select all games in cart for customer
:param conn: the Connection object
:param chat_id:
:return: game with id = top_id or blank list
"""
cur = conn.cursor()
cur.execute("SELECT * FROM cart WHERE chat_id=?", (chat_id,))
return cur.fetchone()
"""##################################################################################################################"""
"""__________________________________________________Message table___________________________________________________"""
def add_message(conn, data):
"""
Add new chat_id in Base
:param conn:
:param data:
:return: None
"""
sql = ''' INSERT INTO messages (chat_id, message_id_current)
VALUES(?, ?) '''
cur = conn.cursor()
cur.execute(sql, data)
def update_message(conn, data):
"""
Update the last message_id for chat_id
:param conn:
:param data:
:return: None
"""
sql = ''' UPDATE messages
SET message_id_current = ?
WHERE chat_id = ?'''
cur = conn.cursor()
cur.execute(sql, data)
def update_message_id_last_current(conn, data):
"""
Update the last message_id for chat_id
:param conn:
:param data:
:return: None
"""
sql = ''' UPDATE messages
SET message_id_current = ?,
message_id_last = ?
WHERE chat_id = ?'''
cur = conn.cursor()
cur.execute(sql, data)
def update_message_last_command(conn, chat_id, command):
"""
Update last command and time it was use for chat_id
:param conn:
:param chat_id:
:param command:
:return:
"""
time_msg = int(time.time() * 100)
sql = ''' UPDATE messages
SET command = ?,
time_msg = ?
WHERE chat_id = ?'''
cur = conn.cursor()
data = [command, time_msg, chat_id]
cur.execute(sql, tuple(data))
def update_callback_data(conn, data):
"""
Update last command in messages for double-click protection
:param conn:
:param data:
:return:
"""
sql = ''' UPDATE messages
SET callback = ?
WHERE chat_id = ?'''
cur = conn.cursor()
cur.execute(sql, tuple(data))
def update_callback_now_data(conn, data):
"""
add current command for button back
:param conn:
:param data:
:return:
"""
sql = ''' UPDATE messages
SET callback_now = ?
WHERE chat_id = ?'''
cur = conn.cursor()
cur.execute(sql, tuple(data))
def update_callback_1_data(conn, data):
"""
Implementation of button "back" - pre-pre-last command
:param conn:
:param data:
:return:
"""
sql = ''' UPDATE messages
SET callback_1 = ?
WHERE chat_id = ?'''
cur = conn.cursor()
cur.execute(sql, tuple(data))
def update_callback_2_data(conn, data):
"""
Implementation of button "back" - pre-pre-pre-last command
:param conn:
:param data:
:return:
"""
sql = ''' UPDATE messages
SET callback_2 = ?
WHERE chat_id = ?'''
cur = conn.cursor()
cur.execute(sql, tuple(data))
def update_messages_flag(conn, data):
"""
:param conn:
:param data:
:return:
"""
sql = ''' UPDATE messages
SET flag = ?
WHERE chat_id = ?'''
cur = conn.cursor()
cur.execute(sql, data)
def delete_all_messages(conn):
"""
Delete all messages from table
:param conn: Connection to the SQLite database
:return:
"""
sql = 'DELETE FROM messages'
cur = conn.cursor()
cur.execute(sql)
def delete_messages_table():
"""
remove table
:return:
"""
conn = create_connection(database)
sql = "DROP TABLE messages"
cur = conn.cursor()
cur.execute(sql)
def select_last_command(conn, chat_id):
"""
Select last command and time from messages for chat_id
:param conn:
:param chat_id:
:return: last command and time if exists or blank list
"""
cur = conn.cursor()
cur.execute("SELECT command, time_msg FROM messages Where chat_id=?", (chat_id,))
rows = cur.fetchall()
if len(rows) > 0:
return rows
else:
return -1
def select_message_id_current(conn, chat_id):
"""
Select current message_id for chat_id
:param conn:
:param chat_id:
:return:
"""
cur = conn.cursor()
cur.execute("SELECT message_id_current FROM messages Where chat_id=?", (chat_id,))
rows = cur.fetchall()
if len(rows) > 0:
return rows[0][0]
else:
return 0
def select_message_id_last(conn, chat_id):
"""
Select last message id for chat_id
:param conn:
:param chat_id:
:return:
"""
cur = conn.cursor()
cur.execute("SELECT message_id_last FROM messages Where chat_id=?", (chat_id,))
rows = cur.fetchall()
if len(rows) > 0:
return rows[0][0]
else:
return 0
def select_callback(conn, chat_id):
"""
:param conn:
:param chat_id:
:return:
"""
cur = conn.cursor()
cur.execute("SELECT callback FROM messages Where chat_id=?", (chat_id,))
rows = cur.fetchall()
if len(rows) > 0:
return rows[0][0]
else:
return -1
def select_callback_now(conn, chat_id):
"""
:param conn:
:param chat_id:
:return:
"""
cur = conn.cursor()
cur.execute("SELECT callback_now FROM messages Where chat_id=?", (chat_id,))
rows = cur.fetchall()
if len(rows) > 0:
return rows[0][0]
else:
return -1
def select_callback_1(conn, chat_id):
"""
:param conn:
:param chat_id:
:return:
"""
cur = conn.cursor()
cur.execute("SELECT callback_1 FROM messages Where chat_id=?", (chat_id,))
rows = cur.fetchall()
if len(rows) > 0:
return rows[0][0]
else:
return -1
def select_callback_2(conn, chat_id):
"""
:param conn:
:param chat_id:
:return:
"""
cur = conn.cursor()
cur.execute("SELECT callback_2 FROM messages Where chat_id=?", (chat_id,))
rows = cur.fetchall()
if len(rows) > 0:
return rows[0][0]
else:
return -1
def select_messages_flag(conn, chat_id):
"""
Flag uses for search and chat with developer. If flag == 1 - search, 2 - developer
:param conn:
:param chat_id:
:return:
"""
cur = conn.cursor()
cur.execute("SELECT flag FROM messages Where chat_id=?", (chat_id,))
rows = cur.fetchall()
if len(rows) > 0:
return rows[0][0]
else:
return 0
def select_all_messages(conn):
"""
Select all messages
:param conn:
:return:
"""
cur = conn.cursor()
cur.execute("SELECT * FROM messages")
return cur.fetchall()
"""##################################################################################################################"""
"""_____________________________________________________My ORM_______________________________________________________"""
def show_all_genres():
conn = create_connection(database)
with conn:
res = select_all_genres_from_games(conn)
return res
def show_games_by_genre(genre):
conn = create_connection(database)
with conn:
res = select_games_by_genre(conn, genre)
return res
def show_games_by_id(list_game):
conn = create_connection(database)
res = []
with conn:
for i in list_game:
if '0' <= str(i) <= '99':
res.append(select_game_name_by_id(conn, i))
return res
def show_search_games(list_game):
conn = create_connection(database)
res = []
with conn:
for i in list_game:
res.append("ggame0"+select_game_name_by_id(conn, int(i))[6:])
return res
def show_games_cost_by_id(list_game):
conn = create_connection(database)
res = 0
with conn:
for i in list_game:
if '0' <= i <= '99':
res += (select_game_cost_by_id(conn, i))
return res
def show_game_by_name(name):
conn = create_connection(database)
with conn:
return select_game_by_name(conn, name)
def search_in_games(needle):
conn = create_connection(database)
with conn:
request = select_in_games(conn, needle)
res = []
for i in request:
res.append(str(i[0]))
return res
def show_all_top():
conn = create_connection(database)
with conn:
res = select_all_from_top(conn)
return res
def delete_top_table():
conn = create_connection(database)
with conn:
delete_top(conn)
def delete_games_table():
conn = create_connection(database)
with conn:
delete_games(conn)
def add_new_chat_id(chat_id, message_id):
conn = create_connection(database)
with conn:
add_message(conn, (chat_id, message_id))
def update_message_id_in_chat_id(chat_id, message_id):
data = [str(message_id), str(chat_id)]
conn = create_connection(database)
with conn:
update_message(conn, tuple(data))
def update_message_id_last_and_current(chat_id, message_id_current):
conn = create_connection(database)
with conn:
message_id_last = select_message_id_current(conn, chat_id)
if message_id_current > int(select_message_id_current(conn, chat_id)):
update_message_id_last_current(conn, (message_id_current, message_id_last, chat_id))
def update_callback(chat_id, callback):
conn = create_connection(database)
with conn:
temp = select_callback_now(conn, chat_id)
temp1 = select_callback(conn, chat_id)
temp2 = select_callback_1(conn, chat_id)
if temp != -1:
update_callback_data(conn, (temp, chat_id))
if temp1 != -1:
update_callback_1_data(conn, (temp1, chat_id))
if temp2 != -1:
update_callback_2_data(conn, (temp2, chat_id))
update_callback_now_data(conn, (callback, chat_id))
def remove_callback(chat_id):
conn = create_connection(database)
with conn:
update_callback_now_data(conn, (None, chat_id))
temp2 = select_callback_2(conn, chat_id)
temp1 = select_callback_1(conn, chat_id)
if temp1 == -1:
update_callback_data(conn, ("/start", chat_id))
else:
update_callback_data(conn, (temp1, chat_id))
if temp2 == -1:
update_callback_1_data(conn, (None, chat_id))
else:
update_callback_1_data(conn, (temp2, chat_id))
update_callback_2_data(conn, (None, chat_id))
def show_all_messages():
conn = create_connection(database)
with conn:
res = select_all_messages(conn)
with open("log.txt", 'a') as log:
for i in res:
log.write(str(i))
def show_message_current(chat_id):
conn = create_connection(database)
with conn:
return select_message_id_current(conn, str(chat_id))
def show_message_last(chat_id):
conn = create_connection(database)
with conn:
return select_message_id_last(conn, chat_id)
def show_callback(chat_id):
conn = create_connection(database)
with conn:
res = select_callback(conn, str(chat_id))
if res is None or res == -1 or "Меню:" in res:
return "/start"
else:
return res
def show_last_command_by_chat_id(chat_id):
conn = create_connection(database)
with conn:
return select_last_command(conn, chat_id)
def show_messages_flag(chat_id):
conn = create_connection(database)
with conn:
return select_messages_flag(conn, chat_id)
def update_flag_in_messages(chat_id, flag):
conn = create_connection(database)
with conn:
update_messages_flag(conn, (flag, chat_id))
def delete_messages():
conn = create_connection(database)
with conn:
delete_all_messages(conn)
def double_click_protection(chat_id, command, message_id=None):
now = int(time.time() * 100)
conn = create_connection(database)
i = show_last_command_by_chat_id(chat_id)
with conn:
if len(command) > 6:
command = command[0:6]
if i == -1:
add_message(conn, (chat_id, message_id))
elif i[0][1] is None:
update_message_last_command(conn, chat_id, command)
return 1
elif now - i[0][1] < 100 and command == i[0][0]:
update_message_last_command(conn, chat_id, command)
return 0
update_message_last_command(conn, chat_id, command)
return 1
def new_customer(chat_id):
conn = create_connection(database)
with conn:
add_to_cart(conn, chat_id)
def update_customers_cart(chat_id, game_id):
"""
Обновляемя корзину покупателя. Попадаем сюда либо в случае добавления новых игр либо удаления игр из корзины.
:param chat_id: Чат айди между ботом и пользователем
:param game_id: Айди игры.
:return:
"""
conn = create_connection(database)
temp = select_cart_for_chat_id(conn, chat_id)
time_add = int(time.time() * 100)
if temp is None:
data = [game_id, time_add, chat_id]
time_ = time_add
else:
game_id = temp[1] + "," + game_id
data = [game_id, time_add, chat_id]
time_ = temp[2]
with conn:
if time_add - time_ > 172800:
update_cart(conn, tuple(["", time_add, chat_id]))
update_cart(conn, tuple(data))
def show_cart():
conn = create_connection(database)
with conn:
response = select_all_from_cart(conn)
with open("log.txt", 'a') as log:
for i in response:
log.write(str(i))
def show_cart_for_chat_id(chat_id):
conn = create_connection(database)
with conn:
response = select_cart_for_chat_id(conn, chat_id)
if response is None:
return [0, "", 0]
return response
def delete_game_from_cart(chat_id, text):
conn = create_connection(database)
with conn:
response = select_cart_for_chat_id(conn, chat_id)
if len(text) == 2 and 'A' <= text[1] <= 'Z':
text = text[0]
try:
game_pos_in_text = response[1].rindex(text)
if game_pos_in_text == 0:
temp = response[1][game_pos_in_text + 2:]
else:
temp = response[1][0:game_pos_in_text - 1] + response[1][game_pos_in_text + 2:]
j = 0
for c in temp:
if c == ",":
j += 1
else:
break
if len(temp) == j:
temp = ","
else:
temp = temp[j:]
data = (temp, int(time.time() * 100), response[0])
update_cart(conn, data)
except Exception:
pass
def clear_cart_for_chat_id(chat_id):
conn = create_connection(database)
time_add = int(time.time() * 100)
with conn:
update_cart(conn, tuple([",", time_add, chat_id]))
def delete_cart_table():
conn = create_connection(database)
with conn:
delete_cart(conn)
"""##################################################################################################################"""
def create_tables():
"""
creating (if needed) and filling db
:return: None
"""
sql_create_games_table = """ CREATE TABLE IF NOT EXISTS games (
id integer PRIMARY KEY,
name text NOT NULL,
description text,
genre text NOT NULL,
date text NOT NULL,
photo text NOT NULL,
price integer NOT NULL,
links text,
tempgames1 text,
tempgames2 text,
tempgames3 text
); """
sql_create_message_table = """ CREATE TABLE IF NOT EXISTS messages (
chat_id text PRIMARY KEY NOT NULL,
message_id_current text NOT NULL,
message_id_last text,
command text,
time_msg integer,
callback text,
callback_now text,
callback_1 text,
callback_2 text,
flag integer,
tempmsg1 text,
tempmsg2 text,
tempmsg3 text
); """
sql_create_top_table = """CREATE TABLE IF NOT EXISTS top (
id integer PRIMARY KEY,
games_id integer,
temptop1 text,
FOREIGN KEY (games_id) REFERENCES games (id)
); """
sql_create_cart_table = """ CREATE TABLE IF NOT EXISTS cart (
chat_id integer PRIMARY KEY,
games_id text,
time_add integer,
tempcart1 text,
tempcart2 text,
tempcart3 text
); """
# create a database tables
conn = create_connection(database)
if conn is not None:
create_table(conn, sql_create_games_table)
create_table(conn, sql_create_top_table)
create_table(conn, sql_create_cart_table)
create_table(conn, sql_create_message_table)
else:
with open("log.txt", 'a') as log:
log.write("Error! cannot create the database connection.")
def fill_games():
conn = create_connection(database)
with conn:
try:
delete_games(conn)
except sqlite3.OperationalError:
pass
create_tables()
games = (
('Anthem', 'Anthem — это новая постапокалиптическая фантастическая игра от BioWare. В мире, заброшенном ещё при создании, человечество борется за выживание в диких условиях, таящих в себе множество опасностей.', 'Экшен', '2019', 'AgADAgADVaoxG5NfcEj2G4q8THxLVqqkOQ8ABE8_AAGRGJMChcCVBQABAg', 2500, ''),
("Assassin's Creed Odyssey", 'Пройдите путь от изгоя до живой легенды: отправьтесь в далекое странствие, чтобы раскрыть тайны своего прошлого и изменить будущее Древней Греции.', 'Приключения', '2018', 'AgADAgADQ6oxG4idMUpFQLyx7NDudNpGOQ8ABF7OEe53rIeQftYBAAEC', 2500, ''),
("Assassin's Creed Origins", 'Раскройте тайны Древнего Египта и узнайте, как было создано Братство ассасинов.', 'Приключения', '2017', 'AgADAgADRKoxG4idMUobP-6e5a_p5J9H8w4ABE5dLaAU9TeNQgIGAAEC', 2500, ''),
('Battlefield 1', 'Cо всеми DLC. Battlefield 1 — шутер от первого лица. Действие игры разворачивается в ходе Первой мировой войны. В Battlefield 1 представлен широкий арсенал из различного оружия того времени.', 'Шутер', '2016', 'AgADAgADwakxG9UYKEqwic6vMLTqa3bztw4ABN4fECDXjaQ07QgGAAEC', 2000, ''),
('Battlefield 4', 'Cо всеми DLC. Шутер от первого лица. Действие игры разворачивается в недалеком будущем.', 'Шутер', '2012', 'AgADAgADQqoxG8L6aUiBIh7B4kNHjqZcXw8ABFbQCJkUCo4S-cECAAEC', 1800, ''),
('Battlefield 5', 'Участвуйте в крупнейшем военном конфликте. Играйте по сети в «Большие операции» и «Совместные бои», а также в «Военные истории» для одного игрока. Сражайтесь по всему земному шару.', 'Шутер', '2018', 'AgADAgADRaoxG4idMUrYDOQHGnEk3OFROQ8ABJBc6rlRFlKYsNcBAAEC', 2500, ''),
('Bloodborne GOTY', 'Действие Bloodborne происходит в древнем городе Яхарнарме (Yharnarm). Годами люди прибывали в Яхарнарм в поисках помощи, но сейчас город стал проклятым местом, пораженным ужасной эпидемией.', 'Боевик', '2015', 'AgADAgADR6oxG4idMUp7D7AUR7qLmOU8OQ8ABPHBMLdryiU_QdgBAAEC', 1300, ''),
('Call of Duty: Black Ops 3', 'Действие Call of Duty: Black Ops 3 разворачивается в далеком будущем, в мире разрываемом войной. Стороны делят территории и ресурсы, а победа зависит о того, на чьей стороне технологическое превосходство.', 'Шутер', '2015', 'AgADAgADVaoxG4idMUqUAAEURfPvxPPeYDkPAAT3r2ofOtRZWeXXAQABAg', 2000, ''),
('Call of Duty: Black Ops 4', 'Продолжение успешной серии Black Ops от команды Treyarch.', 'Шутер', '2018', 'AgADAgADOaoxG4idMUofElZOl-agrFWUOQ8ABPx1TEzYwQskquYDAAEC', 2500, ''),
('Call of Duty: WWII', 'Call of Duty: WWII — шутер от первого лица, разработанный студией Sledgehammer Games. Действие игры разворачивается в ходе Второй мировой войны, а игроки берут на себя роль отважного отряда солдат.', 'Шутер', '2017', 'AgADAgADVqoxG4idMUrP6-RKXPT89buXOQ8ABPZ3CfqGtA1Ngt8DAAEC', 2500, ''),
('Dark Souls 3 Deluxe', 'Deluxe-издание DARK SOULS™ III включает полную версию игры и сезонный пропуск, дающий доступ к дополнительным картам, боссам, противникам, новому оружию и броне.', 'Боевик', '2016', 'AgADAgADXqoxG4idMUri-e3_bHDhSvNcOQ8ABC4rzgJzpAJkcdcBAAEC', 2500, ''),
('Darksiders 3', 'В Darksiders III вы вернетесь на мертвую Землю в роли ЯРОСТИ, которая намерена найти и уничтожить Семь смертных грехов.', 'РПГ', '2018', 'AgADAgADX6oxG4idMUpD7-j3pvq-pE5LXw8ABHrcxFpQBPVphw4BAAEC', 2400, ''),
('Dead Cells', 'В Dead Cells вы — подопытный алхимического эксперимента на проклятом острове, где все меняется и растет. Вы бессмертны, но беспомощны: чтобы передвигаться и сражаться, занимаете чужие тела...', 'Боевик', '2018', 'AgADAgADWqoxG4idMUo9tAAB2lu_QyNDkzkPAAT2QorjZaZ4vALgAwABAg', 900, ''),
('Detroit: Become Human', 'Детройт, 2038 год. Похожие на людей андроиды стали основной рабочей силой на планете. Вам предстоит управлять тремя андроидами, чтобы помочь им понять, кто же они на самом деле.', 'Боевик', '2018', 'AgADAgADWaoxG4idMUrH32TkZwyuIIRJXw8ABLiyYkntGIi8mAsBAAEC', 2500, ''),
('Devil May Cry 5', 'компьютерная игра в жанре слэшер, разработанная и изданная японской компанией Capcom. Пятая игра в одноимённой серии и пятая же в хронологии.', 'Экшен', '2018', 'AgADAgADVqoxG5NfcEisaxL1ix5PqJQGUg8ABFa9QgxMSjvJLC8BAAEC', 2200, ''),
('Diablo 3', 'Diablo 3 - продолжение легендарной ролевой игры, разработанное компанией Blizzard Entertainment.', 'РПГ', '2014', 'AgADAgADW6oxG4idMUp1DO6UDhB36K2cOQ8ABDO3AaJwxvD5ZdwDAAEC', 1300, ''),
('Dishonored 2', 'В игре Dishonored 2 вы снова окажетесь в роли ассасина со сверхъестественными способностями.', 'Боевик', '2016', 'AgADAgADXKoxG4idMUqhLyAWvtzQJ1BrXw8ABE3rlfRjnMwLKAsBAAEC', 1700, ''),
('Divinity: Original Sin II', 'Соберите отряд и отправляйтесь исследовать удивительный мир, в котором единственным ограничением на пути к божественности и спасению всего сущего станет ваше воображение.', 'РПГ', '2018', 'AgADAgADWKoxG4idMUpoJmmIoNQ2ETBiOQ8ABDwZNsZW2QXTYNcBAAEC', 2300, ''),
('DOOM', 'Злобные демоны, мощные пушки, стремительное передвижение — вот основа нового DOOM. Во время сражений вам не придётся прятаться или ждать пока восстановится здоровье.', 'Шутер', '2016', 'AgADAgADXaoxG4idMUqByaVainWBZWNvXw8ABHLgGVqg0d00BRABAAEC', 1300, ''),
('F1 2018', 'Укрепляйте свою репутацию как на трассе, так и за её пределами: к ключевым событиям вашей карьеры добавляются интервью в СМИ. Покажете ли вы себя сдержанным спортсменом или любителем громких заявлений?', 'Гонки', '2018', 'AgADAgADYKoxG4idMUqRwJlxheE6wORTXw8ABEXOFoVzgk9uMQ4BAAEC', 2400, ''),
('Far Cry 5', 'Добро пожаловать в Монтану - округ Хоуп - земли свободных и смелых, захваченные фанатиками Врат Эдема. Дайте отпор Иосифу Сиду и его сторонникам. Разожгите огонь сопротивления.', 'Боевик', '2018', 'AgADAgADYaoxG4idMUqsHhPUQMeAzMujOQ8ABO0amHKzwtHftuUDAAEC', 2500, ''),
('Far Cry New Dawn', 'Far Cry New Dawn — компьютерная игра в жанре шутера от первого лица со структурой открытого мира', 'Боевик', '2019', 'AgADAgADU6oxG5NfcEg0ohmqN3KH6mRSOQ8ABGZNe7smPfGHFY0DAAEC', 1900, ''),
('FIFA 18', 'В FIFA 18, как и в других играх этой серии, игроки смогут принять участие в футбольном чемпионате, выбрав одну из многих команд или собрав собственную.', 'Спорт', '2017', 'AgADAgADY6oxG4idMUoal0COdm41D3NGOQ8ABMw7WPKbN4rJ9dUBAAEC', 1400, ''),
('FIFA 19', 'Главная футбольная игра Мира', 'Спорт', '2018', 'AgADAgADZKoxG4idMUomdWTpUZ74cm5aOQ8ABEBY0MjdPpm-5tcBAAEC', 2500, ''),
('For Honor', 'Побеждайте на полях сражений For Honor.', 'Боевик', '2017', 'AgADAgADYqoxG4idMUof0Yf6SHK_IpxOOQ8ABDcC9-znBtcX_dIBAAEC', 1300, ''),
('God of War', 'God of War — слэшер от третьего лица. Игра является перезапуском знаменитой серии God of War, рассказывающей о жестоком спартанском войне Кратосе, который перебил всех богов Олимпа и ввергнул мир в хаос.', 'Боевик', '2018', 'AgADAgADZaoxG4idMUqGhYZLsoHY-5aiOQ8ABMsUpYQ7wzuir-EDAAEC', 2500, ''),
('Grand Theft Auto V (GTA 5)', 'Grand Theft Auto 5 — продолжение знаменитой серии GTA. В пятой части игроки вернуться в штат Сан-Андреас и знакомый всем город Лос-Сантос.', 'Боевик', '2014', 'AgADAgADZqoxG4idMUo_8PZkzc0lgMZQXw8ABJnNqxeNM4wCUQsBAAEC', 1300, ''),
('Hitman 2. Издание Игра года', 'Путешествуйте по миру и выслеживайте свои цели в экзотических местах. От залитых солнцем улиц до темных и опасных тропических лесов, нигде нельзя спрятаться от Агента 47.', 'Боевик', '2018', 'AgADAgADZ6oxG4idMUor_TmV9v21FaH_9A4ABN0rFSsZgB12FhsEAAEC', 2700, ''),
('Horizon: Zero Dawn', 'Действие игры разворачивается в мире, в котором люди и роботы, эволюционировавшие в различных диких животных, живут в хрупкой гармонии.', 'РПГ', '2017', 'AgADAgADaKoxG4idMUoIK4LsPOl4k5WYOQ8ABHAZ8Q2keYqGhOEDAAEC', 1400, ''),
('Injustice 2: Legendary Edition', 'Развивайте любимых героев вселенной DC в INJUSTICE 2 — лучшем файтинге 2017 года по версии IGN.', 'Файтинг', '2018', 'AgADAgADaqoxG4idMUohhatH-gFuDn6dOQ8ABLNUGrVBDHCmCuUDAAEC', 2200, ''),
('Kingdom Come: Deliverance', 'Вы – сын кузнеца, втянутый в водоворот гражданской войны. Отомстите за смерть своих близких и помогите отразить нападение захватчиков.', 'РПГ', '2018', 'AgADAgADa6oxG4idMUoNTTbNMYrpIFBOOQ8ABOcUUvt11gjk7dIBAAEC', 2200, ''),
("Marvel's Spider-Man Расширенное издание", "В Marvel's Spider-Man вы будете играть за одного из самых культовых супергероев мира, мастера паутины, известного своими акробатическими способностями и талантом к импровизации.", 'Боевик', '2019', 'AgADAgADeKoxG4idMUqa7yVMYtGlJ4GcOQ8ABNExtPPd5AxHWeEDAAEC', 2500, ''),
('Metro Exodus', 'Устрой декоммунизацию всему что стоит. Поглядывай по сторонам, читая надписи на стенах. Это Россия, детка.', 'Боевик', '2019', 'AgADAgADQ6oxG8L6aUjnQcoU04CLXlJOUw8ABASOD-vWx6voLzEBAAEC', 2500, ''),
('Monster Hunter: World', 'Monster Hunter: World — это экшен с ролевыми элементами от студии Capcom. Очередная инсталляция в серии игр, в которых игроки берут на себя роли охотников за монстрами.', 'Боевик', '2018', 'AgADAgADbqoxG4idMUqxylAOGh7LisA_OQ8ABLIyFHOIgU-eRNQBAAEC', 1800, ''),
('Mortal Kombat XL', 'Сочетая в себе кинематографическую подачу беспрецедентного качества и обновленную игровую механику, Mortal Kombat X являет миру самую брутальную из всех Смертельных битв.', 'Файтинг', '2016', 'AgADAgADbaoxG4idMUr3bdrgUhRDipN7Xw8ABFVVVDxyosu4XQ8BAAEC', 2200, ''),
('NBA 2K18', 'NBA 2K18 - это баскетбольный спортивный симулятор, основанный на Национальной Баскетбольной Ассоциации (НБА).', 'Спорт', '2017', 'AgADAgADyakxG9UYKEr9s6gxzdhF4KVUOQ8ABGVCqbj17C_14NkBAAEC', 1500, ''),
('NBA 2K19', 'Вот уже 20 лет серия NBA 2K задает направление развития в спортивных играх — от лучших в своем классе графики и игрового процесса до захватывающих режимов игры и реалистичного открытого мира Neighborhood.', 'Спорт', '2018', 'AgADAgADb6oxG4idMUpgXYGH-bAULEbztw4ABEgCKsZzffgxSQUGAAEC', 2500, ''),
('NHL 19', 'В NHL 19 вы сможете играть на уличных катках, пройти путь от игр на пруду до профессиональных матчей в новых и уже знакомых режимах.', 'Спорт', '2018', 'AgADAgADcKoxG4idMUoR9CWDciEmRXZbXw8ABAS3b6KWTOVg-Q4BAAEC', 2500, ''),
('Overwatch', 'Сетевой шутер от первого лица, разработанный студией Blizzard Entertainment.', 'Шутер', '2016', 'AgADAgADcaoxG4idMUoBCCo30mnIuFRL8w4ABJLDGStxXCpo4QUGAAEC', 2050, ''),
("Playerunknown's Battlegrounds (PUBG)", 'Обыграй, ограбь и обхитри противников, чтобы остаться единственным победителем в этой захватывающей игре, полной неожиданностей и волнующих моментов. ', 'Шутер', '2018', 'AgADAgADcqoxG4idMUqTdkZYsu6uY4x6Xw8ABH7efhAp4OggTw0BAAEC', 1150, ''),
('Red Dead Redemption 2', 'Игра Red Dead Redemption 2 от создателей GTA V и Red Dead Redemption – это грандиозное повествование о жизни в Америке на заре современной эпохи.', 'Приключения', '2018', 'AgADAgADc6oxG4idMUobhbFh9dYNYuFDXw8ABH9e6hy8p7AV1gsBAAEC', 2500, ''),
('Rocket League', 'На ваш выбор - различные автомобили с огромными ракетными ускорителями, взлетающие в воздух, используйте их чтобы забивать голы, демонстрировать невероятные сейвы и даже крушить соперников на невероятных скоростях!', 'Спорт', '2015', 'AgADAgADdKoxG4idMUq4Fd9c0K3TqYX_9A4ABEO0O3d6MztExhEEAAEC', 900, ''),
('Shadow of the Colossus', 'Переиздание оригинальной Shadow of the Colossus.', 'Приключения', '2018', 'AgADAgADyqkxG9UYKEpQmV_Bs2bR8KFJXw8ABK-GoJEmq-1veQwBAAEC', 1400, ''),
('Shadow of the Tomb Raider', 'Проникнитесь судьбоносной историей становления Лары Крофт, легендарной расхитительницы гробниц. Спасая мир от гибели, она пройдет немало испытаний и станет настоящей расхитительницей гробниц.', 'Боевик', '2018', 'AgADAgADd6oxG4idMUp68ru6u76iR-9OXw8ABMgbyMcZTWmV9A0BAAEC', 2400, ''),
('SoulCalibur 6', 'Новая игра в серии SOULCALIBUR! Испытайте новейшую игровую механику с захватывающей графикой, которую вы когда-либо видели!', 'Файтинг', '2018', 'AgADAgADdaoxG4idMUrKNs0R7LgMP0s-8w4ABEJYW1IcBj1qug8GAAEC', 2500, ''),
('Star Wars: Battlefront 2', 'Star Wars: Battlefront II — шутер от первого лица. Игра основана на вселенной Звездных Войн, в которой силы повстанцев и Империи ведут войны на различных планетах.', 'Боевик', '2018', 'AgADAgADRqoxG4idMUqg6EcMieU7viw68w4ABPOp8rC42_AC1AABBgABAg', 1000, ''),
('Street Fighter 5 - Arcade Edition', 'Участвуйте в напряженных боях один на один в Street Fighter V — Arcade Edition! Выбирайте из 28 персонажей, каждый из которых обладает собственной историей и уникальными тренировочными испытаниями.', 'Файтинг', '2016', 'AgADAgADdqoxG4idMUoDpR4of8lXiatPXw8ABIYJ4FQyFFKWohABAAEC', 800, ''),
('Titanfall 2', 'Фантастический шутер от первого лица с элементами симулятора меха, разработанный Respawn Entertainment.', 'Шутер', '2016', 'AgADAgADRKoxG8L6aUjvsehme8nud1idOQ8ABAx3IwABEL0uL--iBQABAg', 1400, ''),
('The Crew 2', 'Ворвитесь в мир моторного спорта США. Лидируйте в состязаниях на суше, на море и в небе. Наслаждайтесь азартом американских моторных состязаний в захватывающем открытом мире The Crew 2.', 'Гонки', '2018', 'AgADAgADV6oxG4idMUryGiAu0O3W4Cbitw4ABLdpnqR1PzIeOAoGAAEC', 2500, ''),
('The Last Of Us', 'Сюжет берет начало в Америке, спустя 20 лет после биологической катастрофы, превратившей большую часть людей в кровожадных мутантов. Герои отправляются в опасное приключение, чтобы добыть лекарство от страшного вируса.', 'Экшен', '2014', 'AgADAgADeaoxG4idMUq4UC_ZyT_oHJ8-OQ8ABA1_Y1wnfs39MNMBAAEC', 900, ''),
('The Witcher 3: Wild Hunt', 'Wild Hunt рассказывает историю Геральта из Ривии, ведьмака и охотника на монстров, отправившегося в опасное приключение, чтобы остановить кошмарные легионы, известные как Дикая Охота (Wild Hunt).', 'РПГ', '2015', 'AgADAgADfaoxG4idMUp7dAKpSTPfqlphXw8ABC4ObUaTBPremQUBAAEC', 1600, ''),
("Tom Clancy's: Rainbow Six Siege\nAdvanced Edition", 'Rainbow Six Осада выводит жаркие перестрелки и тактическое планирование на новый уровень. Cоберите свою команду из лучших оперативников и вступите в бескомпромиссный бой.', 'Боевик', '2018', 'AgADAgADy6kxG9UYKEpHSCqX3mgJhFVgXw8ABCaQy_dMLT2nwwwBAAEC', 1500, ''),
('Tom Clancy\'s The Division 2', 'События происходят через 6 месяцев после своего предшественника в Вашингтоне, округ Колумбия, в котором разразилась гражданская война между выжившими и злодейскими группами мародеров', 'Боевик', '2019', 'AgADAgADVKoxG5NfcEhn8reoEj4ujvVaOQ8ABOUzkEpvqANCLowDAAEC', 2500, ''),
('UFC 3', 'Все действия бойца с высочайшей точностью воссоздают реальность ощущений. Игрокам придётся поднимать шум вокруг боёв, привлекать фанатов, платить за тренировки и соперничать с другими бойцами.', 'Файтинг', '2018', 'AgADAgADeqoxG4idMUpG-T-KULPO9z54Xw8ABOq1yccyng99hQgBAAEC', 2200, ''),
('Uncharted 4: A Thief\'s End', 'Сюжет Uncharted 4: A Thief\'s End рассказывает об искателе приключений, Нейтане Дрейке, который должен отыскать легендарное пиратское сокровище.', 'Приключения', '2016', 'AgADAgADe6oxG4idMUrVtzaeEpvZCIbmtw4ABKzjp8A0_zDQiQYGAAEC', 800, ''),
('Until Dawn', 'Восемь друзей вернулись в уединенную горную хижину, где ровно год назад исчезли двое их товарищей. А все начиналось так хорошо...', 'Экшен', '2015', 'AgADAgADfKoxG4idMUrxgNab3l9BNUHltw4ABKrPwA9oRGrYzAMGAAEC', 800, ''),
('WRC 7 FIA World Rally Championship', 'Пройдите 13 ралли и 52 спецучастка Чемпионата мира по ралли FIA. Выступите в роли гонщиков чемпионата за рулем их машин: Hyundai, Toyota, Citroën и Ford. Все автомобили повторяют свои аналоги. ', 'Гонки', '2017', 'AgADAgADfqoxG4idMUqRuIpurQNz55NUXw8ABCwi5KS0yxG6UQ4BAAEC', 2400, ''),
('WWE 2K19', 'Крупнейшая серия игр о профессиональном рестлинге возвращается вместе с игрой WWE 2K19, в которой вас ждет не только борец-суперзвезда с обложки AJ Styles, но и множество героев и легенд WWE и NXT!', 'Файтинг', '2018', 'AgADAgADf6oxG4idMUpysm2lUa9Yv_Tntw4ABCXxY0i0XLXmjQUGAAEC', 2600, '')
)
# ('Name', 'Description', 'genre', 'date', 'photos/', 1000, ''),
i = 1
for game in games:
add_new_game(conn, game)
def fill_top():
conn = create_connection(database)
with conn:
try:
delete_top(conn)
except sqlite3.OperationalError:
pass
create_tables()
tops = (1,
2,
3,
6,
9,
14,
15,
22,
24,
26,
27,
28,
32,
33,
34,
37,
38,
39,
41,
58)
for i in tops:
add_to_top(conn, i)
def start():
conn = create_connection(database)
with conn:
create_tables(conn) |
class Solution:
# @param A : list of integers
# @param B : list of integers
# @return an integer
def coverPoints(self, A, B):
step = 0
for i in range(len(B)-1):
step = step+max(abs(A[i+1]-A[i]), abs(B[i+1]-B[i]))
return step
# (x,y) to
# (x-1, y-1),
# (x-1, y) ,
# (x-1, y+1),
# (x , y-1),
# (x , y+1),
# (x+1, y-1),
# (x+1, y) ,
# (x+1, y+1)
# You are given a sequence of points and the order in which you need to cover the points.. Give the minimum number of steps in which you can achieve it. You start from the first point.
# NOTE: This question is intentionally left slightly vague. Clarify the question by trying out a few cases in the “See Expected Output” section.
# Input Format
# Given two integer arrays A and B, where A[i] is x coordinate and B[i] is y coordinate of ith point respectively.
# Output Format
# Return an Integer, i.e minimum number of steps.
# Example Input
# Input 1:
# A = [0, 1, 1]
# B = [0, 1, 2]
# Example Output
# Output 1:
# 2
# Example Explanation
# Explanation 1:
# Given three points are: (0, 0), (1, 1) and (1, 2).
# It takes 1 step to move from (0, 0) to (1, 1).
# It takes one more step to move from (1, 1) to (1, 2).
|
jaffa_cakes = 1.00
toilet_roll = 0.50
askProduct = input("What product would you like to buy? ")
if askProduct == 'jaffa cakes':
print("You will get ", jaffa_cakes / 0.2, "clubcard points for your", askProduct)
elif askProduct == 'toilet roll':
print("You will get", toilet_roll / 0.2, "clubcard points for your", askProduct)
elif (askProduct != 'toilet roll' or 'jaffa cakes'):
print("That is not a valid product.")
|
import random
import sys
import time
if __name__ == "__main__":
if len(sys.argv) < 3:
# no argumemnts, print usage message
print("Usage:")
print(" $ python3 similarity.py <data_file> <output_file> [user_thresh (default = 5)]")
sys.exit()
#Save arguments
data_file = str(sys.argv[1])
output_file = str(sys.argv[2])
if len(sys.argv) == 4:
user_thresh = int(sys.argv[3])
else: user_thresh = 5
def create_data_dict(data_file):
""" This function takes a raw data text file as
input and returns a dictionary data structure,
along with print parameters number of lines read
and number of unique user ids"""
data_file = open(data_file, "r")
data = {}
userSet = set()
lineNum = 0
#Reading in data into a dictionary
for line in data_file:
curLine = line.split() #Splitting line into strings
#Initialize a new entry in the dictionary if
#movie is new and we haven't reached the end of
#the file, otherwise append a value entry (which
#is also a dictionary) for the existing movie
if curLine != [] and int(curLine[1]) not in data:
data[int(curLine[1])] = {curLine[0]: int(curLine[2])}
userSet.add(curLine[0])
lineNum += 1
elif curLine != []:
data[int(curLine[1])][curLine[0]] = int(curLine[2])
userSet.add(curLine[0])
lineNum += 1
return data, lineNum, len(list(data.keys())), len(userSet)
def similarity_computation(movieDicta, movieDictb):
""" This function takes two movie ids and returns
the cosine similarity if it exists and there are
at least a specificed (user_thresh) number of users
of both movies, which here is at least five."""
#Computes the average rating for both movies
avgRatingMovie_a = sum(movieDicta.values())/len(movieDicta.values())
avgRatingMovie_b = sum(movieDictb.values())/len(movieDictb.values())
commonUsers=0
numSum = 0
denomSumMovie_a = 0
denomSumMovie_b = 0
#Computing the numerator and denominator of the cosine similarity formula
for key in movieDictb.keys() & movieDicta.keys():
commonUsers += 1
numSum += (movieDicta[key] - avgRatingMovie_a)*(movieDictb[key] - avgRatingMovie_b)
denomSumMovie_a += (movieDicta[key] - avgRatingMovie_a)**2
denomSumMovie_b += (movieDictb[key] - avgRatingMovie_b)**2
denom = (denomSumMovie_a*denomSumMovie_b)**0.5
"""If the similarity ratio exists and there are
enough common viewers, returns the desired value"""
if denom == 0 or commonUsers < user_thresh:
return 'Not Similar', commonUsers
else:
cos_sim = numSum/denom
return cos_sim, commonUsers
def write_similarities(movieDict, output_file):
""" This function takes every pair of movies, stores
the calculated similarity ratios from the above function,
finds the maximum and writes the output to output_file"""
f = open(output_file, "w")
movieList = list(movieDict.keys())
movieList.sort() #Produces sorted list of movie ids
"""Calls the computation function for every pair and writes
the desired parameters to the output file"""
for movie_a in movieList:
maxSim = -2
for movie_b in movieList:
similarity, userNum = similarity_computation(movieDict[movie_a], movieDict[movie_b])
#Updating the maximum ratio, corresponding movie_id, and number of common users
if movie_a != movie_b and similarity != 'Not Similar' and similarity > maxSim:
maxSim = similarity
mostSimMovie = movie_b
mostUserNum = userNum
#Writing output to file in the desired format
f.write("{} ".format(movie_a))
if maxSim == -2:
f.write("\n")
else:
f.write("({},{:.2f},{})\n".format(mostSimMovie,maxSim,mostUserNum))
f.close()
#begin timer
startTime = time.time()
#function calls
movieLens, numLines, numMovies, numUsers = create_data_dict(data_file)
write_similarities(movieLens, output_file)
#end timer
endTime = time.time()
elapsedTime = endTime - startTime
print("Input MovieLens file: {}".format(data_file))
print("Output file for similarity data: {}".format(output_file))
print("Minimum number of common users: {}".format(user_thresh))
print("Read {} lines with total of {} movies and {} users".format(numLines, numMovies, numUsers))
print("Computed similarities in {} seconds".format(elapsedTime))
|
"""
Problem:
Find the sum of the only ordered set of six cyclic 4-digit numbers for
which each polygonal type: triangle, square, pentagonal, hexagonal,
heptagonal, and octagonal, is represented by a different number in the set.
Nota bene:
* Polygonal numbers are also called figurate numbers
Performance time: ~0.037s
"""
from itertools import permutations
from polygonals import nth_triangular as n3
from polygonals import nth_square as n4
from polygonals import nth_pentagonal as n5
from polygonals import nth_hexagonal as n6
from polygonals import nth_heptagonal as n7
from polygonals import nth_octagonal as n8
from timer import timer
# PRE COMPUTED RANGES
poly_range = {
3: (45, 141), # 1035, 9870
4: (32, 100), # 1024, 9801
5: (26, 82), # 1001, 9801
6: (23, 71), # 1035, 9730
7: (21, 64), # 1071, 9828
8: (19, 59), # 1045, 9976
}
poly_func = {3: n3, 4: n4, 5: n5, 6: n6, 7: n7, 8: n8}
polygons = [
[int(poly_func[k](n)) for n in range(*poly_range[k])] for k in range(3, 9)
]
shuffled_polygons = permutations(polygons)
flag = False
sequence = [None] * 6
def cycle(polygons, index=0):
global sequence
if index == 0:
for elem in polygons[index]:
sequence = [elem] + [None] * 5
cycle(polygons, index + 1)
return False
else:
if index < 5:
for elem in polygons[index]:
if elem // 100 == sequence[index - 1] % 100:
sequence[index:] = [elem] + [None] * (5 - index)
cycle(polygons, index + 1)
return False
else:
for elem in polygons[index]:
if elem // 100 == sequence[index - 1] % 100 and \
elem % 100 == sequence[0] // 100:
sequence[index] = elem
print(sum(sequence))
timer.stop()
quit()
timer.start()
for poly_permutation in shuffled_polygons:
cycle(poly_permutation)
|
from math import gcd
def lcm(numbers):
"""
Computes the Least Common Multiple of a series of numbers
Origin : Problem 5
"""
least_multiple = 1
for number in numbers:
least_multiple *= number // gcd(least_multiple, number)
return least_multiple
def prod(iterable, start=1):
for p in iterable:
start *= p
return start
|
"""
Problem :
Find the sum of the only eleven primes that are both truncatable from left
to right and right to left.
Nota bene :
2, 3, 5, and 7 are not considered truncatable, so remove them from the
answer.
Performance time: ~20s
"""
from primes import generate_primes
from primes import is_prime
from timer import timer
def is_truncatable_prime(number):
if number < 10:
return False
left = str(number)
right = str(number)
while len(left) > 0:
if not is_prime(int(left)) or not is_prime(int(right)):
return False
left, right = left[:-1], right[1:]
return True
timer.start()
answer, counter = 0, 0
for prime in generate_primes():
if is_truncatable_prime(prime):
answer, counter = answer + prime, counter + 1
if counter >= 11:
break
print(answer)
timer.stop()
|
"""
Problem :
What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral
formed in the same way?
Performance time: ~0.0010s
"""
from timer import timer
timer.start()
answer = 1
for i in range(2, 1002, 2):
for j in range(1, 5):
answer += (i-1) ** 2 + j * i
print(answer)
timer.stop()
|
# python function can return multiple values together.
# other language like C,C++ or Java needs a class or structure for the same reason.
def add_multiply(a, b):
sum = a+b;
product = a*b
return sum, product
m, n = add_multiply(10, 20)
print("m: " +str(m) + " n: " + str(n))
|
def prompt():
print("Please enter an integer value: ")
# Start of program
print("This program adds together two integers.")
prompt() # Call the function
value1 = int(input("Testing to get input from console")) # all console input are string so, convert it into integer
prompt() # Call the function again
value2 = int(input())
sum = value1 + value2;
print (value1, "+", value2, "=", sum)
|
## for, while loop, continue, break
def main():
x = 2
while(x != 0):
print x
x -= 1 # --x or x-- are not supported
print "##############"
for x in range(2,5): # [2,5)
print x
for x in range(2,6,2): # [2,6) with interval 2
print x
print "################"
for x in (5, 10, 20):
print x
print "################"
Months = ["Jan", "Feb", "March", "April", "May", "june", "July", "August", "Sep", "Oct", "Nov", "Dec"] #list
for x in Months:
print x
print "################"
Days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") #Tupple
for x in Days:
print x
print "################"
Dict = { 1:'a', 2:'b' }
for x in list (Dict.keys()):
print x
for x in list(Dict.values()):
print x
if __name__ == "__main__":
main()
############## continue and break statement
print "###########################"
def main():
x = 10
while( x > 0):
print x
x = x-1
if(x > 5): continue
else: break
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
from labmet.labmetExceptions.labmetExceptions import InputTypeException
class ThornthwaiteETo(object):
"""Thornthwaite ETo
Empirical method based only on the mean air temperature,
which is its main advantage. It was developed for wet
weather conditions and therefore usually has underestimation
of ETP in dry weather conditions. Despite this limitation, it
is a method widely used for climatological purposes in
monthly scales. This method is part of a standard ET (ETo),
which is ET for a month of 30 days, with N = 12h.
"""
def __init__(self, avg_temp, photoperiod, n_days,
avg_annual_temp):
"""Class init method
Init method for the thornthwaite
:param avg_temp: Period average air temperature
:param photoperiod: Period average photoperiod
:param n_days: Number of days
:param avg_annual_temp: Average annual temperature
:type avg_temp: int or float
:type photoperiod: int or float
:type n_days: int
:type avg_annual_temp: int or float
"""
try:
self.avg_temp = float(avg_temp)
self.photoperiod = float(photoperiod)
self.n_days = self.period_validation(n_days)
self.avg_annual_temp = float(avg_annual_temp)
except Exception as e:
print("Error: %s" % e)
self.__temp_max_etp = 26.5
@staticmethod
def period_validation(n_days):
"""Period validation
Static function to validate the maximum
and minimum amount of days in a month
:param n_days: The number of days
:type n_days: int
:return: The number of days, or raises Exception
:rtype:int
"""
if 1 <= int(n_days) <= 31:
return n_days
else:
raise InputTypeException('The number of days in '
'the period must be greater '
'than 1 and lower than 31')
def temp_eto_check(self):
"""Temperature ETo check
method to determinate the type of ETo calculus
:return: Bool flag to ETo calculus type
:rtype: bool
"""
if 0 <= self.avg_temp <= self.__temp_max_etp:
return True
else:
return False
def h_i(self):
"""Heat index
Calculates an heat index which expresses
the level of heat in a region
:return: Heat index
:type: float
"""
return round(12 * math.pow((0.2 * self.avg_annual_temp), 1.514), 2)
def a(self):
"""Thornthwaite ETo "a" exponent
The "a" exponent is a regional thermal
index and is calculated by a polynomial
equation
:return: "a" exponent
:rtype: float
"""
h_i = self.h_i()
return round(0.49239 + (1.7912 * (math.pow(10, -2) * h_i))
- (7.71 * (math.pow(10, -5) * math.pow(h_i, 2)))
+ (6.75 * (math.pow(10, -7) * math.pow(h_i, 3))), 2)
def std_month_fix(self):
"""Standard month fix
The ETo by definition is the monthly evapotranspiration
in a standard month with 30 days and a photoperiod of
12 hours. To get the value of the ETo of a corresponding
month, it is necessary to fix it in function of the real
number of days and photoperiod
:return: Standard month fix factor
:rtype: float
"""
return round(self.photoperiod / 12.0 *
self.n_days / 30.0, 2)
def eto(self):
"""Potential evapotranspiration
This method is responsible to calculate
the potential evapotranspiration by itself.
:return: The ETo
:rtype: float
"""
i = self.h_i()
a = self.a()
if self.temp_eto_check():
return round(16 * math.pow((10 * self.avg_temp / i), a), 2)
else:
return round(-415.85 + ((32.24 * self.avg_temp) -
(0.43 * math.pow(self.avg_temp, 2))), 2)
def eto_month(self):
"""Standard month ETo
Calculates the ETo of a standard month,
by multiplying the ETo with a standard
month factor
:return: The ETo of a given month
:rtype: float
"""
cor = self.std_month_fix()
ETp = self.eto()
return round(cor * ETp, 2)
def eto_day(self):
"""ETo of a day
Brings the ETo to a daily scale.
:return: ETo of a given day
:rtype: float
"""
cor = self.std_month_fix()
ETp = self.eto()
return round((cor * ETp) / self.n_days, 2)
def __str__(self):
return "%.2f mm/month - %.2f mm/day" % (self.eto_month(), self.eto_day())
class ThornthwaiteCamargoETo(ThornthwaiteETo):
"""Thornthwaite Camargo method
It's an adaptation of the thornthwaite method
proposed by Camargo et al. and can be used in
any climate condition. To use it's necessary to
know the local thermal amplitude, instead of the average
air temperature. The advantage is that the ETo is not
underestimated in dry weather conditions. The downside is
that there is now needed the max and min temperatures.
As with the original Thornthwaite method, this method
calculates a standard ET (ETo), which is ET for a month
with 30 days, with N = 12h
"""
def __init__(self, max_temp, min_temp, photoperiod, n_days,
avg_annual_temp):
"""Class init method
The init method for the ThornthwaiteCamargoEto
class.
:param max_temp: The maximum temperature(ºC)
:param min_temp: The minimum temperature(ºC)
:param photoperiod: Period average photoperiod
:param n_days: Number of days
:param avg_annual_temp: Average annual temperature
:type max_temp: int or float
:type min_temp: int or float
:type photoperiod: int or float
:type n_days: int
:type avg_annual_temp: int or float
"""
try:
self.tef = self.effective_temperature(max_temp, min_temp)
except Exception as e:
print("Error: %s" % e)
ThornthwaiteETo.__init__(self, self.tef, photoperiod, n_days,
avg_annual_temp)
@staticmethod
def effective_temperature(t_max, t_min):
"""Effective temperature
Calculus of the effective temperature
:param t_max: The maximum temperature
:param t_min: The minimum temperature
:type t_max: int or float
:type t_min: int or float
:return: Effective temperature
:rtype: float
"""
if t_max < t_min:
t_max, t_min = t_min, t_max
return round(0.36 * (3 * t_max - t_min), 2)
if __name__ == '__main__':
test = ThornthwaiteETo(24, 12.2, 31, 21).eto_day()
print("Thornthwaite: \t\t", test)
test2 = ThornthwaiteCamargoETo(13, 10, 10.6, 31, 21.1)
print("Thornthwaite Camargo: \t", test2)
|
import numpy as np
def normalizeInput(inputImages, precalculatedMeans = None, precalculatedStds = None):
"""
Normalize input such that the mean is 0.0 and std is 1.0 for each channel
Args:
inputImages: an Numpy array that contains all the images. Assume the input is 3D or 4D array
3D: (imageIdx, x, y);
4D: (imageIdx, x, y, colorChannel)
precalculatedMeans: an 1-D Numpy array that contains precalcualted mean values.
The mean values will be calculated if it is not specified
precalculatedStds: an 1-D Numpy array that contains precalcualted standard deviation values.
The standard deviation values will be calculated if it is not specified
Returns:
Numpy array: in-place modified image array
"""
dimension = len(inputImages.shape)
imageMeans = None
imageStds = None
# single color channel
if dimension == 3:
if precalculatedMeans is None:
imageMean = np.mean(inputImages)
imageStd = np.std(inputImages)
else:
imageMean = precalculatedMeans[0]
imageStd = precalculatedStds[0]
inputImages -= imageMean
inputImages /= imageStd
imageMeans = np.array([imageMean])
imageStds = np.array([imageStd])
# multiple color channels
else:
# normalize for each channel
imageMeans = np.zeros(inputImages.shape[dimension-1])
imageStds = np.zeros(inputImages.shape[dimension-1])
for channelIdx in range(inputImages.shape[dimension-1]):
if precalculatedMeans is None:
imageMeans[channelIdx] = np.mean(inputImages[:,:,:,channelIdx])
imageStds[channelIdx] = np.std(inputImages[:,:,:,channelIdx])
else:
imageMeans[channelIdx] = precalculatedMeans[channelIdx]
imageStds[channelIdx] = precalculatedStds[channelIdx]
inputImages[:,:,:,channelIdx] -= imageMeans[channelIdx]
inputImages[:,:,:,channelIdx] /= imageStds[channelIdx]
return inputImages, imageMeans, imageStds
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.