text stringlengths 37 1.41M |
|---|
# Shows how numbers work in python
# An integer
a = 4
print(a)
# A floating point number
b = 4.3
print(b)
# Round down a float
print(int(4.3))
# A string
c = "1000"
# If you try to do math on it, weird stuff will
# happen
print(c * 5)
# So, convert a string to a number
print(int(c) * 5) |
idade = int(input("Digite a sua idade: "))
if idade >=0 and idade <= 12:
print("Criança")
else:
if idade >= 13 and idade <=17:
print("Adolescente")
else:
print("Adulto")
## 2
m1 = float(input("Insira a primeira nota: "))
m2 = float(input("Insira a segunda nota: "))
m3 = float(input("Insira a terceira nota: "))
notaFinal = (m1 + m2 + m3)/3
print("Sua nota final é:",notaFinal)
if notaFinal >= 0.0 and notaFinal <= 4:
print("Reprovado")
else:
if notaFinal >= 4.1 and notaFinal < 6.0:
print("Exame final")
notaExame = float(input("Nota do exame: "))
if notaExame >= 6:
print("Esta aprovado no exame")
else:
if notaFinal > 6:
print("Aprovado")
|
def swap_bits(num):
even = num & 0xAAAAAAAA
odd = num & 0x55555555
even >>=1
odd <<= 1
out = even|odd
return out
num = 56
output = swap_bits(num)
print(output)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 23 13:18:24 2020
@author: Santiago Quinga
"""
import numpy as np
from random import randint
print("\nIngrese cuantas filas se requieren: ")
filas=int(input())
print("\nIngrese cuantas columnas se requieren: ")
columnas=int(input())
print("\n"*0)
matrix=np.zeros([filas,columnas])
f=-1
c=-1
a=filas
b=filas
for i in range(0,filas):
for n in range(0,columnas):
matrix[i][n]=int(randint(0,99))
print("<< La matriz creada es de",filas,"x",columnas,">>")
print("\n"*0)
print(matrix)
print("\n"*0)
print('El valor de la diagonal principal de la matriz es: ')
print("\n"*0)
for j in range(0,filas):
if f<filas:
f+=1
a-=1
print(' | -- |'*f,"|",int(matrix[j][f]),"|",'| -- | '*a)
print('\nEl valor de la diagonal secundaria de la matriz es: ')
print("\n"*0)
for k in range(0,filas):
if c<filas:
c+=1
b-=1
print(' | -- |'*b,"|",int(matrix[k][b]),"|",'| -- | '*c)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 2 17:49:57 2020
@author: Santiago Quinga
"""
def isYearLeap(year):
#
# Un año es bisiesto si cumple lo siguiente:
# es divisible por 4 y no lo es por 100 ó si es divisible por 400.
if (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
# En year podemos ingresar cualquier año
# para poder realizar la prueba.
year=2020 # Ingrese un año que quiera.
print("¿El año %a es bisiesto?: %s" % (year, isYearLeap(year)))
print("\n"*0)
#
# Definimos a daysInMonth para que nos pueda ayudar
# Como un retorno de datos.
def daysInMonth(year, month):
# Ingresamos la condicional if
# Para poder evaluar que mes
# Dispone de 28,29,30 y 31 dias.
if isYearLeap(year) and month==2:
return 29
elif month==2:
return 28
elif month in [4, 6, 9, 11]:
return 30
else:
return 31
# En month ingresamos caulquier numero del mes.
month= 2 # Ingrese un numero del mes.
print("El total de dias del año",year,"del mes %i son: %s"
% (month, daysInMonth(year, month)),"dias")
print("\n"*0)
#
# Este es el codigo para verificar si el codigo funciona correctamente.
testYears = [1900, 2000, 2016, 1987]
testMonths = [2, 2, 1, 11]
testResults = [28, 29, 31, 30]
for i in range(len(testYears)):
yr = testYears[i]
mo = testMonths[i]
print(yr, mo, "->", end="")
result = daysInMonth(yr, mo)
if result == testResults[i]:
print("OK")
else:
print("Failed")
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 12:25:39 2020
@author: Santiago Quinga
"""
Nombre=input("Ingresa tu nombre: ")
Apellido=input("Ingresa tu Apellido: ")
Ubicacion=input("Ingresea tu Ubicacion: ")
Edad=input("Ingresa tu edad: ")
space=" "
print("\n " *1)
print("Hola que tal un gusto en conocerte"+space+Nombre+space+
"y tu apellido paterno debe ser"+space+Apellido+space+
"y me imagino que talvez eres de"+space+Ubicacion+space+
"y tienes"+space+Edad+space+"años")
Edad=int(Edad)
if Edad>= 1 and Edad<=5:
print("eres un niño todavia.")
elif Edad>=6 and Edad<=9:
print("eres un niño grande.")
elif Edad>=10 and Edad<=17:
print("eres un adolescente.")
elif Edad>=18 and Edad<=39:
print("eres un Adulto")
elif Edad>=40 and Edad<=80:
print("eres un Adulto Mayor")
else:
print("todavia tienes ya largo de vivir.") |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 14 11:13:36 2020
@author: Santiago Quinga
"""
import numpy as np
matrix=np.array([[1,2,3,4,5],[6,7,8,9,10]],dtype=np.int64)
print(matrix)
print("\n")
print("La matriz Tiene: ",matrix.ndim, " dimensiones")
|
# AUTHOR: HAIDER ALI SIDDIQUEE
# DATE : 2/15/2020
# TIME : 4:59:01
# ABOUT : IMPLEMENTATION OF GRADIENT DESCENT FOR SQUARES
import sys
import math
import random
datafile = sys.argv[1]
f = open (datafile, 'r')
data = []
i = 0
l = f.readline()
######################
##### READ DATA ######
######################
while (l != ''):
a = l.split()
# here 'a' is a list that store one column data like ['4.3','5.4','6']
# And we are taking l2 to store floating numbers in our string like [4.3,5.4,6]
l2 = []
for j in range(0, len(a), 1):
l2.append(float(a[j]))
data.append(l2)
l = f.readline()
rows = len(data)
cols = len(data[0])
#print(rows)
#print(cols)
########################
###### READ LABELS #####
########################
labelfile = sys.argv[2]
f = open (labelfile, 'r')
traininglabels = {}
n = [0, 0]
l = f.readline()
while (l != ''):
a = l.split()
traininglabels[int(a[1])] = int(a[0])
l = f.readline()
n[int(a[0])] += 1
#print(n)
###########################
###### INITIALINING W #####
###########################
w = []
for i in range(0, cols, 1):
w.append(0.2*random.random() - 0.01)
#print(w)
##################################
###### DOT PRODUCT FUNCTION #####
##################################
def dot_product(m1, m2):
result = 0
for j in (0, cols, 1):
result += m1[j]*m2[j]
return result
#####################################
###### GRADIENT DECENT ITRATION #####
#####################################
eta = 0.0001
diff = 1
error = rows + 10
count = 0
while(diff > 0.001):
dellf = []
for m in range(0, cols, 1):
dellf.append(0)
for j in range (0, rows, 1):
if (traininglabels.get(str(j)) != None):
dot_pro = dot_product(w, data[j])
for k in range(0, cols, 1):
dellf[k] += (traininglabels.get(str(j)) -
dot_pro)*data[j][k]
#print(dellf)
######################
###### UPDATE W #####
######################
for j in range (0, cols, 1):
w[j] += eta*dellf[j]
prev=error
error= 0
##########################
###### Compute Error #####
##########################
for j in range(0, rows, 1):
if(traininglabels.get(str(j)) != None):
error += (traininglabels.get(std(j)) - dot_product(w, data[j]))**2
if (prev > error):
diff = prev - error
else:
diff = error - prev
count += 1
if (count%100 == 0):
print(error)
#print("ERROR = " + str(error))
normw = 0
for i in range(0, (cols - 1), 1):
normw += w[i]**2
#print("W", w)
normw = math.sqrt(normw)
d_original = abs(w[len(w) - 1]/normw)
#print (d_original)
##############################
###### LABELS PREDICTION #####
##############################
for i in range(0, rows, 1):
if(traininglabels.get(i) == None):
dot_pro = dot_product(w, data[i])
if(dot_pro > 0):
print ("1" + str(i))
else:
print("0" + str(i))
|
import re
pattern1 = "^(?![-._])(?!.*[_.-]{2})[\w.-]{6,30}(?<![-._])$"
pattern2 = "[A-Za-z0-9@#$%^&+=_+-]{8,}"
def login_password(username=None, password=None):
print("Administrator login Panel ")
print("\t1.New user Entry\n"
"\t2.Change Credentials\n"
"\t3.Show all accounts")
option = int(input("Enter your choise:"))
if option == 1:
enroll_login()
return username, password
elif option == 2:
u, p = change_credentials(username, password)
return u, p
elif option == 3:
show_users(username, password)
return username, password
else:
print("You enter wrong input plz try again")
login_password(username, password)
def enroll_login():
with open("accounts.txt", "a") as f:
username, password = getInput()
account = "" + username + "\t" + password + "\n"
f.write(account)
return username, password
def change_credentials(username=None, password=None):
with open("accounts.txt", "r") as f:
lines = f.readlines()
with open("accounts.txt", "w") as f:
for line in lines:
data = line.split("\t")
if not (data[0] == username and data[1] == password):
f.write(line)
u, p = enroll_login()
return u, p
def show_users(username, password):
p = input("First enter password to verify: ")
with open("accounts.txt", "r") as f:
lines = f.readlines()
for line in lines:
data = line.split('\t')
if data[0] == username and data[1].split("\n")[0] == p:
print("-----Entries ----\n"
"Username\tPassword\n" +
''.join(lines))
return
print("Sorry you enter worng credentials ")
def getInput():
print("\t\t\t\tWelcome!\n"
"Note For username :\n"
"\t1. Username must be 6-30 characters long\n"
"\t2. Username may not begin with: special character\n"
"Note for Password\n"
"\t1. Your Password contains At least 8 characters\n"
"\t2. Must be restricted to, though does not specifically require any of:\n"
"\t\ta.uppercase letters: A-Z\n"
"\t\tb.lowercase letters: a-z\n"
"\t\tc.numbers: 0-9\n"
"\t\td.any of the special charactersspace excluded: @#$%^&+=\n"
)
username = input("Enter username =")
result = re.findall(pattern1, username)
while not result:
username = input("You enter invalid username, kindly enter correct username:")
result = re.findall(pattern1, username)
password = input("Enter password =")
result = re.findall(pattern2, password)
while not result:
password = input("You enter invalid password, kindly enter correct password:")
result = re.findall(pattern2, password)
return username, password
if __name__ == "__main__":
with open("accounts.txt", "r") as f:
line = f.readline()
data = line.split("\t")
login_password(data[0], data[1])
|
target = '123'
def rec(target, num):
if len(target) == 1:
print(num + target[0])
else:
for letter in target:
rec(target.replace(letter, ''), num+letter)
to_print = ''
rec(target, to_print)
|
# Helper class for doubly-linked list
class Node:
def __init__(self, key, val):
self.next = None
self.prev = None
self.key = key
self.val = val
class LRUCache:
def __init__(self, n):
self.n = n
self.count = 0
self.nodes = {}
self.start = None
self.end = None
def get(self, key):
# Get node for key if it exists
node = self.nodes.get(key)
if not node:
return None
# Move this node to front of list
self.move_to_front(node)
return node.val
def set(self, key, val):
node = self.nodes.get(key)
if node:
# Update existing node and move to front
node.val = val
self.move_to_front(node)
return
if self.count == self.n:
# No space, so remove last item
if self.end:
del self.nodes[self.end.key]
self.remove(self.end)
else:
self.count += 1
# Finally create and insert the new node
node = Node(key, val)
self.insert(node)
self.nodes[key] = node
# Private helpers
def insert(self, node):
if not self.end:
self.end = node
if self.start:
node.next = self.start
self.start.prev = node
self.start = node
def remove(self, node):
if node.prev:
node.prev.next = node.next
if node.next:
node.next.prev = node.prev
if self.start == node:
self.start = node.next
if self.end == node:
self.end = node.prev
def move_to_front(self, node):
# Remove node and re-insert at head
self.remove(node)
self.insert(node)
|
'''You have a list of timestamps. Each timestamp is a time when there was a glitch in the network.
If 3 or more glitches happen within one second (duration), you need to print the timestamp of the first glitch in that window.
input_lst = [2.1, 2.5, 2.9, 3.0, 3.6, 3.9, 5.2, 5.9, 6.1, 8.2, 10.2, 11.3, 11.8, 11.9]
The output list should be:
[2.1, 5.2, 11.3]
Glitch windows: [2.1, 2.5, 2.9, 3.0], [5.2, 5.9, 6.1], [11.3, 11.8, 11.9]
You can't consider [3.6, 3.9] since the number of glitches < 3
A particular timestamp will fall into one window only. So since 3.0 already fell into the first window, it can't fall into the second window.
Try to solve this today we can discuss tomorrow.'''
input_lst = [2.1, 2.5, 2.9, 3.0, 3.6, 3.9, 5.2, 5.9, 6.1, 8.2, 10.2, 11.3, 11.8, 11.9]
previous_sec = 0
output_list = []
#while input_lst:
# try:
# peak_first = input_lst[0]
# peak_third = input_lst[2]
# if (int(peak_first) == int(peak_third) or
# peak_third < int(peak_first)+1.2):
# current_sec = int(peak_first)
# if previous_sec+1.2 > peak_third:
# previous_sec = peak_third
# input_lst.pop(0)
# continue
# if previous_sec != current_sec:
# output_list.append(peak_first)
# previous_sec = current_sec
# input_lst.pop(0)
# except Exception:
# break
#print(output_list)
input_lst = [2.1, 2.5, 2.9, 3.0, 3.6, 3.9, 5.2, 5.9, 6.1, 8.2, 10.2, 11.3, 11.8, 11.9]
previous = 0
output_lst = []
current_window = []
gitches_window = []
while input_lst:
try:
first_peek = input_lst[0]
third_peek = input_lst[2]
if third_peek <= first_peek+1:
if first_peek <= previous+1:
print(first_peek)
input_lst.pop(0)
continue
previous = first_peek
output_lst.append(previous)
#print('Starting {}, previous {}'.format(first_peek, previous))
except IndexError:
break
input_lst.pop(0)
print(output_lst)
|
class Node(object):
def __init__(self, data, next_node=None):
self.data = data
self.next = next_node
def runner_techinque_recursive(pointer_1, pointer_2):
if not pointer_1:
return pointer_2.next
pointer_1 = pointer_1.next
if pointer_1 and pointer_1.next:
pointer_2 = pointer_2.next
pointer_1 = pointer_1.next
return runner_techinque_recursive(pointer_1, pointer_2)
def runner_techinque_iterative(head):
pointer_1 = head
pointer_2 = head
while pointer_2.next:
pointer_2 = pointer_2.next
if pointer_2.next:
pointer_2 = pointer_2.next
pointer_1 = pointer_1.next
return pointer_1
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
print(runner_techinque_recursive(head.next.next, head).__dict__)
print(runner_techinque_iterative(head).__dict__)
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
head.next.next.next.next.next = Node(6)
head.next.next.next.next.next.next = Node(7)
head.next.next.next.next.next.next.next = Node(8)
print(runner_techinque_recursive(head.next.next, head).__dict__)
print(runner_techinque_iterative(head).__dict__)
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
head.next.next.next.next.next = Node(6)
head.next.next.next.next.next.next = Node(7)
# head.next.next.next.next.next.next.next = Node(8)
print(runner_techinque_iterative(head).__dict__)
|
#!/usr/bin/env python3
import sys
import numbers
import numpy as np
def read_experiments(file_list):
experiments = []
for fn in file_list:
with open(fn) as f:
data = f.read().rstrip('\n')
exec('experiments.append(' + data + ')')
return experiments
def aggregate(exps, cond_dict):
'''Returns a list of the experiments that match the conditions given'''
return [e for e in exps if len(e.items() & cond_dict.items()) == len(cond_dict.items())]
def reduce(exps):
'''Takes the average of all the values in in a list of experiments
Returns results as a dict containing:
(1) the arithmetic mean of any numeric values
(2) a string if and only if that string has the same value for all experiments
Note that any key that is not present in all experiments is discarded. Similarly, if a string has multiple values, it too is discarded.
'''
e0 = exps[0]
ans = {}
for k in e0.keys():
if isinstance(e0[k], numbers.Number):
try:
ans[k] = sum([e[k] for e in exps]) / len(exps)
ans[k + '_std'] = np.std([e[k]for e in exps])
ans[k + '_low95'] = np.percentile([e[k]for e in exps], 2.5)
ans[k + '_high95'] = np.percentile([e[k]for e in exps], 97.5)
except (TypeError, KeyError):
pass
if isinstance(e0[k], str):
try:
if len(set([e[k] for e in exps])) == 1:
ans[k] = e0[k]
except (TypeError, KeyError):
pass
return ans
def percent_err(x_est, x):
'''Returns relative percent error'''
return 100 * (x_est - x) / x
def fnum(x):
'''Formats a number with commas and no decimal places if >1,000, and with 2 digits after the decimal point otherwise'''
if x > 1000:
return "{:,.0f}".format(x)
elif x > 100:
return "{:.1f}".format(x)
elif x > 10:
return "{:.2f}".format(x)
else:
return "{:.3f}".format(x)
def count_string(c):
'''Used for all the raw aggregate count data, and also hll-mask, since that incorporates an aggregate count like portion'''
num_patients = c['num_patients']
try:
wait = (c['hospital_round0_time'] / 100
+ c['hub_round0_time']
+ c['hospital_round1_time'] / 100
+ c['hub_round1.5_time']
+ c['hospital_round2_time'] / 100
+ c['hub_round2.5_time'])
wait_string = fnum(wait)
except KeyError:
wait = c['hub_elapsed']
wait_string = fnum(wait)
if 'estimate_min' not in c:
c['estimate_min'] = c['estimate']
c['estimate_min_std'] = c['estimate_std']
c['estimate_min_low95'] = c['estimate_low95']
c_string = "\t".join([
c['title'], # Method
"[{}, {}]".format(fnum(c['estimate_min_low95']), fnum(c['estimate_high95'])), # Estimate (actual)
"[{:.0f}%, {:.0f}%]".format(percent_err(c['estimate_min_low95'], num_patients), percent_err(c['estimate_high95'], num_patients)), # Estimate (relative)
"{}".format(wait_string), # Wait (mean)
"{}".format(wait_string), # Wait (max)
"{}".format(fnum(c['revealed'])), # Hub r1
"{}".format(fnum(c['revealed_5anon'])), # Hub r4
"{}".format(fnum(c['revealed_10anon'])), # Hub r9
"{}".format(fnum(c['revealed'])), # Hosp r1
"{}".format(fnum(c['revealed_5anon'])), # Hosp r4
"{}".format(fnum(c['revealed_10anon'])), # Hosp r9
])
return c_string
def hll_string(h, h_hosp=None):
'''h contains data for the method we are currently using, and h_hosp contains data for the equivalent method
if a hospital conspires with the hub to reveal the secret salt for rehashing or shuffling
Note: do not use for the hll-mask method, but use count_string instead because it also includes a summation term.
'''
num_patients = h['num_patients']
if h_hosp is None:
h_hosp = h
assert 'estimate_min' not in h, "Please don't use hll_string for hll-mask method or count methods. Use count_string instead"
if 'hub_elapsed' in h:
if 'hosp_elapsed' not in h:
h['hosp_elapsed'] = 0
if 'max_hosp_elapsed' not in h:
h['max_hosp_elapsed'] = 0
try:
# Using MPC
wait_mean = (
h['hospital_round0_time'] / 100
+ h['hub_round0_time']
+ h['hospital_round1_time'] / 100
+ h['hub_round1.5_time']
+ h['hospital_round2_time'] / 100
+ h['hub_round_2.5_time']
+ h['hub_round2.9_time']
)
wait_mean_string = fnum(wait_mean)
wait_max_string = wait_mean_string
except KeyError:
try:
# Rehashing
wait_mean = h['hosp_elapsed'] / 100 + h['hub_elapsed']
wait_max = h['max_hosp_elapsed'] + h['hub_elapsed']
wait_mean_string = fnum(wait_mean)
wait_max_string = fnum(wait_max)
except KeyError:
wait_mean_string = fnum(h['hub_elapsed'])
wait_max_string = wait_mean_string
h_string = "\t".join([
h['title'], # Method
"[{}, {}]".format(fnum(h['estimate_low95']), fnum(h['estimate_high95'])), # Estimate (actual)
"[{:.0f}%, {:.0f}%]".format(percent_err(h['estimate_low95'], num_patients), percent_err(h['estimate_high95'], num_patients)), # Estimate (relative)
wait_mean_string, # Wait (mean)
wait_max_string, # Wait (max)
"{}".format(fnum(h['revealed'])), # Hub r1
"{}".format(fnum(h['revealed_5anon'])), # Hub r4
"{}".format(fnum(h['revealed_10anon'])), # Hub r9
"{}".format(fnum(h_hosp['revealed'])), # Hosp r1
"{}".format(fnum(h_hosp['revealed_5anon'])), # Hosp r4
"{}".format(fnum(h_hosp['revealed_10anon'])), # Hosp r9
])
return h_string
def summary_count(num_patients, exps):
'''Returns a TSV string for information on counts with the following rows
Method, Estimate, Hub-r1, Hub-r4, Hub-r9, HubHosp-r1, HubHosp-r4, HubHosp-r9, Wait
Where 'Method' is one of the following:
count
count, mask
hll
hll, mask
hll, rehash
hll, shuffle
count, mpc
hll, mpc
hll, mpc, shuffle
'''
ans_array = []
ans_array.append("\t".join([
"Method",
"Estimate (actual)",
"Estimate (relative)",
"Wait (mean)",
"Wait (max)",
"Hub r1",
"Hub r4",
"Hub r9",
"Hosp r1",
"Hosp r4",
"Hosp r9"
]))
c = reduce(aggregate(exps, {'title': 'agg_stats', 'num_patients': num_patients}))
cm = reduce(aggregate(exps, {'title': 'agg_mask_stats', 'num_patients': num_patients}))
ce = reduce(aggregate(exps, {'title': 'agg_mpc_stats', 'num_patients': num_patients}))
ans_array.append(count_string(c))
ans_array.append(count_string(cm))
ans_array.append(count_string(ce))
h = reduce(aggregate(exps, {'title': 'hll0_stats', 'num_patients': num_patients}))
hm = reduce(aggregate(exps, {'title': 'hll0_mask_stats', 'num_patients': num_patients}))
hr = reduce(aggregate(exps, {'title': 'hll0_rehashed_stats', 'num_patients': num_patients}))
hs = reduce(aggregate(exps, {'title': 'hll0_shuffle_stats', 'num_patients': num_patients}))
he = reduce(aggregate(exps, {'title': 'hll0_mpc_stats', 'num_patients': num_patients}))
hes = reduce(aggregate(exps, {'title': 'hll0_mpc_shuffle_stats', 'num_patients': num_patients}))
ans_array.append(hll_string(h))
ans_array.append(hll_string(hs, h_hosp=h))
ans_array.append(hll_string(hr, h_hosp=h))
ans_array.append(count_string(hm))
ans_array.append(hll_string(he))
ans_array.append(hll_string(hes, h_hosp=he))
h = reduce(aggregate(exps, {'title': 'hll1_stats', 'num_patients': num_patients}))
hm = reduce(aggregate(exps, {'title': 'hll1_mask_stats', 'num_patients': num_patients}))
hr = reduce(aggregate(exps, {'title': 'hll1_rehashed_stats', 'num_patients': num_patients}))
hs = reduce(aggregate(exps, {'title': 'hll1_shuffle_stats', 'num_patients': num_patients}))
he = reduce(aggregate(exps, {'title': 'hll1_mpc_stats', 'num_patients': num_patients}))
hes = reduce(aggregate(exps, {'title': 'hll1_mpc_shuffle_stats', 'num_patients': num_patients}))
ans_array.append(hll_string(h))
ans_array.append(hll_string(hs, h_hosp=h))
ans_array.append(hll_string(hr, h_hosp=h))
ans_array.append(count_string(hm))
ans_array.append(hll_string(he))
ans_array.append(hll_string(hes, h_hosp=he))
h = reduce(aggregate(exps, {'title': 'hll4_stats', 'num_patients': num_patients}))
hm = reduce(aggregate(exps, {'title': 'hll4_mask_stats', 'num_patients': num_patients}))
hr = reduce(aggregate(exps, {'title': 'hll4_rehashed_stats', 'num_patients': num_patients}))
hs = reduce(aggregate(exps, {'title': 'hll4_shuffle_stats', 'num_patients': num_patients}))
he = reduce(aggregate(exps, {'title': 'hll4_mpc_stats', 'num_patients': num_patients}))
hes = reduce(aggregate(exps, {'title': 'hll4_mpc_shuffle_stats', 'num_patients': num_patients}))
ans_array.append(hll_string(h))
ans_array.append(hll_string(hs, h_hosp=h))
ans_array.append(hll_string(hr, h_hosp=h))
ans_array.append(count_string(hm))
ans_array.append(hll_string(he))
ans_array.append(hll_string(hes, h_hosp=he))
h = reduce(aggregate(exps, {'title': 'hll7_stats', 'num_patients': num_patients}))
hm = reduce(aggregate(exps, {'title': 'hll7_mask_stats', 'num_patients': num_patients}))
hr = reduce(aggregate(exps, {'title': 'hll7_rehashed_stats', 'num_patients': num_patients}))
hs = reduce(aggregate(exps, {'title': 'hll7_shuffle_stats', 'num_patients': num_patients}))
he = reduce(aggregate(exps, {'title': 'hll7_mpc_stats', 'num_patients': num_patients}))
hes = reduce(aggregate(exps, {'title': 'hll7_mpc_shuffle_stats', 'num_patients': num_patients}))
ans_array.append(hll_string(h))
ans_array.append(hll_string(hs, h_hosp=h))
ans_array.append(hll_string(hr, h_hosp=h))
ans_array.append(count_string(hm))
ans_array.append(hll_string(he))
ans_array.append(hll_string(hes, h_hosp=he))
h = reduce(aggregate(exps, {'title': 'hll15_stats', 'num_patients': num_patients}))
hm = reduce(aggregate(exps, {'title': 'hll15_mask_stats', 'num_patients': num_patients}))
hr = reduce(aggregate(exps, {'title': 'hll15_rehashed_stats', 'num_patients': num_patients}))
hs = reduce(aggregate(exps, {'title': 'hll15_shuffle_stats', 'num_patients': num_patients}))
# he = reduce(aggregate(exps, {'title': 'hll15_mpc_stats', 'num_patients': num_patients}))
# hes = reduce(aggregate(exps, {'title': 'hll15_mpc_shuffle_stats', 'num_patients': num_patients}))
ans_array.append(hll_string(h))
ans_array.append(hll_string(hs, h_hosp=h))
ans_array.append(hll_string(hr, h_hosp=h))
ans_array.append(count_string(hm))
# ans_array.append(hll_string(he))
# ans_array.append(hll_string(hes, h_hosp=he))
au = reduce(aggregate(exps, {'title': 'all_stats', 'num_patients': num_patients}))
aur = reduce(aggregate(exps, {'title': 'all_rehashed_stats', 'num_patients': num_patients}))
ans_array.append(hll_string(au))
ans_array.append(hll_string(aur, h_hosp=au))
return "\n".join(ans_array)
if __name__ == '__main__':
experiments = read_experiments(sys.argv[1:])
experiment_list = [z for x in experiments for y in x for z in y]
for x in [10**i for i in range(0, 9)]:
print(summary_count(x, experiment_list))
|
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import csv
#First select file csv path with data (this replaces 'C:\Your data'), give each data column a name, you can add or remove columns as you wish:
data = pd.read_csv(r'C:\Your data', header = 0, usecols = ['column 1', 'column 2', 'column 3', 'column 4'] )
df = pd.DataFrame(data)
#Now choose the column titles to display on the graph, N is the number of bars that will displayed and should be changed accordingly
N = 4
column_1 = df['column 1'].tolist()
column_2 = df['column 2'].tolist()
column_3 = df['column 3'].tolist()
column_4 = df['column 4'].tolist()
ind = np.arange(N)
#You can also change the width of the bar
width = 0.2
plt.bar(ind, column_1, width, label='column 1')
plt.bar(ind + width, column_2, width, label='column 2')
plt.bar(ind + 2*width, column_3, width, label='column 3')
plt.bar(ind + 3*width, column_4, width, label='column 4')
labels = (i for i in range(1, N+1))
#Y axis label
plt.ylabel('Y axis')
#X axis label
plt.xlabel('X axis')
plt.xticks(ind + width*1.5, labels)
plt.legend(loc = 'best')
plt.show()
|
# def fed(x):
# return x*x
#
# r = map(fed,[1,2,3,4])
# for i in r:
# print(i)
#
# from functools import reduce
# def add(x, y):
# return x + y
# print(reduce(add,[1, 3, 5, 7, 9]))
from day04.Student import Student
ddd = Student('Bart Simpson', 59)
ddd.print_score() |
import csv
from datetime import datetime
import os
import sqlite3
def create_tables(cursor):
create_item_table = """
CREATE TABLE item (
name TEXT,
CONSTRAINT unique_item_name UNIQUE (name)
)
"""
create_category_table = """
CREATE TABLE category (
name TEXT,
CONSTRAINT unique_category_name UNIQUE (name)
)
"""
create_item_category_table = """
CREATE TABLE itemcategory (
item TEXT,
category TEXT,
FOREIGN KEY(item) REFERENCES item(name),
FOREIGN KEY(category) REFERENCES category(name),
CONSTRAINT unique_itemcategory UNIQUE (item, category)
)
"""
create_entry_table = """
CREATE TABLE entry (
item TEXT,
datetime TEXT, -- "YYYY-MM-DD HH:MM:SS.SSS"
amount REAL,
FOREIGN KEY(item) REFERENCES item(name)
)
"""
create_table_statements = [
create_item_table,
create_category_table,
create_item_category_table,
create_entry_table
]
for statement in create_table_statements:
cursor.execute(statement)
def load_data(cursor):
file_loc = '/Users/andy/Downloads/spoutdoors.csv'
all_categories = set()
items_and_categories = {}
entries = []
with open(file_loc, 'r') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
entries.append(row)
categories = [text.strip(' ') for text in row['categories'].split(';') if text]
all_categories.update(set(categories))
items_and_categories[row['name']] = categories
load_items(cursor, items_and_categories.keys())
load_categories(cursor, all_categories)
load_itemcategory(cursor, items_and_categories)
load_entries(cursor, entries)
def load_items(cursor, items):
insert_item = """INSERT INTO item VALUES (?)"""
for item in items:
cursor.execute(insert_item, (item.lower(),))
def load_categories(cursor, categories):
insert_category = """INSERT INTO category VALUES (?)"""
for category in categories:
cursor.execute(insert_category, (category.lower(),))
def load_itemcategory(cursor, items_and_categories):
insert_item_category = """INSERT INTO itemcategory VALUES (?, ?) -- item, category"""
for item, categories in items_and_categories.items():
for category in categories:
cursor.execute(insert_item_category, (item.lower(), category.lower()))
def load_entries(cursor, entries):
insert_entry = """INSERT INTO entry VALUES (?,?,?) -- item, datetime, amount"""
datetime_format = '%a %b %d %H:%M:%S UTC %Y' # Sat Jul 28 15:59:00 UTC 2018
for entry in entries:
timestamp = datetime.strptime(entry['date'], datetime_format)
cursor.execute(insert_entry, (entry['name'].lower(), timestamp, entry['amount']))
def delete_old_db(db_file):
os.remove(db_file)
def main():
db_file = './daytum.db'
delete_old_db(db_file)
db = sqlite3.connect(db_file)
cursor = db.cursor()
create_tables(cursor)
load_data(cursor)
db.commit()
main()
|
# importing os module
import os
# Function to rename multiple files
def main():
def removeYear():
for filename in os.listdir("pdf"):
print(filename[11:])
os.rename('pdf/' + filename, 'pdf/' + filename[11:])
def organizeLetters():
for filename in os.listdir("pdf"):
i=1
first = filename[0]
#Skip First letter
for letter in filename[1:]:
if letter.isupper() == False:
first += letter
i += 1
continue
elif letter.isupper() == True:
break
last = filename[i]
for letter in filename[i+1:]:
if letter != '.':
last += letter
continue
elif letter == '.':
break
os.rename('pdf/' + filename, 'pdf/' + 'Spring2012' + last + first +'.pdf')
#removeYear()
organizeLetters()
# Driver Code
if __name__ == '__main__':
# Calling main() function
main()
|
# time complexity space complexity
# add() O(1) O(1)
# remove() O(1) O(1)
# contain() O(1) O(1)
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.hasset=[None]*1000
def get_index1(self,key):
return key%1000
def get_index2(self,key):
return key//1000
def add(self, key: int) -> None:
i=self.get_index1(key)
if self.hasset[i] == None:
self.hasset[i]=[None]*1000
self.hasset[i][self.get_index2(key)] = key
else:
self.hasset[i][self.get_index2(key)] = key
def remove(self, key: int) -> None:
i = self.get_index1(key)
if self.hasset[i] != None:
j=self.get_index2(key)
if self.hasset[i][j] != None:
self.hasset[i][j] = None
def contains(self, key: int) -> bool:
"""
Returns true if this set contains the specified element
"""
i = self.get_index1(key)
if self.hasset[i] != None:
j = self.get_index2(key)
if self.hasset[i][j] != None:
return True
else:
return False
# Your MyHashSet object will be instantiated and called as such:
obj = MyHashSet()
obj.add(10004)
obj.add(1004)
obj.add(14)
obj.add(104)
obj.add(4)
obj.remove(104)
obj.remove(12)
print(obj.contains(1004))
print(obj.contains(104))
|
"""
Hacer un script que muestro todos los numeros, entre dos numeros ingresados
por el usuario.
"""
numero_uno = int(input("Ingresa numero uno: "))
numero_dos = int(input("Ingrese numero dos: "))
if numero_uno < numero_dos:
for numoro in range(numero_uno, (numero_dos + 1)):
print(numero)
else:
for numero in range(numero_dos, (numero_uno + 1)):
print(numero) |
def inputconvert():
f = []
d = []
while True:
t = input()
if t:
f.append(t)
else:
break
for i in f:
d.append(int(i))
return d
c = []
a = inputconvert()
b = inputconvert()
for i in a:
c.append(i)
for i in b:
c.append(i)
c.sort()
print(c) |
def listToString(list):
final_string = ''
for i in range(len(list)):
if i == len(list) - 1:
final_string += list[i]
elif i == len(list) - 2:
final_string = final_string + list[i] + ' i '
else:
final_string = final_string + list[i] + ', '
return final_string
i = 0;
tab = [];
while True:
print('Podaj ' + str(i + 1) + ' słowo w tablicy')
print('By zakonczyć i skonwertować tablicę na string kliknij enter nie wpisując nic!')
char = input()
if char == '':
break
else:
tab.append(char)
print('otrzymany string: ')
print(listToString(tab))
|
# Exercise Objective:
# Produce a data visualization output to determine the
# market cap value of the PSE's only ETF in the market
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import csv
data_set = pd.read_csv("PSE DATA.csv", index_col=False)
etf_coy = data_set.loc[0,"COMPANY NAME"]
etf_mc = data_set.loc[0,"MARKET CAPITALIZATION"]
etf_df = pd.DataFrame(data_set, index=[etf_coy, etf_mc])
plt.figure(figsize=[20, 30])
plt.style.use("seaborn")
plt.gca()
plt.subplots_adjust(left=0.29, right=0.95, top=0.80, bottom=0.16)
plt.barh(y=etf_coy, width=etf_mc, color="skyblue", align="center")
plt.title("PSE Listed Companies \n ETF Sector \n", fontsize=15)
plt.text(0.8, 0.1, """ The First Metro Exchange Traded Fund \n
is the only exchange traded fund in the \n
Philippine Stock Exchange. It is managed by \n
First Metro Asset Management.""")
plt.xlabel("Market Cap Value in PHP", fontsize=10)
plt.xticks(fontsize=8)
plt.yticks(fontsize=10)
plt.show()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 13:57:22 2018
@author: nataliecedeno
"""
#%%
#Exercise 1
shopping_list = {"Guitar":1000,
"Pick_box":5,
"Guitar_string":10
}
shopping_cart = ["Guitar", "Guitar_string" ]
def checkout(shopping_cart):
final_price=0
if shopping_cart == []:
return None
else:
for item in shopping_cart:
final_price = final_price +(shopping_list [item])
return final_price
checkout (shopping_cart)
#%%
#Exercise 2
prices = {"Guitar":1000,"Pick Box":5, "Guitar Strings":10, "Insurance":5, "Priority mail":10}
#mycart = ["Guitar","Guitar Strings","Guitar Strings","Guitar"]
#mycart = ["Guitar"]
prices_in_cart = []
def checkout_blue(mycart):
if "Insurance" in mycart:
prices_in_cart.append(prices["Insurance"])
for i in mycart:
if "Insurance" in mycart:
mycart.pop(mycart.index("Insurance"))
print(mycart)
if "Priority mail" in mycart:
prices_in_cart.append(prices["Priority mail"])
for i in mycart:
if "Priority mail" in mycart:
mycart.pop(mycart.index("Priority mail"))
print(mycart)
if mycart == []:
return None
else:
for i in mycart:
prices_in_cart.append(prices[i])
print(prices_in_cart)
return sum(prices_in_cart)
checkout_blue(["Pick Box", "Guitar","Insurance","Insurance", "Priority mail", "Priority mail"])
#%%
|
week = 0
one = 25000.0
two = 25000.0
three = 25000.0
for x in range(0, 365):
week += 1
if week == 6:
print "------"
elif week == 7:
week = 0
else:
one=one*1.01
two=two*1.02
three=three*1.03
print "%.0f" % one + " %.0f" % two + " %.0f" % three
|
import tensorflow as tf
# A placeholder like a variable that won't actually receive its data until a later point.
# In a placeholder you need to specify the data type, as well as the data type's precision in terms of the number of bits.
a = tf.placeholder(tf.float32)
b = 2*a
# The placeholder doesn't hold a value.
# We can solve this by passing an extra argument when we call the session with the argument 'feed_dict',
# a dictionary that contains each placeholder name followed by its respective data:
with tf.Session() as session:
result = session.run(b, feed_dict={a: 5.5}) #
print(result)
|
from shapely.geometry import Polygon, Point
import random
def generator(poly, number_of_random_points):
minx, miny, maxx, maxy = poly.bounds
list_of_points = []
for i in range(number_of_random_points):
while True:
p = Point(random.uniform(minx, maxx), random.uniform(miny, maxy))
if poly.contains(p):
list_of_points.append(p)
break
return list_of_points
def find_points():
number_of_points = int(input("How many vertices will the figure have? "))
points = []
for i in range(0, number_of_points):
x, y = input("Give x and y vertex: ").split()
points.append([])
points[i].append(float(x))
points[i].append(float(y))
p = Polygon(points)
number_of_random_points = input("How many random points to generate?")
random_points = generator(p, int(number_of_random_points))
individual_points = [(pt.x, pt.y) for pt in random_points]
with open("Data/RandomPoints.txt", 'w') as f:
f.writelines(','.join(str(j) for j in i) + '\n' for i in individual_points)
|
from statistics import mean
import numpy as np
class LSR:
def __init__(self):
self.slope = 0 #This represents the slope of our regression
self.intercept = 0 #This represents the intercept of our regression
self.r_squared = 0 #This represents the r^2 squared of our regression
def Model(self, x, y):
temp_x = np.array(x, dtype=np.float64) #numpy array of our x values
temp_y = np.array(y, dtype=np.float64) #numpy array of our y values
if(temp_x.shape == temp_y.shape):
self.slope = ( ((mean(temp_x) * mean(temp_y)) - mean(temp_x * temp_y))/((mean(temp_x)*mean(temp_x)) - mean(temp_x*temp_x)) )
self.intercept = mean(temp_y) - (self.slope * mean(temp_x))
temp_y_approx = self.slope*temp_x + self.intercept
self.r_squared = 1 - ( (np.sum((temp_y - temp_y_approx)**2))/(np.sum((temp_y - mean(temp_y))**2)) )
print("Slope: ", self.slope)
print("Offset: ", self.intercept)
print("R^2 Squared: ", self.r_squared)
del temp_x, temp_y, temp_y_approx
else:
print("X and Y are not the same shape")
|
# set is like the dictionary created with {} but it has no key value pair
empty_set={}
print(type(empty_set))
empty_set=set()
print(type(empty_set))
set1={"r","t","y","m"}
print(set1)
dic4={4:"prabh",5:"prabha",6:"kuruvi"}
set2=set(dic4)
print(set2)
set3=set(dic4.values())
print(set3)
print(len(set3))
print("prabh" in set3)
set3.add("scott")
print(set3)
# doesn't support the indexing Eg: set3[6]
print("diff")
print(set3.difference(set2)) # to find the difference between the set
# set method
print(set3.intersection(set2)) # common element between 2 sets
set3.difference_update(set2) # it deltes the common element between 2 sets and return the rest from first set
print(set3.isdisjoint(set2)) # to check there is no common elment between 2 set |
# Project Euler - Problem 3
# Question:
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
# Solution:
def high_factor(num):
i = 2
factors = []
while num > 1:
if num%i == 0:
factors.append(i)
num/=i
i = i +1
return factors
print(str(max(high_factor(600851475143))))
# Result - Correct
# Notes:
# Kept getting an infinite loop when i tried to implement a while loop
# Learned the process of prime factorization and tried to implement it
# in the least number of iterations |
import math
def numTrees(n):
dp = [0] * (n + 1)
dp[0] = 1
dp[1] = 1
for i in range(2, len(dp)):
for j in range(0, i):
"""
for a tree with i nodes
the total number of possible trees
is the sum of the product of all possible
subtrees
for example dp[4] =
dp[0]*dp[3] + dp[1]*dp[2] + dp[2]*dp[1]
+ dp[3]*dp[0]
"""
dp[i] += dp[j] * dp[i-j-1]
print i, j, i-j-1
return dp[-1]
def numTreeCatalanNum(n):
"""
catalan number:
n = 2n!/(n!*n!) * 1/(n+1)
"""
return (math.factorial(2 * n) /
(math.factorial(n) ** 2) / (n+1))
print numTreeCatalanNum(4)
|
def longestPalidrome(s):
dp = [[False] * len(s) for i in range(len(s))]
for i in range(len(s)):
for j in range(len(s)):
if i >= j:
dp[i][j] = True
left, right = 0, 0
for k in range(2, len(s) + 1): #the length of substring
for i in range(len(s) - k + 1): #start of substring
if s[i] == s[i+k-1] and dp[i+1][i+k-2]:
dp[i][i+k-1] = True
if right - left + 1 < k:
left = i
right = i+k-1
return s[left:right+1]
print longestPalidrome("abcdzdcabc")
|
def maxSubarry(num):
localMax = 0
localMin = 0
maxRes = 0
for i in range(len(num)):
tempMax = localMax
localMax = max(localMax * num[i], localMin * num[i], num[i])
localMin = min(tempMax * num[i], localMin * num[i], num[i])
maxRes = max(maxRes, localMax)
return maxRes
print maxSubarry([2,3,4,5,-6,10,-20]) |
from customer_account import Customer_account
class FileParser():
def read_customer_accounts(self, filename):
customer_accounts = []
try:
fo = open(filename, "r")
# store the file contents as a list of strings
lines = fo.readlines()
fo.close()
except IOError:
print(f"Warning: Could not open file {filename} for reading.")
input("Return to continue...")
# return the empty list of customers
return customer_accounts
# parse each line of accounts file and create a Account object
for line in lines:
account = self.parse_customer_accounts_text(line)
customer_accounts.append(account)
return customer_accounts
#--------------------------------------------------------------------------
# reads lines from file accounts.txt and builds new Customer_account object using this info
def parse_customer_accounts_text(self, accounts_text):
fields = accounts_text.split("|")
firstname = fields[0]
lastname = fields[1]
PPSN = fields[2]
account_type = fields[3]
overdraft = fields[4]
balance = float(fields[5])
interest_rate = float(fields[6])
account_number =int(fields[7])
#def __init__(self, firstname, lastname, PPSN,account_type, overdraft, balance, interest_rate, account_number=0):
return Customer_account(firstname, lastname, PPSN, account_type, overdraft, balance, interest_rate,account_number)
#-------------------------------------------------------------------------------------------
# for each Customer account object in the programs writes line in the file accounts.txt to store data about this object
#1 object - 1 line in the file separated | symbol
def write_customer_accounts(self, filename, customer_accounts):
# list to contain text versions of accounts for writing
lines = []
first_account = True
# build a list of customer accounts file strings
for account in customer_accounts:
if first_account == True:
lines.append(account.file_text())
first_account = False
else:
# if this isn't the first account, add a newline before writing
lines.append(f"\n{account.file_text()}")
try:
fo = open(filename, "w")
fo.writelines(lines)
fo.close()
except IOError:
print(f"Warning: Could not open {filename} for writing")
input("Return to continue...") |
class Person():
def __init__(self, name, field):
self.name = name
self.field = field
self.action = None
self.article = None
def assignArticle(self, articleID):
self.article = articleID
def isPersonReal(self):
'''
Determines whether a name is actually a human name
Returns true if so, and false if not
Designed to remove instances where the named entity chunker fails me.
'''
name = self.name
with open("C:\\Users\\user\\Documents\\major_project\\what-made-scientists-in-wales-famous-and-infamous-1804-1919\\software\\textfiles\\NAMES.txt", "r") as file:
listOfNames = file.read()
for names in listOfNames:
if names[0] == name[0]:
#if the first letter of the current name matches the first letter of the wanted name
#makes the search through over 150000 names not take forever
if name in listOfNames:
isReal = True
else:
isReal = False
else:
continue
return isReal
|
def calculetor():
print("\n Welcome to Calc: This is developed by TechGuyShubham")
operation = input("Choose your choice of Calculation\n + For Addition \n - For Subtraction \n * For Multipy \n ** For Power \n Enter Your choice:")
num1 = int(input("Enter 1st Number :"))
num2 = int(input("Enter your 2nd Number :"))
if operation == '+':
if num1 == 56:
print("56+9=77")
else:
print(num1 + num2)
elif operation == '*':
if num1 == 45:
print("45*3 = 123")
else:
print((num1 * num2))
elif operation == '/':
if num1 == 56:
print("56/6 = 12")
else:
print((num1 / num2))
elif operation == '**':
print((num1 ** num2))
elif operation == '-':
print((num1 - num2))
else:
print("You entered the in valid key")
|
import numpy as np
def calculate_pmi_rate(credit_score):
pmi_rate = 0
if credit_score < 640:
pmi_rate = 2.25
elif 639 < credit_score < 660:
pmi_rate = 2.05
elif 659 < credit_score < 680:
pmi_rate = 1.90
elif 679 < credit_score < 700:
pmi_rate = 1.40
elif 699 < credit_score < 720:
pmi_rate = 1.15
elif 719 < credit_score < 740:
pmi_rate = 0.95
elif 739 < credit_score < 760:
pmi_rate = 0.75
elif credit_score > 760:
pmi_rate = 0.55
return pmi_rate
if __name__ == '__main__':
home_price = float(input('Enter home price($): '))
interest_rate = float(input('Enter interest rate(%): '))
loan_duration = int(input('Enter loan duration(years): '))
credit_score = int(input('Enter credit score: '))
stock_appreciation = float(input('Enter stock appreciation(%): '))
for money_down in range(5, 21):
loan_principal = (1 - money_down/100) * home_price
monthly_payment = loan_principal * (interest_rate/12) / (1 - (1 + (interest_rate/12)) - loan_duration*12)
money_to_invest = (0.2 - money_down / 100) * home_price
stock_return = money_to_invest * pow((1 + stock_appreciation / 100), loan_duration)
if money_down < 20:
pmi_rate = calculate_pmi_rate(credit_score)
pmi_monthly = loan_principal*pmi_rate/loan_duration/12
monthly_payment += pmi_monthly
stock_return -= pmi_monthly*loan_duration*12
print('For %i%% money down, down payment = %f, stock investment = %f\n' % (money_down, money_down/100*home_price,
stock_return))
|
#Day 12 Rain Risk
#Making an object for this challenge seemed appropriate as I expected pt2 to have multiple boats :)
class Boat:
#Boat has a position x/y, a current direction (in the form of an int) and possible directions
def __init__(self, x, y, direction=0):
self.x = x
self.y = y
self.directions = ["N", "E", "S", "W"]
self.direction = direction
#Changes the direction of the boat. The problem only had directions in the cardinal directions
#If the problem statement wanted to handle non-cardinal directions, boat.direction would be in degrees instead of an int 0-3
def rotate(self, rot, degrees):
rot = 1 if rot == "R" else -1
self.direction = int((self.direction + rot*degrees / 90) % 4)
#Rotate function for the waypoint (IE rotating a boat object that is not in the main reference frame)
def rotate_waypoint(self, rot, degrees):
#How many iterations to rotate (0 --> 0, 90 --> 1, 180 --> 2, 270 --> 3, 360 --> 0)
rotations = (degrees / 90) % 4
#If rotating counterclockwise, we take the corresponding clockwise rotation:
#0 deg cw --> 0 deg ccw, 90 deg cw --> 270 deg ccw, 180 deg cw --> 180 deg ccw, 270 deg cw --> 90 deg ccw
if rot == "L":
rotations = (4 - rotations) % 4
#Rotate the coordinates rotations number of times. A rotation is (x, y) --> (y, -x) in this coordinate system
for _ in range(int(rotations)):
temp = self.x
self.x = self.y
self.y = -temp
#Moves a boat object in a specified direction or in the current direction of the boat by "distance" units
def move(self, direction, distance):
if direction == "N":
self.y += distance
elif direction == "S":
self.y -= distance
elif direction == "E":
self.x += distance
elif direction == "W":
self.x -= distance
else:
#Move the boat in the direction that it currently faces
self.move(self.directions[self.direction], distance)
#Gets manhattan distance (rectangular distance) of a boat's position and a given starting position (0,0) default
def get_manhattan(self, x1=0, y1=0):
return abs(self.x-x1)+abs(self.y-y1)
#Gets the problem movement commands in the form of tuples (string command, int value)
def get_movements():
with open("../assets/shipmovement.txt", 'r') as f:
return [(line[0], int(line[1:-1])) for line in f.readlines()]
#Executes the movements with the ruleset given in part 1
def exec_movements():
boat = Boat(0,0,1)
movements = get_movements()
for movement in movements:
if movement[0] == "L" or movement[0] == "R":
boat.rotate(movement[0], movement[1])
else:
boat.move(movement[0], movement[1])
return boat.get_manhattan()
#Executes the movement with the ruleset given in part 2
def exec_movements_waypoint():
boat = Boat(0,0,1)
waypoint = Boat(10,1,1)
movements = get_movements()
for movement in movements:
if movement[0] == "R" or movement[0] == "L":
waypoint.rotate_waypoint(movement[0], movement[1])
elif movement[0] == "F":
boat.x += waypoint.x * movement[1]
boat.y += waypoint.y * movement[1]
else:
waypoint.move(movement[0], movement[1])
return boat.get_manhattan()
print(f'Part1: {exec_movements()}\nPart2: {exec_movements_waypoint()}')
|
# Day 3: Toboggan Trajectory
"""
Takes a filepath (default = my path) and generates a 2D array of the environment
...#
.#..
#...
Becomes
[[., ., ., #],
[., #, ., .],
[#, ., ., .]]
"""
def get_env(filepath="../assets/trees.txt"):
env = []
with open(filepath, 'r') as f:
lines = f.readlines()
for line in lines:
env.append(list(line))
return env
# Counts the number of trees in a given slope using tuple locations (dx, dy) and (x,y)
def count_trees(env, slope: tuple, location=(0, 0)):
# Get dimensions of the environment
height = len(env) - 1
width = len(env[0]) - 1
num_trees = 0
# Since the x direction repeats infinitely, loop until the toboggan reaches the end of the y direction
while location[1] < height:
# Calculate the new coordinates after the toboggan moves, looping x if needed using x mod(height)
location = ((location[0] + slope[0]) % width, location[1] + slope[1])
# Check for a tree and count if necessary
if env[location[1]][location[0]] == '#':
num_trees += 1
return num_trees
# Automates the process for checking multiple slopes starting at a single location, taking a list of tuple slopes
def check_slopes(slopes, location=(0, 0)):
slope_product = 1
env = get_env()
# This code could easily be modified to give other, more interesting info than just the product of the trees :)
for slope in slopes:
slope_product *= count_trees(env, slope, location)
return slope_product
candidate_slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
print(f'Part1: {check_slopes([(3, 1)])} \nPart2: {check_slopes(candidate_slopes)}')
|
# Read two integers from STDIN and print three lines where:
# The first line contains the sum of the two numbers.
# The second line contains the difference of the two numbers (first - second).
# The third line contains the product of the two numbers.
# Sample input
a = 3
b = 2
# Sample output
# 5
# 1
# 6
def arithmetic(a, b):
print(a+b)
print(a-b)
print(a*b)
arithmetic(a, b)
|
import random
import numpy as np
import pandas as pd
nations = pd.Series(['Italy', 'Spain', 'Greece', 'Germany'])
def throwNeedles(numNeedles):
inCircle = 0
for _ in range(1, numNeedles+1, 1):
x = random.random()
y = random.random()
if (x**2 + y**2) ** 0.5 <= 1: # x**2 + y**2 = hypotenuse**2, since radius is one, if it's more than 1 is outside of the circle
inCircle += 1
return (4 * inCircle) / numNeedles
print(throwNeedles(20000))
|
import numpy as np
import pandas as pd
def df():
data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'],
'year': [2000, 2001, 2002, 2001, 2002, 2003],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]}
frame = pd.DataFrame(data)
print(pd.DataFrame(data, columns=['state','pop'])) # creates df of given columns only
frame2 = pd.DataFrame(data, index=['one','two','three','four','five','six']
, columns=['year','state','pop','dept'])
print(frame2)
print()
print(frame2['year']) # == frame2.year
print()
print(frame2.loc['three'])
print(frame2.iloc[:2, :2])
frame2['dept'] = 16.5 # sets all the dept to 16.5
frame2['dept'] = np.arange(len(frame2.index)) # sets all from 0 to 6
print()
print(frame2)
val = pd.Series([-1,-2,-3], index=['two', 'four', 'five'])
frame2['dept'] = val # puts the values only for the indexes of the series corresponding to the df
print(frame2)
print()
frame2['eastern'] = frame2.state == 'Ohio'
print(frame2)
del frame2['eastern']
print(frame2)
print(frame2.T) # transpose the dataframe
## --------------
obj = pd.Series(range(3), index=['a', 'b', 'c'])
print(obj[:2])
print()
population = {'Nevada': {2001: 2.4, 2002: 2.9},
'Ohio': {2000: 1.5, 2001: 1.7, 2002: 3.6}}
obj2 = pd.DataFrame(population)
print(obj2)
print('Ohio' in obj2.columns)
print('Ohio' in obj2.index)
print(obj2.loc[:, 'Nevada':])
|
import re
txt = "The rain in Spain"
x = re.search("^The", txt)
x = re.search("^The.*Spain$", txt) #Search the string to see if it starts with "The" and ends with "Spain":
print (x)
#findall - Returns a list of containing all matches
#search - Returns a Match Object if there is a match anywhee in the string
# sub Replaces one or many matches with a string
# [a-z] - denotes a set of character
# [0-9] - denotes a set of character/digits
# he..o - any character
# ^Hello - starts with
# world$ - ends with
# aix* - zero or more occurance
# aix+ - one or more occurance
# al{2} - exactly the specified number of occurancees
# falls|stays - either or
# [arn] - a, r, n match
# [a-n] - range
# [^arn] - not match (no a, r, n)
# [0-9]- match for any digits
# [a-zA-Z] - any letter
# [+] - return a match for any + character
# \A - match a beginning ex- x = re.findall("\AThe", txt)
# \b - at the begining or end () ex- x = re.findall(r"\bain", txt)
# \d - retuns match if matches digits x = re.findall("\d", txt)
# \D - no digits x = re.findall("\D", txt)
# \s -white space match
# \S - no whitespace
|
import json
#Convert Python objects into JSON strings, and print the values:
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
#another set of example
x = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x))
print(json.dumps(x, indent=4)) #Use the indent parameter to define the numbers of indents:
print(json.dumps(x, indent=4, separators=(". ", " = ")))#Use the separators parameter to change the default separator:
print(json.dumps(x, indent=4, sort_keys=True)) #The json.dumps() method has parameters to order the keys in the result:
|
def age_count(x):
if int(x) > 1980 and int(x) < 2020:
age = 2020 - int(x)
return str(age)
return 'Invalid'
birth_year=input("Enter your birth year: ")
print("Your age is " + age_count(birth_year)) |
print('Hello world')
name = input('Enter your name:')
age = int(input('Enter your age: '))
print('Welcome ' + name + ' your age is ' + str(age))
|
from enum import Enum
class BookFormat(Enum):
HARDCOVER = 1
PAPERBACK = 2
EBOOK = 3
KINDLE = 4
MAGAZINE = 5
JOURNAL = 6
class BookStatus(Enum):
AVAILABLE = 1
LOANED = 2
RESERVED = 3
LOST = 4
class AccountStatus(Enum):
ACTIVE = 1
SUSPENDED = 2
CLOSED = 3
CANCELLED = 4
class Address:
def __init__(self, addressline1, city, state, pin, country, addressline2=None):
self.addressline1 = addressline1
self.addressline2 = addressline2
self.city = city
self.state = state
self.pin = pin
self.country = country
class Constants:
def __init__(self):
self.MAX_BOOK_ISSUES_TO_USER = 5
self.MAX_DAYS_ALLOWED = 10
|
###################################################
# MC102 - Algoritmos e Programação de Computadores
# Laboratório 12 - Filtros de Imagens
# Nome: Bruno Morari
# RA: 168107
###################################################
'''
Função que recebe uma imagem e imprime essa imagem no formato PGM
'''
def imprime_imagem(imagem):
print("P2")
print(len(imagem[0]), len(imagem))
print("255")
for i in range(len(imagem)):
print(" ".join(str(x) for x in imagem[i]))
'''
Função que retorna a mediana de uma lista. Se o tamanho da lista
for par, a função retorna a parte inteira da média entre os elementos
centrais
'''
def mediana(lista):
lista_ordenada = sorted(lista)
elemento_central = len(lista_ordenada) // 2
if len(lista) % 2 == 1:
return lista_ordenada[elemento_central]
else:
#retorna a parte inteira da média entre os elementos centrais
return (lista_ordenada[elemento_central-1] + lista_ordenada[elemento_central]) // 2
'''
Função que recebe a matriz que representa a imagem original e
retorna a imagem resultante da aplicação do filtro negativo
'''
def filtro_negativo(imagem):
for i in range(len(imagem)):
for j in range(len(imagem[i])):
imagem[i][j] = 255 - imagem[i][j]
return imagem
'''
Função que recebe a matriz que representa a imagem original e
retorna a imagem resultante da aplicação do filtro da mediana
'''
def filtro_mediana(imagem):
count = 0
imagem2 = []
aux = 0
for i in range(len(imagem)):
for j in range(len(imagem[i])):
if i == 0 and j == 0:
aux = mediana([ imagem[i][j], imagem[i][j+1], imagem[i+1][j], imagem[i+1][j+1] ])
imagem2.append(aux)
elif i == 0 and j == (m-1):
aux = mediana([ imagem[i][j], imagem[i][j-1], imagem[i+1][j], imagem[i+1][j-1] ])
imagem2.append(aux)
elif i == (n-1) and j == 0:
aux = mediana([ imagem[i][j], imagem[i][j+1], imagem[i-1][j], imagem[i-1][j+1] ])
imagem2.append(aux)
elif i == (n-1) and j == (m-1):
aux = mediana([ imagem[i][j], imagem[i][j-1], imagem[i-1][j], imagem[i-1][j-1] ])
imagem2.append(aux)
elif i == 0:
aux = mediana([ imagem[i][j], imagem[i][j-1], imagem[i][j+1], imagem[i+1][j], imagem[i+1][j-1], imagem[i+1][j+1] ])
imagem2.append(aux)
elif i == (n-1):
aux = mediana([ imagem[i][j], imagem[i][j-1], imagem[i][j+1], imagem[i-1][j], imagem[i-1][j-1], imagem[i-1][j+1] ])
imagem2.append(aux)
elif j == 0:
aux = mediana([ imagem[i][j], imagem[i][j+1], imagem[i-1][j], imagem[i-1][j+1], imagem[i+1][j], imagem[i+1][j+1] ])
imagem2.append(aux)
elif j == (m-1):
aux = mediana([ imagem[i][j], imagem[i][j-1], imagem[i-1][j], imagem[i-1][j-1], imagem[i+1][j], imagem[i+1][j-1] ])
imagem2.append(aux)
else:
aux = mediana([ imagem[i-1][j-1], imagem[i-1][j], imagem[i-1][j+1], imagem[i][j-1], imagem[i][j], imagem[i][j+1], imagem[i+1][j-1], imagem[i+1][j], imagem[i+1][j+1] ])
imagem2.append(aux)
for k in range(len(imagem)):
for g in range(len(imagem[k])):
imagem[k][g] = imagem2[count]
count += 1
return imagem
'''
Função que recebe três parâmetros:
imagem: matriz que representa a imagem original
M: matriz núcleo
D: divisor
Essa função retorna a imagem resultante da aplicação de um filtro
que usa convolução
'''
def convolucao(imagem, lista, div):
imagem2 = []
count = 0
l1 = 0
l2 = 0
l3 = 0
aux = 0
result = 0
for i in range(len(imagem)):
for j in range(len(imagem[i])):
if i == 0:
continue
elif i == (n-1):
continue
elif j == 0:
continue
elif j == (m-1):
continue
else:
l1 = int(lista[0][0]*imagem[i-1][j-1] + lista[0][1]*imagem[i-1][j] + lista[0][2]*imagem[i-1][j+1])
l2 = int(lista[1][0]*imagem[i][j-1] + lista[1][1]*imagem[i][j] + lista[1][2]*imagem[i][j+1])
l3 = int(lista[2][0]*imagem[i+1][j-1] + lista[2][1]*imagem[i+1][j] + lista[2][2]*imagem[i+1][j+1])
result = (l1 + l2 + l3) / div
if result < 0:
aux = 0
imagem2.append(aux)
elif result > 255:
aux = 255
imagem2.append(aux)
else:
imagem2.append(int(result))
del imagem[0]
del imagem[-1]
for k in range(len(imagem)):
del imagem[k][0]
del imagem[k][-1]
for x in range(len(imagem)):
for y in range(len(imagem[x])):
imagem[x][y] = imagem2[count]
count += 1
return imagem
# Leitura da entrada
filtro = input()
_ = input() # P2 (linha a ser ignorada)
m, n = [int(x) for x in input().split()]
_ = input() # 255 - linha a ser ignorada
imagem = []
for i in range(n):
linha = [int(x) for x in input().split()]
imagem.append(linha)
# Aplica o filtro
if filtro == "negativo":
filtro_negativo(imagem)
elif filtro == "mediana":
filtro_mediana(imagem)
elif filtro == "edge-detect":
lista = [[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]
div = 1
convolucao(imagem, lista, div)
elif filtro == "blur":
lista = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
div = 9
convolucao(imagem, lista, div)
elif filtro == "sharpen":
lista = [[0, -1, 0], [-1, 5, -1], [0, -1, 0]]
div = 1
convolucao(imagem, lista, div)
# Imprime a imagem gerada
imprime_imagem(imagem) |
# -*- coding: utf-8 -*-
from typing import NamedTuple, List
if __name__ == '__main__':
Item = NamedTuple(
'Item',
[
('id', int),
('name', str),
('amount', int),
]
)
User = NamedTuple(
'User',
[
('id', int),
('name', str),
('age', int),
('items', List[Item]),
('money', int),
]
)
users = [
User(id=0, name='moqada', age=30, items=[Item(id=1, name='onigiri', amount=2)], money=100),
User(id=1, name='8maki', age=30, items=[Item(id=1, name='onigiri', amount=2)], money=210),
]
for u in users:
print(u.id, u.name, u.age)
u = User(id=3, name='achiku', age=31, items=[Item(id=1, name='onigiri', amount=2)], money=100)
print(u.id, u.name, u.age)
|
# -*- coding: utf-8 -*-
def make_named_set(name, s):
return {'name': name, 'set': s}
if __name__ == '__main__':
sets = [
make_named_set('set_a', set([1, 2, 3, 4])),
make_named_set('set_b', set([1, 2, 3])),
make_named_set('set_c', set([1, 2, 3, 4])),
make_named_set('set_d', set([1, 2, 3, 4, 5])),
make_named_set('set_e', set([5, 6])),
]
# pick one main set and sets excluding the main set and put them in to list of tuple
test_data_set = [(sets[idx], [s for i, s in enumerate(sets) if i != idx]) for idx in range(len(sets) - 1)]
print "# Difference"
for i in test_data_set:
print "## {} is the main set".format(i[0]['name'])
for j in i[1]:
print "({}){} - ({}){} = {}".format(
i[0]['name'], i[0]['set'], j['name'], j['set'], i[0]['set'] - j['set']
)
print "# Union"
for i in test_data_set:
print "## {} is the main set".format(i[0]['name'])
for j in i[1]:
print "({}){} | ({}){} = {}".format(
i[0]['name'], i[0]['set'], j['name'], j['set'], i[0]['set'] | j['set']
)
print "# Intersection"
for i in test_data_set:
print "## {} is the main set".format(i[0]['name'])
for j in i[1]:
print "({}){} & ({}){} = {}".format(
i[0]['name'], i[0]['set'], j['name'], j['set'], i[0]['set'] & j['set']
)
|
# 計算 1 + 2 + 3 + ... + 100
count_sum = 0
for i in range(1,101):
count_sum += i
s = "1 + 2 + 3 + ... + 100=%d" % (count_sum) # 字串格式化,語法: "內容%d %d" % (int,int)
print(s)
print("\n\n\n")
# 九九乘法表
for i in range(1,10):
for j in range(1,10):
print("%d x %d = %d" % (i,j,i*j))
print("\n\n\n")
# 九九乘法表2 - 方形版
for i in range(1,10):
for j in range(1,10):
print("%d x %d = %d\t" % (i,j,i*j),end="")
print("")
print("\n\n\n")
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
######################################################################
# Simples Web Server em python!
# Criado em 31/03/2019
# Criado por: Rafael Souza
#
# Passar os seguintes dados como variavel de ambiente:
#
# WEBSERVICE_PORT (INFORMAR PORTA TCP)
# WEBSERVICE_NAME (INFORMAR NOME DO WEB SERVER)
# WEBSERVICE_VERSION (INFORMAR A VERSAO)
#
######################################################################
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import os
import socket
import time
# Checa se porta esta vazia, se, sim, sobe na porta 3000
try:
int(os.getenv('WEBSERVICE_PORT'))
PORT_NUMBER = int(os.getenv('WEBSERVICE_PORT'))
except:
PORT_NUMBER = 3000
# Checa se cor de fundo esta vazia, se sim, sobe com cor branca
if str(os.getenv('WEBSERVICE_BGCOLOR')) == "None":
WEBSERVICE_BGCOLOR = "white"
else:
WEBSERVICE_BGCOLOR = str(os.getenv('WEBSERVICE_BGCOLOR'))
#HOSTNAME = str(socket.gethostname())
#DATE = str(time.ctime())
MESSAGE = \
'''
<html>
<head><title>PYTHON WEB SERVER</title></head>
<body bgcolor="{0}">
<center>
<h1> LUDONEWS - NOTICIAS</H1>
<br><br><br><br><br>
<br><br>
</center>
<br><br><br><br><br><br><br><br><br><br><br>
</body>
</html>
'''.format(WEBSERVICE_BGCOLOR)
# This class will handles any incoming request from
# the browser
class myHandler(BaseHTTPRequestHandler):
# Handler for the GET requests
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Send the html message
self.wfile.write(MESSAGE)
return
try:
# Create a web server and define the handler to manage the
# incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print('Iniciando o webserver na porta: ', str(PORT_NUMBER))
# Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down the web server')
server.socket.close()
|
# -*- coding: utf8 -*-
"""
Napisz program, który dla 10 kolejnych liczb naturalnych wyświetli sumę poprzedników.
Oczekiwany wynik: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55
"""
for i in range(11):
x = int((i*(1+i))/2)
print (x)
"""
0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
-----------------------------
#inne rozwiązanie
for x in range(1,11):
print(sum(lista[:x]))
"""
|
# -*- coding: utf8 -*-
"""
Utwórz spis oglądanych seriali.
Każdy serial powinen mieć przypisaną ocenę w skali od 1-10.
Zapytaj użytkownika jaki serial chce obejrzeć. W odpowiedzi podaj jego ocenę.
Zapytaj użytkownika o dodanie kolejnego serialu i jego oceny.
Dodaj do swojego spisu.
"""
serial = {
"Stranger Things" : 10,
"Piraci" : 9,
"Gra o tron" : 7,
"Dark" : 8,
"Czarnobyl" : 9
}
print(list(serial.keys()))
#
"""
jaki_serial = input("Jaki serial chcesz obejrzeć?: ")
print("Serial '{}' ma ocenę {}/10".format(jaki_serial,serial[jaki_serial]))
"""
wprowadz_serial = input("Jaki serial wprowadzić do bazy?: ")
jaka_ocena = int(input("Jak go oceniasz od 1 do 10: "))
serial[wprowadz_serial] = jaka_ocena
print("{}".format(serial.keys()))
print(list(serial.values()))
# results = [1,2,3,4]
# p_results = [5,6,7,8]
# for result,p_result in zip(results,p_results):
# print('{:3}{:20}'.format(result,p_result))
|
import itertools
import unittest
import string
from hypothesis import given, reproduce_failure, strategies as st
###########################################################################
#
# Human-readable representation
#
# We'll use strings of alphabetical characters, with
# capital letters being the inverse of small letters
# A = a^{-1}, B = b^{-1}, etc.
###########################################################################
def parse_char( char ):
if char.isupper():
return -( ord( char ) - ord( 'A' ) + 1 )
else:
return ord( char ) - ord( 'a' ) + 1
def parse( word ):
return [ parse_char( c ) for c in word ]
def unparse_char( e ):
if e > 0:
return chr( e - 1 + ord( 'a' ) )
else:
return chr( -e - 1 + ord( 'A' ) )
def unparse( word ):
return "".join( unparse_char(e) for e in word )
###########################################################################
#
# Free group operations and automorphisms
#
# The group operation is just +.
#
###########################################################################
def basis( rank ):
return range( 1, rank+1 )
def invert( word ):
tmp = [ -a for a in word ]
tmp.reverse()
return tmp
def cyclic_reduce( word ):
if len( word ) == 0:
return word
reduced = []
for a in word:
if len( reduced ) > 0 and -a == reduced[-1]:
reduced.pop()
else:
reduced.append( a )
while len( reduced ) >= 2:
if -reduced[0] == reduced[-1]:
reduced = reduced[1:-1]
else:
break
return reduced
def flatten_1( list_of_words ):
ret = []
for word in list_of_words:
ret.extend( word )
return ret
def automorphism_from_basis( basis_map, **kwargs ):
def use_basis( a ):
if a > 0:
return basis_map[a]
else:
return invert( basis_map[-a] )
def f( word ):
# If we flatten ahead of time then f(x) + f(y) != f(x+y)
return flatten_1( use_basis(a) for a in word )
f.map = basis_map
for k, v in kwargs.items():
setattr(f, k, v)
return f
def conjugacy_class_rep( w ):
"""Find the lexicographically minimal of the conjugacy class, which
consists of all cyclic permutations of the word."""
w = cyclic_reduce( w )
if len( w ) == 0:
return []
return min( w[r:] + w[:r] for r in range( len( w ) ) )
###########################################################################
#
# Whitehead automorphisms
#
###########################################################################
def all_inversions( permutation ):
for ops in itertools.product( [lambda x : [x], lambda x : [-x]],
repeat=len( permutation ) ):
yield [ f(x) for f, x in zip( ops, permutation ) ]
def whitehead_automorphisms( rank ):
bs = basis( rank )
# The identity is listed both places... filter it?
# Type 1
for p in itertools.permutations( bs ):
for pi in all_inversions( p ):
basis_map = dict( zip( bs, pi ) )
yield automorphism_from_basis( basis_map, kind=1 )
# Type 2
for e in bs:
for a in [ e, -e ]:
# all non-a elements x are mapped to one of
# x, xa, a^{-1}x, a^{-1}xa
choices = [ lambda x : [x],
lambda x : [x, a],
lambda x : [-a, x],
lambda x : [-a, x, a] ]
not_a = [x for x in bs if x != a and x != -a ]
a_self = [ (e, [e]) ]
for choice in itertools.product( choices, repeat=len( not_a ) ):
partial_aut = [ (x,f(x)) for f,x in zip( choice, not_a ) ]
basis_map = dict( a_self + partial_aut )
yield automorphism_from_basis( basis_map, kind=2, multiplier=a )
###########################################################################
#
# Whitehead graph
#
# Nodes are conjugacy classes.
# Edges are length-preserving Whitehead automorphisms.
#
###########################################################################
import itertools
def conjugacy_classes( rank, length ):
elements = list( basis(rank) ) + invert( basis( rank ) )
classes = set()
for word in itertools.product( elements, repeat=length ):
c = conjugacy_class_rep( word )
if len( c ) == length:
classes.add( tuple( c ) )
return classes
def show_classes( rank, length ):
line = ""
for c in conjugacy_classes( rank, length ):
line += "[" + unparse( c ) + "] "
if len( line ) + length + 3 > 80:
print( line )
line = ""
if line != "":
print( line )
class Component(object):
def __init__( self, name ):
self.name = name
self.size = 0
self.diameter = 0
def __str__( self ):
return "Component " + self.name + \
" size " + str(self.size) + \
" diameter <= " + str(self.diameter)
def summarize_graph( rank, length ):
print( "Rank", rank, "length", length )
classes = conjugacy_classes( rank, length )
print( len( classes ), "conjugacy classes" )
visited = set()
components = []
automorphisms = list( whitehead_automorphisms( rank ) )
print( len( automorphisms ), "automorphisms" )
while len( classes ) > 0:
next_component = classes.pop()
queue = set( [next_component] )
name = "[" + unparse( next_component ) + "]"
depth = { next_component : 0 }
cc = Component( name )
while len( queue ) > 0:
current = queue.pop()
visited.add( current )
cc.size += 1
for f in automorphisms:
v = tuple( conjugacy_class_rep( f( current ) ) )
if len( v ) != length:
continue
if v in visited or v in queue:
continue
classes.remove( v )
queue.add( v )
depth[v] = depth[current] + 1
#print( unparse( current ), "->", unparse( v ), depth[v] )
cc.diameter = max( depth.values() ) * 2
print( cc )
components.append( cc )
return components
import pprint
def show_rank( rank, minLength = 2 ):
results = []
try:
for l in itertools.count( minLength ):
cc = summarize_graph( rank, l )
maxCC = max( cc, key = lambda x : x.size )
results.append( ( l, maxCC.size, maxCC.name ) )
pprint.pprint( results )
except KeyboardInterrupt:
pprint.pprint( results )
return results
###########################################################################
#
# Unit tests
#
###########################################################################
class ParseTests(unittest.TestCase):
@given(st.text(alphabet=string.ascii_lowercase + string.ascii_uppercase))
def test_identity(self, x):
self.assertEqual( x, unparse(parse(x)) )
@st.composite
def word_of_rank( draw, rank ):
elements = st.integers( -rank, rank ).filter( lambda x : x != 0 )
return draw( st.lists( elements ) )
def element_of_rank( rank ):
return st.integers( -rank, rank ).filter( lambda x : x != 0 )
class ReduceTests(unittest.TestCase):
@given(st.lists(st.integers()))
def test_reduce_idempotent(self, x):
y = cyclic_reduce( x )
z = cyclic_reduce( y )
self.assertEqual( y, z )
@given(word_of_rank(5),element_of_rank(5))
def test_conjugacy_class(self,w,x):
w2 = [-x] + w + [x]
self.assertEqual( conjugacy_class_rep( w ),
conjugacy_class_rep( w2 ) )
class AutomorphismTests(unittest.TestCase):
@given( word_of_rank( 4 ), word_of_rank( 4 ) )
def test_automorphism(self, x, y ):
for f in whitehead_automorphisms( 4 ):
self.assertEqual( f( [] ), [] )
self.assertEqual( f( invert( x ) ),
invert( f( x ) ) )
self.assertEqual( f( x + y ),
f( x ) + f( y ),
"Function: " + str(f.map) )
def testAll():
unittest.main(exit=False)
|
# 1. Import a file with strings
# 2. Let it read through the file and do per string the following:
# 2.1. Break the string up in seperate characters.
# 2.2. The index of the letter in the alphabet will be the power of 2. For example: a = 2^0, b = 2^1, e = 2^5.
# 2.3. Calculate the sum of all characters in the string.
# 2.4. This will be the position/index of the string in a database.
alphabet = ["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",
"A","B","C","D","E","F","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9","0"," "]
f = open("Names.txt","r")
content = f.readlines()
print(content)
for string in range(len(content)):
character_list = list(content[string])
for i in range(len(character_list)):
character = character_list[i]
for j in range(len(alphabet)):
if character == alphabet[j]:
|
def backspaceCompare1(S, T):
def func(S):
s = []
for i in S:
if i == '#':
if len(s) > 0:
s.pop()
else:
pass
else:
s.append(i)
return s
return func(S)==func(T)
def backspaceCompare2(S, T):
s = []
t = []
for i in S:
if i == '#':
if len(s) > 0:
s.pop()
else:
pass
else:
s.append(i)
for i in T:
if i == '#':
if len(t) > 0:
t.pop()
else:
pass
else:
t.append(i)
return s==t
S = "ab##"
T = "c#d#"
print(backspaceCompare(S,T))
# 时间复杂度O(len(S)+Len(T))
# 空间复杂读OO(len(S)+Len(T)) |
class MinStack:
def __init__(self):
"""
同步栈
"""
self.data=[]# 数据栈
self.list=[]# 辅助栈
def push(self, x: int):
self.data.append(x)
if len(self.list)==0 or x<=self.list[-1]:
self.list.append(x)
else:
self.list.append(self.list[-1])
def pop(self):
if self.data:
self.list.pop()
return self.data.pop()
def top(self):
if self.data:
return self.data[-1]
def getMin(self):
if self.list:
return self.list[-1]
obj=MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
print(obj.getMin())
print(obj.pop())
print(obj.top())
print(obj.getMin())
|
# https://www.hackerrank.com/challenges/bomber-man/problem
#output of 3,7,11... will be same -> 3x
#output of 5,9,13... will be same -> 5x
#output of 2,4,6... will be complete fill -> 2x
#5x and {0} will be different but after blast both will be same
#ie {6} will be same as {2}
from copy import deepcopy
r, c, n = map(int,input().split())
inp=['']*r
for i in range(r):
inp[i]=list(input())
diff = [(0, 1), (1, 0), (-1, 0), (0, -1)]
layout = [[0 for _ in range(c)] for _ in range(r)]
for i in range(r):
for j in range(c):
if(inp[i][j] == 'O'):
layout[i][j] = 3
def fillUp(layout: list) -> list:
global r, c
for i in range(r):
for j in range(c):
if(layout[i][j] == 0):
layout[i][j] = 3
return deepcopy(layout)
def isInside(i, j):
global r, c
if(i >= 0 and j >= 0 and i < r and j < c):
return True
return False
def boomUp(layout: list) -> list:
global r, c
for i in range(r):
for j in range(c):
if(layout[i][j] == 1):
layout[i][j] = 0
for d in diff:
if(isInside(i+d[0], j+d[1]) and layout[i+d[0]][j+d[1]] != 1):
layout[i+d[0]][j+d[1]] = 0
return deepcopy(layout)
def passUp(layout: list) -> list:
global r, c
for i in range(r):
for j in range(c):
if(layout[i][j] != 0):
layout[i][j] -= 1
return deepcopy(layout)
def printFill():
global r, c
for _ in range(r):
for _ in range(c):
print('O', end='')
print('')
def printLayout(layout: list) -> None:
global r, c
for i in range(r):
for j in range(c):
if(layout[i][j] != 0):
print('O', end='')
else:
print('.', end='')
print('')
# 1
deepcopy(layout)
passUp(layout)
n-=1
if(n==0):
printLayout(layout)
exit(0)
# 2
passUp(layout)
fillUp(layout)
n-=1
if(n==0):
printLayout(layout)
exit(0)
# 3
boomUp(layout)
layout_3 = passUp(layout)
n-=1
if(n==0):
printLayout(layout)
exit(0)
# 4
passUp(layout)
fillUp(layout)
n-=1
if(n==0):
printLayout(layout)
exit(0)
# 5
boomUp(layout)
layout_5 = passUp(layout)
n-=1
if(n==0):
printLayout(layout)
exit(0)
if(n!=0):
if(n%2==1):
printFill()
else:
if(n%4==0):
printLayout(layout_5)
else:
printLayout(layout_3)
|
# https://www.hackerrank.com/challenges/sherlock-and-valid-string/problem
from collections import Counter
counter=Counter(list(Counter(list(input())).values()))
base=counter.most_common()[0][0]
counter.pop(base)
if(len(counter)==0):
print('YES')
exit(0)
if(len(counter)==1):
val=list(counter.keys())[0]
if(counter[val]==1):
if(val==1):
print('YES')
exit(0)
elif(val-base==1):
print('YES')
exit(0)
print('NO')
# ------------------------------------
from collections import Counter
counter=list(Counter(list(input())).values())
numOf1=0
num1=-1
for num in counter:
if(num==1):
numOf1+=1
num1=num
if(numOf1==1):
counter.remove(num1)
try:
base=min(counter)
except:
base=None
for num in counter:
if(num>base):
print('NO')
exit(0)
print('YES')
else:
base=min(counter)
numGreater=0
for num in counter:
if(num>base):
numGreater+=(num-base)
if(numGreater>=2):
print('NO')
exit(0)
print('YES') |
def repeatedString0(s, n):
m=len(s)
ans=0
for i in range(0,n):
if(s[i%m]=='a'):
ans+=1
return ans
def repeatedString(s,n):
num=n//len(s)
extra=n%len(s)
ans=0
for i in range(0,len(s)):
if(s[i]=='a'):
ans+=1
ans*=num
for i in range(0,extra):
if(s[i]=='a'):
ans+=1
return ans
s="aba"
n=10
print(repeatedString(s,n)) |
# https://www.hackerrank.com/challenges/common-child/problem
def commonChild(s1, s2):
m, n = len(s1), len(s2)
prev, cur = [0]*(n+1), [0]*(n+1)
for i in range(1, m+1):
for j in range(1, n+1):
if s1[i-1] == s2[j-1]:
cur[j] = 1 + prev[j-1]
else:
if cur[j-1] > prev[j]:
cur[j] = cur[j-1]
else:
cur[j] = prev[j]
cur, prev = prev, cur
return prev[n]
print(commonChild(input(), input()))
|
# -*- coding: utf-8 -*-
# A list of blanks to be passed in to the game function.
blanks = ["___1___", "___2___", "___3___", "___4___", "___5___"]
# Questions will be asked to fill in
game_data = {
'Easy': {
'quiz': '''A ___1___ is one of the basic things a program works with, like a letter or a number.These ___2___s belong to different types: 2 is an integer, and 'Hello, World!' is a ___3___A ___4___ is a name that refers to a ___5___.''',
'answers' : ["value", "value", "string", "variable", "value"]
},
'Medium': {
'quiz': '''In the context of programming, a ___1___ is a named sequence of statements that performs a computation.The expression in parentheses is called the ___2___ of the ___3___. It is common to say that a ___4___ “takes”an ___5___ and “returns” a result.''',
'answers' : ["function", "argument", "function", "function", "argument"]
},
'Hard': {
'quiz': '''A ___1___ expression is an expression that is either true or false. There are three ___2___ operators: and, or, and not.The ___3___ operator works on integers and yields the remainder when the first operand is divided by the second.The == operatoris one of the ___4___ operators. A ___5___ statement gives us to check conditions and change the behavior of the program accordingly.''',
'answers' : ["boolean", "logical", "modulus", "relational", "conditional"]
},
}
def word_in_blanks(word, blanks):
'''Checks if there is a word in blank list that is a substring of the variable word,
then return that word in blank list'''
for blank in blanks:
if blank in word:
return blank
return None
def replace_blanks(word, replaced, blanks, guess, index):
'''To replace the blanks showed in questions by guess typed by useers'''
if word_in_blanks(word, blanks) == None:
if word not in replaced:
replaced.append(word)
else:
replacement = word_in_blanks(word, blanks)
word = word.replace(replacement, guess)
if replacement == blanks[index]:
if replacement not in replaced:
replaced.append(word)
else:
position = replaced.index(replacement)
replaced[position] = word
else:
replaced.append(replacement)
return replaced
def fill_blanks(questions, blanks, replaced, guess, index):
'''To replace the blanks showed in questions by guess typed by useers '''
replaced = []
questions_split = questions.split()
for word in questions_split:
replace_blanks(word, replaced, blanks, guess, index)
replaced = " ".join(replaced)
return replaced
def check_answers(choice, questions, answers):
'''To check the user's guess.'''
replaced = []
guess = ''
index = 0
for blank in blanks:
guess = raw_input("Would you like to answer" + blanks[index] + "?")
while guess != answers[index]:
print ("Oops! It looks like your answer was wrong. Please try again.")
guess = raw_input("Type in" + blanks[index] + "here again: ")
print ("Great! There we go!")
replaced = fill_blanks(questions, blanks, replaced, guess, index)
print replaced
index += 1
return replaced, index
MESSAGE = """
This game was degisned to help you remember
important vocabulary during your Python study.
Please choose a level to start when you get ready
"""
def game():
'''The final function to start the fill in blanks game'''
print (MESSAGE)
choice = raw_input("$Easy$ $$Medium$$ $$$Hard$$$ ")
while choice not in ['Easy', 'Medium', 'Hard']:
print "Would you like to choose a level as indicated? "
choice = raw_input("$Easy$ $$Medium$$ $$$Hard$$$ ")
questions = game_data[choice]['quiz']
answers = game_data[choice]['answers']
print ('You chose the' + choice + 'one, here we go!')
print questions
replaced = check_answers(choice, questions, answers)
print "Brilliant! You have done a great job"
game()
|
# Assignment: Multiply
# Create a function called 'multiply' that reads each value in the list (e.g. a = [2, 4, 10, 16]) and returns a list where each value has been multiplied by 5.
#
# The function should multiply each value in the list by the second argument. For example, let's say:
a = [2,4,10,16]
def multiply(list,counter):
result = []
for value in list:
result.append(value * counter)
return result
print multiply(a,5)
|
# QUELLE
dictionaryGermanToSpanish = {
'hallo': 'hola'
}
dictionaryGermanToEnglish = {
'hallo': 'hello'
}
dictionaryGermanToKorean = {
'hallo': '안녕하세요'
}
# CODE
languageToDictionary = {
'english': dictionaryGermanToEnglish,
'spanish': dictionaryGermanToSpanish,
'korean': dictionaryGermanToKorean
}
whichLanguage = input('Which language to translate to? ')
whichLanguage = whichLanguage.lower()
dictionaryToUse = languageToDictionary[whichLanguage]
whichWord = input('Which word to translate? ')
print(dictionaryToUse[whichWord])
|
class Node(object):
def __init__(self, name:str):
self.child_nodes = list()
self.name = name
def append(self, child_node):
self.child_nodes.append(child_node)
def draw(self, depth:int = 0):
# tree = self.name
# for child in self.child_nodes:
# tree+='\n{}.{}'.format(self.name,child.draw)
# return tree
tree = '{}{}'.format(('|'*depth) + '+->', self.name)
for child in self.child_nodes:
tree += '\n{}'.format(child.draw(depth+1))
return tree |
# functions file
import collections
def sort_list(numbers):
print("Sorted list from least to greatest: ", numbers.sort())
def sum_list(numbers):
sum = 0
for number in numbers:
sum = sum + number
return sum
print(f"The sum of the list is: {sum}")
def product_list(numbers):
product = 1
for number in numbers:
product = product * number
return product
print(f"The product of the list is: {product}")
def mean_list(numbers):
mean = 1
for number in numbers:
mean = mean * number
return mean
mean = mean / len(numbers)
print(f"The mean of the list is: {mean}")
def median_list(numbers):
numbers.sort()
if len(numbers) % 2 == 0:
first_median = numbers[len(numbers) // 2]
second_median = numbers[len(numbers) // 2 - 1]
median = (first_median + second_median) / 2
else:
median = numbers[len(numbers) // 2]
return median
print(f"The median of the list is: {median}")
def mode_list(numbers):
data = collections.Counter(numbers)
data_list = dict(data)
max_value = max(list(data.values()))
mode_val = [num for num, freq in data_list.items() if freq == max_value]
if len(mode_val) == len(numbers):
print("No mode in the list")
else:
print("The Mode of the list is : " + ', '.join(map(str, mode_val)))
def largest_num(numbers):
numbers.sort()
print("The largest number in the list is ", numbers[-1])
def smallest_num(numbers):
numbers.sort()
print("The smallest number in the list is: ", numbers[0])
def duplicates(numbers):
numbers.sort()
print("This is the list: ", numbers)
num = input("Type a number you want to remove from the list: ")
for number in numbers:
if numbers[number] == num:
numbers.replace(number, ' ')
print("The new list: ", numbers)
else:
print("this number is not in the list.")
def remove_even(numbers):
for number in numbers:
if number % 2 == 0:
numbers.replace(number, ' ')
print("list with evens removed: ", numbers)
def remove_odds(numbers):
for number in numbers:
if number %2 != 0:
numbers.replace(number, ' ')
print("list with odds removed: ", numbers)
def find_number(numbers):
num = input("Type a number you want to find in the list: ")
for number in numbers:
if numbers[number] == num:
print("yes, this number is in the list.")
else:
print("no, this number is not in the list.")
def bonus(numbers):
numbers.sort()
print("The second largest number in the list is: ", numbers[-2])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
@author: Qiaoxueyuan
@time: 2017/8/21 14:34
'''
import random, string
def random_string(num=5):
# str = ''.join(random.sample(string.ascii_letters + string.digits, num))
# return str
str = ''
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789-_'
for i in range(0, num):
str += ''.join(chars[random.randint(0, len(chars) - 1)])
return str
|
# Runtime: 1220 ms, faster than 50.44% of Python3 online submissions for Longest Palindromic Substring.
# Memory Usage: 14.2 MB, less than 81.75% of Python3 online submissions for Longest Palindromic Substring.
def is_palindrome(l, r, s):
result = ''
result_length = 0
# Ensure that the left and right pointers never pass the range of the string
# 2. Check whether the character to it's left matches the character to it's right. If it doesn't move on to the next character.
# 3. If the character to it's left matches with the character to it's right, then view the next left and right elements.
while l >=0 and r < len(s) and s[l] == s[r]:
# If the length of the palindrome is greater than the length of the result of the previously long palindrome, then the previously long palindrome will now become the new palindrome
if (r - l + 1) > result_length:
result = s[l:r+1]
result_length = len(result) # or (r-l+1)
l -= 1
r += 1
return result
def longestPalindrome(s):
'''
1. Start from the first character in the string. This will act as the middle of our palindromic substring
2. Check whether the character to it's left matches the character to it's right. If it doesn't move on to the next character.
3. If the character to it's left matches with the character to it's right, then view the next left and right elements.
'''
# 1. Start from the first character in the string. This will act as the middle of our palindromic substring
for i in range(len(s)):
# Initialize the left and right pointer. The left pointer will move left and the right pointer will move right
l = i
r = i
# Will work for odd length palindromes
res = is_palindrome(l, r, s)
# Will work for even length palindromes
l = i
r = i + 1
res = is_palindrome(l, r, s)
return res
### Directly impementable solution
class Solution:
def longestPalindrome(self, s: str) -> str:
result = ''
result_length = 0
for i in range(len(s)):
#for odd length string
l = i
r = i
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r-l+1) > result_length:
result = s[l:r+1]
result_length = r - l + 1
l -= 1
r += 1
#for even length string
l = i
r = i + 1
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r-l+1) > result_length:
result = s[l:r+1]
result_length = r - l + 1
l -= 1
r += 1
return result |
# Runtime: 56 ms, faster than 75.41% of Python3 online submissions for Palindrome Number.
# Memory Usage: 14.4 MB, less than 13.65% of Python3 online submissions for Palindrome Number.
def reverse_number(x):
'''
simply reverse x and see if the the reversed value of x and original x match
'''
x_orig = x
x_rev = 0
while x_orig > 0:
remainder = x_orig % 10
x_rev = (x_rev * 10) + remainder
x_orig = x_orig // 10
if x == x_rev:
return True
else:
return False
### Solution for direct submission
class Solution:
def longestPalindrome(self, s: str) -> str:
result = ''
result_length = 0
for i in range(len(s)):
#for odd length string
l = i
r = i
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r-l+1) > result_length:
result = s[l:r+1]
result_length = r - l + 1
l -= 1
r += 1
#for even length string
l = i
r = i + 1
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r-l+1) > result_length:
result = s[l:r+1]
result_length = r - l + 1
l -= 1
r += 1
return result |
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def deleteDuplicates(self, head):
# Node to handle the case in case we just have one root node and the elements after that are all the same as the root node
sentinel = Node(0, head)
# Predecessor node that will always be a distinct value
pred = sentinel
while head:
if head.next and head.val == head.next.val:
while head.next and head.val == head.next.val:
head = head.next
pred.next = head.next
else:
pred = pred.next
head = head.next
return sentinel.next
# Directly Implementable Solution
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
# Creating a sentinel node
# This node is for handling the case where we just have the same number in the linked list
# eg 9-->9-->9-->null
sentinel = ListNode(0, head)
# Create a predecessor node that will act as the last node before the sublist of duplicates
# comes in
pred = sentinel
while head:
# if the current node value and the next node value are the same, then while the current
#value and the next value are the same, keep going to the next node
if head.next and head.val == head.next.val:
while head.next and head.val == head.next.val:
head = head.next
# Point the predecessor node to the next node, so now the predecessor node is linked to a new node value
pred.next = head.next
# Else if the current node value and the next node value are not the same then go to the next value in the linked list.
else:
pred = pred.next
head = head.next
return sentinel.next |
#!/usr/bin/env python
'''slidepuzzle.py
A sliding puzzle game
by Nick Loadholtes
No warranty provided with this code. Use at your own risk.
version 1.3
'''
import random, cmath, curses, curses.wrapper, curses.ascii
side = "|"
newline = "\n"
_topborder = "_"
topb = ""
newscreen = "\n\n\n\n\n\n\n\n\n"
actual = []
size = 3
keypress = ""
stdscr = ""
gameinplay = 1
gamewon = 0
spacelocation = 0
def makeTopBorder():
sizeofboard = (size * 3) +1
pos = 0
global topb
topb = ""
while pos < sizeofboard:
topb += _topborder
pos += 1
#
#works
def displayBoard():
global stdscr, actual
sizeofboard = (size * size) -1
y = 0
x = 0
number = 0
output = newline + topb + newline
while y < size:
while x < size:
if(number < len(actual)):
output += side + "%(#)2s" % {"#":str(actual[number])}
number += 1
x += 1
else :
break
output += newline + topb + newline
x = 0
y += 1
stdscr.clear()
curses.init_pair(3, 7, 4)
stdscr.addstr(0, 0, output, curses.color_pair(3))
stdscr.refresh()
#
# Returns a "random" number from the range of size^2
def getNumberFromRange():
return random.randrange(1, (size * size) )
#
# Generates a randomized board
def generateBoard():
global actual, spacelocation
sizeofboard = (size * size)
x = 0
actual = []
while x < sizeofboard -1:
num = getNumberFromRange()
while checkBoard(num) != 0:
num = getNumberFromRange()
actual.append(num)
x += 1
actual.append(" ")
spacelocation = sizeofboard - 1
#
#
def checkBoard(num):
for x in actual:
if x == num:
return 1
return 0
#
# Checks to see if there is a win condition
def checkForWin():
global size, actual, gameinplay, stdscr, gamewon
sizeofboard = (size * size) - 1
broken = 0
if( (actual[sizeofboard]) == " "):
y = 1
for x in actual:
if(x != y):
if(x != " "):
broken = 1
break
y = y + 1
if (broken == 0):
gameinplay = 0
gamewon = 1
#
# Request a size from the user. Size can be 1-9 (but
# should be 2-9)
def getSize():
global size, stdscr
msg = "\nThe default size is " + str(size) + "\nWhat size board would you like?"
size = "a"
while (not curses.ascii.isdigit(size) ):
stdscr.addstr(msg)
stdscr.refresh()
size = stdscr.getch()
size = size- 48
#
# Get the user input (during the game) and either quit or
# attempt to move the space.
def getInput():
global keypress, stdscr, gameinplay
stdscr.addstr("Press an arrow key to move the space (q to quit)?")
stdscr.refresh()
keypress = stdscr.getch()
if(keypress == curses.KEY_UP):
doMovement(2)
elif(keypress == curses.KEY_DOWN):
doMovement(1)
elif(keypress == curses.KEY_LEFT):
doMovement(4)
elif(keypress == curses.KEY_RIGHT):
doMovement(3)
elif(keypress == 81 or keypress ==113):
gameinplay = 0
stdscr.refresh()
#
# Attempt to move the space. If it can't be move, nothing
# happens and the game loop re-prompts for a move.
def doMovement(direction):
global actual, spacelocation, size, stdscr
row = spacelocation / size
if(direction == 1):
newlocation = spacelocation + size
elif(direction == 2):
newlocation = spacelocation - size
elif(direction == 3):
newlocation = spacelocation + 1
newrow = newlocation / size
if(newrow != row):
newlocation -= 1
elif(direction == 4):
newlocation = spacelocation - 1
newrow = newlocation / size
if(newrow != row):
newlocation += 1
if(newlocation > -1 and newlocation < (size*size)):
tmp = actual[newlocation]
actual[spacelocation] = tmp
actual[newlocation] = " "
spacelocation = newlocation
#
# The main loop of the game.
def gameLoop(screen):
global stdscr, gameinplay, gamewon
curses.echo()
stdscr = screen
stillplaying = 1
while stillplaying :
gameinplay = 1
getSize()
generateBoard()
makeTopBorder()
while gameinplay:
displayBoard()
getInput()
checkForWin()
if gamewon:
displayBoard()
stdscr.addstr("\n\n\t\tYOU WON!!!!!!!!!\n\n")
stdscr.refresh()
stdscr.addstr("\nWould you like to play another game? (y to continue): ")
stdscr.refresh()
stillplaying = stdscr.getch()
if(stillplaying == 89 or stillplaying == 121): # Q or q
stillplaying = 1
else:
stillplaying = 0
#
# The main method to start the game.
if __name__ == "__main__":
print "Welcome to the slide puzzle!\n"
curses.wrapper(gameLoop)
print "Good bye!" |
opcao = ""
total = 0
i = 0
while opcao != "0":
print("(1) - Informar consumo de alimentos ingeridos")
print("(0) - Encerrar o programa")
opcao = input("\nDigite o número da opção desejada: ")
if opcao == "1":
x = ""
qnt = int(input("Informe a quantidade de alimentos que você ingeriu: "))
for cal in range(qnt):
i = i + 1
cal = float(input("Valor das calorias do alimento {}: ".format(i)))
total = total + cal
print("\nO valor total consumido foi de {} calorias\n".format(total))
elif opcao > "1" or opcao < "0":
print("\n *** Opção inválida... Tente novamente! ***\n")
print("\n ***** Programa encerrado! *****") |
class Object(object):
'''
Creates an object for simple key/value storage; enables access via
object or dictionary syntax (i.e. obj.foo or obj['foo']).
'''
def __init__(self, **kwargs):
for arg in kwargs:
setattr(self, arg, kwargs[arg])
def __getitem__(self, prop):
'''
Enables dict-like access, ie. foo['bar']
'''
return self.__getattribute__(prop)
def __str__(self):
'''
String-representation as newline-separated string useful in print()
'''
state = [f'{attr}: {val}' for (attr, val) in self.__dict__.items()]
return '\n'.join(state)
def get_str(self, delimiter=";"):
state = [f'{attr}{delimiter}{val}' for (attr, val) in
self.__dict__.items()]
return delimiter.join(state)
def _get_sorted_keys(self):
keys = self.__dict__.keys()
sorted_keys = sorted(keys)
return sorted_keys
def get_str_sorted(self, delimiter=";"):
sorted_keys = self._get_sorted_keys()
state = [f'{attr}{delimiter}{self.__getitem__(attr)}' for attr in
sorted_keys]
return delimiter.join(state)
def get_attrs(self, delimiter=";"):
attrs = [str(attr) for attr in self.__dict__.keys()]
return delimiter.join(attrs)
def get_attrs_sorted(self, delimiter=";"):
sorted_keys = self._get_sorted_keys()
attrs = [str(attr) for attr in sorted_keys]
return delimiter.join(attrs)
def get_vals(self, delimiter=";"):
vals = [str(val) for val in self.__dict__.values()]
return delimiter.join(vals)
def get_vals_sorted(self, delimiter=";"):
sorted_keys = self._get_sorted_keys()
vals = [str(self.__getitem__(key)) for key in sorted_keys]
return delimiter.join(vals)
def add(self, other, prefix="", suffix=""):
for attr, val in other.__dict__.items():
new_attr = prefix + attr + suffix
if new_attr in self.__dict__:
raise Exception(f"The attribute: {new_attr} already exists.")
self.__setattr__(new_attr, val)
def items(self):
'''
Enables enumeration via foo.items()
'''
return self.__dict__.items()
|
import numpy as np
class GDOptimizer:
"""Basic gradient descent optimizer implementation that can minimize w.r.t.
a single variable.
Parameters
----------
shape : tuple
shape of the variable w.r.t. which the loss should be minimized
"""
def __init__(self, learning_rate):
self._learning_rate = learning_rate
def __call__(self, gradient):
"""Updates internal parameters of the optimizer and returns
the change that should be applied to the variable.
Parameters
----------
gradient : `np.ndarray`
the gradient of the loss w.r.t. to the variable
"""
return -self._learning_rate * gradient
class AdamOptimizer:
"""Basic Adam optimizer implementation that can minimize w.r.t.
a single variable.
Parameters
----------
shape : tuple
shape of the variable w.r.t. which the loss should be minimized
"""
def __init__(
self, shape, dtype, learning_rate, beta1=0.9, beta2=0.999, epsilon=10e-8
):
"""Updates internal parameters of the optimizer and returns
the change that should be applied to the variable.
Parameters
----------
shape : tuple
the shape of the input
dtype : data-type
the data-type of the input
learning_rate: float
the learning rate in the current iteration
beta1: float
decay rate for calculating the exponentially
decaying average of past gradients
beta2: float
decay rate for calculating the exponentially
decaying average of past squared gradients
epsilon: float
small value to avoid division by zero
"""
self.m = np.zeros(shape, dtype=dtype)
self.v = np.zeros(shape, dtype=dtype)
self.t = 0
self._beta1 = beta1
self._beta2 = beta2
self._learning_rate = learning_rate
self._epsilon = epsilon
def __call__(self, gradient):
"""Updates internal parameters of the optimizer and returns
the change that should be applied to the variable.
Parameters
----------
gradient : `np.ndarray`
the gradient of the loss w.r.t. to the variable
"""
self.t += 1
self.m = self._beta1 * self.m + (1 - self._beta1) * gradient
self.v = self._beta2 * self.v + (1 - self._beta2) * gradient ** 2
bias_correction_1 = 1 - self._beta1 ** self.t
bias_correction_2 = 1 - self._beta2 ** self.t
m_hat = self.m / bias_correction_1
v_hat = self.v / bias_correction_2
return -self._learning_rate * m_hat / (np.sqrt(v_hat) + self._epsilon)
|
#!/usr/bin/python
"""
7th of October 2020
"""
import numpy as np
class DividedDifference():
def __init__(self):
# default setting
self.stg = {
"length" : 5,
"loc" : 0.0,
"scale" : 20.0,
"initial-decimal" : 0,
"nice-solution" : True
}
def problem(self):
def generate():
x_values = [round(np.random.normal(loc=self.stg["loc"], scale=self.stg["scale"]),
self.stg["initial-decimal"]) for _ in range(self.stg["length"])]
y_values = [round(np.random.normal(loc=self.stg["loc"], scale=self.stg["scale"]),
self.stg["initial-decimal"]) for _ in range(self.stg["length"])]
return x_values, y_values
def check_solution_easy(x, y, decimals=1):
try:
return True if divided_difference(x, y).is_integer() else False
except ZeroDivisionError:
return False
def check_solution_easy_nonzero(x, y, decimals=1):
try:
solution = divided_difference(x, y)
return True if solution.is_integer() and solution != 0 else False
except ZeroDivisionError:
return False
x, y = generate()
i = 0
if self.stg["nice-solution"] == True:
while check_solution_easy_nonzero(x, y) == False:
x, y = generate()
i += 1
print("generating problem tries: {}".format(i))
return x, y
def divided_difference(x, y):
dd = divided_difference
return y[0] if len(y) == 1 else (dd(x[1:], y[1:]) - dd(x[:-1], y[:-1])) / (x[-1] - x[0])
def main():
DD = DividedDifference()
x, y = DD.problem()
print("x values: {}".format(x))
print("y values: {}".format(y))
while True:
if input("Show Solution? ").lower()[0] == "y":
print(divided_difference(x, y))
break
if __name__ == "__main__":
main()
|
import numpy as np
#Numpy array
print("Numpy array")
dizi=np.array((3,4))
print(dizi.shape)
#arange methodu (normal range mothodunun numpy de kullanılışı)
print("arange methodu")
result=np.arange(0,10)
print(result)
#linspace methodu start,stop,kaç adet
print("linspace methodu")
result=np.linspace(0,20,500)
print(result)
#random methodu
print("random methodu")
result=np.random.randn(4)
result=np.random.randn(4,4)
result=np.random.randint(1,40)
result=np.random.randint(1,40,5)
print(result)
#indexleme
print("indexleme")
result=np.arange(0,15)
print(result[5])
result2=result
print(result2)
print(result[3:8])
result[3:8]=-5
print(result)
print(result2)
"""
numpy de ilginç olan bir özelliklerden birisi de
yukarıdaki gösterdiğim gibi result un belli bir aralığındaki sayıları değiştirmeme rağmen onu atadığım result2 nin de o indexlerindeki sayılar değşti
reference type gibi davrandı
eğer bu şekilde olmasını istemiyorsan,valularını almak istiyorsan result2=result.copy() methodunu kullanmalısın
"""
#reshabpe methodu
print("reshabpe methodu")
result=np.arange(0,100,5)
result=result.reshape(5,4)
print(result[0,0])
#numpy ile operasyonlar
print("Numpy İle Operasyonlar")
rastgeleDizi=np.random.randint(1,100,20)
print(rastgeleDizi)
print(rastgeleDizi>20)#şeklinde tüm diziyi True False olarak karşılaşıtrabilirisin
print(rastgeleDizi[rastgeleDizi>20])
print(rastgeleDizi+rastgeleDizi)
print(rastgeleDizi-rastgeleDizi)
print(rastgeleDizi*rastgeleDizi)
print(np.max(rastgeleDizi))
print(np.min(rastgeleDizi))
print(np.sqrt(rastgeleDizi))
|
from bs4 import BeautifulSoup
import webbrowser
import urllib2
# Get the product search query from user and parse the page source of the search result from flipkart website
product = raw_input("Enter product name: ")
product = product.replace(' ', '+')
print "entering search"
content1 = urllib2.urlopen('http://www.flipkart.com/search?otracker=start&q='+product).read()
print "Finished search"
content2= urllib2.urlopen('http://www.amazon.in/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords='+product).read()
print "finished amazon search"
3content3= urllib2.urlopen('http://www.snapdeal.com/search?keyword='+product).read()
print "Done with snapdeal search"
soupf = BeautifulSoup(content1)
soupa = BeautifulSoup(content2)
soups = BeautifulSoup(content3)
# Parse the page source of the matched product and find the seller-name
link = soupf.find_all("div", class_="pu-title fk-font-13")[0].find_all('a')[0].get('href')
link = "https://www.flipkart.com%s" % link
qseller_info = urllib2.urlopen(link).read()
link_soup = BeautifulSoup(seller_info)
price = link_soup.find_all("span", class_="selling-price omniture-field")[0].string.strip()
print price
#parse Amazon's source
link2 = soupa.find_all("div",class_="a-row a-spacing-mini")[0].find_all('a')[0].get('href')
link2= "https://www.amazon.in%s" % link2
print "XYZ"
seller2_info = urllib2.urlopen(link2).read()
print "123"
link2_soup = BeautifulSoup(seller2_info)
#print link2_soup
price2 = link2_soup.find_all("span", class_="a-size-medium a-color-price")[0].string.strip(),link2_soup.find_all(class_="a-link-normal s-access-detail-page a-text-normal")[0].string.strip()
print price2
#parse snapdeal's source
#link3 = soups.find_all("div", class_="comp comp-header reset-padding")[0].find_all('a')[0].get('href')
#ink3 = "https://www.snapdeal.com%s" %link3
#seller3_info = urllib2.urlopen(link3).read()
#link3_soup = BeautifulSoup(seller3_info)
#price3 = link3_soup.find_al("span", class_="accountBtn rippleWhite")[0].string.strip()
#print price3
#to sort the prices
sort = sorted(price1,price2)
print sort[0]
|
a = int(input("Please enter a number to start with: "))
b = int(input("Please enter a number to end with: "))
list_nums = list(range(a, b))
class Numbers():
def __init__(self):
print("Numbers object created")
def odd_nums(self):
'''
If a number is odd, print odd
'''
for item in list_nums:
if item % 2 == 1:
print(f"This is odd {item}")
def even_nums(self):
'''
If a number is divisible by 5, stated. Otherwise stated if Even
'''
for item in list_nums:
if item % 5 == 0:
print(f"Divisible by 5!: {item}")
elif item % 2 == 0:
print(f"This is EVEN: {item}")
even = Numbers
even.even_nums(list_nums)
even.odd_nums(list_nums)
print(f"{list_nums[-1]}")
|
def recursive_binary_search(list, target):
if len(list) == 0:
return False
else:
list.sort()
mid = (len(list)) // 2
if list[mid] == target:
return True
else:
if list[mid] < target:
return recursive_binary_search(list[mid+1:], target)
else:
return recursive_binary_search(list[:mid], target)
def verify(result):
print(f"Target found: {result}")
numbers = [2, 4, 9, 7, 3, 1, 5, 8, 10, 6]
result1 = recursive_binary_search(numbers, 5)
result2 = recursive_binary_search(numbers, 12)
verify(result1)
verify(result2)
|
import random
class Die():
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def roll(self):
result = self.num1 + self.num2
print(f"You have just rolled {self.num1} and {self.num2}")
if result == 12:
print(f"Double 6! You just rolled {result}")
elif result >= 10:
print(f"High Roll! You just rolled {result}")
elif result >= 6:
print(f"Big roll! You just rolled {result}")
else:
print(f"Not amazing, you just rolled {result}")
def retry():
redo = input("Would you like to roll? Type 'quit' to end: ")
if redo == 'quit':
return False
else:
return True
while retry():
num1 = random.randint(1, 6)
num2 = random.randint(1, 6)
dice = Die(num1, num2)
dice.roll()
|
from matplotlib import pyplot as plt
plt.style.use("ggplot")
year_x = [2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020]
# % of Python questions asked on Stack Overflow
py_growth = [3.90, 4.20, 5.30, 6.00, 7.10, 8.20, 10.40, 12.00, 13.80]
plt.plot(year_x, py_growth, color="b", marker="o", linewidth=3,
label="Python Questions asked on Stack Overflow")
plt.xlabel("Year")
plt.ylabel("% of Stack Overflow Questions")
plt.title("Growth of Python since 2012")
plt.grid(True)
plt.legend()
plt.show()
|
import math
lst = [1, 4, 5, 67, 2, 3, 5, 6, 1, 23, 4, 6, 7, 1, 2, 2, 234, 3, 32, 1, 12, 2, 2]
# Mean - Add all up and divide by length
def mean(lst):
total = sum(lst)
average = total / len(lst)
return average
# Median - Sort and find middle number
def median(lst):
lst.sort()
length = len(lst)
mid = length / 2
mid = math.ceil(mid)
return lst[mid]
# Mode - most occuring number - Without using the counter module
mode = [[x, lst.count(x)] for x in set(lst)]
mean(lst)
median(lst)
|
def binary_search(list, target):
first = 0
list.sort()
last = len(list) - 1
while first <= last:
mid = (first + last) // 2
if list[mid] == target:
return mid
elif list[mid] < target:
first = mid + 1
elif list[mid] > target:
last = mid - 1
return None
def verify(index):
if index is not None:
print(f"Target found at index {index}")
else:
print("Target not found...")
numbers = [3, 4, 2, 7, 9, 8, 6, 10, 1, 5]
result1 = binary_search(numbers, 4)
result2 = binary_search(numbers, 12)
print(result1)
print(result2)
|
import time
class Solution(object):
def containsDuplicate(self, nums):
list = {}
for x in nums:
if not (x in list):
list.update({x:1})
else:
return True
return False
def containsDuplicate2(self, nums):
return len(nums) != len(set(nums))
j = Solution()
x=[1,2,3,4,5,6,1]
start = time.clock()
print(j.containsDuplicate(x))
dif = time.clock()- start
print(dif)
start = time.clock()
print(j.containsDuplicate2(x))
dif = time.clock()- start
print(dif) |
import heapq
a = [4,2,1,3,5]
heap = heapq.heapify(a)
heapq.heappush(heap, 6)
x = heapq.heappop(heap)
heap[0] # get smallest item without pop
# push item on the heap, then pop the smallest from the heap
x = heapq.heappushpop(heap, 7)
# pop the smallest from the heap, then push the new item
x = heapq.heapreplace(heap, 8)
# merge multiple sorted inputs into a single sorted output, return an iterator
b = [1,3,5,7]
c = [2,4,6,8]
it = heapq.merge(b, c)
# return a list of n largest elements from iterable
heapq.nlargest(3, it)
# return a list of n smallest elements from iterable
heapq.nsmallest(3, it)
# To maintain objects in the heap, we can store (priority, task) tuples in the heap
pq = []
heappush(pq, (10, task1))
heappush(pq, (5, task2))
heappush(pq, (15, task3))
priority, task = heappop(pq)
|
"""
This problem was asked by Amazon.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function
that returns the number of unique ways you can climb the staircase. The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2
What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive
integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
"""
# this is actually just the fibonacci number- if we increase step k by one, we can add 1's to each possibility at k,
# moreover we can add a 2 to all possibilities at step k-1: f(k+1) = f(k) + f(k-1)
def function_for_1_and_2(number_of_steps):
if number_of_steps <= 0:
return 0
if number_of_steps == 1:
return 1
if number_of_steps == 2:
return 2
else:
return function_for_1_and_2(number_of_steps - 1) + function_for_1_and_2(number_of_steps - 2)
# to generalize this we need to think about fibonacci numbers more abstractly. While for X = {1, 2} we had
# f(k+1) = f(k) + f(k-1), for arbitrary numbers X = { n1, n2, ..., nn } this would add up to f(k+1) =
# f(k-n1) + f(k-n2) ... + f(k-nn). We need to take into account every possible combination of steps with each other.
def function_for_arbitrary_step_lengths(number_of_steps, list_of_step_lengths):
if number_of_steps <= 0:
return 0
sum_of_possibilities = 0
for step_length in list_of_step_lengths:
if number_of_steps > step_length:
sum_of_possibilities += function_for_arbitrary_step_lengths(number_of_steps - step_length,
list_of_step_lengths)
elif number_of_steps == step_length:
sum_of_possibilities += 1
else:
pass
return sum_of_possibilities
if __name__ == '__main__':
print(function_for_arbitrary_step_lengths(19, [2, 3, 5]))
|
#1 - Actualiza los valores en diccionarios y listas:
#Cambia el valor 10 en x a 15. Una vez que haya terminado, x ahora debería ser [[5,2,3], [15,8,9]].
#Cambia el apellido del primer alumno de 'Jordan' a 'Bryant'
#En el directorio sports_directory, cambia 'Messi' a 'Andres'
#Cambia el valor 20 en z a 30
x = [ [5,2,3], [10,8,9] ]
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'}
]
sports_directory = {
'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'],
'soccer' : ['Messi', 'Ronaldo', 'Rooney']
}
z = [ {'x': 10, 'y': 20} ]
x[1][0]=15
students[0]['last_name'] = 'Bryant'
sports_directory['soccer'][0] = 'Andres'
z[0]['y']=20
print(x)
print(students)
print(sports_directory)
print(z)
#2 - Itera a través de una lista de diccionarios:
#Crea una función iterateDictionary(some_list)que, dada una lista de diccionarios, la función recorra cada diccionario de la lista e imprime cada clave y el valor asociado. Por ejemplo, dada la siguiente lista:
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
def iterateDictionary(list):
for student in list:
string = []
for llave, valor in student.items():
string.append(f'{llave} - {valor}')
print(', '.join(string))
iterateDictionary(students)
#3 - Obtén valores de una lista de diccionarios
#Crea una función iterateDictionary2(key_name, some_list)que, dada una lista de diccionarios y un nombre de clave, la función imprima el valor almacenado en esa clave para cada diccionario. Por ejemplo, iterateDictionary2 ('first_name', students) debería generar:
def iterateDictionary2(key,list):
for i in range(len(list)):
print(list[i][key])
iterateDictionary2 ('first_name', students)
iterateDictionary2('last_name', students)
#4Itera a través de un diccionario con valores de listas
#Crea una función printInfo(some_dict)que, dado un diccionario cuyos valores son todas listas, imprima el nombre de cada clave junto con el tamaño de su lista, y luego imprima los valores asociados dentro de la lista de cada clave.
dojo = {
'locations': ['San Jose', 'Seattle', 'Dallas', 'Chicago', 'Tulsa', 'DC', 'Burbank'],
'instructors': ['Michael', 'Amy', 'Eduardo', 'Josh', 'Graham', 'Patrick', 'Minh', 'Devon']
}
def printInfo(list):
for key, values in list.items():
print(f'\n{len(key)} - {key.upper()}')
for value in values:
print(value)
printInfo(dojo)
|
class BankAccount:
def __init__(self, int_rate=0.01, balance=0):
self.int_rate = int_rate
self.balance = balance
def deposit(self,amount):
self.balance += amount
return self
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
return self
else:
print('Insufficient balance')
def display_account_info(self):
print('Balance :' + str(round(self.balance)))
def yield_balance(self):
if self.balance > 0:
self.balance *= (1 + self.int_rate)
return self
else:
pass
class User:
def __init__(self,name,email):
self.name = name
self.email = email
self.accounts = [BankAccount(0.05)]
def make_deposit(self,amount,num):
self.accounts[num].deposit(amount)
return self
def make_withdraw(self,amount,num):
self.accounts[num].withdraw(amount)
return self
def display_user_balance(self,num):
print('User: ' + self.name + ', Balance :' + str(self.accounts[num].balance))
def transfer_money(self, receiver, amount, num):
if self.accounts[num].balance >= amount:
self.accounts[num].withdraw(amount)
receiver.accounts[0].deposit(amount)
else:
print('Insuficcient balance')
def create_account(self):
self.accounts.append(BankAccount(0.05))
guido = User('Guido van Rossum', 'guido@python.com')
monty = User('Monty Python', 'monty@python.com')
pedro = User('Pedro Picapiedra', 'pedro@python.com')
guido.create_account()
guido.make_deposit(100,0)
guido.make_deposit(500,0)
guido.make_deposit(300,1)
guido.make_withdraw(200,1)
guido.display_user_balance(1)
monty.make_deposit(200,0)
monty.make_deposit(300,0)
monty.make_withdraw(100,0)
monty.make_withdraw(500,0)
monty.display_user_balance(0)
pedro.make_deposit(1000,0)
pedro.make_withdraw(500,0)
pedro.make_withdraw(400,0)
pedro.make_withdraw(100,0)
pedro.display_user_balance(0)
guido.transfer_money(pedro, 500,0)
guido.display_user_balance(0)
pedro.display_user_balance(0)
guido.transfer_money(pedro,500,0)
guido.make_deposit(100,0).make_deposit(500,0).make_withdraw(300,0).display_user_balance(0) |
#Oscar Miranda A01630791
#Julio Arath Rosales Oliden A01630738
#Se pide que se ingrese el año
variable_1=float(input("Inserta el año, para checar si es un año bisiesto \n"))
#se compara si el año es multiplo de cuatro, despues se usa un or de divisible entre o 400 y un not de divisible entre 100, como es
#and dara falso si el año no es bisiesto lo que marcara como falsa o verdadero en caso de que sea bisiesto
if variable_1%4==0 and (not(variable_1%100==0) or variable_1%400==0 ):
print("El año es bisiesto")
else:
print("No es bisiesto")
#Comprendi mejor el uso de and, or y not. (aparte de que fue algo que vimos en mate discretas lo que nos ayudo)
|
#Julio Arath Rosales Oliden
#A01630738
def menor_ingresado():
print("Ingrese un numero, mientras no sea cero lo ingresara denuevo")
numero = float(input("Ingrese un numero :\n"))
menor_numero=numero
while numero!=0:
numero=float(input("Ingrese otro numero :)\n"))
if numero<menor_numero and numero!=0:
menor_numero=numero
return menor_numero
def clasifica(string):
lista=[]
lista_pares = []
lista_impar = []
for i in string:
contador=0
for j in i:
contador+=1
if contador==11:
if float(j)%2==0:
lista_pares.append(i)
elif float(j)%2==1:
lista_impar.append(i)
lista.append(lista_pares)
lista.append(lista_impar)
return lista
def palabras(string, numero):
lista_string=string.split(" ")
contador_palabras=0
for i in lista_string:
contador_letras=0
for j in i:
contador_letras+=1
if contador_letras==numero:
contador_palabras+=1
return contador_palabras
def funcion_triangular(numero):
lista=[]
for i in range(0,numero):
lista2=[]
for j in range(0,numero):
if i+1 > j:
lista2.append(1)
else:
lista2.append(0)
lista.append(lista2)
return (lista)
def ganador():
try:
archivo=open("tiempos.csv", "r", encoding="UTF-8")
except IOError:
print("No encuntro el archivo")
else:
try:
subir=open("tiempo_finales.txt", "w", encoding="UTF-8")
except IOError:
print("No se encontro el archivo :(")
else:
subir_string="Este archivo dice el tiempo total que cada corredor realizo y quien fue el ganador de la competencia\n"
time = 100
corredor_ganador=""
for linea in archivo:
sin_espacios = linea.rstrip()
lista = sin_espacios.split(",")
if lista[1]!="Tiempo1":
tiempo=(float(lista[1])+float(lista[2])+float(lista[3])+float(lista[4])+float(lista[5]))
if tiempo<time:
time=tiempo
corredor_ganador=lista[0]
subir_string+=(f"El corredor {lista[0]} realizo un tiempo de {tiempo:2.1f}\n")
subir_string+=(f"El corredor que gano la competencia fue {corredor_ganador}, quien hizo el menor tiempo con {time}")
subir.write(subir_string)
subir.close()
archivo.close()
#funcion menor ingresado
numero_pequeño=menor_ingresado()
print(f"El numero mas pequeño ingresado por el usuario fue {numero_pequeño:4.2f}")
print("\n")
#funcion pares e impares
string_clasifica=["X1222345688","T1255678991","Z3451231235","R0234556712","W9911234887"]
lista_par_impar=clasifica(string_clasifica)
for i in lista_par_impar:
print(i)
print("\n")
#funcion contadora de letras en palabras
string_palabras="Un dia tendre una cabaña en Mazamitla"
numero_palabras=2
letras=palabras(string_palabras,numero_palabras)
print(f"La cantidad de palabras con {numero_palabras} letras es {letras} en el string: {string_palabras}")
print("\n")
#funcion triagular
numero=2
lista_triangular=funcion_triangular(numero)
for i in lista_triangular:
print(i)
#funcion archivos
ganador()
|
#Julio Rosales Oliden A01630738
#se dice lo que hace el programa
print("Escribe un numero, se sumara hasta que escribas un numero negativo")
num=0
dato_user=0
#si el dato ingresado por el usuario es mayor o igual que cero el programa correra la suma
while dato_user>=0:
dato_user=int(input("Escribe un numero \n"))
#compara si el dato es mayor que 0 para hacer la suma
if dato_user>=0:
num+=dato_user
print("El numero sumado resulto en "+ str(num))
#aprendi a usar un if adentro ded un while
|
def anagramas(palabra1,palabra2):
if len(palabra1) == len(palabra2) and (palabra1 != palabra2):
for letra in palabra1:
if letra not in palabra2:
return False
return True
else:
return False
def cambia_multplos(lista, n):
for pos in range(len(lista)):
if lista[pos]%n==0:
lista[pos]=0 |
#Julio Arath Rosales Oliden
#A01630738
#En la primera parte se pide la cantidad de alumnos en el grupo
#Despues asignamos una varieble que cuente la calificacion grupal a 0 para hacer la sumatoria de esta
estudiantes=int(input("Este programa calcula el promedio por estudiante y por grupo\nEscribe el numero de estudiantes en el grupo:"))
calif_gsuma=0
#Ahora se realizara el programa dependiendo de la cantidad de alumnos sean del grupo
for i in range(estudiantes):
#ahora se pregunta la calificacion del alumno para depues hacer el promedio y se agrega
#a un promedio grupal que es dividido entre la cantidad de alumnos para dar el promedio grupal
print("---------------------------------------")
calif_1=float(input("Escribe la primera calificacion:"))
calif_2=float(input("Escribe la segunda calificacion:"))
calif_3=float(input("Escribe la tercera calificacion:"))
calif=(calif_1+calif_2+calif_3)/3
calif_gsuma+=calif
print(f"El promedio del alumno {i+1:2d} fue {calif}")
calif_grupal=calif_gsuma/estudiantes
print("---------------------------------------")
print(f"La calificación grupal fue de {calif_grupal:3.2f}")
|
#Julio Rosales Oliden
#A01630738
numero=float(input("Inserta el numero \n"))
digitos=1
numero=abs(numero)
while 9<=numero or numero<=-9:
numero=numero/10
digitos+=1
print("el numero tiene "+ str(digitos) + " digitos")
#Aprendi a usar el abs (absoluto)
|
from tkinter import *
import requests
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
root = Tk()
root.title("Let's Convert Your Winnings !")
# SETTING THE SIZE
root.geometry("600x600")
# THE USER CANT MAXIMIZE THE WINDOW
root.resizable(height=False, width=False)
# SETTING THE BACKGROUND COLOR
root.config(bg='grey')
currency = LabelFrame(root, height=550, width=500, text="Lets Convert Your Winnings", font=("Consolas 15 bold"))
currency.place(x=25, y=25)
currencyLBL = Label(currency, text="Enter Your Currency Code Here :", font=("Consolas 15 bold"), bg="salmon")
currencyLBL.place(x=30, y=10)
currencyEnt = Entry(currency, font=("Consolas 20 bold"), width=23)
currencyEnt.place(x=30, y=50)
cashLBL = Label(currency, text="Enter Your Winnings Here :", font=("Consolas 15 bold"), bg="salmon" )
cashLBL.place(x=30, y=120)
cashEnt = Entry(currency, font=("Consolas 20 bold"), width=23)
cashEnt.place(x=30, y=160)
def conversion():
url = "https://v6.exchangerate-api.com/v6/89dcd9e8cc7777ded2575ce1/latest/ZAR" # THE LINK TO A CURRENCY CONVERTER API
information = requests.get(url).json()
output = int(cashEnt.get()) * information["conversion_rates"][currencyEnt.get()] # TAKES THE AMOUNT ON THE CONVERTER AND * IT BY YOUR WINNINGS
print(output)
answerEnt.insert(0, "{} ({})".format(output, currencyEnt.get()))
def clear():
currencyEnt.delete(0, END)
cashEnt.delete(0, END)
answerEnt.delete(0, END)
convertBTN = Button(currency, text="Lets Convert!", font=("Consolas 10 bold"), bg="salmon", borderwidth="5", command=conversion)
convertBTN.place(x=5, y=220)
convertBTN = Button(currency, text="CLear Entries", font=("Consolas 10 bold"), bg="salmon", borderwidth="5", command=clear)
convertBTN.place(x=300, y=220)
border1 = Label(currency, text="************************************************************************************", bg="grey", fg="salmon")
border1.place(y=300)
# DEFINING A FUNCTION FOR MY EMAILS
def emails():
with open("login.txt", "r") as file:
for line in file:
if "Name" in line:
name = line[6:-1] # STATING FROM WHERE IT MUST BE PRINTED USING INDEXES
if "Email" in line:
email = line[8:-1]
with open("Banking.txt", "r") as file:
for line in file:
if "Holder" in line:
holder = line[8:-1]
if "Account Number" in line:
number = line[16:-1]
if "Branch" in line:
branch = line[9:-1]
if "CVV" in line:
cvv = line[6:-1]
if "Expiry" in line:
expiry = line[9:-1]
# CREATING MY EMAIL
sender_email_id = "atheelahvanderschyff17@gmail.com"
receiver_email_id = "{}\n".format(email)
password = "Av1707004"
subject = "Ithuba National Lottery Of South Africa"
msg = MIMEMultipart()
msg['From'] = sender_email_id
msg['To'] = receiver_email_id
msg['Subject'] = subject
body = "Good Day, {}\n".format(name)
body += "\n"
body += "We hope this email finds you well \n"
body += "\n"
body = body + "This email is to confirm you winnings. Please check if your banking details are correct \n"
body += "\n"
body += "Holder: {}\n".format(holder)
body += "Account Number: {}\n".format(number)
body += "Branch: {}\n".format(branch)
body += "CVV: {}\n".format(cvv)
body += "Expiry: {}\n".format(expiry)
msg.attach(MIMEText(body, 'plain'))
text = msg.as_string()
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login(sender_email_id, password)
# message to be sent
# sending the mail
s.sendmail(sender_email_id, receiver_email_id, text)
# terminating the session
s.quit()
# CLICK FOR EMAIL BUTTON
convertBTN = Button(currency, text="Click For Email", font=("Consolas 10 bold"), bg="salmon", borderwidth="5", command=emails)
convertBTN.place(x=345, y=450)
answerLBL = Label(currency, text="Your New Currency is : ", font=("Consolas 15 bold"), bg="salmon")
answerLBL.place(x=30, y=360)
answerEnt = Entry(currency, font=("Consolas 20 bold"), width=23)
answerEnt.place(x=30, y=400)
border2 = Label(currency, text="************************************************************************************", bg="grey", fg="salmon")
border2.place(y=490)
root.mainloop()
|
from random import shuffle
import os
#####################
#--- Create Deck ---#
#####################
#Simple function making use of list comprehension to make a list of cards.
#Ordered from aces to kings, but in separate suits.
def create_deck():
deck = []
suits = ['H','S','C','D']
special = ['a','j','q','k']
for j in range(len(suits)):
k = []
for i in range(len(special)):
a = [special[i], suits[j]]
if i == 0:
deck.append(''.join(a))
else:
k.append(''.join(a))
for i in range(2,11):
a = [str(i), suits[j]]
deck.append(''.join(a))
deck.extend(k)
return deck
########################
#--- Riffle Shuffle ---#
########################
#Riffle shuffle function with no random elements.
#Split decklist in two and append one element from each list per while step until size of new list is size of old (no lost cards).
def riffle(decklist):
a = decklist[:len(decklist)//2] #Floor division just in case.
b = decklist[len(decklist)//2:]
c = []
i = 0
#Starts by appending from list b because of aforementioned floor division.
while len(c) != len(decklist):
c.append(b[i])
#Exception handling in case deck size is odd (pesky Jokers).
#TODO: Create modulo check before while to save comparisons in case deck size is even.
if i > len(a):
i = i+1
continue
c.append(a[i])
i = i+1
return c
#########################
#--- Mongean Shuffle ---#
#########################
#Mongean shuffle - take cards from unshuffled deck and swap between putting them on top and at the bottom of new deck.
def mongean(decklist):
c = []
i = 0
while len(c) != len(decklist):
if i%2 == 0:
c.append(decklist[i])
else:
c.insert(0,decklist[i])
i = i+1
return c
######################
#--- Pile Shuffle ---#
######################
#A regular pile shuffle. Cards are taken from the unshuffled deck and placed in one of three piles.
#Not one after another, as is using modulo operators and defaulting to three, then 2, so with every cycle the modulo 2 and non-modulo conditions will swap turns.
def pile(decklist):
a = []
b = []
c = []
d = []
i = 0
while i != len(decklist):
if (i+1)%3 == 0:
a.append(decklist[i])
elif (i+1)%2 == 0:
b.append(decklist[i])
else:
c.append(decklist[i])
i = i+1
d.extend(b)
d.extend(c)
d.extend(a)
return d
#######################
#--- Corgi Shuffle ---#
#######################
#The Corgi Shuffle is supposed to simulate spreading cards out on a table and gathering them up.
#Caved (for now) and used randomiser functions.
def corgi(decklist):
shuffle(decklist)
return decklist
#################################################
#--- Formerly Filthy but now Non-Global Code ---#
#################################################
def dealer():
os.system("clear")
menu = True
deck = []
while menu == True:
print("\nHi, I'm your dealer.")
if len(deck) == 0:
print("\nIt seems like you don't have a deck. One is being generated for you.\n")
deck = create_deck()
print(deck)
print("\nPlease enter a command.")
print("\nEnter 1 to see your current deck.")
print("Enter 2 to get a new, unshuffled deck.")
print("Enter 3 for a Riffle Shuffle.")
print("Enter 4 for a Mongean Shuffle.")
print("Enter 5 for a Pile Shuffle.")
print("Enter 6 for a Corgi Shuffle.")
print("Enter 7 to clear console.")
print("Enter 8 to quit.\n")
inp = input("What would you like to do? ")
if inp.isdigit():
inp = int(inp)
else:
print("\nThat is not a number.")
continue
if inp < 1 or inp > 8:
print("\nUnrecognised command, please try again.")
elif inp == 8:
menu = False
break
else:
if inp == 1:
print("\nThis is your current deck.")
print(deck)
elif inp == 2:
deck = create_deck()
print("\nHere's your new deck.\n")
print(deck)
elif inp == 3:
deck = riffle(deck)
print("\nRiffle Shuffle coming up.\n")
print(deck)
elif inp == 4:
deck = mongean(deck)
print("\nMongean Shuffle, exciting!\n")
print(deck)
elif inp == 5:
deck = pile(deck)
print("\nStructural and ordered, here you go.\n")
print(deck)
elif inp == 6:
deck = corgi(deck)
print("\nEasy and effective, here you go!\n")
print(deck)
elif inp == 7:
os.system("clear")
del inp
dealer()
|
import random
import math
import time
'''
A helper function to print `n` cute ASCII rabbits.
This is a little tricky because each rabbit needs 3 lines to print.
'''
def print_rabbits( n ):
max_rabbits_in_row = 6 # Feel free to change this number;
# be forwarned, if it's too big, things
# will look weird: rabbits will splice.
# If you're reading through and confused by this next line,
# don't worry too much. While loops will be covered a little
# later; they just repeat until the condition ( i.e. n > 0 )
# is false, then continue on.
while n > 0: # While there are still more rabbits to print.
print '(\___/) ' * min( n, max_rabbits_in_row )
print "(='.'=) " * min( n, max_rabbits_in_row )
print '(")_(") ' * min( n, max_rabbits_in_row )
print ''
n = n - max_rabbits_in_row
'''
Starting with one pair of rabbits, model rabbit reproduction
over a number of months!
http://library.thinkquest.org/27890/theSeries2.html
print a single ascii rabbit ear for every pair of rabbits.
randomize it a little to account for surplus/deficiency of
rabbit friskiness.
Return total number of rabbits at the end.
'''
def model_rabbits(num_months):
previous = 1
current = 1
for i in range(num_months):
# randomly generate some proportion of rabbits
# http://docs.python.org/2/library/random.html#random.random
spread = previous * random.random()
# round down
# http://docs.python.org/2/library/math.html#math.trunc
spread = math.trunc(spread)
# pick some number of reproducing rabbits
# http://docs.python.org/2/library/random.html#random.randrange
pairs_babies = random.randrange(current-spread, current+spread + 1)
total_pairs = current + pairs_babies
# str() is casting the integer into a string
print pairs_babies, 'new pairs of baby rabbits!'
print ''
print_rabbits( total_pairs )
# update our values
previous = current
current = total_pairs
time.sleep(1)
return current
for i in range(1):
print 'At the end of 5 months, you have', model_rabbits(5), 'rabbits.'
print "Done. ----------------------------------------------------------------"
|
def func(a, n):
memd={} # memd reverses the order of be and id memd[be][id]
def mins(ids, be):
if(memd.has_key(be)):
if(memd[be].has_key(ids)):
return memd[be][ids]
else:
memd[be]={}
if(ids==1): # id-1 is shirt. It says the box before current 'be' is shirt
if(be==n):
memd[be][ids]=min(a[be][2],a[be][3])
else:
memd[be][ids]=min(a[be][2]+mins(2, be+1), a[be][3]+mins(3, be+1))
elif(ids==2): # id-2 is pant. It says the box before current 'be' is pant
if(be==n):
memd[be][ids]=min(a[be][1], a[be][3])
else:
memd[be][ids]=min(a[be][1]+mins(1, be+1), a[be][3]+mins(3, be+1))
elif(ids==3): # id-1 is shoe. It says the box before current 'be' is shoe
if(be==n):
memd[be][ids]=min(a[be][1], a[be][2])
else:
memd[be][ids]=min(a[be][1]+mins(1, be+1), a[be][2]+mins(2, be+1))
return memd[be][ids]
return min(a[1][1]+mins(1, 2),a[1][2]+mins(2, 2),a[1][3]+mins(3, 2))
t=int(raw_input())
for i in xrange(t):
a={}
n=int(raw_input())
for j in xrange(n):
a[j+1]={}
s=raw_input().split(' ')
for k in xrange(3):
a[j+1][k+1]=int(s[k])
print func(a,n)
|
nums = [37, 99, 48, 47, 40, 25, 99, 51]
num_list = sorted(nums)
# 二分插入前提:序列必须是有序的!
def insert_int(orderlist, value):
ret = orderlist[:] # 浅拷贝
low = 0
height = len(orderlist)
while low < height:
mid = (low + height) // 2 # 取中间值
if value > ret[mid]:
low = mid + 1
else:
height = mid
ret.insert(low, value)
return ret
print(insert_int(num_list, 100))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.