text
stringlengths 37
1.41M
|
---|
import pandas as pd
import matplotlib.pyplot as plt
"""
requires a csv with money and date columns
What do we want to know?
biggest stock movement day
what does my money movement look like without paychecks
what is just growth per day without "paycheck growth" in dollars
what is just growth per day without "paycheck growth" in percents
must take into account days where we lose in the stock market enough to offset the 4000 dollar paycheck addition
do percent diffs
ignore diffs depending on days which were pay check daysG
"""
if __name__ == '__main__':
moneyData = pd.read_csv("personalValue.csv")
moneyData = moneyData.iloc[::-1]
moneyData = moneyData.reset_index()
moneyData = pd.DataFrame({ 'money': moneyData['money'], 'date': moneyData['date'] })
"""
gets percent change compared to yesterday for today
filters percent change by days that are not paycheck days
"""
def growthNonPaycheck():
moneyDiffs = moneyData['money'].rolling(2).apply(lambda r: (r[1]-r[0])/r[0])
isNotPaycheckDay = moneyData['money'].rolling(2).apply(lambda r: (r[1] - r[0]) < 3000) == 1.0
moneyGrowth = moneyData['money'][isNotPaycheckDay].rolling(37).apply(lambda r: (r[36] - r[0])/r[0])
diffs = pd.DataFrame({
'moneyGrowth': moneyGrowth,
'date': moneyData['date'][isNotPaycheckDay],
'growth': moneyDiffs[isNotPaycheckDay]
})
plt.plot('date', 'moneyGrowth', data=diffs, color='black')
plt.plot('date', 'growth', data=diffs, color='blue')
plt.legend()
plt.show()
|
import pytesseract
import cv2
from googletrans import Translator
def text_recognition(image_path):
#Proccesses the image and makes it the right size
# load the input image and grab the image dimensions
image = cv2.imread(image_path)
#makes the image pop up
cv2.imshow( 'image' , image)
image_height, image_width, image_channels = image.shape
#Testing if it got the width and hight
#print(str(image_width) + " " + str(image_height))
orig = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Performing OTSU threshold
ret, thresh1 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV)
# Specify structure shape and kernel size.
# Kernel size increases or decreases the area
# of the rectangle to be detected.
# A smaller value like (10, 10) will detect
# each word instead of a sentence.
rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25, 25))
# Appplying dilation on the threshold image
dilation = cv2.dilate(thresh1, rect_kernel, iterations = 1)
# Finding contours
contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_NONE)
# Creating a copy of image
im2 = image.copy()
#array for storing text
output_text = []
# Looping through the identified contours
# Then rectangular part is cropped and passed on
# to pytesseract for extracting text from it
# Extracted text is then written into the text file
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
# Drawing a rectangle on copied image
rect = cv2.rectangle(im2, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Cropping the text block for giving input to OCR
cropped = im2[y:y + h, x:x + w]
# Apply OCR on the cropped image
text = pytesseract.image_to_string(cropped)
#print(text)
output_text.append(text)
cv2.imshow( 'image' , im2)
return output_text[::-1]
#Get rid of extra space around the text
def clean_string(image_text):
clean = image_text.strip()
return clean
def translate_text(image_text, starting_lang, ending_lang):
translator = Translator()
results = translator.translate(str(image_text), src=starting_lang, dest=ending_lang)
#print(results)
return results.text
def main():
#image_path = "C:\\Users\\Natalie\\Desktop\\Coding_Project\\OCRtests\\First_test.png"
image_path = input("Please input image path using two \ ")
orig_lang = input("Original language: ")
ending_lang = input("Language to translate into: ")
string_from_image =text_recognition(image_path)
#test for for loop
#string_from_image = ["hello ", " yoooo", "\n yike \n"]
#Runs through the list cleaning the extra white space
striped_string = []
final_text = ''
for i in range(len(string_from_image)):
x = clean_string(string_from_image[i])
striped_string.append(x)
trans_text = translate_text(x, orig_lang, ending_lang)
print(trans_text)
# x = striped_string[0]
# print(type(x))
# print(x)
# Using the special variable
# __name__
if __name__=="__main__":
main() |
class Node:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def set_right(self, node):
self.right = node
def set_left(self, node):
self.left = node
def get_right(self):
return self.right
def get_left(self):
return self.left
def get_data(self):
return self.data
class BinaryTree:
def __init__(self, data=None):
if data is not None:
self.root = Node(data)
else:
self.root = None
def get_root(self):
return self.root
#Insert data into the binary tree
def insert(self, data):
#Check if tree has root node
if self.root is None:
self.root = Node(data)
else:
self.insert_into_node(data, self.root)
#Insert data at a given node
def insert_into_node(self, data, node):
left = node.get_left()
right = node.get_right()
node_data = node.get_data()
#Check if node already exists
if node_data == data:
return
#If node is less than current node, insert into left otherwise right
if data < node_data:
if left is not None:
self.insert_into_node(data, left)
else:
node.set_left(Node(data))
else:
if right is not None:
self.insert_into_node(data, right)
else:
node.set_right(Node(data))
def print(self):
self.print_tree(self.root, 0)
def print_tree(self, current, indent):
if current is not None:
print(indent * " " + "-> " + str(current.get_data()))
left = current.get_left()
self.print_tree(left, indent + 4)
right = current.get_right()
self.print_tree(right, indent + 4)
|
import Queue
class Graph:
'''
NOTE!!!! : this Graph class is describing un-weight graph, graph where all edges have constant "weight".
It means it's not important nature of node's connection but only fact that they are connected.
'''
def __init__(self):
self.nodes = []
@staticmethod
def bfs(root_node):
'''
(Wikipadia):"Breadth-first search (BFS) is an algorithm for traversing graph data structures.
It starts at some arbitrary node of a graph, and explores the neighbor nodes first, before moving to the next level
neighbors."
:param root_node: apply dfs starting from specific node
:return: list of nodes t representing breadth-first traversal
'''
# put result here.
result = []
# we keep track on visited nodes to avoid multiple processing of same node
# ... and we add root node to visited
visited = [root_node]
# here we keep nodes that should be processed
# in the start it's only root node. then we get it from queue and add there his neighbours
queue = Queue.Queue()
queue.put(root_node)
while not queue.empty():
processing = queue.get()
result.append(processing)
for n in processing.neighbours:
# check if note is already processed.
# if it's not processed add to 'visited' collection
if n not in visited:
visited.append(n)
queue.put(n)
return result
@staticmethod
def dfs(root_node):
'''
(Wikipadia): "Depth-first search (DFS) is an algorithm for traversing graph data. One starts at some arbitrary node
and explores as far as possible along each branch before backtracking."
:param root_node: apply dfs starting from specific node
:return: list of nodes t representing depth-first traversal
'''
# put result here.
result = []
# we keep track on visited nodes to avoid multiple processing of same node
# ... and we add root node to visited
visited = [root_node]
# here we keep nodes that should be processed
# in the start it's only root node. then we pop it from stack and add there his neighbours
stack = [root_node]
while len(stack) != 0:
processing = stack.pop()
result.append(processing)
for n in processing.neighbours:
# check if note is already processed.
# if it's not processed add to 'visited' collection
if n not in visited:
visited.append(n)
stack.append(n)
return result
'''
THIS METHOD IS FOR Unweighted graphs
'''
@staticmethod
def shortest_paths(root_node):
'''
(Wikipadia): In graph theory, the shortest path problem is the problem of finding a path between two vertices
(or nodes) in a graph such that the sum of the weights of its constituent edges is minimized.
:param root_node: node for which we are looking shortest cuts to other nodes
:return: dictionary in format key:node.value, value:distance from root_node.
'''
# we'll keep here shortest distance from given node (root_node) to rest of nodes in the three
# ... and we put there given node with distance 0 (from himself to himself)
distances = {root_node.value: 0}
# we'll use Depth-first search approach so we need a queue
q = Queue.Queue()
q.put(root_node)
# we keep track on visited nodes to avoid multiple processing of same node
# ... and we add root node to visited
visited = [root_node]
while not q.empty():
processing = q.get()
for n in processing.neighbours:
# check if note is already processed.
# if it's not processed add to 'visited' collection
if n not in visited:
visited.append(n)
q.put(n)
# we need to check if neighbour is in distances collection.
if n not in distances:
# ...just put neighbour in distances collection.
distances[n.value] = -1
# distance from root node to n node is distance from processing node + 1
distances[n.value] = distances[processing.value] + 1
return distances
'''
THIS METHOD IS FOR Unweighted, undirected graphs
'''
@staticmethod
def connected_components(nodes):
'''
NOTE: Valid only for undirected graphs.
In graph theory, a connected component (or just component) of an undirected graph is a subgraph in which any two
vertices are connected to each other by paths, and which is connected to no additional vertices in the
supergraph.
:return:
'''
components = []
visited = []
for node in nodes:
if not (node in visited):
com = Graph.bfs(node)
components.append(com)
for n in com:
visited.append(n)
return components
|
# -*- coding: utf-8 -*-
# 2 задание
# список из квадратов, которые являются четными и находятся на нечетных позициях,
# тут все просто перебираем от 0 до 10, с шагом в 2, особенность в том что индексация
# в питоне начинается с 0 поэтому четные и нечетные позиции меняются местами.
a = [i * 2 for i in range(0, 10, 2) if i % 2 == 0]
print a
|
import numpy as np
import numpy.linalg as la
import scipy.optimize as opt
######## EXAMPLE FOR USING MINIMIZE_SCALAR ##############
# Define function
def f(alpha,x,s):
return rosenbrock(x + alpha*s)
# Call routine - min now contains the minimum x for the function
#min = opt.minimize_scalar(f,args=(x,s)).alpha
#########################################################
def rosenbrock(x):
x1 = x[0]
x2 = x[1]
return 100*(x2 - x1**2)**2 + (1-x1)**2
def gradient(x):
# Returns gradient of rosenbrock function at x as numpy array
x1 = x[0]
x2 = x[1]
grad = np.array([400*x1**3 - 400*x1*x2 + 2*x1 -2,
200*(x2-x1**2)])
return grad
def hessian(x):
x1 = x[0]
x2 = x[1]
# Returns hessian of rosenbrock function at x as numpy array
hess = np.array([[1200*x1**2 - 400*x2 + 2, -400*x1],
[-400*x1, 200]])
return hess
# INSERT NEWTON FUNCTION DEFINITION
def nm(x):
for i in range(10):
s = la.solve(hessian(x), -gradient(x))
x = x + s
return x
# INSERT STEEPEST DESCENT FUNCTION DEFINITION
def sd(x):
for i in range(10):
s = gradient(x)
alpha = opt.minimize_scalar(f,args=(x,s)).x
x = x + alpha*s
return x
# DEFINE STARTING POINTS AND RETURN SOLUTIONS
start1 = np.array([-1.,1.])
nm1 = nm(start1)
sd1 = sd(start1)
start2 = np.array([0.,1.])
nm2 = nm(start2)
sd2 = sd(start2)
start3 = np.array([2.,1.])
nm3 = nm(start3)
sd3 = sd(start3)
|
#!/usr/bin/python3
import re
ip = "my name is srinu"
kk = re.sub(r'srinu', r'vas',ip)
print (kk)
|
#!/usr/bin/python3
'''
Without using any string methods, try to print the following:
Note that "" represents the values in between.
enter 3
res 123
'''
no = int(input("Enter the no : "))
i = 1
st = ''
while (i <= no):
st = st + str(i)
i +=1
print ("{} value result is {}".format(no,st))
|
#!/usr/bin/python3
'''
You have a record of N students. Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry. The marks can be floating values. The user enters some integer N followed by the names and marks for N students. You are required to save the record in a dictionary data type. The user then enters a student's name. Output the average percentage marks obtained by that student, correct to two decimal places.
Sample Input 0
3
Krishna 67 68 69
Arjun 70 98 63
Malika 52 56 60
Malika
Sample Output 0
56.00
'''
i = 1;
no = int(input("Ente the no : "))
while (i <= no):
str = input("Enter the details student : ")
pp = input("Enter the person : ")
sum = 0
list = str.split(' ')
name = list.pop(0)
ss = len(list)
#print (ss)
for k in list:
#print (k)
sum += int(k)
if name == pp:
avg = sum/ss
print ("{} is per {}".format(name,avg))
i +=1
|
#!/usr/bin/python3
aa = int(input("Enter the no : "))
bb = int(input("Enter the no: "))
## int div
dd = aa//bb
print (dd)
## float div
ee = aa/bb
print (ee)
|
#!/usr/bin/python3
n = 6
for i in range(1,15,2):
print(" "*n+"*"*i)
n-=1
|
#!/usr/bin/python3
test_list = [True, False, True, False, True, True, False]
# printing original list
print ("The original list is : " + str(test_list))
# using lambda + filter() + range()
# False indices
res = list(filter(lambda i: not test_list[i], range(len(test_list))))
print (res)
|
#!/usr/bin/python3
a = input("Enter the value :")
#a = str(a)
b = a[::-1]
if (a == b):
print ("{} is palindram.".format(a))
else:
print ("{} is not palindram.".format(a))
ll = 123;
print (type(ll))
oo = str(ll)
print (type(oo))
print (ll)
print (oo)
aa = "hh aa"
str = 'Python' #initial string
reversed=''.join(reversed(str))
print(reversed)
|
#!/usr/bin/python3
pets = {'cats': 1, 'dogs': 2, 'fish': 3}
if 'dogs' in pets:
print('Dogs are found!')
else:
print('Dogs are notfound!')
ll = 50
if ll is None:
print(ll)
|
#!/usr/bin/python3
# Use of Inheritance in Python
## parrent class or base class
class Pets:
def __init__(self):
print ("okkk")
def cc1(self):
print ("parrent cc1 fun")
def dd1(self):
print ("parrent dd1 fun")
## child class or derived class
class Dog(Pets):
def __inti__(self):
super().__init__(self)
print ("start child")
def cc1(self):
print ("child cc1 fun")
def ss1(self):
print ("child ss1 fun")
Chi = Dog();
Chi.cc1()
Chi.dd1()
Chi.ss1()
|
#!/usr/bin/python3
import re
class Employee:
# 'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
aa = [["nn",10],["yy",20],["oo",30],["hh",80]]
OP = 0
for i in range(0,len(aa)):
#print (aa[i][0],aa[i][1])
OP = Employee(aa[i][0],aa[i][1])
#print (OP.name,OP.salary)
OP.displayEmployee()
SS = OP.__dict__
OP.displayCount()
print (SS)
'''
aa = Employee(aa[i][0],aa[i][1])
aa.displayCount()
aa.displayEmployee()
'''
|
#!/usr/bin/python3
import re
def Read_file(file):
dict = {}
fh = open(file,"r")
for line in fh.readlines():
line = line.strip()
if re.match(r'^\s*$',line): continue
line = ' '.join(line.split(' '))
#print (line)
try:
dict[line] +=1
except:
dict[line] = 1
for dd in sorted dict.keys():
print (dd)
fh.close()
if __name__ == "__main__":
Read_file("file.txt")
|
#!/usr/bin/python3
def Switch_case(aa):
switches = {
2 : "this is value 2",
5 : "this is value 5",
0 : "this is value 0"
}
return switches.get(aa,"nothing")
if __name__ == "__main__":
aa = 10;
pp = Switch_case(aa)
print (pp)
|
#!/usr/bin/python3
list = (1,2,3,4,5,6,7)
print(list[::1])
|
#!/usr/bin/python3
a = 10
b = 20
c = "hello"
## strig concat
bb = c + str(a) + str(b)
print (bb)
## rep
cc = c * 2
print (cc)
if (cc == bb):
print ("match")
else:
print ("doen't match")
|
#!/usr/bin/python3
## without using range
no = input("Enter the no for range : ")
i = 1
while (i < int(no)):
print (i)
i +=1
|
#!/usr/bin/python3
def Flages(*hh):
aa = 8
falg = 0
for i in hh:
# print (i)
if (i == 8):
flag = 1
break
else:
flag = 0
return flag
if __name__ == "__main__":
aa = Flages(1,2,3,4,5,6,8,9,8,9,26)
print ("print flag returns ==> {} ".format(aa))
|
from numpy.random import rand, exponential
class basic_vertex(object):
"""
Represents a vertex to be matched in the system.
Implements three methods:
- match_value (value of matching to another vertex of the same type).
important that a.match_value(b) == b.match_value(a)
- unmatched_value: value of leaving unmatched. important that a.unmatched_value == a.b
For now represents a very basic structure where assortative matching is optimal
"""
def __init__(self, arr_time):
if rand() < 0.5:
self.type = "1"
else:
self.type = "2" # two types "1" and "2" for now. TODO: change to attributes
self.arrival_time = arr_time
self.id = arr_time
self.dep_time = arr_time + exponential(10)
# For now, vertices are uniquely identified by when they arrive (only one arrival per time step)
def match_value(self, other_vertex):
if other_vertex == self:
return 0 # self.unmatched_value() # self match is the same as leaving unmatched.
elif self.type == other_vertex.type:
return 10
else:
return 1
def unmatched_value(self):
return 0
def departure(self, time):
if time >= self.dep_time:
return True
else:
return False
class basic_vertex_generator(object):
def __init__(self):
self.name = "basic"
self.data_dir = ""
self.mode = ""
def new_vertex(self, i):
return basic_vertex(i)
|
print(f'{"="*26}\n{"BANCO JC":^26}\n{"="*26}')
valor = int(input('Que valor você quer sacar? R$'))
total = valor
ced = 50
totced = 0
while True:
if total >= ced:
total -= ced
totced += 1
else:
if totced > 0:
print(f'Total dde {totced} cédulas de R${ced}')
if ced == 50:
ced = 20
elif ced == 20:
ced = 10
elif ced == 10:
ced = 1
totced = 0
if total == 0:
break
print(f'{"="*26}\nVolte sempre ao BANCO JC! Tenha um bom dia!')
|
media = 0
nomeMaisVelho = 0
mulherMenos20 = 0
idadeMaisVelho = 0
for p in range(1, 5):
print('---- {}º PESSOA ----'.format(p))
nome = str(input('Nome: ')).strip().upper()
idade = int(input('Idade: '))
sexo = str(input('Sexo [M/F]: ')).strip().upper()
media += idade
if sexo == 'M':
if p == 1:
idadeMaisVelho = idade
nomeMaisVelho = nome
elif idadeMaisVelho < idade:
nomeMaisVelho = nome
idadeMaisVelho = idade
if sexo == 'F':
if idade < 20:
mulherMenos20 += 1
print('\nA média de idade das pessoas foi de {:.2f}\n'
'O homem mais velho tem {} e se chama "{}"\n'
'Dentre essas pessoas existe {} mulher(es) menores de 20 anos'
.format(media/p,idadeMaisVelho, nomeMaisVelho, mulherMenos20))
|
num = ((int(input('Digite um número: '))),
(int(input('Digite outro número: '))),
(int(input('Digite mais um número: '))),
(int(input('Digite o último númrto: '))))
print(f'Você digitou os valores {num}\n'
f'O valor 9 apareceu {num.count(9)} vez')
if 3 in num:
print(f'O valor 3 apareceu na {num.index(3) + 1}º poaição')
else:
print(f'O valor 3 não foi digitado em nenhuma posição')
print('O(s) valor(es) par(es) digitado(s) foi(ram): ', end='')
for n in num:
if n % 2 == 0:
print(n, end=' ')
|
v = float(input('Qual é o valor do produto que deseja comprar? R$'))
nv = v*0.95
d = v*0.05
print(f'Com um desconto de 5%, a vista, você irá pagar apenas R${nv:.2f} neste produto.'
f'\nRecebendo um desconto de R${d:.2f}.') |
s = 0
cont = 0
for c in range(1, 501, 2):
if c % 3 == 0:
s += c
cont += 1
print('O somatório de todos os {} números ímpares múltiplos de três foi {}!'.format(cont, s))
|
n = int(input('Digite um número para calcular seu fatorial: '))
print(f'Calculando {n}! = ', end='')
cont = 1
while n != 0:
print(f'{n}', end='')
print(' x ' if n > 1 else ' = ', end='')
cont *= n
n = n - 1
print(f'{cont}')
|
n1 = float(input('Digite um valor: '))
n2 = float(input('Digite um valor: '))
s = n1 + n2
print(f'A soma entre o valor {n1} e {n2} é igual: {s}')
|
valores = [int(input('Digite um valor: '))]
print('Valor adicionado com sucesso...')
while True:
continuar = str(input('Quer continuar? ')).strip().upper()[0]
if continuar == 'S':
valor = int(input('Digite um valor: '))
if valor not in valores:
valores.append(valor)
print('Valor adicionado com sucesso...')
else:
print('Valor Duplicado! Não irei adicionar!')
elif continuar == 'N':
break
print(f'{"-="*32}\nVocê digitou os valores {sorted(valores)}')
|
palavras = ('EU', 'AMO', 'à', 'ADELCINA',
'GOSTO', 'DE', 'JOGAR', 'CLASH', 'OF', 'CLANS',
'ESTOU', 'APREDENDO', 'PYTHON')
for pal in palavras:
print(f'\nNa palara {pal.upper()} temos ', end='')
for letra in pal:
if letra.lower() in 'aâãáàeéèêiìíîoõôòóuúùû':
print(letra.lower(), end=' ')
|
d = int(input('Informe a quantidade de dias usando o carro: '))
k = float(input('Informe a quantidade de kilometros percorridos: '))
v = (d*60) + (k*0.15)
print (f'O total a pagar pelo aluguel do carro, que foi usado por {d} dias e que rodou {k}km, é de {v:.2f} reais.')
|
pessoas = list()
soma = 0
while True:
pessoa = {'Nome': str(input('Nome: ')).strip()}
while True:
pessoa['Sexo'] = str(input('Sexo: [M/F] ')).strip().upper()[0]
if pessoa['Sexo'] in 'MF':
break
print('ERRO! Por favor, digite apenas M ou F.')
pessoa['Idade'] = int(input('Idade: '))
soma += pessoa['Idade']
pessoas.append(pessoa.copy())
pessoa.clear()
while True:
r = str(input('Quer continuar? [S/N] ')).strip().upper()[0]
if r in 'SN':
break
print('ERRO! Por favor, digite apenas S ou N.')
if r == 'N':
break
print(f'{"-="*30}\nA) O grupo tem {len(pessoas)} pessoas.\n'
f'B) A média de idade é de {soma/len(pessoas):.2f} anos.\n'
f'C) As mulheres cadastradas foi(ram): ', end='')
for i in pessoas:
if i['Sexo'] == 'F':
print(f'{i["Nome"]};', end=' ')
print(f'\nD) Lista das pessoas que estão acima da média:')
for i in pessoas:
if i['Idade'] > soma/len(pessoas):
print(' ', end='')
for k, v in i.items():
print(f'{k} = {v}; ', end='')
print()
print('<< ENCERRANDO >>')
|
valores = []
cont = 0
for c in range(0, 5):
valor = int(input('Digite um valor: '))
if c == 0 or valor > valores[-1]:
valores.append(valor)
print('Adicionado no final da lista...')
else:
pos = 0
while pos < len(valores):
if valor <= valores[pos]:
valores.insert(pos, valor)
print(f'Adicionado na posição {pos}...')
break
pos += 1
print(f'{"-="*30}\nOs valores digitados em ordem foram {valores}')
|
n1 = float(input('Digete a metragem: '))
k = n1/1000
h = n1/100
da = n1/10
d = n1*10
c = n1*100
m = n1*1000
print(f'O valor desta metragem\nem quilômetros é {k}\nem hectometros é {h};'
f'\nem decâmetro é {da};\n em decímetro é {d}\nem centímetros é {c};\nem milímetros é {m};')
|
n1 = int(input('Digite um valor: '))
m2 = n1*2
m3 = n1*3
r = n1**(1/2)
print(f'O dobro de {n1} é {m2};\no triplo de {n1} é {m3};\na raiz de {n1} é {r:.2f}')
|
#python3 script
#constant step size method, the difference of values between consecutive steps are random
#author: Xiang Chao
import numpy as np
import matplotlib.pyplot as plt
import random
def OneRun_1(arm_num, eps, step_num):#using sample averages, alpha = 1/n
value = np.zeros(arm_num)
Q = np.zeros(arm_num)#the estimate of value for each arm
N = np.zeros(arm_num)#the numbers of exploitations for each arm
reward = np.zeros(step_num)#the reward of each step
if_optimal = np.zeros(step_num)#1 for the optimal action;0 for other actions
for i in range(step_num):
value = value + np.random.normal(0, 1, arm_num)
if random.random() > eps:#random.random() returns a number in [0,1) randomly
A = np.argmax(Q)#A is index of the first max element in Q
if value[A] == np.max(value):
if_optimal[i] = 1
else:
A = random.randint(0, 9)#A is a random integer from 0 to 9
if value[A] == np.max(value):
if_optimal[i] = 1
R = random.gauss(value[A], 1)#mu=value[A], sigma=1;the reward for arm A
reward[i] = R
N[A] = N[A] + 1
Q[A] = Q[A] + (R - Q[A])/N[A]
return [reward, if_optimal]
def OneRun_2(arm_num, eps, step_num, alpha):#using a constant step-size, alpha = 0.1
value = np.zeros(arm_num)
Q = np.zeros(arm_num)#the estimate of value for each arm
reward = np.zeros(step_num)#the reward of each step
if_optimal = np.zeros(step_num)#1 for the optimal action;0 for other actions
for i in range(step_num):
value = value + np.random.normal(0, 1, arm_num)
if random.random() > eps:#random.random() returns a number in [0,1) randomly
A = np.argmax(Q)#A is index of the first max element in Q
if value[A] == np.max(value):
if_optimal[i] = 1
else:
A = random.randint(0, 9)#A is a random integer from 0 to 9
if value[A] == np.max(value):
if_optimal[i] = 1
R = random.gauss(value[A], 1)#mu=value[A], sigma=1;the reward for arm A
reward[i] = R
Q[A] = Q[A] + (R - Q[A])*alpha
return [reward, if_optimal]
repeat_num = 2000
arm_num = 10
eps = 0.1
alpha = 0.1
step_num = 2000
ave_reward = np.zeros((2,step_num))
rate_optimal = np.zeros((2,step_num))
for i in range(repeat_num):
[a, b] = OneRun_1(arm_num, eps, step_num)
ave_reward[0,:] = ave_reward[0,:] + a
rate_optimal[0,:] = rate_optimal[0,:] + b
ave_reward[0,:] = ave_reward[0,:] / repeat_num
rate_optimal[0,:] = rate_optimal[0,:] / repeat_num
for i in range(repeat_num):
[a, b] = OneRun_2(arm_num, eps, step_num, alpha)
ave_reward[1,:] = ave_reward[1,:] + a
rate_optimal[1,:] = rate_optimal[1,:] + b
ave_reward[1,:] = ave_reward[1,:] / repeat_num
rate_optimal[1,:] = rate_optimal[1,:] / repeat_num
step = range(step_num)
plt.plot(step, ave_reward[0,:], label='$\\alpha = 1/n$', color='r')
plt.plot(step, ave_reward[1,:], label='$\\alpha = 0.1$', color='g')
plt.xlabel('Steps')
plt.ylabel('Average reward')
plt.legend()
plt.savefig('rdv_Average_reward.png')
plt.show()
plt.plot(step, rate_optimal[0,:], label='$\\alpha = 1/n$', color='r')
plt.plot(step, rate_optimal[1,:], label='$\\alpha = 0.1$', color='g')
plt.xlabel('Steps')
plt.ylabel('rate of optimal action')
plt.legend()
plt.savefig('rdv_Rate_optimal.png') |
name= input("Name: ")
print("Welcome, " +name )
print(f"Welcome, {name} ") |
import matplotlib.pyplot as plt
# 'go' stands for green dots
plt.plot([1,2,3,4,5], [1,2,3,4,10], 'go')
plt.show()
# Draw two sets of scatterplots in same plot
# Draw two sets of points
plt.plot([1,2,3,4,5], [1,2,3,4,10], 'go') # green dots
plt.plot([1,2,3,4,5], [2,3,4,5,11], 'b*') # blue stars
plt.show()
#The plt object has corresponding methods to add each of this.
plt.plot([1,2,3,4,5], [1,2,3,4,10], 'go', label='GreenDots')
plt.plot([1,2,3,4,5], [2,3,4,5,11], 'b*', label='Bluestars')
plt.title('A Simple Scatterplot')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc='best') # legend text comes from the plot's label parameter.
plt.show()
#The easy way to do it is by setting the figsize inside plt.figure() method.
plt.figure(figsize=(10,7)) # 10 is width, 7 is height
plt.plot([1,2,3,4,5], [1,2,3,4,10], 'go', label='GreenDots') # green dots
plt.plot([1,2,3,4,5], [2,3,4,5,11], 'b*', label='Bluestars') # blue stars
plt.title('A Simple Scatterplot')
plt.xlabel('X')
plt.ylabel('Y')
plt.xlim(0, 6)
plt.ylim(0, 12)
plt.legend(loc='best')
plt.show()
# Draw 2 scatterplots in different panels
# Create Figure and Subplots
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(10,4), sharey=True, dpi=120)
# Plot
ax1.plot([1,2,3,4,5], [1,2,3,4,10], 'go') # greendots
ax2.plot([1,2,3,4,5], [2,3,4,5,11], 'b*') # bluestart
# Title, X and Y labels, X and Y Lim
ax1.set_title('Scatterplot Greendots'); ax2.set_title('Scatterplot Bluestars')
ax1.set_xlabel('X'); ax2.set_xlabel('X') # x label
ax1.set_ylabel('Y'); ax2.set_ylabel('Y') # y label
ax1.set_xlim(0, 6) ; ax2.set_xlim(0, 6) # x axis limits
ax1.set_ylim(0, 12); ax2.set_ylim(0, 12) # y axis limits
# ax2.yaxis.set_ticks_position('none')
plt.tight_layout()
plt.show()
'''create one subplot at a time (using plt.subplot() or plt.add_subplot()) and immediately call plt.plot() or plt.{anything}
to modify that specific subplot (axes). Whatever method you call using plt will be drawn in the current axes'''
plt.figure(figsize=(10,4), dpi=120) # 10 is width, 4 is height
# Left hand side plot
plt.subplot(1,2,1) # (nRows, nColumns, axes number to plot)
plt.plot([1,2,3,4,5], [1,2,3,4,10], 'go') # green dots
plt.title('Scatterplot Greendots')
plt.xlabel('X'); plt.ylabel('Y')
plt.xlim(0, 6); plt.ylim(0, 12)
# Right hand side plot
plt.subplot(1,2,2)
plt.plot([1,2,3,4,5], [2,3,4,5,11], 'b*') # blue stars
plt.title('Scatterplot Bluestars')
plt.xlabel('X'); plt.ylabel('Y')
plt.xlim(0, 6); plt.ylim(0, 12)
plt.show()
# Draw multiple plots using for-loops using object oriented syntax
import numpy as np
from numpy.random import seed, randint
seed(100)
# Create Figure and Subplots
fig, axes = plt.subplots(2,2, figsize=(10,6), sharex=True, sharey=True, dpi=120)
# Define the colors and markers to use
colors = {0:'g', 1:'b', 2:'r', 3:'y'}
markers = {0:'o', 1:'x', 2:'*', 3:'p'}
# Plot each axes
for i, ax in enumerate(axes.ravel()):
ax.plot(sorted(randint(0,10,10)), sorted(randint(0,10,10)), marker=markers[i], color=colors[i])
ax.set_title('Ax: ' + str(i))
ax.yaxis.set_ticks_position('none')
plt.suptitle('Four Subplots in One Figure', verticalalignment='bottom', fontsize=16)
plt.tight_layout()
plt.show()
# FuncFormatter using matplotlib
from matplotlib.ticker import FuncFormatter
def rad_to_degrees(x, pos):
'converts radians to degrees'
return round(x * 57.2985, 2)
plt.figure(figsize=(12,7), dpi=100)
X = np.linspace(0,2*np.pi,1000)
plt.plot(X,np.sin(X))
plt.plot(X,np.cos(X))
# 1. Adjust x axis Ticks
plt.xticks(ticks=np.arange(0, 440/57.2985, 90/57.2985), fontsize=12, rotation=30, ha='center', va='top') # 1 radian = 57.2985 degrees
# 2. Tick Parameters
plt.tick_params(axis='both',bottom=True, top=True, left=True, right=True, direction='in', which='major', grid_color='blue')
# 3. Format tick labels to convert radians to degrees
formatter = FuncFormatter(rad_to_degrees)
plt.gca().xaxis.set_major_formatter(formatter)
plt.grid(linestyle='--', linewidth=0.5, alpha=0.15)
plt.title('Sine and Cosine Waves\n(Notice the ticks are on all 4 sides pointing inwards, radians converted to degrees in x axis)', fontsize=14)
plt.show()
|
class Solution:
"""
Given a string s, find the longest palindromic substring in s. You may
assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
def naive_longest_palindromic_substring(self, s):
"""
Have a nested for loop to go through all possible substrings. Then use
another loop to verify that the substring is a palindrome,
Time Complexity: O(n^3)
"""
longest_palindrome = ""
n = len(s)
for i in range(n):
for j in range(n):
if i <= j:
substring_length = len(s[i:j+1])
if substring_length == 1 and \
len(s[i:j+1]) > len(longest_palindrome):
longest_palindrome = s[i:j+1]
continue
k = 0
is_palindrome = True
while k < substring_length // 2:
if s[i+k] != s[j-k]:
is_palindrome = False
break
k += 1
if is_palindrome and substring_length > len(longest_palindrome):
longest_palindrome = s[i:j+1]
continue
return longest_palindrome
def longest_palindromic_substring(self, s):
"""
Go through each character in the string and create a "boundary" that
continues to expand outwards while the characters at the boundary also
match. Keep track of the largest boundary and return that substring.
For the case where the length of the string is even, go through the
string two characters at a time to find a match and then expand the
boundary outward.
Time Complexity: O(n^2)
"""
n = len(s)
if n == 0:
return ""
longest_palindrome = s[0]
for i in range(n):
boundary = 1
while i - boundary >= 0 and \
i + boundary < n and \
s[i-boundary] == s[i+boundary]:
if 2 * (boundary) + 1 > len(longest_palindrome):
longest_palindrome = s[i - boundary: i+boundary+1]
boundary += 1
for i in range(n-1):
boundary = 1
j = i + 1
if s[i] == s[j]:
if len(s[i:j+1]) > len(longest_palindrome):
longest_palindrome = s[i:j+1]
while i - boundary >= 0 and \
j + boundary < n and \
s[i-boundary] == s[j+boundary]:
if 2 * (boundary) + 2 > len(longest_palindrome):
longest_palindrome = s[i - boundary: j+boundary+1]
boundary += 1
return longest_palindrome
if __name__ == "__main__":
s = Solution()
print(s.longest_palindromic_substring("babad")) # -> "bab"
print(s.longest_palindromic_substring("cbbd")) # -> "bb"
print(s.longest_palindromic_substring("abcd")) # -> "a"
print(s.longest_palindromic_substring("bananas")) # -> "anana"
|
import pygame
pygame.init()
screen = (600, 500)
win = pygame.display.set_mode(screen)
pygame.display.set_caption("Sudoku!")
red = (255, 0, 0)
black = (0, 0, 0)
grey = (210, 210, 210)
blue = (0, 0, 255)
green = (0, 255, 0)
clock = pygame.time.Clock()
font = pygame.font.SysFont("Gill Sans MT (Body)", 50)
font2 = pygame.font.SysFont("comicsans", 25)
text_button = font2.render("Resolve",1,black)
text_next = font2.render("Play Next", 1, black)
rows = {}
columns = {}
cuadrants = {}
d = {}
cells = []
cellCount = 0
w = 0
modifying = ""
class Cell:
def __init__(self, row, column, value):
self.column = column
self.row = row
self.key = str(w)+str(row)+str(column)
self.color = black
self.visible = False
self.modifiable = True
self.modic = False
self.done = False
if self.row <= 3 and self.column <= 3:
self.cuadrante = 1
elif self.row <= 3 and self.column <= 6:
self.cuadrante = 2
elif self.row <= 3 and self.column <= 9:
self.cuadrante = 3
elif self.row <= 6 and self.column <= 3:
self.cuadrante = 4
elif self.row <= 6 and self.column <= 6:
self.cuadrante = 5
elif self.row <= 6 and self.column <= 9:
self.cuadrante = 6
elif self.row <= 9 and self.column <= 3:
self.cuadrante = 7
elif self.row <= 9 and self.column <= 6:
self.cuadrante = 8
elif self.row <= 9 and self.column <= 9:
self.cuadrante = 9
self.value = value
self.correct_value = 0
self.posible_values = []
if self.value in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
self.correct_value = self.value
self.done = True
self.modifiable = False
self.imposible_values = []
self.posible_values = []
for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
if n != self.value:
self.imposible_values.append(n)
if n == self.value:
self.posible_values.append(n)
rows[self.row].append(self.value)
columns[self.column].append(self.value)
cuadrants[self.cuadrante].append(self.value)
else:
self.imposible_values = []
self.posible_values = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def draw(self):
global modifying
if pos[0] > (self.column * 50) - 50 and pos[0] < self.column * 50 and pos[1] > (self.row * 50) - 50 and pos[1] < self.row * 50:
pygame.draw.rect(win, grey, (self.column * 50, self.row * 50, -50, -50), 3)
if self.value != self.correct_value:
self.color = red
else:
self.color = black
if self.value != 0:
self.text = font.render(str(self.value), 1, self.color)
win.blit(self.text, (17+(50*(self.column-1)), 12+(50*(self.row-1))))
if click[0] > (self.column * 50) - 50 and click[0] < self.column * 50 and click[1] > (self.row * 50) - 50 and click[1] < self.row * 50:
if self.modifiable:
pygame.draw.rect(win, blue, (self.column * 50, self.row * 50, -50, -50), 5)
modifying = self.key
def modify(self):
self.value = int(event.unicode)
def resolve(self):
l = []
for u in self.posible_values:
l.append(u)
for x in l:
if x not in columns[self.column] and x not in rows[self.row] and x not in cuadrants[self.cuadrante]:
i = 0
for m in d.keys():
if d[m].cuadrante == self.cuadrante and x in d[m].imposible_values and d[m].key != self.key:
i += 1
if i == 8:
self.posible_values = [x]
self.imposible_values = [1, 2, 3, 4, 5, 6, 7, 8, 9]
self.imposible_values.pop(self.imposible_values.index(x))
break
else:
self.imposible_values.append(x)
self.posible_values.pop(self.posible_values.index(x))
if len(self.posible_values) == 1:
self.correct_value = self.posible_values[0]
self.posible_values = []
rows[self.row].append(self.correct_value)
columns[self.column].append(self.correct_value)
cuadrants[self.cuadrante].append(self.correct_value)
self.done = True
def draw_grid():
win.fill((255, 255, 255))
pygame.draw.line(win, (0, 0, 0), (0, 0), (600, 0), 5)
pygame.draw.line(win, (0, 0, 0), (0, 0), (0, 500), 5)
pygame.draw.line(win, (0, 0, 0), (600, 0), (600, 500), 5)
pygame.draw.line(win, (0, 0, 0), (0, 500), (600, 500), 5)
pygame.draw.line(win, (0, 0, 0), (50, 0), (50, 450), 2)
pygame.draw.line(win, (0, 0, 0), (100, 0), (100, 450), 2)
pygame.draw.line(win, (0, 0, 0), (150, 0), (150, 450), 5)
pygame.draw.line(win, (0, 0, 0), (200, 0), (200, 450), 2)
pygame.draw.line(win, (0, 0, 0), (250, 0), (250, 450), 2)
pygame.draw.line(win, (0, 0, 0), (300, 0), (300, 450), 5)
pygame.draw.line(win, (0, 0, 0), (350, 0), (350, 450), 2)
pygame.draw.line(win, (0, 0, 0), (400, 0), (400, 450), 2)
pygame.draw.line(win, (0, 0, 0), (450, 0), (450, 450), 5)
pygame.draw.line(win, (0, 0, 0), (0, 50), (450, 50), 2)
pygame.draw.line(win, (0, 0, 0), (0, 100), (450, 100), 2)
pygame.draw.line(win, (0, 0, 0), (0, 150), (450, 150), 5)
pygame.draw.line(win, (0, 0, 0), (0, 200), (450, 200), 2)
pygame.draw.line(win, (0, 0, 0), (0, 250), (450, 250), 2)
pygame.draw.line(win, (0, 0, 0), (0, 300), (450, 300), 5)
pygame.draw.line(win, (0, 0, 0), (0, 350), (450, 350), 2)
pygame.draw.line(win, (0, 0, 0), (0, 400), (450, 400), 2)
pygame.draw.line(win, (0, 0, 0), (0, 450), (450, 450), 5)
def draw_buttons():
pygame.draw.rect(win,grey,(475,25,100,50),0)
if pos[0] > 475 and pos[0] < 575 and pos[1] > 25 and pos[1] < 75:
pygame.draw.rect(win, blue, (475, 25, 100, 50), 0)
win.blit(text_button, (494,42))
pygame.draw.rect(win,grey,(475,100,100,50),0)
if pos[0] > 475 and pos[0] < 575 and pos[1] > 100 and pos[1] < 150:
pygame.draw.rect(win,blue,(475,100,100,50),0)
win.blit(text_next,(488,42+75))
return
def redrawGameWindow():
draw_grid()
draw_buttons()
for n in d.keys():
d[n].draw()
pygame.display.update()
return
sudokus = [[[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]],
[[6,8,5,1,3,0,0,4,7],
[7,0,0,0,0,0,0,1,0],
[0,1,0,7,6,4,0,5,0],
[9,0,0,0,7,0,5,0,4],
[8,0,1,0,0,9,0,7,2],
[4,0,3,0,0,6,0,0,0],
[0,0,0,4,2,7,3,9,0],
[0,4,0,9,0,0,0,6,8],
[1,0,7,0,0,0,4,0,0]],
[[0,0,7,0,1,0,0,0,5],
[0,0,0,2,0,0,0,0,0],
[5,0,1,9,8,4,0,7,0],
[4,0,0,0,3,0,7,0,1],
[0,1,8,7,0,5,6,9,0],
[7,5,0,0,0,0,0,0,0],
[9,6,2,0,7,8,0,1,0],
[0,0,5,4,0,9,3,0,0],
[3,0,4,0,6,1,8,0,9]]]
def initialize(sudoku):
global cells, d, w, rows,columns, cuadrants, run, congratulations
w += 1
congratulations = 0
rows = {x: [] for x in range(1, 10)}
columns = {x: [] for x in range(1, 10)}
cuadrants = {x: [] for x in range(1, 10)}
d = {}
for row in range(1, 10):
for column in range(1, 10):
d[str(w)+str(row)+str(column)] = Cell(row, column, sudoku[row-1][column-1])
cells = []
for key in d.keys():
cells.append(d[key])
c = 0
check_if_solvable = 0
while c < 81 and check_if_solvable < 100:
c = 0
check_if_solvable += 1
for key in d.keys():
if d[key].done:
c += 1
else:
d[key].resolve()
if check_if_solvable >= 100:
run = False
return
s = 0
initialize(sudokus[s])
click = (0,0)
resolveAll = False
run = True
while run:
clock.tick(30)
for event in pygame.event.get():
pos = pygame.mouse.get_pos()
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
mx, my = pygame.mouse.get_pos()
click = (mx,my)
mod = False
if mx > 0 and mx < 450 and my > 0 and my < 450:
mod = True
if event.type == pygame.KEYDOWN:
if event.unicode in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]:
if d[modifying].modifiable:
d[modifying].modify()
old_mod = modifying
if event.unicode == " ":
for key in d.values():
del key
if click[0] > 475 and click[0] < 575 and click[1] > 25 and click[1] < 75:
resolveAll = True
if resolveAll:
cellCount += 50
cells[cellCount//81].value = cells[cellCount//81].correct_value
if cellCount > 80*81:
resolveAll = False
cellCount = 0
if click[0] > 475 and click[0] < 575 and click[1] > 100 and click[1] < 150:
click = (0, 0)
if s >= len(sudokus)-1:
s = 0
else:
s += 1
initialize(sudokus[s])
resolveAll = False
cellCount = 0
redrawGameWindow()
pygame.quit()
|
from html_scraper import scrape_all_html
import csv
from download_html import download_all
def generate_csv():
print 'Collecting toilet information from html files. This may take a few minutes.'
toilets = scrape_all_html(True)
print 'Generating CSV'
filename = 'ableroad_data.csv'
with open(filename, 'wb') as csv_file:
writer = csv.writer(csv_file, delimiter=',',
quotechar='"', quoting=csv.QUOTE_ALL)
writer.writerow(['Name', 'Categories','Street Address', 'Zip Code',
'Neighbourhood', 'Locality', 'State',
'Yelp Rating', 'Num Yelp Ratings', 'Yelp Review Start', 'Distance',
'Ableroad Rating', 'Ableroad Num Ratings', 'Ableroad Review Text', 'Thumbnail URL', 'Details URL'])
for toilet in toilets:
writer.writerow([toilet.name, toilet.categories, toilet.street_address,
toilet.zipcode, toilet.neighbourhood, toilet.locality, toilet.state, toilet.yelp_rating
, toilet.yelp_num_ratings, toilet.yelp_review_start, toilet.distance,
toilet.ableroad_rating, toilet.ableroad_num_ratings, toilet.ableroad_review_text,
toilet.thumbnail_url, toilet.details_url])
print 'done writing file: ' + filename
if __name__ == '__main__':
download_all()
generate_csv()
|
import random
start = input('请输入初始值:')
end = input('请输入末尾值:')
start = int(start)
end = int(end)
r = random.randint(start,end)
count = 0
while True :
count += 1
num = input("请输入数字:")
num = int(num)
if num > r :
print('太大了,小一点!')
elif num < r :
print('太小了,大一点!')
else :
print('恭喜你猜对了')
print('这是你猜对的第',count,'次')
break |
import re
import string
input = open("../data/day5.txt").read()[:-1]
pattern = "|".join([str(lower) + str(lower.upper()) + "|" +
str(lower.upper()) + str(lower)
for lower in list(string.ascii_lowercase)])
while True:
str_length_prev = len(input)
input = re.sub(pattern, "", input)
if str_length_prev == len(input):
break
# now we have the updated input from the first exercise,
# next, we remove each alphabet one by one to test which leads
# the smallest string output
for lower in list(string.ascii_lowercase):
new_input = re.sub(lower + "|" + lower.upper(), "", input)
while True:
str_length_prev = len(new_input)
new_input = re.sub(pattern, "", new_input)
if str_length_prev == len(new_input):
break
print("when {} is removed, len is {}".format(lower, str_length_prev))
|
# install chatterbot lib.
# then we import chatbot class from chatterbot module
# and now we will create a new chatbot
# so take a var(bot) and put class(chatbot)in it and make class object and pass constructor here(constructor)
# ----- we must create a set(no duplicacy) of conversation / and put this set of conversation in a DATABASE / and give refrence of this set to listtrainer() to fetch data from database
# for this we can use SQLITE DATABASE for conversation
# we can ADAPTOR to TRAIN
# install lib. pyttsx3 for audio msgs
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot
from tkinter import *
import pyttsx3 as pp
import speech_recognition as s # for spech recognise #taking query
# threading(a module)for calling takequery func we created a thread
import threading
engine = pp.init() # initializing pp and it returne a module named engine
voices = engine.getProperty('voices') # it will take all male / female voices
engine.setProperty('voice', voices[0].id)
def speak(word):
engine.say(word) # using say func
engine.runAndWait() # runandwait method using
# now create object of chatbot class: -
robot = ChatBot("write anything here like-my Bot")
list = [
'hello',
'hi',
'how are you',
'fine',
'what is your name',
'my name is bot',
'where you live',
'i live in india',
'which language you speak',
'mostly i speak english'
]
# now create an object of listtrainer
trainer = ListTrainer(robot)
# now train the bot with help of trainer # trainer help our robot to learn all conversation
trainer.train(list)
#answer = robot.get_response("hello")
# print(answer)
# print('talk: ')
# while True:
# query = input()
# if query == "exit":
# break
# ans = robot.get_response(query)
# print('bot:', ans)
window = Tk()
window.geometry('500x450') # width x height x=x not *
window.title('my chatbot')
# now taking audio as input and convert it into string and give that string to our robot to print
# so now create a fun.
def takequery():
sr = s.Recognizer()
# this line is not imp. # read documentation and understand threshold
sr.pause_threshold = 1
print('bot is listening so speak .........')
with s.Microphone() as m:
audio = sr.listen(m)
text = sr.recognize_google(audio, language='eng-in')
print(text)
textF.delete(0, END)
textF.insert(0, text)
ask()
def ask():
question = textF.get()
answer = robot.get_response(question)
msg.insert(END, 'you: ' + question)
msg.insert(END, 'robot: ' + str(answer))
speak(answer) # here our speaker becomes active//calling speak func
textF.delete(0, END) # deleting text field automatically
msg.yview(END) # automatically shows us end msg
#img = PhotoImage(file=r'C:\Users\RIG1\Desktop\robot.png')
#photoL = Label(window, Image=img)
# photoL.pack(pady=5)
frame = Frame(window)
sc = Scrollbar(frame)
# create object of a list box
# (yscrollcommand=scrol.set= just to active our scroll bar)
# yscrollcommand is an attribute
msg = Listbox(frame, width=60, height=20, yscrollcommand=sc.set)
sc.pack(side=RIGHT, fill=Y)
msg.pack(side=LEFT, fill=BOTH, pady=20)
frame.pack()
# now creating text field
textF = Entry(window)
textF.pack(fill=X, pady=10)
# creating button
btn = Button(window, text='ask', command=ask)
btn.pack()
# creating a function for enter:-
def enter(event): # write event(an object) is important
btn.invoke()
# now bind(joint) main window with enter key
# (here binding RETURN means ENTER with our window) AND (giving refrence of ENTER function not calling enter)
window.bind('<Return>', enter)
def repeatListen(): # for taking audio againand agin from user
while True:
takequery() # our function name
# takequery() # for calling takequery function here we create a THREAD
# not using() to call func.just giving name/reference of func with its name
t = threading.Thread(target=repeatListen) # repeat - our function
t.start() # so now our thread is staring with calling takequery func.
window.mainloop()
|
# Park Se-hun, Exercise4
import math
def distance(x1, y1, x2, y2):
dist_x = x2-x1
dist_y = y2-y1
return math.sqrt(dist_x**2 + dist_y**2)
dot1_x = input("input x-coordinate of Dot1 : ")
dot1_y = input("input y-coordinate of Dot1 : ")
dot2_x = input("input x-coordinate of Dot2 : ")
dot2_y = input("input y-coordinate of Dot2 : ")
result = distance(dot1_x, dot1_y, dot2_x, dot2_y)
print "Distance of Dot1 and Dot2 is %.2f" %result |
import cv2
#from cv2 import cv
#method = cv.CV_TM_SQDIFF_NORMED
methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR',
'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']
# Read the images from the file
small_image = cv2.imread('img/2_rot.jpg')
large_image = cv2.imread('img/1.jpg')
result = cv2.matchTemplate(small_image, large_image, 1)
# We want the minimum squared difference
mn,_,mnLoc,_ = cv2.minMaxLoc(result)
# Draw the rectangle:
# Extract the coordinates of our best match
MPx,MPy = mnLoc
# Step 2: Get the size of the template. This is the same size as the match.
trows,tcols = small_image.shape[:2]
# Step 3: Draw the rectangle on large_image
cv2.rectangle(large_image, (MPx,MPy),(MPx+tcols,MPy+trows),(0,0,255),2)
# Display the original image with the rectangle around the match.
#cv2.imshow('output',large_image)
cv2.imwrite('out.png',large_image)
# The image is only displayed if we call this
#cv2.waitKey(0) |
"""
9. Среди натуральных чисел, которые были введены, найти
наибольшее по сумме цифр. Вывести на экран это число и сумму его цифр.
"""
A = input("введите число 1 ")
B = input("введите число 2 ")
C = input("введите число 3 ")
def sum_for_string(A):
sum = 0
for num in A:
sum = sum + int(num)
return sum
A_STR_SUM = int(sum_for_string(A))
B_STR_SUM = int(sum_for_string(B))
C_STR_SUM = int(sum_for_string(C))
if A_SUM > B_SUM and A_SUM > C_SUM:
print (f'Победило число {A}. Сумма его цифр {A_SUM}')
elif B_SUM > A_SUM and B_SUM > C_SUM:
print (f'Победило число {B}. Сумма его цифр {B_SUM}')
elif C_SUM > A_SUM and C_SUM > B_SUM:
print (f'Победило число {C}. Сумма его цифр {C_SUM}')
else:
print ("Что-то пошло не так")
|
"""
4. Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ...
Количество элементов (n) вводится с клавиатуры.
"""
N = int(input("Введите число"))
A_NEXT = 1
A_SUM = 1
while N > 0:
A_NEXT = A_NEXT*-0.5
A_SUM = A_SUM + A_NEXT
N -=1
print(A_SUM)
|
from typing import Optional
class PostalCode:
"""
This model represents a japanese postal code.
Postal codes in Japan are 7-digit numeric codes using the format NNN-NNNN, where N is a digit.
The first two digits refer to one of the 47 prefectures (for example, 40 for the Yamanashi Prefecture),
the next digit for one of a set of adjacent cities in the prefecture (408 for Hokuto, Yamanashi),
the next two for a neighborhood and the last two for a street in a city (408-0301 to 408-0307 for the Mukawa-cho neighborhood in Hokuto).
Source: Wikipedia, https://en.wikipedia.org/wiki/Postal_codes_in_Japan
"""
def __init__(self, postal_code: str):
self.validate_postal_code(postal_code)
self.__store_postal_code(postal_code)
def __store_postal_code(self, postal_code: str):
self.prefecture_id = int(postal_code[0:2])
self.city_id = int(postal_code[2])
self.neighborhood_id = int(postal_code[3:5])
self.street_id = int(postal_code[5:7])
def __str__(self):
return f"{self.prefecture_id}{self.city_id}-{self.neighborhood_id}{self.street_id}"
def __eq__(self, other: Optional['PostalCode']):
if other is None:
return False
if self.prefecture_id == other.prefecture_id and \
self.city_id == other.city_id and \
self.neighborhood_id == other.neighborhood_id and \
self.street_id == other.street_id:
return True
return False
@staticmethod
def validate_postal_code(postal_code: str):
if not postal_code.isdigit():
raise ValueError(f"Input postal code was not a sequence of digits: {postal_code}")
if len(postal_code) != 7:
raise ValueError(f"Input postal code was not 7 digits long: {postal_code}")
@staticmethod
def from_string(postal_code: str) -> 'PostalCode':
return PostalCode(postal_code)
|
def inout():
# simple input and output with a text file
my_file = open("text.txt") # can also put file location
# print(my_file)
print(my_file.read())
print(my_file.read()) # this does not print because the cursor is @ EOF
my_file.seek(0) # put it back to start
print(my_file.read()) # can print again
my_file.seek(0)
print(my_file.readlines())
my_file.close()
with open("text.txt") as my_new_file: # this closes the file at the end
contents = my_new_file.read()
print(contents)
with open("text.txt", mode="r") as myfile: # mode r - read; w - write; a - append; r+ = read and write; w+ - write and read [overwrites the existing file or creates a new one]
contents = myfile.read()
print(contents)
return
if __name__ == "__main__":
inout()
print("-----")
|
while True:
days = 1
start = float(input('Введите дистанцию, которую пробеает спортсмен за первый день - '))
last = float(input('Введите дистанцию, к которой готовиться спортсмен - '))
if start <= 0 or last <= 0:
print('Результаты должны быть больше нуля! Стартовое значение != 0')
else:
while start < last:
start *= 1.10
days += 1
print(f'Спрортмену нужно на подготовку к забегу {days} день(дней)')
|
a = 5
b = 4
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b) |
import numpy as np
import matplotlib.pyplot as plt
def estimateB0B1(x, y):
n = np.size(x)
averageX = np.mean(x)
averageY = np.mean(y)
sumXY = np.sum((x - averageX) * (y - averageY))
sumXX = np.sum(x * (x - averageX))
b1 = sumXY / sumXX
b0 = averageY - (b1 * averageX)
return b0, b1
def plotRegression(x, y, b):
plt.scatter(x, y, color = "g", marker = "o", s = 30)
predY = b[0] + b[1] * x
plt.plot(x, predY, color = "g")
plt.xlabel("x-Independiente")
plt.ylabel("y-Dependiente")
plt.show()
def run():
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 3, 5, 6, 5])
b = estimateB0B1(x, y)
print("Los valores de b0 = {}, b1 = {}".format(b[0], b[1]))
plotRegression(x, y, b)
if __name__ == "__main__":
run() |
keywords = {
"and": "Logical and",
"as": "Part of the with-as statement",
"assert": "Assert (ensure) that something is true",
"break": "Stop the loop right now",
"class": "Define a class",
"continue": "Don't process more of the loop, do it again",
"def": "Define a function",
"del": "Delete from dictionary",
"elif": "Else if condition",
"else": "Else condition",
"except": "If an exception happens, do this",
"exec": "Run a string as Python",
"finally": "Exceptions or not, finally do this no matter what",
"for": "Loop over a collection of things",
"from": "Import specific parts of a module",
"global": "Declare that you want a global variable",
"if": "If condition",
"import": "Import a module into this one to use",
"in": "Part of for-loops, also a test of X in Y",
"is": "Like == to test equality",
"lambda": "Create a short anonimous function",
"not": "Logical not",
"or": "Logical or",
"pass": "This block is empty",
"print": "Print this string",
"raise": "Raise an exception when things go wrong",
"return": "Exit the function with a return value",
"try": "Try this block, and if exception, go to except",
"while": "While loop",
"with": "With a expression as a variable do",
"yield": "Pause here and return to caller"
}
points = 0
for keyword, description in list(keywords.items()):
print(f"{description}:", end=' ')
answer = input()
if answer == keyword:
points += 1
else:
print("WRONG")
print(f"Correct answer is: '{keyword}''")
print("Press ENTER to continue...")
input()
print(f"Your score: {points}/{len(keywords)}") |
"""
Implement a Circular Array class.
"""
class CircularArray:
def __init__(self):
self.head = 0
self.data = []
self.max_iter = 100
def append(self, item):
self.data.append(item)
def extend(self, items):
for item in items:
self.data.append(item)
def __iter__(self):
return self
def __next__(self):
self.head += 1
self.head = self.head % len(self.data)
return self.data[self.head]
if __name__ == "__main__":
ca = CircularArray()
ca.extend(list(range(10)))
for i in range(20):
print(next(ca))
|
import numpy as np
class Suit:
def __init__(self, v):
self.suit_map = {0:"Club", 1:"Diamond", 2:"Heart", 3:"Spade"}
self.value = v
def getValue(self):
return self.value
def getSuitFromValue(self, value):
return self.suit_map[value]
class Deck:
def __init__(self, deckOfCards):
self.cards = []
self.dealtIndex = 0
self.setDeckOfCards(deckOfCards)
self.shuffle()
def setDeckOfCards(self, deckOfCards):
self.cards = deckOfCards
def shuffle(self):
np.random.shuffle(self.cards)
def remainingCards(self):
return len(self.cards)-self.dealtIndex
def dealHand(self, number):
pass
def dealCard(self):
if self.cards:
return self.cards.pop()
else:
print("Empty deck of cards.")
return None
pass
class Card:
def __init__(self, c, s):
self.available = True
self.faceValue = c
self.suit = s
def value(self):
return self.faceValue
def suit(self):
return self.suit
def isAvailable(self):
return self.available
def markUnavailable(self):
self.available = False
def markAvailable(self):
self.available = True
class Hand:
def __init__(self):
self.cards = []
def score(self):
self.score = 0
for card in self.cards:
self.score += card.value()
return self.score
def addCard(self, card):
self.cards.append(card) |
from numpy import random
class Card:
def __init__(self, family, value):
self.family = family
self.value = value
def __str__(self):
if self.value == 1:
value_desc = "As"
elif self.value <= 10:
value_desc = str(self.value)
else:
value_dict = {11:"Valet", 12:"Reine", 13:"Roi"}
value_desc = value_dict[self.value]
family_dict = {1:"Pique", 2:"Coeur", 3:"Trefle", 4:"Carreau"}
family_desc = family_dict[self.family]
return "{} de {}".format(value_desc, family_desc)
class Deck:
def __init__(self):
print('Creation of a new deck of cards')
self.pile = self.createFullSet()
def pop(self):
if not self.pile:
print('The pile is empty...')
return None
else:
return self.pile.pop()
def createFullSet(self):
self.pile = []
for fam in range(1, 5):
for value in range(0, 13):
self.pile.append(Card(fam, value))
return self.pile
def shuffle(self):
random.shuffle(self.pile)
class Player:
def __init__(self, name):
self.name = name
self.hand = set()
def receiveCard(self, card):
self.hand.add(card)
def removeCard(self, card):
self.hand.discard(card)
return card
if __name__ == '__main__':
alice = Player("alice")
bob = Player("bob")
deck = Deck()
deck.shuffle()
for i in range(2):
alice.receiveCard(deck.pop())
bob.receiveCard(deck.pop())
for card in alice.hand:
print(card) |
from queue import deque
class BasicNode:
def __init__(self, level):
self.level = level
self.isAvailable = True
self.parent = None
def setParent(self, node):
self.parent = node
def getParent(self):
return self.parent
class CallPool:
def __init__(self):
self.pool = deque()
director = BasicNode(level="Director")
for _ in range(3):
manager = BasicNode("Manager")
manager.setParent(director)
for _ in range(3):
respondent = BasicNode("Respondent")
respondent.setParent(manager)
self.pool.append(respondent)
def incomingCall(self):
print('A call is incoming...')
interlocutor = self.pool.pop()
if interlocutor.isAvailable:
interlocutor.isAvailable = False
self.pool.appendleft(interlocutor)
print('Respondent has been reached')
else:
if interlocutor.parent.isAvailable:
print('Manager has been reached')
# TODO: Should recursively go up in the tree to get the closer hierarchical parent
pass
if __name__ == "__main__":
callCenter = CallPool()
|
"""
Partition
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
def partition(node, x):
head = node
tail = node
while node:
next = node.next
if node.data < x:
node.next = head
head = node
else:
tail.next = node
tail = node
node = next
tail.next = None
return head
if __name__ == "__main__":
values = [8, 3, 2, 1, 4, 9, 19]
nodes = []
for v in values:
node = Node(v)
nodes.append(node)
for i in range(len(nodes)-1):
nodes[i].next = nodes[i+1]
head = partition(nodes[0], 5)
node = head
while node:
print(node.data)
node = node.next |
"""
Chapter 4: Trees and Graph
Question 2: Minimal Tree
"""
import networkx as nx
import pdb
import random
from collections import defaultdict
import matplotlib.pyplot as plt
class TreeNode:
def __init__(self, val):
self.value = val
self.left = None
self.right = None
def build_bst(array):
n = len(array)
if n == 0:
return None
middle = n//2
node = TreeNode(array[middle])
node.left = build_bst(array[:middle])
node.right = build_bst(array[middle+1:])
return node
def graph_from_tree(node, graph):
if node:
if not graph:
graph = defaultdict(set)
if node.left:
graph[node.value].add(node.left.value)
graph_from_tree(node.left, graph)
if node.right:
graph[node.value].add(node.right.value)
graph_from_tree(node.right, graph)
return graph
def visualise_graph(graph):
G = nx.Graph()
for source in graph:
for target in graph[source]:
G.add_edges_from([(source, target)])
nx.draw(G, with_labels=True, node_color="red")
plt.axis('off')
plt.show()
if __name__ == "__main__":
array = [i for i in range(2**4-1)]
tree = build_bst(array)
graph = graph_from_tree(tree, None)
visualise_graph(graph)
|
"""
Implement the Jigsaw game.
"""
import random
class Board:
def __init__(self):
self.board = list(range(9))
self.board[-1] = "X"
self.empty_pos = (2, 2)
print("Create an empty board")
print(self)
def __repr__(self):
string = ""
line = " ______"
for i in range(3):
string += line+"\n"
string += "|{}|{}|{}|".format(*self.board[i*3:(i+1)*3])+"\n"
string += line +"\n"
return string
def get_pos(self, i):
return (i//3, i%3)
def get_index(self, pos):
return pos[0]*3+pos[1]
def is_valid_swap(self, tuple1, tuple2):
dx, dy = abs(tuple1[0]-tuple2[0]), abs(tuple1[1]-tuple2[1])
dx, dy = sorted([dx, dy])
return dx == 0 and dy == 1
def is_valid_pos(self, tuple):
return 0<=tuple[0]<3 and 0<=tuple[1]<3
def swap(self, i, j):
if not (self.board[i] == "X" or self.board[j] == "X"):
print("Trying to swap non empty tiles")
return False
if not 0<=i<9 or not 0<=j<9:
print('Invalid swap')
return False
t1, t2 = self.get_pos(i), self.get_pos(j)
if not self.is_valid_swap(t1, t2):
print("Invalid swap")
return False
self.board[i], self.board[j] = self.board[j], self.board[i]
def get_swap_empty_index(self):
# find empty position
index_empty = 0
while self.board[index_empty] != "X":
index_empty += 1
pos_empty = self.get_pos(index_empty)
pos = []
for i,j in [(1,0), (-1,0), (0,1), (0,-1)]:
potential_pos = (pos_empty[0]+i, pos_empty[1]+j)
if self.is_valid_pos(potential_pos):
pos.append(potential_pos)
return [self.get_index(p) for p in pos]
def get_empty_index(self):
index = random.randint(0, 8)
while self.board[index] != "X":
index += 1
index = index % 9
return index
if __name__ == "__main__":
board = Board()
for i in range(100000):
empty_index = board.get_empty_index()
moves = board.get_swap_empty_index()
index_move = random.randint(0, len(moves)-1)
board.swap(empty_index, moves[index_move])
print(board) |
def generateParens(remaining):
S = set()
if remaining == 0:
S.add("")
else:
prev = generateParens(remaining-1)
for string in prev:
for i in range(0, len(string)):
if string[i] == "(":
s = insertInside(string, i)
S.add(s)
S.add("()"+string)
return S
def insertInside(string, leftIndex):
left = string[0:leftIndex+1]
right = string[leftIndex+1: len(string)]
return left + "()" + right
if __name__ == "__main__":
print(generateParens(3)) |
class Salary:
def __init__(self, pay, reward):
self.pay = pay
self.reward = reward
def annual_salary(self):
return (self.pay * 12) + self.reward
class Employee:
def __init__(self, name, position, sal):
self.name = name
self.position = position
self.final_salary = sal
def final_salary_m(self):
return self.final_salary.annual_salary()
def display(self):
print("Your Name: ", self.name)
print("Position: ", self.position)
sal = Salary(120000, 20000)
emp = Employee("Sarosh", "Backend Dev", sal)
emp.display()
print(emp.final_salary_m())
|
# def function_name_print(a, b, c, d):
# print(a, b, c, d)
# function_name_print("Sarosh", "Faraz", "Atiq", "Sabiha")
def funargs(owner, *args, **kwargs):
print("Normal Arguments")
print(owner)
print("Printing arguments (*args)")
for name in args:
print(name)
print("Printing **kwargs")
for key, value in kwargs.items():
print(f"{key} is a {value}")
names = ["Sarosh", "Faraz", "Atiq", "Sabiha"]
owner = "sarosh1"
kw = {"Sarosh": "Programmer", "Faraz": "Doctor", "Daddy": "Advocate"}
funargs(owner, *names, **kw)
|
class Polygon:
__width = None
__height = None
def set_value(self, width, height):
self.__width = width
self.__height = height
def get_width(self):
return self.__width
def get_height(self):
return self.__height
class Square (Polygon):
def area(self):
return self.get_width() * self.get_height()
class Triangle(Polygon):
def area(self):
return self.get_width() * self.get_height() * 1/2
s1 = Square()
s1.set_value(10, 20)
print(s1.area())
t1 = Triangle()
t1.set_value(11, 10)
print(t1.area()) |
'''
converter.py: test suite for converter class
This test can be run using PyUnit's test discovery from the comment line.
> cd project_directory
> python -m unittest discover
NB. For the sake of simplicity we are only testing the conversion of a single
unit value. Were this real production code it would probably be an idea to
add some auto-generated data tests that test a range of values for each unit
type and check that the conversion process was successful. For the purposes
of this coding exercise I believe that this is adequate to demonstrate my
general appreciation for writing unit tests using PyUnit.
'''
import unittest
import unitconverter
class ConverterTestCase(unittest.TestCase):
def setUp(self):
self.__converter = unitconverter.Converter()
def testFromMetresToYards(self):
self.assertEquals('1.0936133 yd', self.__converter.convert('1 m to yd'))
self.assertEquals('1.0936133 yard', self.__converter.convert('1 m to yard'))
self.assertEquals('1.0936133 yards', self.__converter.convert('1 m to yards'))
self.assertEquals('1.0936133 yd', self.__converter.convert('1 meter to yd'))
self.assertEquals('1.0936133 yard', self.__converter.convert('1 meter to yard'))
self.assertEquals('1.0936133 yards', self.__converter.convert('1 meter to yards'))
self.assertEquals('1.0936133 yd', self.__converter.convert('1 metre to yd'))
self.assertEquals('1.0936133 yard', self.__converter.convert('1 metre to yard'))
self.assertEquals('1.0936133 yards', self.__converter.convert('1 metre to yards'))
self.assertEquals('1.0936133 yd', self.__converter.convert('1 meters to yd'))
self.assertEquals('1.0936133 yard', self.__converter.convert('1 meters to yard'))
self.assertEquals('1.0936133 yd', self.__converter.convert('1 metres to yd'))
self.assertEquals('1.0936133 yard', self.__converter.convert('1 metres to yard'))
self.assertEquals('1.0936133 yards', self.__converter.convert('1 metres to yards'))
def testFromMetresToInches(self):
self.assertEquals('39.3700787 in', self.__converter.convert('1 m to in'))
self.assertEquals('39.3700787 inch', self.__converter.convert('1 m to inch'))
self.assertEquals('39.3700787 inches', self.__converter.convert('1 m to inches'))
self.assertEquals('39.3700787 in', self.__converter.convert('1 meter to in'))
self.assertEquals('39.3700787 inch', self.__converter.convert('1 meter to inch'))
self.assertEquals('39.3700787 inches', self.__converter.convert('1 meter to inches'))
self.assertEquals('39.3700787 in', self.__converter.convert('1 metre to in'))
self.assertEquals('39.3700787 inch', self.__converter.convert('1 metre to inch'))
self.assertEquals('39.3700787 inches', self.__converter.convert('1 metre to inches'))
self.assertEquals('39.3700787 in', self.__converter.convert('1 meters to in'))
self.assertEquals('39.3700787 inch', self.__converter.convert('1 meters to inch'))
self.assertEquals('39.3700787 inches', self.__converter.convert('1 meters to inches'))
self.assertEquals('39.3700787 in', self.__converter.convert('1 metres to in'))
self.assertEquals('39.3700787 inch', self.__converter.convert('1 metres to inch'))
self.assertEquals('39.3700787 inches', self.__converter.convert('1 metres to inches'))
def testFromYardsToInches(self):
self.assertEquals('36.0 in', self.__converter.convert('1 yd to in'))
self.assertEquals('36.0 inch', self.__converter.convert('1 yd to inch'))
self.assertEquals('36.0 inches', self.__converter.convert('1 yd to inches'))
self.assertEquals('36.0 in', self.__converter.convert('1 yard to in'))
self.assertEquals('36.0 inch', self.__converter.convert('1 yard to inch'))
self.assertEquals('36.0 inches', self.__converter.convert('1 yard to inches'))
self.assertEquals('36.0 in', self.__converter.convert('1 yards to in'))
self.assertEquals('36.0 inch', self.__converter.convert('1 yards to inch'))
self.assertEquals('36.0 inches', self.__converter.convert('1 yards to inches'))
def testFromYardsToMetress(self):
self.assertEquals('0.9144 m', self.__converter.convert('1 yd to m'))
self.assertEquals('0.9144 meter', self.__converter.convert('1 yd to meter'))
self.assertEquals('0.9144 metre', self.__converter.convert('1 yd to metre'))
self.assertEquals('0.9144 meters', self.__converter.convert('1 yd to meters'))
self.assertEquals('0.9144 metres', self.__converter.convert('1 yd to metres'))
self.assertEquals('0.9144 m', self.__converter.convert('1 yard to m'))
self.assertEquals('0.9144 meter', self.__converter.convert('1 yard to meter'))
self.assertEquals('0.9144 metre', self.__converter.convert('1 yard to metre'))
self.assertEquals('0.9144 meters', self.__converter.convert('1 yard to meters'))
self.assertEquals('0.9144 metres', self.__converter.convert('1 yard to metres'))
self.assertEquals('0.9144 m', self.__converter.convert('1 yards to m'))
self.assertEquals('0.9144 meter', self.__converter.convert('1 yards to meter'))
self.assertEquals('0.9144 metre', self.__converter.convert('1 yards to metre'))
self.assertEquals('0.9144 meters', self.__converter.convert('1 yards to meters'))
self.assertEquals('0.9144 metres', self.__converter.convert('1 yards to metres'))
def testFromInchesToYards(self):
self.assertEquals('0.0277778 yd', self.__converter.convert('1 in to yd'))
self.assertEquals('0.0277778 yard', self.__converter.convert('1 in to yard'))
self.assertEquals('0.0277778 yards', self.__converter.convert('1 in to yards'))
self.assertEquals('0.0277778 yd', self.__converter.convert('1 inch to yd'))
self.assertEquals('0.0277778 yard', self.__converter.convert('1 inch to yard'))
self.assertEquals('0.0277778 yards', self.__converter.convert('1 inch to yards'))
self.assertEquals('0.0277778 yd', self.__converter.convert('1 inches to yd'))
self.assertEquals('0.0277778 yard', self.__converter.convert('1 inches to yard'))
self.assertEquals('0.0277778 yards', self.__converter.convert('1 inches to yards'))
def testFromInchesToMetress(self):
self.assertEquals('0.0254 m', self.__converter.convert('1 in to m'))
self.assertEquals('0.0254 meter', self.__converter.convert('1 in to meter'))
self.assertEquals('0.0254 metre', self.__converter.convert('1 in to metre'))
self.assertEquals('0.0254 meters', self.__converter.convert('1 in to meters'))
self.assertEquals('0.0254 metres', self.__converter.convert('1 in to metres'))
self.assertEquals('0.0254 m', self.__converter.convert('1 inch to m'))
self.assertEquals('0.0254 meter', self.__converter.convert('1 inch to meter'))
self.assertEquals('0.0254 metre', self.__converter.convert('1 inch to metre'))
self.assertEquals('0.0254 meters', self.__converter.convert('1 inch to meters'))
self.assertEquals('0.0254 metres', self.__converter.convert('1 inch to metres'))
self.assertEquals('0.0254 m', self.__converter.convert('1 inches to m'))
self.assertEquals('0.0254 meter', self.__converter.convert('1 inches to meter'))
self.assertEquals('0.0254 metre', self.__converter.convert('1 inches to metre'))
self.assertEquals('0.0254 meters', self.__converter.convert('1 inches to meters'))
self.assertEquals('0.0254 metres', self.__converter.convert('1 inches to metres'))
def testFromMetresToYardsMixedCase(self):
self.assertEquals('1.0936133 yd', self.__converter.convert('1 M to Yd'))
self.assertEquals('1.0936133 yard', self.__converter.convert('1 M to Yard'))
self.assertEquals('1.0936133 yards', self.__converter.convert('1 M to Yards'))
self.assertEquals('1.0936133 yd', self.__converter.convert('1 Meter to Yd'))
self.assertEquals('1.0936133 yard', self.__converter.convert('1 Meter to Yard'))
self.assertEquals('1.0936133 yards', self.__converter.convert('1 Meter to Yards'))
self.assertEquals('1.0936133 yd', self.__converter.convert('1 Metre to Yd'))
self.assertEquals('1.0936133 yard', self.__converter.convert('1 Metre to Yard'))
self.assertEquals('1.0936133 yards', self.__converter.convert('1 Metre to Yards'))
self.assertEquals('1.0936133 yd', self.__converter.convert('1 Meters to Yd'))
self.assertEquals('1.0936133 yard', self.__converter.convert('1 Meters to Yard'))
self.assertEquals('1.0936133 yd', self.__converter.convert('1 Metres to Yd'))
self.assertEquals('1.0936133 yard', self.__converter.convert('1 Metres to Yard'))
self.assertEquals('1.0936133 yards', self.__converter.convert('1 Metres to Yards'))
def testFromMetresToInchesMixedCase(self):
self.assertEquals('39.3700787 in', self.__converter.convert('1 M to In'))
self.assertEquals('39.3700787 inch', self.__converter.convert('1 M to Inch'))
self.assertEquals('39.3700787 inches', self.__converter.convert('1 M to Inches'))
self.assertEquals('39.3700787 in', self.__converter.convert('1 Meter to In'))
self.assertEquals('39.3700787 inch', self.__converter.convert('1 Meter to Inch'))
self.assertEquals('39.3700787 inches', self.__converter.convert('1 Meter to Inches'))
self.assertEquals('39.3700787 in', self.__converter.convert('1 Metre to In'))
self.assertEquals('39.3700787 inch', self.__converter.convert('1 Metre to Inch'))
self.assertEquals('39.3700787 inches', self.__converter.convert('1 Metre to Inches'))
self.assertEquals('39.3700787 in', self.__converter.convert('1 Meters to In'))
self.assertEquals('39.3700787 inch', self.__converter.convert('1 Meters to Inch'))
self.assertEquals('39.3700787 inches', self.__converter.convert('1 Meters to Inches'))
self.assertEquals('39.3700787 in', self.__converter.convert('1 Metres to In'))
self.assertEquals('39.3700787 inch', self.__converter.convert('1 Metres to Inch'))
self.assertEquals('39.3700787 inches', self.__converter.convert('1 Metres to Inches'))
def testFromYardsToInchesMixedCase(self):
self.assertEquals('36.0 in', self.__converter.convert('1 yd to In'))
self.assertEquals('36.0 inch', self.__converter.convert('1 yd to Inch'))
self.assertEquals('36.0 inches', self.__converter.convert('1 yd to Inches'))
self.assertEquals('36.0 in', self.__converter.convert('1 yard to In'))
self.assertEquals('36.0 inch', self.__converter.convert('1 yard to Inch'))
self.assertEquals('36.0 inches', self.__converter.convert('1 yard to Inches'))
self.assertEquals('36.0 in', self.__converter.convert('1 yards to In'))
self.assertEquals('36.0 inch', self.__converter.convert('1 yards to Inch'))
self.assertEquals('36.0 inches', self.__converter.convert('1 yards to Inches'))
def testFromYardsToMetressMixedCase(self):
self.assertEquals('0.9144 m', self.__converter.convert('1 yd to M'))
self.assertEquals('0.9144 meter', self.__converter.convert('1 yd to Meter'))
self.assertEquals('0.9144 metre', self.__converter.convert('1 yd to Metre'))
self.assertEquals('0.9144 meters', self.__converter.convert('1 yd to Meters'))
self.assertEquals('0.9144 metres', self.__converter.convert('1 yd to Metres'))
self.assertEquals('0.9144 m', self.__converter.convert('1 yard to M'))
self.assertEquals('0.9144 meter', self.__converter.convert('1 yard to Meter'))
self.assertEquals('0.9144 metre', self.__converter.convert('1 yard to Metre'))
self.assertEquals('0.9144 meters', self.__converter.convert('1 yard to Meters'))
self.assertEquals('0.9144 metres', self.__converter.convert('1 yard to Metres'))
self.assertEquals('0.9144 m', self.__converter.convert('1 yards to M'))
self.assertEquals('0.9144 meter', self.__converter.convert('1 yards to Meter'))
self.assertEquals('0.9144 metre', self.__converter.convert('1 yards to Metre'))
self.assertEquals('0.9144 meters', self.__converter.convert('1 yards to Meters'))
self.assertEquals('0.9144 metres', self.__converter.convert('1 yards to Metres'))
def testFromInchesToYardsMixedCase(self):
self.assertEquals('0.0277778 yd', self.__converter.convert('1 In to Yd'))
self.assertEquals('0.0277778 yard', self.__converter.convert('1 In to Yard'))
self.assertEquals('0.0277778 yards', self.__converter.convert('1 In to Yards'))
self.assertEquals('0.0277778 yd', self.__converter.convert('1 Inch to Yd'))
self.assertEquals('0.0277778 yard', self.__converter.convert('1 Inch to Yard'))
self.assertEquals('0.0277778 yards', self.__converter.convert('1 Inch to Yards'))
self.assertEquals('0.0277778 yd', self.__converter.convert('1 Inches to Yd'))
self.assertEquals('0.0277778 yard', self.__converter.convert('1 Inches to Yard'))
self.assertEquals('0.0277778 yards', self.__converter.convert('1 Inches to Yards'))
def testFromInchesToMetressMixedCase(self):
self.assertEquals('0.0254 m', self.__converter.convert('1 In to M'))
self.assertEquals('0.0254 meter', self.__converter.convert('1 In to Meter'))
self.assertEquals('0.0254 metre', self.__converter.convert('1 In to Metre'))
self.assertEquals('0.0254 meters', self.__converter.convert('1 In to Meters'))
self.assertEquals('0.0254 metres', self.__converter.convert('1 In to Metres'))
self.assertEquals('0.0254 m', self.__converter.convert('1 Inch to M'))
self.assertEquals('0.0254 meter', self.__converter.convert('1 Inch to Meter'))
self.assertEquals('0.0254 metre', self.__converter.convert('1 Inch to Metre'))
self.assertEquals('0.0254 meters', self.__converter.convert('1 Inch to Meters'))
self.assertEquals('0.0254 metres', self.__converter.convert('1 Inch to Metres'))
self.assertEquals('0.0254 m', self.__converter.convert('1 Inches to M'))
self.assertEquals('0.0254 meter', self.__converter.convert('1 Inches to Meter'))
self.assertEquals('0.0254 metre', self.__converter.convert('1 Inches to Metre'))
self.assertEquals('0.0254 meters', self.__converter.convert('1 Inches to Meters'))
self.assertEquals('0.0254 metres', self.__converter.convert('1 Inches to Metres'))
|
"""
list and tuplas exercise
#exercicio 1
A= ['1', '0', '5', '-2', '-5', '7']
soma = A[0]+A[1]+A[5]
A[4]=100
#print(soma)
for i in A:
print(i)
#exercicio 2
vetor = ['']
for x in range(0,6):
n=int(input('Digite um valor:\n'))
vetor.append(n)
for valor in vetor:
print(valor)
#exercicio 3
dado = ['']
result = ['']
for x in range(0, 10):
valor = int(input('digite um valor real\n'))
# calcula o quadrado de todo valor informado via teclado
quadrado = valor ** 2
dado.append(valor)
result.append(quadrado)
for numero in dado:
print(numero)
for numero in result:
print(numero)
#exercicio 4
vetor = []
for x in range(0,8):
valor = int(input('digite um valor'))
vetor.append(valor)
x=int(input())
y=int(input())
resultado = vetor[x]+vetor[y]
print(f'o resultado da soma da posição {x}={vetor[x]} + {y}={vetor[y]} = {resultado}')
********************
# exercico 5
#exercico 6
vetor = []
for x in range(0, 10):
valor = int(input('digite um valor real\n'))
vetor.append(valor)
print(f'Minimo: {min(vetor)}')
print(f'Maximo: {max(vetor)}')
#exerccio 7
vetor = []
for x in range(0, 3):
valor = int(input('digite um valor real\n'))
vetor.append(valor)
maximo = max(vetor)
print(f'o maior elemento :{maximo}')
print(f'index : {vetor.index(maximo)}')
print('o vetor é :')
for x,y in enumerate(vetor):
print(f'index:{x} valor :{y}')
#exercicio 8:
vetor = []
while len(vetor) < 6:
x = int(input('digite um valor:'))
vetor.append(x)
for i in range(5, 0 , -1):
print(vetor[i])
exercicio 10
notas = []
soma = 0
while len(notas) < 15:
nota = int(input('Digite a nota do aluno:'))
notas.append(nota)
for x in notas:
soma +=x
print(f'A media dos alunos é {soma/15}')
#exercicio 11
vetor = []
somaN = 0
somaP = 0
while len(vetor) < 10:
nota = int(input('Digite um numero:'))
if nota < 0 :
somaN += 1
else:
somaP += nota
vetor.append(nota)
print(f"a soma dos numeroas positivos desse vetor é {somaP} e a ")
print(f"quantidade de numeros negativos é {somaN}")
#exercicio 13
vetor = []
while len(vetor) < 5:
nota = int(input('Digite um numero:'))
vetor.append(nota)
maior = max(vetor)
menor = min(vetor)
print(f' O maior numero esta no indice :{vetor.index(maior)}')
print(f' O maior numero esta no indice :{vetor.index(menor)}')
exercicio 14
vetor = []
rep = []
while len(vetor) < 10:
nota = int(input('Digite um numero:'))
vetor.append(nota)
for numeros in vetor:
quantas_vezes = vetor.count(numeros)
if numeros in rep:
continue
if quantas_vezes > 1:
print('Os valores repetidos neste vetor é:')
print(f'{numeros}, {quantas_vezes} vezes')
rep.append(numeros)
#exercicio 15
vetor = []
while len(vetor) < 20:
valor = int(input('digite um valor'))
vetor.append(valor)
x = set(vetor)
for i in x:
print(i)
exercicio 16
vetor = []
op = 0
while len(vetor) < 5:
valor = int(input('Valor:'))
vetor.append(valor)
while True:
x = 'oi'
while True:
try:
op = int(input('Dite um valor'))
except:
print('Digite um inteiro')
if type(op) == int:
break
if op == 0:
print('saindo...')
break
elif op == 1:
for x in vetor:
print(x)
elif op == 2:
for num in range(4,0-1,-1):
print(vetor[num])
else:
print('codigo invalido!')
exercicio 17
vetor = []
while len(vetor) < 10:
x = int(input('Digite um valor:'))
if x < 0:
vetor.append(0)
else:
vetor.append(x)
print(vetor[::])
#exercicio 19
vetor = []
for x in range(0,51):
i = x
valor = (i+5*i)%(i+1)
vetor.append(valor)
for indice,valor in enumerate(vetor):
print(f'valor:{valor} indice:{indice}')
#exercicio 20
A = []
B = []
resultado = []
def preencher(nome,name):
print(f'Preencha o Vetor {name}: \n')
while len(nome) < 10:
dado = int(input('Digite um valor:'))
nome.append(dado)
preencher(A,'A')
preencher(B,'B')
for i in range(0,9+1):
valor = A[i] * B[i]
resultado.append(valor)
print(resultado[::])
#exercicio 24
A = []
B = []
resul = 0
def preencher(nome,name):
print(f'Preencha o Vetor {name}: \n')
while len(nome) < 5:
dado = int(input('Digite um valor:'))
nome.append(dado)
preencher(A,'A')
preencher(B,'B')
for x in range(0,4):
resul += (A[x]*B[x])
print(resul)
exercio 24
aluno = {}
while len(aluno) < 10:
numero = int(input('Digite o numero do aluno:'))
altura = float(input('Digite a altura do aluno:'))
aluno.update({altura:numero})
print(f'O menor(-) aluno é o numero {aluno.get(min(aluno))}, Com altura de {min(aluno)} M')
print(f'O Maior(+) aluno é o numero {aluno.get(max(aluno))}, Com altura de {max(aluno)} M')
#exercicio 25
a = []
numero = 0
letra = ''
while len(a) < 100:
if numero < 10:
if numero % 7 == 0:
numero += 1
continue
else:
a.append(numero)
numero += 1
else:
letra = str(numero)
if numero % 7 == 0 or letra[1] == '7':
numero += 1
continue
else:
a.append(numero)
numero += 1
print(a)
#exercicio 28
v = []
v1 = []
v2 = []
while len(v) < 10:
valor = int(input('Digite o valor:'))
v.append(valor)
if valor % 2 == 1:
v1.append(valor)
elif valor % 2 == 0:
v2.append(valor)
for x in v1:
print(f'impar {x}')
for x in v2:
print(f'par {x}')
exercicio 29
vetor = []
num_pares = 0
soma_pares = 0
num_impares = 0
soma_impares = 0
while len(vetor) < 6:
valor = int(input('Digite o valor:'))
vetor.append(valor)
if valor % 2 == 0:
num_pares += 1
soma_pares += valor
elif valor % 2 == 1:
num_impares += 1
soma_impares += valor
print(f' N impates: {num_impares} soma dos impares: {soma_impares}')
print(f'N pares {num_pares} soma dos pares {soma_pares}')
exercicio 31
etor1 = []
vetor2 = []
while len(vetor1) < 3:
valor = int(input('Digite o valor:'))
vetor1.append(valor)
while len(vetor2) < 3:
valor = int(input('Digite o valor:'))
vetor2.append(valor)
uniao = set(vetor1).union(vetor2)
print(uniao)
x = []
y = []
soma = 0
uniao = 0
multi = 0
dife = 0
while len(x) < 5:
valor = int(input('Digite o valor:'))
x.append(valor)
while len(y) < 5:
valor = int(input('Digite o valor:'))
y.append(valor)
for indice in range(0,5):
soma += x[indice] + y[indice]
multi += x[indice] * y[indice]
dife += x[indice] - y[indice]
uniao = set(x).union(y)
ambos = set(x).intersection(y)
print(soma)
print(multi)
print(dife)
print(uniao)
print(ambos)
exercicio 33
vetor = []
i=0
while len(vetor) < 15:
x = int(input("digite um valor"))
vetor.append(x)
while 0 in vetor:
if vetor[i] == 0:
vetor.pop(i)
i+=1
print(vetor)
exercicio 34
vetor = []
while len(vetor) < 10:
x = int(input("digite um valor"))
if x in vetor:
print('Digite um novo valor!')
continue
else:
vetor.append(x)
print(vetor)
a = []
b = []
mais = []
op=False
soamtoria = 0
while op != True:
valora = int(input('digite um valor < 10000 A:\n'))
valorb = int(input('digite um valor < 10000 B:\n'))
if valora < 10000 and valorb < 10000:
a = list(str(valora))
b = list(str(valorb))
if len(a) > len(b):
while len(b) != len(a):
dado= 0
b.append(dado)
if len(b) > len(a):
while len(a) != len(b):
dado= 0
a.append(dado)
if len(a)==len(b):
for i in range(0,len(a)):
s= i
soma = int(a[i]) + int(b[i])
if mais == [ ]:
if soma > 10:
soma = soma - 10
colocar = 1
mais.append(colocar)
soamtoria += soma
elif mais[s-1] == 1:
soma += 1
s=s+1
print(soamtoria)
else:
print('valor invalido')
continue
vetor = []
while len(vetor) < 10:
x = int(input('digite um valor'))
vetor.append(x)
vetor.sort()
print(vetor)
exercicio 37
vetor = []
ordem = []
while len(vetor) < 11:
x = int(input('digite um valor'))
vetor.append(x)
vetor.sort()
for i in range(11-1,5,-1):
ordem.append(vetor[i])
print(vetor[0:6]+ordem)
exercicio 38
vetor = []
while len(vetor) < 10:
x = int(input('digite o valor'))
vetor.append(x)
vetor.sort()
print(vetor)
PARTE 2 MATRIZES
$exercicio 1
vetor= [
[], [], [], [],
]
dez= []
for i in range(0,4):
while len(vetor[i]) < 4 :
x = int(input('digite um valor:'))
if x > 10:
dez.append(x)
vetor[i].append(x)
print(vetor)
print(f'a quantidade de numeros maiores que 10 nessa matriz é {len(dez)}')
print()
for i in range(0,4):
print(vetor[i])
exercicio 3
vetor= [
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
]
for linha in range(0,4):
for coluna in range(0,4):
dado = linha * coluna
vetor[linha][coluna]=dado
print(vetor)
exercicio 4
vetor= [
[], [], [], [],
]
maior = 0
for i in range(0,4):
while len(vetor[i]) < 4 :
x = int(input('digite um valor:'))
if x > maior:
maior = x
lin = i
col = len(vetor[i])
vetor[i].append(x)
print(vetor)
for i in range(0,4):
print(vetor[i])
print(f'o maior numero é {maior} e a localização linha: {lin} coluna:{col}')
exercicio 5
vetor= [
[], [], [], [],[],
]
maior = 0
for i in range(0,4+1):
while len(vetor[i]) < 4+1 :
x = int(input('digite um valor:'))
if x > maior:
maior = x
lin = i
col = len(vetor[i])
vetor[i].append(x)
print(vetor)
tem = False
dado = int(input('DIgite o valor a ser pesqusiado:'))
for i in range(0,4+1):
if dado in vetor[i]:
print( vetor[i].index(dado))
tem = True
linha = i
col = vetor[i].index(dado)
if tem ==True:
print(f'A matriz contem o valor {dado}. ele esta localizado na linha {linha+1} colua {col+1}')
for i in range(0,4+1):
print(vetor[i])
"""
|
"""calculator.py
Using our arithmetic.py file from Exercise02, create the
calculator program yourself in this file.
"""
from arithmetic import *
while True:
user_input = raw_input("> ")
tokens = user_input.split()
arg3 = ["+", "-", "*", "/", "pow", "mod"]
arg2 = ["square", "cube"]
if ((tokens[0] in arg3 and len(tokens) < 3) or
(tokens[0] in arg2 and len(tokens) != 2)):
print("Wrong number of arguments")
continue
if tokens[0] == "+":
print('{0:.2f}'.format(reduce((lambda x,y: add(int(x), int(y))), tokens[1:])))
elif tokens[0] == "-":
print('{0:.2f}'.format(reduce((lambda x,y: subtract(int(x), int(y))), tokens[1:])))
elif tokens[0] == "*":
print('{0:.2f}'.format(reduce((lambda x,y: multiply(int(x), int(y))), tokens[1:])))
elif tokens[0] == "/":
print('{0:.2f}'.format(reduce((lambda x,y: divide(int(x), int(y))), tokens[1:])))
elif tokens[0] == "square":
print('{0:.2f}'.format(square(int(tokens[1]))))
elif tokens[0] == "cube":
print('{0:.2f}'.format(cube(int(tokens[1]))))
elif tokens[0] == "pow":
print('{0:.2f}'.format(reduce((lambda x,y: power(int(x), int(y))), tokens[1:])))
elif tokens[0] == "mod":
print('{0:.2f}'.format(reduce((lambda x,y: mod(int(x), int(y))), tokens[1:])))
elif tokens[0].lower() == "q":
break
else:
print("I don\'t understand")
|
def primes():
p = [2,3,5,7,11,13,17,19]
for i in p:
yield i
def primes_again():
prime_gen = primes()
for prime_number in prime_gen:
yield prime_number
if __name__ == '__main__':
primes_again_gen = primes_again()
for i in primes_again_gen:
print(i)
|
def multi(n):
sum3 = 0
sum5 = 0
for i in range(n):
if i % 3 == 0:
sum3 += i
elif i % 5 == 0:
sum5 += i
print(sum3 + sum5)
multi(1000)
|
print('Nomor 2, Class Ikan')
class Ikan():
'Ikan adalah hewan yang hidup di air'
jumlah=0
def __init__ (self, nama_ikan, jenis_ikan, umur_ikan, ukuran_ikan, harga):
self.nama_ikan = nama_ikan
self.jenis_ikan = jenis_ikan
self.umur_ikan = umur_ikan
self.ukuran_ikan = ukuran_ikan
self.harga = harga
Ikan.jumlah += 1
def set_harga(self, harga_baru):
self.harga = harga_baru
def get_harga(self):
return self.harga
def total_ikan(self):
return Ikan.jumlah
Ikan1 = Ikan('Anu','Lohan','12 Bulan','20 cm','100000')
Ikan2 = Ikan('Ane','Koi','2 Bulan', '10 cm','40000')
Ikan3 = Ikan('Ola','Cupang','5 Bulan','5 cm','25000')
Ikan1.set_harga('120000')
print('Harga Ikan2 : ',Ikan2.get_harga())
print('Jumlah dalam akuarium : ', Ikan1.total_ikan()) |
"""
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
=> Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
=> Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
"""
def reverseString(string):
string.reverse()
return string
if __name__ == "__main__":
string = ["h","e","l","l","o"]
print(reverseString(string))
string = ["H","a","n","n","a","h"]
print(reverseString(string)) |
"""
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cab" can be written as "-.-..--...", (which is the concatenation "-.-." + ".-" + "-..."). We'll call such a concatenation, the transformation of a word.
Return the number of different transformations among all words we have.
=> Example:
Input: words = ["gin", "zen", "gig", "msg"]
Output: 2
Explanation:
The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
There are 2 different transformations, "--...-." and "--...--.".
=== Note ===
The length of words will be at most 100.
Each words[i] will have length in range [1, 12].
words[i] will only consist of lowercase letters.
"""
def numberOfTransformationsInMorseCode(words):
if len(words) == 0:
return 0
if len(words) == 1:
return 1
morse_code = {
'a': ".-", 'b': "-...", 'c': "-.-.", 'd': "-..", 'e': ".",
'f': "..-.", 'g': "--.", 'h': "....", 'i': "..", 'j': ".---",
'k': "-.-", 'l': ".-..", 'm': "--", 'n': "-.", 'o': "---",
'p': ".--.", 'q': "--.-", 'r': ".-.", 's': "...", 't': "-",
'u': "..-", 'v': "...-", 'w': ".--", 'x': "-..-", 'y': "-.--", 'z': "--.."
}
words_in_morse = []
word_in_morse = ""
for word in words:
for w in word:
word_in_morse += morse_code[w]
words_in_morse.append(word_in_morse)
word_in_morse = ""
return len(set(words_in_morse))
if __name__ == "__main__":
words = ["rwjje","aittjje","auyyn","lqtktn","lmjwn"]
print(numberOfTransformationsInMorseCode(words))
|
"""
Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note that elements beyond the length of the original array are not written.
Do the above modifications to the input array in place, do not return anything from your function.
=> Example 1:
Input: [1,0,2,3,0,4,5,0]
Output: null
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]
=> Example 2:
Input: [1,2,3]
Output: null
Explanation: After calling your function, the input array is modified to: [1,2,3]
=== Note ===
1 <= arr.length <= 10000
0 <= arr[i] <= 9
"""
def duplicateZeros(arr):
j = 0
for x in arr:
if arr[j] == 0:
arr.insert(j, 0)
arr.pop()
j += 1
j += 1
if j >= len(arr):
break
return arr
if __name__ == "__main__":
arr = [1,0,2,3,0,4,5,0]
print(duplicateZeros(arr)) |
'''
Sell, sell, sell!
Python Algorithms
Suppose we are given an array of n integers which represent the value of some stock over time. Assuming you are allowed to buy the stock exactly once and sell the stock once, what is the maximum profit you can make? Can you write an algorithm that takes in an array of values and returns the maximum profit?
For example, if you are given the following array:
[2, 7, 1, 8, 2, 8, 14, 25, 14, 0, 4, 5]
The maximum profit you can make is 24 because you would buy the stock when its price is 1 and sell when it's 25. Note that we cannot make 25, because the stock is priced at 0 after it is priced at 25 (e.g you can't sell before you buy).
'''
|
"""
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
=> Example 1:
Input: x = 123
Output: 321
=> Example 2:
Input: x = -123
Output: -321
=> Example 3:
Input: x = 120
Output: 21
=> Example 4:
Input: x = 0
Output: 0
=== Constraints ===
-231 <= x <= 231 - 1
"""
def reverseInteger(integer):
maximum = 2 ** 31
minimum = (2 ** 31) * -1
integer = "-" + str(integer)[:0:-1] if not str(integer)[0].isnumeric() else str(integer)[::-1]
integer = int(integer)
return integer if minimum < integer < maximum else 0
if __name__ == "__main__":
integer = 123
print(reverseInteger(integer))
integer = -123
print(reverseInteger(integer))
integer = 120
print(reverseInteger(integer))
integer = 0
print(reverseInteger(integer)) |
"""
On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.
=> You can move according to these rules:
In 1 second, you can either:
move vertically by one unit,
move horizontally by one unit, or
move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).
You have to visit the points in the same order as they appear in the array.
You are allowed to pass through points that appear later in the order, but these do not count as visits.
=> Example 1:
Input: points = [[1,1],[3,4],[-1,0]]
Output: 7
Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]
Time from [1,1] to [3,4] = 3 seconds
Time from [3,4] to [-1,0] = 4 seconds
Total time = 7 seconds
=> Example 2:
Input: points = [[3,2],[-2,2]]
Output: 5
=== Constraints ===
points.length == n
1 <= n <= 100
points[i].length == 2
-1000 <= points[i][0], points[i][1] <= 1000
"""
def minimumTimeVisitingPoints(points):
minimum_time = 0
if len(points) == 0 or len(points[0]) == 1:
return minimum_time
for i in range(0, len(points)-1):
abs_curr_point = abs(points[i][0]-points[i+1][0])
abs_next_point = abs(points[i][1]-points[i+1][1])
minimum_time += max(abs_curr_point, abs_next_point)
return minimum_time
# === HARD CODE ===
# while points[i][0] != points[i+1][0] or points[i][1] != points[i+1][1]:
# if points[i][0] < points[i+1][0]:
# points[i][0] += 1
# elif points[i][0] > points[i+1][0]:
# points[i][0] -= 1
# else:
# pass
# if points[i][1] < points[i+1][1]:
# points[i][1] += 1
# elif points[i][1] > points[i+1][1]:
# points[i][1] -= 1
# else:
# pass
# minimum_time += 1
#print(points[i])
if __name__ == "__main__":
points = [[1,1],[3,4],[-1,0]]
print(minimumTimeVisitingPoints(points)) |
# Return the fibonacci number at the position given by user
def fib_number_at(pos):
list_numbers = []
for i in range(pos+1):
if i == 0 or i == 1:
list_numbers.append(i)
else:
list_numbers.append(list_numbers[i-2]+list_numbers[i-1])
return list_numbers[pos]
# It returns a list of n fibonacci numbers
def fib_num_list(n):
list_numbers = []
for i in range(n):
if i == 0 or i == 1:
list_numbers.append(i)
else:
list_numbers.append(list_numbers[i-2]+list_numbers[i-1])
return list_numbers
# It creates a fibonacci numbers generator
def fib_sequence(n):
n1 = 0
n2 = 1
for i in range(n):
yield n1
temp = n1
n1 = n2
n2 = temp + n2
print(fib_number_at(10))
print(fib_num_list(10))
for x in fib_sequence(20):
print(x)
|
for i in range(1, 11):
for j in range(1, 11):
multi = str(i * j)
right_multi = multi.rjust(3)
print(f'{right_multi}', end=' ')
print(' ')
|
"""module with the definitions of an area and of a Maze"""
from sources.characters import Hero, Villain
from sources.items import Item
from sources.constants import *
import random
import pygame
class Area:
""" Area on the map. has an index in each dimension: x and y"""
def __init__(self, x, y, genre):
self.x = x
self.y = y
self.genre = genre # genre: whether the tile is a floor ("S") or a wall ("M")
def __str__(self):
return self.genre + " "
class Maze:
""" represents the maze with:
a 2-dimension array of areas,
and an array of items lying on the ground
"""
def __init__(self, link):
"""Maze constructor
link parameter is the link to a maze file
"""
# create an array that contains each area of the maze
self.map = list(list())
self.items = list()
# read the maze.txt file to get the map, each area
floor_list = list() # array of areas where items can spawn
with open(link, 'r') as file:
for i in range(MAZE_HEIGHT):
line = file.readline()
line_list = list()
j = 0
for char in line:
if char == " " or char == "\n":
continue
else:
line_list.append(Area(j, i, char))
if char == "S":
floor_list.append([i, j])
j += 1
self.map.append(line_list)
# removing the starting area and the guard's area
floor_list.remove([1, 1])
floor_list.remove([13, 13])
file.readline()
line = file.readline()
# read characters
line = line.split("\t")
self.mac_gyver = Hero(int(line[1]), int(line[2]), line[0])
line = file.readline()
line = line.split("\t")
self.guard = Villain(line[0], int(line[1]), int(line[2]), line[3], line[4], line[5])
file.readline()
# create items with random location
for i in range(3):
line = file.readline()
line = line.split("\n")
j = random.randint(0, len(floor_list)-1)
item = Item(line[0], floor_list[j][1], floor_list[j][0])
floor_list.remove(floor_list[j])
self.items.append(item)
del floor_list
def __str__(self):
""" representing the map in a text terminal"""
map_string = ""
# a representation of the maze
for i in self.map:
for j in i:
has_item = False
for k in self.items:
if k.x == j.x and k.y == j.y:
has_item = True
break
if self.mac_gyver.x == j.x and self.mac_gyver.y == j.y:
map_string += 'G '
elif self.guard.x == j.x and self.guard.y == j.y:
map_string += 'V '
elif has_item:
map_string += 'O '
else:
map_string += j.genre + " "
map_string += "\n"
map_string += "\n"
for i in self.items:
if i.x == self.mac_gyver.x and self.mac_gyver.y == i.y:
map_string += "lying on the floor, waiting to be gathered: {}".format(i.name)
# printing the inventory
map_string += '\ninventory: \n'
for i in self.mac_gyver.inventory:
map_string += "{}\n".format(i)
return map_string
def print_maze(self, window):
"""representing the maze in a pygame window"""
for i in self.map:
for j in i:
if j.genre == "M":
wall_image = pygame.image.load("img/wall.png").convert()
window.blit(wall_image, (j.x*AREA_SIZE, j.y*AREA_SIZE))
elif j.genre == "S":
floor_image = pygame.image.load("img/floor.png").convert()
window.blit(floor_image, (j.x*AREA_SIZE, j.y*AREA_SIZE))
for i in self.items:
item_image = pygame.image.load("img/item.png").convert_alpha()
window.blit(item_image, (AREA_SIZE*i.x, AREA_SIZE*i.y))
# print the keeper's image
keeper_image = pygame.image.load("img/keeper.png").convert_alpha()
window.blit(keeper_image, (AREA_SIZE*self.guard.x, AREA_SIZE*self.guard.y))
# print Mac gyver's image
mac_gyver_image = pygame.image.load("img/mac_gyver.png").convert_alpha()
window.blit(mac_gyver_image, (AREA_SIZE*self.mac_gyver.x, AREA_SIZE*self.mac_gyver.y))
# print the inventory item
counter = 0
for i in self.mac_gyver.inventory:
item_image = pygame.image.load("img/"+i+".png").convert()
x = (counter+1) * AREA_SIZE * 2 + counter * INVENTORY_ITEMS_SIZE
y = WINDOW_HEIGHT-INVENTORY_ITEMS_SIZE
window.blit(item_image, (x, y))
counter += 1
# print the inventory frame
floor_image = pygame.image.load("img/floor.png").convert()
for i in range(MAZE_WIDTH):
window.blit(floor_image, (AREA_SIZE*i, WINDOW_HEIGHT-3*AREA_SIZE))
for i in [0, 1, 4, 5, 8, 9, 12, 13, 14]:
window.blit(floor_image, (AREA_SIZE*i, WINDOW_HEIGHT-2*AREA_SIZE))
for i in [0, 1, 4, 5, 8, 9, 12, 13, 14]:
window.blit(floor_image, (AREA_SIZE*i, WINDOW_HEIGHT-AREA_SIZE))
if self.mac_gyver.x == 1 and self.mac_gyver.y == 1:
text = "moving: Z,Q,S,D or arrows.\n gathering an item: e or space"
else:
text = ""
police = pygame.font.Font("font/Android 101.ttf", 15)
y = WINDOW_HEIGHT-3*AREA_SIZE-40
for line in text.splitlines():
rendered_line = police.render(line, True, pygame.Color("#FFFFFF"))
rect_text = rendered_line.get_rect()
rect_text.center = (MAZE_WIDTH*AREA_SIZE/2, y)
window.blit(rendered_line, rect_text)
y += 17
def test_victory(self):
"""function testing if the game ends with a victory or a lose.
should be called only when Mac Gyver walks on a keeper
"""
for i in self.guard.death_items:
item_in_inventory = False
for j in self.mac_gyver.inventory:
if i == j:
item_in_inventory = True
break
if not item_in_inventory:
return "lose"
return "win"
|
#Create a window with required number of buttons
from tkinter import*
import math
root=Tk()
root.geometry("275x330")
root.title('Calculator')
display =None
class Calc():
def __init__(self):
self.current_value = 0
self.operation_pending = True
self.total_value =0
self.new_num=True
self.op = 0
self.equal_operation =False
def num_Button(self,num):
temp1 = display.get()
temp2 = str(num)
if self.new_num:
self.current_value = temp2
self.new_num = False
else:
self.current_value = temp1 + temp2
self.display(self.current_value)
def op_Button(self,operator):
self.op = operator
if self.operation_pending:
self.result(self.current_value)
else:
self.total_value =float(self.current_value)
self.operation_pending =True
self.new_num =True
def result(self, value):
value = float(value)
if (self.op == '+'):
self.total_value = self.total_value + value
print("current value is :%f, total value is %f"%(float(self.current_value),self.total_value))
elif (self.op == '-'):
self.total_value = self.total_value - value
print("current value is :%f, total value is %f"%(float(self.current_value),self.total_value))
elif (self.op == '*'):
self.total_value = self.total_value * value
print("current value is :%f, total value is %f"%(float(self.current_value),self.total_value))
elif (self.op == '/'):
if (value == 0):
print("cannot be divided by zero")
else:
self.total_value = self.total_value / value
print("current value is :%f, total value is %f"%(float(self.current_value),self.total_value))
elif (self.op == 's'):
self.total_value = math.sqrt(self.total_value)
print("current value is :%f, total value is %f"%(float(self.current_value),self.total_value))
elif (self.op == '!'):
self.total_value = math.factorial(round(abs(value)))
print("current value is :%f, total value is %f"%(float(self.current_value),self.total_value))
elif (self.op == '^'):
self.total_value = self.total_value ** value
print("current value is :%f, total value is %f"%(float(self.current_value),self.total_value))
elif (self.op == 'e'):
self.total_value = round(math.exp(self.total_value),3)
print("current value is :%f, total value is %f"%(float(self.current_value),self.total_value))
elif (self.op == '%'):
self.total_value = (self.total_value)% (value)
print("current value is :%f, total value is %f"%(float(self.current_value),self.total_value))
elif (self.op == 'ln'):
self.total_value = round(math.log(float(self.current_value),3))
print("current value is :%f, total value is %f"%(float(self.current_value),self.total_value))
elif (self.op == 'log'):
self.total_value = round(math.log(float(self.current_value),10),3)
print("current value is :%f, total value is %f"%(float(self.current_value),self.total_value))
elif (self.op == '+/-'):
self.current_value = -value
self.display(self.current_value)
self.total_value = self.current_value
self.operation_pending = False
print("current value is :%f, total value is %f"%(float(self.current_value),self.total_value))
self.current_value =self.total_value
def equal_Button(self):
if self.equal_operation:
temp = self.total_value
else:
temp = self.current_value
self.equal_operation = False
self.result(temp)
self.display(str(self.total_value))
self.operation_pending = False
def ans_Button(self):
self.total_value = self.current_value
def clearall_Button(self):
self.display(0)
def clear_Button(self):
display.delete(0,END)
def display(self,value):
display.delete(0,END)
display.insert(0,value)
calc = Calc()
#-------Creating Two frames -----------------
#-----------------Frame1 ----------------
frame1 =Frame(root)
frame1.pack(side =TOP)
display = Entry(frame1,justify =RIGHT, width =50, font ="Times 24 bold")
display.insert(0,"")
display.pack()
#-------------- Frame2-------------------
frame2 = Frame(root)
frame2.pack()
Button(frame2,text = "7" ,width =8, height=2, command = lambda :calc.num_Button(7)).grid(row = 4,column =0)
Button(frame2,text = "8" ,width =8, height=2, command = lambda :calc.num_Button(8)).grid(row = 4,column =1)
Button(frame2,text = "9" ,width =8, height=2, command = lambda :calc.num_Button(9)).grid(row = 4,column =2)
Button(frame2,text = "4" ,width =8, height=2, command = lambda :calc.num_Button(4)).grid(row = 5,column =0)
Button(frame2,text = "5" ,width =8, height=2, command = lambda :calc.num_Button(5)).grid(row = 5,column =1)
Button(frame2,text = "6" ,width =8, height=2, command = lambda :calc.num_Button(6)).grid(row = 5,column =2)
Button(frame2,text = "1" ,width =8, height=2, command = lambda :calc.num_Button(1)).grid(row = 6,column =0)
Button(frame2,text = "2" ,width =8, height=2, command = lambda :calc.num_Button(2)).grid(row = 6,column =1)
Button(frame2,text = "3" ,width =8, height=2, command = lambda :calc.num_Button(3)).grid(row = 6,column =2)
Button(frame2,text = "1/x" ,width =8, height=2, command = lambda :calc.op_Button("1/x")).grid(row = 2,column =0)
Button(frame2,text = "ANS" ,width =8, height=2, command = lambda :calc.ans_Button()).grid(row = 7,column =2)
Button(frame2,text = "log" ,width =8, height=2, command = lambda :calc.op_Button("log")).grid(row = 2,column =2)
Button(frame2,text = "+/-" ,width =8, height=2, command = lambda :calc.op_Button("+/-")).grid(row = 2,column =3)
Button(frame2,text = "0" ,width =8, height=2, command = lambda :calc.num_Button(0)).grid(row = 7,column =1)
Button(frame2,text = "." ,width =8, height=2, command = lambda :calc.num_Button('.')).grid(row = 7,column =0)
Button(frame2,text = "=" ,width =8, height=2, command = lambda :calc.equal_Button()).grid(row = 7,column =3)
Button(frame2,text = "+" ,width =8, height=2, command = lambda :calc.op_Button('+')).grid(row = 6,column =3)
Button(frame2,text = "-" ,width =8, height=2, command = lambda :calc.op_Button('-')).grid(row = 5,column =3)
Button(frame2,text = "*" ,width =8, height=2, command = lambda :calc.op_Button('*')).grid(row = 4,column =3)
Button(frame2,text = "/" ,width =8, height=2, command = lambda :calc.op_Button('/')).grid(row = 3,column =3)
Button(frame2,text = "mod" ,width =8, height=2, command = lambda :calc.op_Button('%')).grid(row = 2,column =1)
Button(frame2,text = "sqrt" ,width =8, height=2, command = lambda :calc.op_Button('s')).grid(row = 3,column =0)
Button(frame2,text = "!" ,width =8, height=2, command = lambda :calc.op_Button('!')).grid(row = 3,column =1)
Button(frame2,text = "e" ,width =8, height=2, command = lambda :calc.op_Button('e')).grid(row = 3,column =2)
Button(frame2,text = "C" ,width =8, height=2, command = lambda :calc.clear_Button()).grid(row = 1,column =3)
Button(frame2,text = "ln" ,width =8, height=2, command = lambda :calc.op_Button('log')).grid(row = 1,column =0)
Button(frame2,text = "x^y" ,width =8, height=2, command = lambda :calc.op_Button('^')).grid(row = 1,column =1)
Button(frame2,text = "AC" ,width =8, height=2, command = lambda :calc.clearall_Button()).grid(row = 1,column =2)
root.mainloop()
|
# A3 - Ask the user for a password, if they enter the password "qwerty123", print "You have successfully logged in".
# If they get it wrong, print "Password failure"
password = "qwerty123"
user_guess = input("What is your password?\n")
if user_guess == password:
print("You have successfully logged in.")
else:
print("Password failure.")
|
# C1 - Create the following list of items: Apples, Cherries, Pears, Pineapples, Peaches, Mangoes
fruits = ["Apples", "Cherries", "Pears", "Pineapples", "Peaches", "Mangoes"]
# C2 - Add "Grapes" to the list
fruits.append("Grapes")
# C3 - Change "Pears" to "Strawberries"
fruits[2] = "Strawberries"
# C4 - Remove "Apples" from the list
del fruits[0]
# C5 - Print out the current length of the list
print(len(fruits))
# C6 - Print out the list
print(fruits)
# C7 - Order the list alphabetically
fruits.sort()
# C8 - Print out the list again
print(fruits)
|
# D3 - Print all odd numbers from 1 to 100
for x in range(1, 101, 2):
print(x)
|
import math
#shared variables
invalid = "INVALID KEY PLEASE TRY AGAIN."
variables = ["Enter the length of the", "Enter the height of the", "Enter the base of the","Enter the radius of the", "Enter the width of the", ]
def area_calc():
#area specific variables
area_message = "The area of the"
#area specific list
shapes = ["square", "rectangle", "triangle", "circle", "parrallelogram"]
square_values = []
rectangle_values = []
triangle_values = []
circle_values =[]
parrallelogram_values = []
#introduction
print("You have selected the AREA CALCULATOR \n")
#allows user to select a shape
while True:
try:
option_select = int(input(f"""Please select a shape by selecting its number
[1] {shapes[0]}
[2] {shapes[1]}
[3] {shapes[2]}
[4] {shapes[3]}
[5] {shapes[4]}
>>> """))
#Checks for invalid types
except ValueError:
print(invalid)
continue
#Calculates Area of a Square
if option_select == 1:
while True:
try:
length = float(input(f"{variables[0]} {shapes[0]}.>>> "))
except ValueError:
print(invalid)
continue
else:
area_square = length * length
print(f"{area_message} {shapes[0]} is {area_square} \n")
square_values.insert(0, area_square)
break
#Calculates Area of a Rectangle
elif option_select == 2:
while True:
try:
length = float(input(f"{variables[0]} {shapes[1]}.>>> "))
except ValueError:
print(invalid)
continue
else:
break
while True:
try:
width = float(input(f"{variables[4]} {shapes[1]}.>>> "))
except ValueError:
print(invalid)
continue
else:
area_rectangle = length * width
print(f"{area_message} {shapes[1]} is {area_rectangle} \n")
rectangle_values.insert(0, area_rectangle)
break
#Calculates Area of a Triangle
elif option_select == 3:
while True:
try:
height = float(input(f"{variables[1]} {shapes[2]}.>>> "))
except ValueError:
print(invalid)
continue
else:
break
while True:
try:
base = float(input(f"{variables[2]} {shapes[2]}.>>> "))
except ValueError:
print(invalid)
continue
else:
area_triangle = (height * base)/2
print(f"{area_message} {shapes[2]} is {area_triangle} \n")
triangle_values.insert(0, area_triangle)
break
#Calculates Area of a Circle
elif option_select == 4:
while True:
try:
radius = float(input(f"{variables[3]} {shapes[3]}.>>> "))
except ValueError:
print(invalid)
continue
else:
area_circle = math.pi * radius ** 2
print(f"{area_message} {shapes[3]} is {area_circle}\n")
circle_values.insert(0, area_circle)
break
#Calculates area of a parrallelogram
elif option_select == 5:
while True:
try:
base = float(input(f"{variables[2]} {shapes[4]}.>>> "))
except ValueError:
print(invalid)
continue
else:
break
while True:
try:
height = float(input(f"{variables[1]} {shapes[4]}.>>> "))
except ValueError:
print(invalid)
continue
else:
area_parrallelogram = height * base
print(f"{area_message} {shapes[4]} is {area_parrallelogram} \n")
parrallelogram_values.insert(0, area_parrallelogram)
break
#checks intial user input for invalid options
elif option_select != len(shapes):
print(invalid)
continue
#allows user to run the program again or terminate it
while True:
rerun = input("would you like to find the area of another shape? y or n \n >>> ")
if rerun.lower() == "y":
print("\n")
i = 0
break
elif rerun.lower() == "n":
#prints values for all calculations done
if len(square_values) > 0:
print(f"area for each square calculated:\n {square_values} \n")
if len(rectangle_values) > 0:
print(f"area for each rectangle calculated:\n{rectangle_values} \n")
if len(triangle_values) > 0:
print(f"area for each triangle calculated:\n{triangle_values} \n")
if len(circle_values) > 0:
print(f"area for each cricle calculated:\n{circle_values} \n")
if len(parrallelogram_values) > 0:
print(f"area for each parrollelogram calculated:\n{parrallelogram_values} \n")
input("press any KEY continue")
i = 1
break
elif rerun.lower() != "y" or "n":
print(invalid)
continue
if i == 0:
continue
if i == 1:
break
break
return""
def volume_calc():
#varibales
area_message = "The volume of the"
#list
shapes = ["square", "rectangle", "pyramid", "circle", "cylinder"]
square_values = []
rectangle_values = []
pyramid_values = []
circle_values =[]
cylinder_values = []
#introduction
print("You have selected the VOLUME CALCULATOR! \n")
#allows user to select a shape
while True:
try:
option_select = int(input(f"""please select a shape by selecting its number
[1] {shapes[0]}
[2] {shapes[1]}
[3] {shapes[2]}
[4] {shapes[3]}
[5] {shapes[4]}
>>> """))
#Checks for invalid types
except ValueError:
print(invalid)
continue
#Calculates Volume of a Square
if option_select == 1:
while True:
try:
length = float(input(f"{variables[0]} {shapes[0]}.>>> "))
except ValueError:
print(invalid)
continue
else:
volume_square = length * length * length
print(f"{area_message} {shapes[0]} is {volume_square} \n")
square_values.insert(0, volume_square)
break
#Calculates Volume of a Rectangle
elif option_select == 2:
while True:
try:
length = float(input(f"{variables[0]} {shapes[1]}.>>> "))
except ValueError:
print(invalid)
continue
else:
break
while True:
try:
height = float(input(f"{variables[1]} {shapes[1]}.>>> "))
except ValueError:
print(invalid)
continue
else:
break
while True:
try:
width = float(input(f"{variables[4]} {shapes[1]}.>>> "))
except ValueError:
print(invalid)
continue
else:
volume_rectangle = length * width * height
print(f"{area_message} {shapes[1]} is {volume_rectangle} \n")
rectangle_values.insert(0, volume_rectangle)
break
#Calculates Volume of a pyramid
elif option_select == 3:
while True:
try:
height = float(input(f"{variables[1]} {shapes[2]}.>>> "))
except ValueError:
print(invalid)
continue
else:
break
while True:
try:
length = float(input(f"{variables[0]} {shapes[2]}.>>> "))
except ValueError:
print(invalid)
continue
else:
break
while True:
try:
base = float(input(f"{variables[2]} {shapes[2]}.>>> "))
except ValueError:
print(invalid)
continue
else:
volume_pyramid = (height * base * length) / 3
print(f"{area_message} {shapes[2]} is {volume_pyramid} \n")
pyramid_values.insert(0, volume_pyramid)
break
#Calculates Volume of a Circle
elif option_select == 4:
while True:
try:
radius = float(input(f"{variables[3]} {shapes[3]}.>>> "))
except ValueError:
print(invalid)
continue
else:
volume_circle = (4 / 3) * math.pi * radius ** 3
print(f"{area_message} {shapes[3]} is {volume_circle}\n")
circle_values.insert(0, volume_circle)
break
#Calculates Volume of a cylinder
elif option_select == 5:
while True:
try:
radius = float(input(f"{variables[3]} {shapes[4]}.>>> "))
except ValueError:
print(invalid)
continue
else:
break
while True:
try:
height = float(input(f"{variables[1]} {shapes[4]}.>>> "))
except ValueError:
print(invalid)
continue
else:
volume_cylinder = math.pi * radius ** 2 * height
print(f"{area_message} {shapes[4]} is {volume_cylinder} \n")
parrallelogram_values.insert(0, volume_cylinder)
break
#checks intial user input for invalid options
elif option_select != len(shapes):
print(invalid)
continue
#allows user to run the program again or terminate it
while True:
rerun = input("would you like to find the volume of another shape? y or n \n >>> ")
if rerun.lower() == "y":
print("\n")
i = 0
break
elif rerun.lower() == "n":
#prints values for all calculations done
if len(square_values) > 0:
print(f"volume for each square calculated:\n {square_values} \n")
if len(rectangle_values) > 0:
print(f"volume for each rectangle calculated:\n{rectangle_values} \n")
if len(pyramid_values) > 0:
print(f"volume for each pyramid calculated:\n{pyramid_values} \n")
if len(circle_values) > 0:
print(f"volume for each cricle calculated:\n{circle_values} \n")
if len(cylinder_values) > 0:
print(f"volume for each cylinder calculated:\n{cylinder_values} \n")
input("press any KEY to continue")
i = 1
break
elif rerun.lower() != "y" or "n":
print(invalid)
continue
if i == 0:
continue
if i == 1:
break
break
return""
#allows user to select area or volume calculator / main screen
while True:
try:
function_select = int(input("""Please select a function
[1] Area calculator
[2] Volume calculator
[3] Exit Program
>>> """))
#Checks for invalid types
except ValueError:
print(invalid)
continue
#runs area calculator
if function_select == 1:
print(area_calc())
#runs volume calculator
elif function_select == 2:
print(volume_calc())
elif function_select == 3:
exit()
elif function_select != 1 or 2 or 3:
print(invalid)
continue
|
# -*- coding: utf-8 -*-
# @Author: Admin
# @Date: 2020-01-10 00:58:05
# @Last Modified by: Jingyuexing
# @Last Modified time: 2020-01-11 14:21:04
class Rank(object):
"""排序算法"""
def insert(self,data=[]):
if isinstance(data,list):
for i in range(2,len(data)):
key = data[i]
j=i-1
while i>0 and data[j]>key:
data[j+1]=data[j]
j=j-1
data[j+1]=key
return data
def bubbleSort(self,data=[]):
for i in range(1,len(data)):
for j in range(0,len(data)-i):
if data[j]>data[j+1]:
data[j],data[j+1] = data[j+1],data[j]
return data
def quickSort(self,array=[],begin=0,end=0):
i,j,key= begin,end,array[begin]
while i<j:
while i<j and array[j]>=key: j=j-1
if i < j:
array[i] = array[j]
i=i-1
while i<j and array[i]<key:i=i+1
if i<j:
array[j]=array[i]
j=j-1
array[i]=key
self.quickSort(array,begin,i-1)
self.quickSort(array,i+1,end)
return array
if __name__ == "__main__":
pass |
"""Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome."""
# greedy solution: when see a missmatch, compare the two scenario of whether next char matched
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
i = 0
j = len(s) - 1
while i <= j:
if s[i] != s[j]:
if s[i + 1] == s[j]:
if checkPalindrome(s[i:j]):
return True
elif s[i] == s[j - 1]:
print s[i:j], j
return checkPalindrome(s[i:j])
else:
return False
i += 1
j -= 1
return True
def checkPalindrome(s):
i = 0
j = len(s) - 1
while i <= j:
if s[i] != s[j]:
return False
else:
i += 1
j -= 1
return True
|
arr_ = [2,34,52,1,7,82,1234,8472,22,245,138]
def bubbleSort(arr):
sorted_ = False
while not sorted_:
sorted_ = True
for i in range(1,len(arr)):
tmp = arr[i-1]
if arr[i-1] > arr[i]:
arr[i-1] = arr[i]
arr[i] = tmp
sorted_ = False
return arr
print(bubbleSort(arr_)) |
# Program to print BFS traversal from a given source
# vertex. BFS(int s) traverses vertices reachable
# from s.
from collections import defaultdict
# This class represents a directed graph using adjacency
# list representation
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# Function to print a BFS of graph
def BFS(self, s):
visited = [0] * len(self.graph) # boolean array to keep track of every vertices visited
queue = [s] # queue for bfs search
while(len(queue)!=0):
v = queue.pop(0)
if not visited[v]:
print v
visited[v] = 1
for each in self.graph[v]:
queue.append(each)
# Driver code
# Create a graph given in the above diagram
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print "Following is Breadth First Traversal (starting from vertex 2)"
g.BFS(2) |
"""
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence.
A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence,
leaving the remaining elements in their original order.
"""
class Solution(object):
# This solution use a linear dynamic programming
# The max wiggle length is the previous longest plus one if the next element follows the rule
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
up = 0
down = 0
for i in range(1,len(nums)):
if nums[i-1] > nums[i]:
down = up+1
elif nums[i-1] < nums[i]:
up = down+1
return max(up,down) |
class DoYouKnowRecursion:
def __init__(self,recursion_learned):
self.recursion_learned = True
def learn_recursion(self):
try:
assert self.recursion_learned == False
print 'You are an idiot'
return self.learn_recursion()
except AssertionError:
print "Don't be a fool, you don't know recursion!"
self.recursion_learned = False
return self.learn_recursion()
except RuntimeError:
print 'Give it up, you idiot.'
if __name__ == "__main__":
what_i_did_this_afternoon = DoYouKnowRecursion(False)
what_i_did_this_afternoon.learn_recursion() |
arr_ = [2,34,52,1,7,82,1234,8472,22,245,138]
def insertionSort(arr):
for i in range(1,len(arr)):
tmp = arr[i]
j = i - 1
while j >= 0 and tmp < arr[j]:
arr[j+1] = arr[j]
j-=1
arr[j+1] = tmp
return arr
print(insertionSort(arr_)) |
pahbet = list("abcdefghijklmnopqrstuvwxyz")
def checkifword():
for i in list(times):
for e in pahbet:
if i == e:
return True
return False
times = "bruh"
#key = list("@,=/}^~+%{>#.?$&)(!_-<*|:;")
while checkifword():
times = input("How many words to decrypt? ")
#password = list("!|^,%")
key = list(input("Key: "))
cipher = list("abcdefghijklmnopqrstuvwxyz ")
cipheru = list("|:;?/>.<,+=_-!@#$%^&*()~}{`")
bruh = []
#check if space ava
if times is "":
times = 1
#importing key
for i in range(int(times)):
password = list(input("Word: "))
for i in key:
bruh.append(int(cipheru.index(i)))
for i in bruh:
bruh[bruh.index(i)] = cipher[i]
#print (bruh)
for i in password:
password[password.index(i)] = int(key.index(i))
#print (password)
for i in password:
password[password.index(i)] = cipher[i]
bruh = []
goodpw = "".join(password)
print("text: " + str(goodpw))
|
import os,shutil
path = './files/'
ext = input('Digite a extensão dos arquivos que deseja copiar (ex: .txt) :')
new_path = './copias/'
for folderName, subfolders , filenames in os.walk(path):
for file in filenames:
if (file.endswith(ext)):
shutil.copy(folderName+'/' + file,
new_path + file)
input("Arquivos " + ext +" copiados! ENTER para sair.")
|
import random
def noop():
pass
class Game:
congratulation_message = "Congratulations, you won! :)"
separator = "---------------------------------------------------------"
def start(self):
finished = False
while not finished:
finished = self.__play_round()
def __play_round(self):
self.print_turn()
if self.is_finished():
print(self.separator)
print(self.congratulation_message)
return True
self.take_turn()
print(self.separator)
return False
def take_turn(self):
raise NotImplementedError()
def is_finished(self):
raise NotImplementedError()
def print_turn(self):
pass
|
ingreso=int(input("ingrese su sueldo mensual: "))
mes=int(input("Ingrese la cantidad de meses trabajados: "))
gratificacion=int(input("Cantidad de gratificaciones recibidas: "))
UIT=4300
afiliacion=int(input("Estas afiliado a: \n1)ESSALUD - 1 \n2)ESP - 2 \n3)Ninguno - 3 \nIngrese un número: "))
if afiliacion==1:
plus=ingreso*0.09
elif afiliacion==2:
plus=ingreso*0.0675
elif afiliacion==3:
plus=0
else:
print("no existe")
RemuneracionBrutalAnual = (ingreso * mes) + ((gratificacion*(ingreso*2))+plus)
if RemuneracionBrutalAnual<=(7*UIT):
print("\nSueldo anual : ", RemuneracionBrutalAnual)
else:
RemuneracionNetaAnual=RemuneracionBrutalAnual-30100
if RemuneracionBrutalAnual<=(5*UIT):
ImpuestoAnualProyectado = RemuneracionBrutalAnual*0.08
elif RemuneracionBrutalAnual<=(20*UIT):
ImpuestoAnualProyectado=RemuneracionBrutalAnual*0.14
elif RemuneracionBrutalAnual<=(35*UIT):
ImpuestoAnualProyectado=RemuneracionBrutalAnual*0.17
elif RemuneracionBrutalAnual<=(45*UIT):
ImpuestoAnualProyectado=RemuneracionBrutalAnual*0.2
elif RemuneracionBrutalAnual>(45*UIT):
ImpuestoAnualProyectado=RemuneracionBrutalAnual*0.3
ImpuestoMensual=ImpuestoAnualProyectado/mes
ganancia = ingreso-ImpuestoMensual
print("╔═════════════════════════════════════════════════")
print("║Ingreso mensual: ", ingreso)
print("║Impuesto mensual: ", ImpuestoMensual)
print("║Sueldo mensual menos impuesto mensual: ",ganancia)
print("║Ingreso Anual: ",RemuneracionBrutalAnual)
print("║Impuesto anual: ", ImpuestoAnualProyectado)
print("╚═════════════════════════════════════════════════")
|
# 문제1.
# 다음 세 개의 리스트가 있을 때,
# subs = [‘I’, ‘You’]
# verbs = [‘Play’, ‘Love’]
# objs = [‘Hockey’, ‘Football’]
#
# 3형식 문장을 모두 출력해 보세요. 반드시 comprehension을 사용합니다.
subs = ["I", "You"]
verbs = ["Play", "Love"]
objs = ["Hockey", "Football"]
[print(subs[a], verbs[b], objs[c]) for a in range(0, len(subs)) for b in range(0, len(verbs)) for c in range(0, len(objs))]
|
# 문제9.
# 주어진 if 문을 dict를 사용해서 수정하세요.
menu = input('메뉴: ')
dict = {'오뎅': 300, '순대': 400, '만두': 500}
print('가격: {0}'.format(dict.get(menu) if dict.get(menu) != None else 0))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.