text stringlengths 37 1.41M |
|---|
import unittest
from tests import unit_case_example
TestMethod = unit_case_example.UnitCaseExample()
class RunUnitCaseExample(unittest.TestCase):
def setUp(self):
print('Start TensorMSA')
def tearDown(self):
print('Finish TensorMSA')
def test_returnValue(self):
self.assertEqual(TestMethod.returnString(), 'successful')
def test_upper(self):
test = 'test'
self.assertEqual(TestMethod.returnUpper(test), 'TEST')
def test_isupper(self):
test = 'TEST'
self.assertTrue(TestMethod.checkUpper(test))
#self.assertFalse(TestMethod.checkUpper(test))
def test_split(self):
test = 'TensorMSA Test'
# check that s.split fails when the separator is not a string
self.assertRaises(TypeError, TestMethod.splitString(test))
self.assertEqual(TestMethod.splitString(test), ['TensorMSA', 'Test'])
if __name__ == '__main__':
unittest.main()
|
##Problem Set 3
#Name: Arianna O'Brien Cannon
#Time Spent: 20 mins
#Last Modified: 9/23/19
#def main
def main ():
#create empty dictionary
empty_dict = {}
#make actual dictionary
dict_1 = {'Jeff Bezos & family':160, 'Bill Gates':97, 'Warren Buffett':88.3, 'Mark Zuckerberg':61, 'Larry Ellison':58.4, 'Larry Page':53.8, 'Charles Koch':53.5}
#update empty dictionary to actual dictionary
(empty_dict.update(dict_1))
#for statement
for key in empty_dict:
#print keys
print(key)
#print values
print(empty_dict.values())
if __name__ == '__main__':
main() |
class SampleClass():
def __init__ (self, param2, param2):
self.param1 = param1
self.param2 = param2
def some_method(self):
print(self.param1)
class Dog():
species = 'mammal'
def __init__(self, breed, name, spots):
self.breed = breed
self.name = name
self.spots = spots
#methods
def bark(self,time):
print('WOOF! My name is {}'.format((self.name +' ') * time))
my_dog = Dog(breed = 'tibert', name = 'Sam', spots = False)
my_dog.breed
my_dog.species
my_dog.bark(time = 3)
class Circle():
#class object attribute
pi = 3.14
def __init__(self, radius = 1):
self.radius = radius
self.area = radius*radius*Circle.pi
def calculate_circumference(self):
return(2*self.radius*Circle.pi)
my_circle = Circle(15)
my_circle.calculate_circumference()
my_circle.area
class Animal():
def __init__(self):
print ('animal created')
def who_am_i(self):
print('I am an animal')
def eat(self):
print('I am eating')
some_animal = Animal()
some_animal.eat()
class Dog(Animal):
def __init__(self):
Animal.__init__(self)
print('Dog created')
#overwrite inherited method
def who_am_i(self):
print('I am a dog')
def bark(self):
print('WOLF')
my_dog = Dog()
my_dog.eat()
my_dog.who_am_i()
class Dog():
def __init__(self,name):
self.name = name
def speak(self):
return (self.name + ' says woof!')
class Cat():
def __init__(self,name):
self.name = name
def speak(self):
return (self.name + ' says meow!')
niko = Dog('niko')
felix = Cat('felix')
niko.speak()
felix.speak()
#though using same method name, these methods are defined independently
#and they can be called in function totaly the same
for pet in [niko,felix]:
print(type(pet))
print(pet.speak())
def pet_speak(pet):
print(pet.speak())
pet_speak(niko)
pet_speak(felix)
|
'''
pyhton3 实现多进程方式:
1. Unix/Linux/MacOS 独有的方式:os模块中的fork
2. 跨平台方式:使用multiprocessing模块
'''
# os 模块中的 fork 方法来源于Unix/Linux系统中的fork系统调用,调用一次返回两次。原因是当前进程复制出一份几乎相同的子进程,
# 子进程永远返回0,而当前进程(父进程)返回子进程的ID,注意不要与os.getpid()弄混淆
import os
if __name__ == '__main__':
print('current Process (%s) start ...' % (os.getpid())) # os.getpid()获取当前进程ID
pid = os.fork() # fork调用一次返回两次 <!-- 相当于获取当前进程的子进程ID -->
if pid < 0:
print('Error in fork')
elif pid == 0:
print("I'm child process(%s) and my parent process is (%s)" % (os.getpid(), os.getppid()))
else:
print('I(%s) created a child process (%s)' % (os.getpid(), pid))
|
def count_words(text):
""" Count and returns the number of words in a string.
The counting is performed iterating over the characters
in the text and counting the number of times that an
space character (space, tabs, new lines) is preceeded
by a non-space character.
Args:
text (str): text to have words counted
Returns:
int: the number of words in the text
Raises:
ValueError: If text is not an instance of str.
"""
if not isinstance(text, str):
raise TypeError('The argument must be an instance of str')
total_words = 0
is_current_space = None
is_previous_char = None
for char in text:
is_current_space = char.isspace()
if is_current_space and is_previous_char:
total_words += 1
is_previous_char = not is_current_space
if is_previous_char:
total_words += 1
return total_words
|
rango_inferior = int(input('Ingresa un rango inferior: '))
rango_superior = int(input('Ingresa un número mayor al anterior: '))
comparacion = int(input('Ingresa un número de comparación: '))
while (comparacion < rango_inferior) or (comparacion > rango_superior):
print('El número ' + str(comparacion) + ' no está en el rango')
comparacion = int(input('Prueba con otro número: '))
print( 'El número ' + str(comparacion) + ' sí está en el rango') |
class Polynomial:
def __init__(self, coeffs):
if not isinstance(coeffs, list):
raise TypeError("Coeffs not list or constant")
for i in coeffs:
if type(i) is not int and type(i) is not float:
raise TypeError("Coeffs not int or float")
self.coeffs = coeffs[:]
if len(coeffs) != 0:
while self.coeffs[0] == 0 and len(self.coeffs) > 1:
del self.coeffs[0]
else:
self.coeffs.append(0)
def __add__(self, poly_coef):
if isinstance(poly_coef, Polynomial):
result = []
self_len = len(self.coeffs)
poly_coef_len = len(poly_coef.coeffs)
if self_len > poly_coef_len:
result = self.coeffs[:]
for i in range(0, len(poly_coef.coeffs)):
result[self_len - poly_coef_len + i] += poly_coef.coeffs[i]
else:
result = poly_coef.coeffs[:]
for i in range(0, len(self.coeffs)):
result[-(self_len - poly_coef_len) + i] += self.coeffs[i]
else:
if self.coeffs:
result = self.coeffs[:]
result[-1] += poly_coef
else:
result = poly_coef
return Polynomial(result)
def __radd__(self, poly_coef):
return self + poly_coef
def __negative__(self):
return Polynomial([ -n_coef for n_coef in self.coeffs])
def __sub__(self, poly_coef):
if not isinstance(poly_coef, (Polynomial, int, float)):
raise TypeError("Error type")
if isinstance(poly_coef, (int, float)):
return self.__add__(-poly_coef)
elif isinstance(poly_coef, Polynomial):
return self.__add__(poly_coef.__negative__())
def __rsub__(self, poly_coef):
if not isinstance(poly_coef, (Polynomial, int, float)):
raise TypeError("Error type")
temp = []
if type(poly_coef) is type(self):
temp = poly_coef.coeffs
else:
temp.append(poly_coef)
self_len = len(self.coeffs)
poly_coef_len = len(temp)
result = []
ext = [0] * (self_len - poly_coef_len)
ext.extend(temp)
for i in range(self_len):
result.append(ext[i] - self.coeffs[i])
while result[0] == 0 and len(result) > 1:
result.pop(0)
return Polynomial(result)
def __mul__(self, poly_coef):
if isinstance(poly_coef, Polynomial):
result = [0] * (len(self.coeffs) + len(poly_coef.coeffs) - 1)
for i, j in enumerate(self.coeffs):
for k, l in enumerate(poly_coef.coeffs):
result[i + k] += j * l
elif isinstance(poly_coef, int) or isinstance(poly_coef, float):
result = [i * poly_coef for i in self.coeffs]
else:
raise TypeError("Coeffs not int or float")
return Polynomial(result)
def __rmul__(self, poly_coef):
return self * poly_coef
def __eq__(self, poly_coef):
if isinstance(poly_coef, Polynomial):
return poly_coef.coeffs == self.coeffs
elif isinstance(poly_coef, int) or isinstance(poly_coef, float):
return len(self.coeffs) == 1 and self.coeffs[0] == poly_coef
else:
raise TypeError("Not equal")
def __ne__(self, poly_coef):
if not isinstance(poly_coef, (Polynomial, int, float)):
raise TypeError("Error type")
if isinstance(poly_coef, (int, float)):
if len(self.coeffs) > 1:
return True
else:
return poly_coef != self.coeffs[0]
elif isinstance(poly_coef, Polynomial):
return self.coeffs != poly_coef.coeffs
def __str__(self):
str_poly = ""
lenght = len(self.coeffs)
if lenght == 1 and self.coeffs[0] == 0:
return str(0)
for i in self.coeffs:
lenght = lenght - 1
if (i == 1 or i == -1) and lenght != 0:
if lenght == len(self.coeffs) - 1 and i > 0:
str_poly = str_poly + "x^" + str(lenght)
elif lenght == len(self.coeffs) - 1 and i < 0 or (lenght != 1 and i < 0):
str_poly = str_poly + "-" + "x^" + str(lenght)
elif lenght != len(self.coeffs) - 1 and lenght != 1 and i > 0:
str_poly = str_poly + "+" + "x^" + str(lenght)
if i != 1 and i != -1 and lenght != 0:
if lenght == len(self.coeffs) - 1 or (lenght != 1 and i < 0):
str_poly = str_poly + str(i) + "x^" + str(lenght)
elif lenght != len(self.coeffs) - 1 and lenght != 1 and i > 0:
str_poly = str_poly + "+"+str(i) + "x^" + str(lenght)
if lenght == 1 and i > 0:
str_poly = str_poly + "+" + "x"
elif lenght == 1 and i < 0:
str_poly = str_poly + "-" + "x"
if lenght == 0 and i < 0:
str_poly = str_poly + str(i)
elif lenght == 0 and i > 0:
str_poly = str_poly + "+" + str(i)
return str_poly
|
import sys
def anagram(string):
'''
Observación clave:
Si no hay anagramas de longitud uno,
no hay anagramas de longitud mayor a
uno con esa letra.
'''
anagrams = dict()
moreTone = 0
for c in string:
if c in anagrams:
anagrams[c] = anagrams[c] + 1
moreTone = moreTone + 1
else:
anagrams[c] = 1
return anagrams
if __name__ == '__main__':
line = sys.stdin.readline()
|
# make a closest number function to find out which two pairs have the smallest difference
# Author: Wanjiru Wang'ondu
#
# # first, we create an array
# array_one = [1, 2] # 3, 66, 77, 8, 9, 12]
# array_differences = {}
#
#
# def find_differences(array, diff_array):
# for i in array:
# for j in array:
# difference = i - j
# print(difference)
# (i, j, difference)
# print(diff_array)
#
#
# find_differences(array_one, array_differences)
from typing import Dict
dictA = {1, "2"}
dictA[2] = [3, 4]
print(dictA)
|
# -*- coding: utf-8 -*-
from Conta import *
conta1 = Conta(123, 'lucas', 100, 100)
conta2 = Conta(113, 'luis', 120, 140)
# conta1.extrato()
# conta2.extrato()
# conta1 = None -> Apaga a referencia entre a variavel e o objeto
# conta1.extrato() Após apagar a referencia, nao existe mais esse endereco
"""from datas import DataFormat
data = DataFormat(20, 5, 1997)
data.formatada()
"""
# conta1.transferencia(15, conta2)
# conta1.extrato()
# conta2.extrato()
# conta1.set_limite(1500)
# print(conta1.get_limite())
print(conta1.limite)
conta1.limite = 150
print(conta1.limite)
print(conta1.saldo)
conta1.saque(250.5)
print(Conta.codBanco())
codigo = Conta.codBanco()
print(codigo['BB'])
conta1 = None
conta2 = None
|
'''
mock
1.接口测试的测试场景比较难模拟,需要大量的工作才能做好
2.该接口的测试,依赖其他模块的接口,依赖的接口尚未开发完成
测试条件不充分,怎么开展接口测试
使用mock模拟接口的返回值
'''
import requests
from unittest import mock
'''
支付接口:http://www.zhifu.com/
方法:post
参数:{"订单号":“12345”,"支付金额":20.56,"支付方式":"支付宝/微信/余额宝/银行卡"}
返回值:{"code":200,"msg":"支付成功"}、{"code":201,"msg":"支付失败"}
接口尚未实现
'''
class Pay:
def zhifu(self,data):
r=requests.post("http://www.zhifu.com/",data=data)
return r.json()
def test_001():
pay=Pay()
#通过mock模拟接口的返回值
pay.zhifu=mock.Mock(return_value={"code":200,"msg":"支付成功"})
canshu={"订单号":"12345","支付金额":20.56,"支付方式":"支付宝"}
r=pay.zhifu(canshu)
print(r)
assert r['msg']=="支付成功"
def test_002():
pay=Pay()
#通过mock模拟接口的返回值
pay.zhifu=mock.Mock(return_value={"code":201,"msg":"支付失败"})
canshu={"订单号":"12345","支付金额":-20.56,"支付方式":"支付宝"}
r=pay.zhifu(canshu)
print(r)
assert r['msg']=="支付失败"
# 模块名,类名,方法名
@mock.patch("test_001.Pay.zhifu",return_value={"code":200,"msg":"支付成功"})
def test_003(mock_pay):
pay=Pay()
canshu={"订单号":"12345","支付金额":201.56,"支付方式":"微信"}
r=pay.zhifu(canshu)
print(r)
assert r['msg']=="支付成功"
class Quxian:
def quxian(self,data):
url="http://www.zhifu.com/member/withdraw"
r=requests.post(url,data=data)
return r.json()
def test_004():
qx=Quxian()
qx.quxian=mock.Mock(return_value={"status":1,"code":"10001","msg":"取现成功"})
canshu={"mobilephone":"13213577531","amount":223}
r=qx.quxian(canshu)
print(r)
assert r["msg"]=="取现成功" |
def seqSearchLast(myList, target):
for i in range(len(myList)-1, -1, -1):
if myList[i] == target:
return i
return None
def trinarySearch(myList, target):
low = 0
high = len(myList)-1
while low <= high:
oneThird = low + (high - low)/3
twoThirds = high - (high - low)/3
if myList[oneThird] == target:
return oneThird
if myList[twoThirds] == target:
return twoThirds
if target < myList[oneThird]:
high = oneThird - 1
else:
if target > myList[oneThird] and target < myList[twoThirds]:
low = oneThird + 1
high = twoThirds - 1
else:
low = twoThirds + 1
return None
def backwardsBubbleSort(myList):
for i in range(len(myList)-1, 0, -1):
for i in range(len(myList)-1, 0, -1):
if myList[i] < myList[i-1]:
myList[i], myList[i-1] = myList[i-1], myList[i]
return myList
def backwardsSelectionSort(myList):
i = len(myList)-1
while i >= 0:
maxIndex = i
j = i
while j >= 0:
if myList[maxIndex] < myList[j]:
maxIndex = j
j-=1
myList[i], myList[maxIndex] = myList[maxIndex], myList[i]
i-=1
return myList
|
#tuple creation
bra=("CSE","IT","Mech","ECE","CSE")
#print
print(bra)
#Data type of bra
print(type(bra))
#size of tuple
print("Size of tuple is: {}" .format(len(bra)))#4
#Max element
max_ele=max(bra)
print("Max element is %s" %(max_ele))
#Min element
min_ele=min(bra)
print("Min element is %s" %(min_ele))
repetition=bra.count("IT")
print("CSE is repeated %s times" %(repetition))
#slicing
'''
('CSE', 'IT', 'Mech', 'ECE', 'CSE')
<type 'tuple'>
Size of tuple is: 5
Max element is Mech
Min element is CSE
CSE is repeated 1 times
'''
|
class Set:
def __init__(self, value = []): # Constructor
self.data = [] # Manages a list
self.concat(value)
def intersection(self, other): # other is any sequence
res = [] # self is the subject
for x in self.data:
if x in other: # Pick common items
res.append(x)
return Set(res) # Return a new Set
def union(self, other): # other is any sequence
res = self.data[:] # Copy of my list
for x in other: # Add items in other
if not x in res:
res.append(x)
return Set(res)
def concat(self, value):
for x in value:
if not x in self.data: # Removes duplicates
self.data.append(x)
def __len__(self): return len(self.data) # len(self)
def __getitem__(self, key): return self.data[key] # self[i], self[i:j]
def __and__(self, other): return self.intersection(other) # self & other
def __or__(self, other): return self.union(other) # self | other
def __repr__(self): return 'Set({})'.format(repr(self.data))
def __iter__(self): return iter(self.data) # for x in self:
def issubset(self, other) :
inter = 0
for i in self.data :
if i in other.data :
inter += 1
if inter == len(self.data) :
return True
else :
return False
def issuperset(self, other) :
inter = 0
for i in other.data :
if i in self.data :
inter += 1
if len(self.data) >= len(other.data) and inter == len(other.data) :
return True
else :
return False
def intersection_update(self, *others) :
a = self.data
for i in others :
for j in a :
if j not in i :
a.remove(j)
self = Set(a)
return self
def difference_update(self, *others) :
a = self.data
for i in others :
for j in i :
if j in a : # 위와 같은 실수함 (others 안의 i를 리스트 안의 요소라고 생각함)
a.remove(j)
self = Set(a)
return self
def symmetric_difference_update(self, other) :
a = self.data
b = other.data
c = a + b
d = Set(c)
for i in a :
if i in b :
d.remove(i)
self = d
return self
def add(self, elem) :
if elem not in self.data :
self.data.append(elem)
def remove(self, elem) :
try :
if elem in self.data :
self.data.remove(elem)
else :
raise KeyError
except KeyError :
print("There is no {0} in current set".format(elem))
def __lt__(self, other) :
if self.data != other.data and self.issubset(other) :
return True
else :
return False
def __le__(self, other) :
if self.issubset(other) == True :
return True
else :
return False
def __gt__(self, other) :
if self.data != other.data and self.issuperset(other) :
return True
else :
return False
def __ge__(self, other) :
if self.issuperset(other) == True :
return True
else :
return False
def __ior__(self, other) :
for i in other.data :
if i not in self.data :
self.data.append(i)
return self
def __iand__(self, other) :
self = self.intersection_update(other)
return self
def __isub__(self, other) :
a = self.data
for i in other.data :
if i in a :
a.remove(i)
self = Set(a)
return self
def __ixor__(self, other) :
a = self.symmetric_difference_update(other)
self = Set(a)
return self
A = Set([1,3,5])
B = Set([2,3,4])
A^=B
print(A)
C = Set([1,2,3])
D = Set([3,4,5])
C&=D
print(C)
E = Set([1,2,3])
F = Set([4,5,6,7])
E|=F
print(E)
G = Set([1,2,3,4])
H = Set([3,4,5,6])
G-=H
print(G)
a = Set([1,2,3,4])
b = Set([1,2])
print(a>=b)
print(a>b)
print(b<a)
#issubset
print(b.issubset(a))
#issuperset
print(b.issuperset(a))
print(a.issuperset(b))
aa = Set([1,2,3])
bb = Set([1,2,3])
print(aa>bb)
print(aa<bb)
print(aa.issubset(bb))
print(bb.issubset(aa))
x = Set([1,2,3,3,4])
y = Set([2,1,4,5,6])
z = Set([4,5,6,7,8])
print(x, y, z, len(x))
#intersection_update
print(x.intersection_update(y,z))
print(x, y, z, len(x))
#difference_update
d = Set([5,6,7,9])
e = Set([3,5,7,8,6])
f = Set([2,4,6,8])
print(d, e, f, len(d))
print(d.difference_update(e,f))
print(d, e, f, len(x))
#symmetric_difference_update(other)
my = Set([1,2,5,6])
your = Set([1,2,5,7])
print(my.symmetric_difference_update(your))
print(my)
#add(elem)
my1 = Set([1,2,3])
my1.add(4)
my1.add(10)
print(my1)
#remove(elem)remove(elem)
my2 = Set([1,2,3,4,5,10])
my2.remove(1)
my2.remove(11)
print(my2)
|
x=raw_input
y=int(x)
if x=str(::-1):
print("x is polindram")
else:
print("x is no ploindram")
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
cars = 100 # we put a value into a variable
space_in_a_car = 4.0 # we put a value into a variable
drivers = 30 # we put a value into a variable
passengers = 90 # we put a value into a variable
cars_not_driven = cars - drivers # We define a variable using two other variables
cars_driven = drivers # We define a variable using other variable
carpool_capacity = cars_driven * space_in_a_car # We define a variable using two other variables
average_passengers_per_car = passengers / cars_driven # We define a variable using two other variables
print "There are", cars, "cars available." # The specified value goes into 'cars' (=100)
print "There are only", drivers, "drivers available." # The specified value goes into 'drivers' (=30)
print "There will be", cars_not_driven, "empty cars today." # The specified value goes into 'cars_not_driven'
print "We can transport", carpool_capacity, "people today." # The specified value goes into 'carpool_capacity'
print "We have", passengers, "to carpool today." # The specified value goes into 'passengers' (=90)
print "We need to put about", average_passengers_per_car, "in each car." # The specified value goes into 'average_passengers_per_car'
|
class Atm(object):
"""
Error-
<bound method Atm.BalanceEnquiry of <__main__.Atm object at 0x000002BCE4ED7FA0>>
"""
# Ma'am pls help me with this error
def __init__(self,cardNumber,pinNumber):
self.cardNumber = cardNumber
self.pinNumber = pinNumber
def CashWithdrawal(self,cardNumber,pinNumber):
cardN = input("Enter cardNumber: ")
pinN = input("Enter pin number: ")
if(cardN == cardNumber & pinN == pinNumber):
Money = input("How much money would you like to withdraw: ")
print(Money," Has been successfully withdrawed")
else:
print("The card number/pin number is incorrect")
def BalanceEnquiry(self,cardNumber,pinNumber):
cardN = input("Enter cardNumber: ")
pinN = input("Enter pin number: ")
if(cardN == cardNumber & pinN == pinNumber):
print("Contact 109838282 to check your account balance")
else:
print("The card number/pin number is incorrect")
def DepositCash(self,cardNumber,pinNumber):
cardN = input("Enter cardNumber: ")
pinN = input("Enter pin number: ")
if(cardN == cardNumber & pinN == pinNumber):
Cash = input("How much cash would you like to deposit: ")
print(Cash," Has been successfully deposited")
else:
print("The card number/pin number is incorrect")
Card = Atm(5555555555554444,5621)
print(Card.BalanceEnquiry) |
shopping_list=['milk', 'bananas', 'bread', 'bread', 'books']
new_item = input('What would you like to add to your shopping list?')
shopping_list.append(new_item)
shopping_list.insert(0,'impulse buy')
print("Items in your shopping list:\t",shopping_list)
del shopping_list[0]
print(shopping_list)
shopping_list.pop(1)
print(shopping_list)
lost_item=shopping_list.pop(1)
print('You lost:',lost_item)
print(shopping_list)
removed="books"
shopping_list.remove(removed)
print(shopping_list) |
age=0
if age<2:
print('baby')
elif age>=2 and age<4:
print('toddler')
elif age>=4 and age<13:
print('kid')
elif age>=13 and age<20:
print('teenager')
elif age>=20 and age<65:
print('adult')
elif age>=65:
print('elder') |
#Python strings are very flexible, but if we try to create a string that occupies multiple lines we find ourselves face-to-face with a SyntaxError. Python offers a solution: multi-line strings. By using three quote-marks (""" or ''') instead of one, we tell the program that the string doesn’t end until the next triple-quote.
# Assign the string here
to_you = """Stranger, if you passing meet me and desire to speak to me, why
should you not speak to me?
And why should I not speak to you?"""
print(to_you) |
from __future__ import print_function, division
from main import *
from pylab import *
''' This file is used to test different starting conditions on the iterative algorithm. Here I was using
the approach of first creating zeros, expanding them and then checking the solved zeros against the original zeros. '''
if __name__ == "__main__":
lowest_order = 2 # Lowest order of tested polynomial, I always use 2.
highest_order = 15 # Highest order of test polynomial
zero_bound = 1000 # Maximum coefficients of the zero
pol_bound = 1000 # Maximum initial guess coefficient
tests_per_order = 10 # How many tests should be done per 1 order of a polynomial
iteration_number = 1 # How many iterations the algorithm should perform
h = 0.01 # timestep
T = 1 # T-value described in the algorithm. Always 1 for my purposes.
# The string below is used to name the file, to track what it actually is.
string = str(zero_bound) + ' - ' + str(pol_bound) + '_' + str(iteration_number) + str(h)[1:] + '-O-' + str(highest_order) + ".txt"
# Clear the files or create them
f = open("trial_data." + string, "w") # This stores summary of error of each degree
g = open("trial_dataQ." + string, "w") # This stores detailed data of errors each trial
f.close()
g.close()
average_errors = zeros(highest_order - lowest_order + 1) # array storing largest errors, for plotting purposes
degrees = array(range(lowest_order, highest_order+1)) # array storing degree, for plotting purposes.
for degree in range(lowest_order, highest_order+1): # We iterate through each degree.
g = open("trial_dataQ." + string, "a") # We open in append mode to be able to edit the file
f = open("trial_data." + string, "a")
# We create a separator for each degree so it is easier to read.
f.write("----------------------------------------" '\n')
f.write("Degree = " + str(degree) + '\n')
f.write("----------------------------------------" '\n')
g.write("----------------------------------------" '\n')
g.write("Degree = " + str(degree) + '\n')
g.write("----------------------------------------" '\n')
largest_error = 0 # Will store the largest error of the polynomial
total_error = 0 # Will store the cummulative errors of all trials. Later used to find mean error.
for j in range(tests_per_order):
print("i : j |", degree, ':', j) # Printed so user can see progress of the program
f.write("\n***Trial " + str(j+1) + ":\n")
# We generate random zeros from which we make a polynomial
correct_zeros = zero_bound * (rand(degree) + 1j * rand(degree))
p = Polynomial(degree, correct_zeros, [-zero_bound, zero_bound])
# We perform the iterative numerical integration.
for i in range(iteration_number):
p.evaluate_time_zeros(h, T)
# We sort the approximated zeros and the original zeros by their real part.
correct_zeros = sort(correct_zeros) # sort the original zeros
p.time_zeros = sort(p.time_zeros) # sort the approximated zeros
difference = absolute(correct_zeros - p.time_zeros) # estimate their error
error = norm(difference)
# We check if the trial had an error larger than any previous trial
if norm(difference) > largest_error:
largest_error = error # if so, we change the largest error
# Regardless, we add the biggest error of this trial to the total error.
total_error += error
# Whe then output that data into a file
f.write("Correct zeros: \n")
f.write(str(correct_zeros) + '\n')
f.write("Evaluated zeros: \n")
f.write(str(p.time_zeros) + '\n')
f.write("Error array: \n")
f.write(str(difference) + '\n')
f.write("Error = " + str(error))
f.write('\n')
f.write('\n')
# Here we write the summary of the errors into the g file.
average_errors[degree - lowest_order] = total_error / tests_per_order
g.write("largest error of all trials = " + str(largest_error) + "\n")
g.write("average error of all trials = " + str(total_error/tests_per_order) + '\n')
g.write('\n')
f.close()
g.close()
# We plot the results
figure()
title('number of iterations: ' + str(iteration_number))
xlabel("polynomial degree")
ylabel("average error")
semilogy(degrees, average_errors)
show()
|
#I'm using Python 2.x.
#The following import makes division work as in Python 3. Thus 2/3=0.66666....
#rather than 2/3=0 (in Python 2 division between integers yields an integer;
#Python 3 has the additional operator // for integer division)
from __future__ import division
from pylab import *
from scipy.linalg import solve
def PolyLagrange(absc, ordi, x):
"""Evaluates at x the polynomial passing through the points having
abscissas 'absc' and ordinates 'ordi' using Lagrange's method.
Input:
absc, ordi: 1D arrays or iterable python objects that convert to 1D
array. They must have the same length.
x: 1D array or a number
Output: 1D array of same length as x, or a number if x is a number.
"""
absc = array(absc)
ordi = array(ordi)
if shape(absc) != shape(ordi):
raise ValueError("Abscissas and ordinates have different length!")
if len(shape(absc)) != 1:
raise ValueError("Abscissas and ordinates must be 1D objects!")
Npts = len(absc)
product = ones((Npts,) + shape(x))
for i in range(Npts):
for j in range(Npts):
if i == j : continue
product[i] *= (x-absc[j])/(absc[i]-absc[j])
return dot(ordi, product)
#------------------------------------------------------------
# Hints for exercise n.3
def SplineCoefficients(absc, ordi):
"""Computes a matric containing the coefficients of the polynomials
forming a set of natural cubic splines interpolating the points (absc, ordi).
Input:
absc, ordi: 1D arrays or iterable python objects that convert to 1D
array. They must have the same length. absc must be ordered
in growing order.
Output:
A matrix with four columns and as many rows as the elements in absc
minus one. If c0, c1, c2, c3 are the elements along the i-th row, the
corresponding interpolating polynomial is
S_i(x)=c0 + c1*(x - absc[i]) + c2*(x - absc[i])**2 + c3*(x - absc[i])**3
"""
#Delete 'pass' and put here your code.
#To solve eq. 3.24 in the book, use
# c = solve(A,K)
#where A is the matrix containing the deltas and K is the vector
#of the know solutions (you must prepare them both).
#'solve' has been imported at the beginning of this code.
pass
def __evaluate_spline(coeff, absc, x):
"""Don't use this directly. Call 'evaluate_spline', instead."""
#Delete 'pass' and put here your code. It might useful to know
#that, if a is ordered in growing order, as it should be, then
# 'searchsorted(a, x)'
#returns the index of the smallest element in a which is larger
#than x
pass
def evaluate_spline(coeff, absc, x):
"""Evaluates at x the the natural spline interpolant.
Input:
coeff: matrix containinig the coefficients of the cubic interpolants.
This is the output of 'SplineCoefficients'.
absc: the same abscissas passed to 'SplineCoefficients' to compute 'coeff'.
x: 1D array or a number
Output: 1D array of same length as x, or a number if x is a number.
"""
# x is a number
if shape(x)==():
p = __evaluate_spline(coeff, absc, x)
# x is a 1D array, or list, or tuple
else:
x = array(x)
p = zeros_like(x)
for i in range(len(x)):
p[i] = __evaluate_spline(coeff, absc, x[i])
return p
#------------------------------------------------------------
function = lambda x: 1./(1+x**2)
interval = [-5, 5]
Npts = 9
L = interval[1]-interval[0]
x = linspace(interval[0], interval[1], 1001)
# constant interval abscissas
a = linspace(interval[0] + L/Npts/2, interval[1] - L/Npts/2 , Npts)
print(a)
o = function(a)
p = PolyLagrange(a, o, x)
figure(1)
plot(x, p, 'b-',
x, function(x), 'g-',
a, o, 'or')
xlabel("Abscissas", fontsize=20)
ylabel("Ordinates", fontsize=20)
legend(["Polynomial fit", "Original function", "Interpolation nodes"],
loc="upper center")
title("Maximum absolute error: {:7.4f}".format(amax(fabs(p - function(x)))), fontsize=20 )
plt.show()
|
import math
x,y = map(int,input().split())
f = y*math.log(x)
s = x*math.log(y)
if f<s:
print("<")
elif f>s:
print(">")
else:
print("=") |
import sense_hat
from time import sleep, time
from random import randint
sense = sense_hat.SenseHat()
sense.clear()
"""
Make your Sense HAT into a Flappy HAT!
Help the bird fly though the columns. Each column is
one point. How many points can you get?
Read through the code to learn how the game is made and
try changing some of the variables at the top. Turn on
debug_mode to print extra information about what the program
is doing.
Inspired by the Astro Pi team's flappy astronaut!
https://www.raspberrypi.org/learning/flappy-astronaut
Note: Requires sense_hat version 2.2.0 or later
"""
# Edit these variables to change key game parameters
col_color = (0, 255, 0) # RGB color of column pixels
bg_color = (0, 0, 0) # RGB color of background pixels
bird_color = (200, 200, 0) # RGB color of the bird pixel
bird_y = 2 # Where the player starts
bird_lives = 3 # How many lives does the bird get?
columns = [(7, 3, 3)] # Starting column x index, gap y start, gap size
column_speed_base = 1 # Base speed for column movement, from 1 to 5
debug_mode = False # Set to true to print extra information
# Variables for convenience and readability
up_key = sense_hat.DIRECTION_UP
pressed = sense_hat.ACTION_PRESSED
# Initial settings - should be no need to alter these
speed = 0
game_over = False
setup = True
moved = False
column_interval = 10
# Debug functions: pause or print messages if debug_mode is set to True
def debug_message(message):
if debug_mode:
print(message)
def debug_pause(message):
# Currently not used
# To examine a specific portion of the program, add a debug_pause with a message
# Or, change an existing debug_message call to debug_pause to pause there
if debug_mode:
eval(input(str(message) + " Press enter to continue..."))
# Get true color values for comparisons: get_pixel() sometimes returns different values
sense.set_pixel(0, 0, col_color)
col_color = sense.get_pixel(0, 0)
sense.set_pixel(0, 0, bg_color)
bg_color = sense.get_pixel(0, 0)
sense.set_pixel(0, 0, bird_color)
bird_color = sense.get_pixel(0, 0)
sense.clear()
# Save setup in a tuple to restart game
reset_state = (col_color, bg_color, bird_color, bird_y, bird_lives, columns,
column_speed_base, speed, game_over)
####
# Game functions
####
def move_columns():
debug_message("Moving columns")
global columns
starting_cols = len(columns)
# Shift x coordinate of colums to left
columns = [(c[0] - 1, c[1], c[2]) for c in columns]
# Add a new column if needed
if max([c[0] for c in columns]) == 4:
gap_size = randint(2, 4)
row_start = randint(1 + gap_size, 6)
columns.append((7, row_start, gap_size))
def draw_column(col, custom_color=None):
debug_message("Drawing column")
if custom_color:
back_color = custom_color
else:
back_color = bg_color
# Construct a list of column color and background color tuples, then set those pixels
x, gap_start, gap_size = col
c = [col_color] * 8
c[gap_start - gap_size: gap_start] = [back_color] * gap_size
for y, color in enumerate(c):
sense.set_pixel(x, y, color)
def draw_screen(custom_color=None):
debug_message("Drawing screen")
if custom_color:
back_color = custom_color
else:
back_color = bg_color
sense.clear(back_color)
# Filter out offscreen columns then draw visible columns
visible_cols = [c for c in columns if c[0] >= 0]
for c in visible_cols:
draw_column(c, back_color)
def draw_bird(falling=True):
debug_message("drawing bird")
global bird_y, bird_lives, game_over
# Replace bird with upcoming background or column at x=4
sense.set_pixel(3, bird_y, sense.get_pixel(3, bird_y))
if falling:
bird_y += speed
# Stay onscreen
if bird_y > 7:
bird_y = 7
if bird_y < 0:
bird_y = 0
# Collisions are when the bird moves onto a column
hit = sense.get_pixel(3, bird_y) == col_color
if hit:
flash_screen()
bird_lives -= 1
# ignore any keypresses here
sense.stick.get_events()
# Draw bird lives
if bird_lives > 8:
# Can only draw 8 at a time
draw_lives = 8
else:
draw_lives = bird_lives
for i in range(draw_lives):
sense.set_pixel(0, i, (200, 200, 200))
game_over = bird_lives < 0
# Draw bird in new position
sense.set_pixel(3, bird_y, bird_color)
debug_message("Bird drawn")
def flash_screen():
for i in range(3):
custom_color = ([randint(50, x) for x in [255, 255, 255]])
draw_screen(custom_color)
# Make sure bird is still visible
sense.set_pixel(3, bird_y, bird_color)
sleep(.1)
draw_screen()
####
# Main Game Loop
####
while True:
if setup:
col_color, bg_color, bird_color, bird_y, bird_lives, columns, column_speed_base, speed, game_over = reset_state
# Initial screen setup
last_redraw = round(time(), 1) * column_interval
draw_screen()
draw_bird()
# Clear joystick events
sense.stick.get_events()
column_speed = int(column_speed_base)
setup = False
column_tick = round(time(), 1) * column_interval
if (column_tick % (column_interval - column_speed) == 0) and (
column_tick > last_redraw):
# Enough time has passed: columns move
debug_message("Tick!")
speed = 1
# make columns faster if possible as game goes on
if column_interval > (column_speed + 2):
column_speed = column_speed_base + len(columns) // (
column_interval * 3)
move_columns()
draw_screen()
draw_bird()
debug_message("Tick length: " + str(column_tick - last_redraw) \
+ " Speed: " + str(column_speed) \
+ "Columns: " + str(len(columns)))
last_redraw = column_tick
events = sense.stick.get_events()
if events:
for e in events:
debug_message("Processing joystick events")
if e.direction == up_key and e.action == pressed:
# User pressed up: move bird up and columns over
debug_message("Joystick up press detected")
move_columns()
draw_screen()
speed = -1
draw_bird()
moved = True
# Prevent double falls
last_redraw -= column_interval // 2
else:
moved = False
if game_over:
flash_screen()
# Score is number of columns survived
score = len(columns) - 2
sense.show_message(str(score) + "pts!", text_colour=(255, 255, 255))
# Start over
setup = True
|
def rec(n, i):
value="" #1 BigO Runtime
if i<len(b)-1:
value=rec(n,i+1)
return value+" "+n[i]
a="awesome is This"
b=a.split(' ')
print(rec(b,0))
#BigO Runtime 1
value <- empty value
if i < length of b then - 1
value <- REC
return value
a <- user input
b <- function to reverse string
print REC
|
# 条件分岐その2: 「もし○○なら、☆☆、そうでなければ△△」(if-else)
# score = 80
#
# if score >= 70:
# print('Great!!')
# else:
# print('So so')
# 条件分岐その2: 「もし○○なら、☆☆、
# そうでなくて□□なら××
# どれでもなければyy」(if-elif-else)
score = 40
if score >= 70:
print('Great!!')
elif score >= 40:
print('So so')
else:
print('Bad...') |
import matplotlib.pyplot as pyplot
from sklearn.cluster import KMeans
def k_means_clustering(X, k=None):
pyplot.figure()
#pyplot.scatter(X[:, 0], X[:, 1], label='True Position')
if k is None:
kmeans = KMeans()
else:
kmeans = KMeans(n_clusters=k)
kmeans.fit_predict(X)
pyplot.title("K-Means")
pyplot.scatter(X[:, 0], X[:, 1], s=15, c=kmeans.labels_, cmap='rainbow')
pyplot.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], color='black') # Centroidi
|
# 1. Loops
"""
1. for
2. while
"""
price_list = []
# Initialization : 0 is like i=0
i=0
#print("Break Loop")
# Condition : 100 is like i<100
while(i<100):
price_list = price_list + [i]
# Incrementation : 1 is like i++
i = i + 1
# if (i==50):
# print("Break")
# break
print(price_list)
input()
# For Loop
price_list = []
# range(0,100,1)
# Initialization : 0 is like i=0
# Condition : 100 is like i<100
# Incrementation : 1 is like i++
for i in range(0,100,2):
print(i,j)
#price_list.append(i)
print(price_list)
input()
price_list = []
for i in range(0,100,2):
price_list = price_list + [i]
#[]+[0] = [0]
#[0]+[1] = [0,1]
# [0,1]+[2] = [0,1,2]
print(price_list)
#i=0,i<100,i++
# While Loop
price_list = []
# Initialization : 0 is like i=0
i=0
print("While Loop")
# Condition : 100 is like i<100
while(i<100):
price_list = price_list + [i]
# Incrementation : 1 is like i++
i = i + 1
print(price_list)
# Break in loop
price_list = []
# Initialization : 0 is like i=0
i=0
print("Break Loop")
# Condition : 100 is like i<100
while(i<100):
price_list = price_list + [i]
# Incrementation : 1 is like i++
i = i + 1
if (i==50):
print("Break")
break
print(price_list)
# Continue in Loop
price_list = []
# Initialization : 0 is like i=0
i=0
print("Continue Loop")
# Condition : 100 is like i<100
while(i<100):
price_list = price_list + [i]
# Incrementation : 1 is like i++
i = i + 1
if (i==50):
print("Continue")
pass
print(price_list)
print("Pass")
# Pass in loop
for i in range(0,100):
pass
print("Continue")
# Pass in loop
for j in range(0,50):
for i in range(0,100):
break
print(j) |
# 1. Exception Handling
"""
1. try
2. except
3. finally
"""
# Simple try-except block
personal_details = {"name":"csk","age":25}
# Error - KeyError
#print(personal_details["city"])
try:
print(personal_details["city"])
except(KeyError,AttributeError) as err:
personal_details["city"] = "Bangalore"
print("Exception Block")
print(personal_details["city"])
except:
pass
# try-except-finally block
print("try-except-finally block")
try:
print(personal_details["city"])
except(KeyError):
personal_details["city"] = "Bangalore"
print("Exception Block")
print(personal_details["city"])
finally:
print("Finally") |
# array|list
#element list of array with same data types
element_list = ["apple","orange","grapes"]
# element list of array with different data types
element_list_mutiple_dt = ["apple","orange","grapes",12,2.5]
# index starts from zero
print(element_list[0])
print(element_list_mutiple_dt)
# numeric list
age_list = [21,22,23,24,25]
print(age_list)
# for loop in one line
# list comprehension
age_list_10 = [i+10 for i in age_list]
print(age_list_10)
print(dir(age_list_10))
# Assignment : Explore array|list functions
# ['append', 'clear', 'copy', 'count',
# 'extend', 'index', 'insert', 'pop', 'remove',
# 'reverse', 'sort']
age_list_10.append(20)
print(age_list_10)
score_list = [90,80,70,60]
# Array : append functionality: I appends a value at the end of the array.
score_list.append(60)
print(score_list)
print(dir(score_list))
# Array functions : 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'
# String
# Float
# Integer
# Tuple
# set
# dictionary
|
#x^2+bx+c=0
import math as m
a = int(input("Ведите значение а: "))
b = int(input("Ведите значение b: "))
c = int(input("Ведите значение c: "))
if a == a and b == b and c == c:
(d) = b * b - 4 * a *c
elif a == -a and b == -b and c == -c:
(d) = -b *(-b) - 4 * (-a) * (-c)
else:
print("Ошибка!")
print("Дискриминант равен: " + str(d))
if d > 0:
x1 = (-b + m.sqrt(d))/(a + a)
print("X равен: " + str(x1))
xtoo = (-b - m.sqrt(d))/(a + a)
print("X2 равен: " + str(xtoo))
elif d == 0:
x = -b/(a + a)
print("Будет один корень, и он равен: " + str(x))
elif d < 0:
print("Дискриминант отрицательный и он равен: " + str(d))
else:
print("Error!!!")
|
# 此处可 import 模块
"""
@param string line 为单行测试数据
@return string 处理后的结果
"""
def solution(line):
char_list = line.split(',')
#先找最大的正数
max = 0
for i in char_list:
num = int(i)
if num > max:
max = num
bucket = list(range(max+1))
for i in range(max+1):
bucket[i] = 0
for i in char_list:
num = int(i)
if num > 0:
bucket[num] = 1
for i in range(1, max+1):
if bucket[i] == 0:
return i
return max + 1
line = "3,-1,1,2,5"
result = solution(line)
print(result) |
def solution(line):
stack = []
for char in line:
if char == '(':
stack.append(char)
continue
elif char == '[':
stack.append(char)
continue
elif char == '{':
stack.append(char)
continue
elif char == ')':
if len(stack) == 0:
return '0'
elif stack[len(stack)-1] == '(':
stack.pop()
else:
return '0'
elif char == ']':
if len(stack) == 0:
return '0'
elif stack[len(stack)-1] == '[':
stack.pop()
else:
return '0'
elif char == '}':
if len(stack) == 0:
return '0'
elif stack[len(stack)-1] == '{':
stack.pop()
else:
return '0'
if len(stack) == 0:
return '1'
else:
return '0'
line = "[()]{}"
result = solution(line)
print(result) |
import turtle
import random
playrone=turtle.Turtle()
playrone.color("green")
playrone.shape("turtle")
playrone.penup()
playrone.goto(-200,100)
playrtwo=playrone.clone()
playrtwo.color("blue")
playrtwo.penup()
playrtwo.goto(-200,-100)
playrone.goto(300,60)
playrone.pendown()
playrone.circle(40)
playrone.penup()
playrone.goto(-200,100)
playrtwo.penup()
playrtwo.goto(300,-140)
playrtwo.pendown()
playrtwo.circle(40)
playrtwo.penup()
playrtwo.goto(-200,-100)
dice=[1,2,3,4,5,6]
for i in range(20):
if playrone.pos()>=(300,100):
print("player one wins")
break
if playrtwo.pos()>=(300,-100):
print("player two wins")
break
else:
playroneturn=input("Press the enter key to start the game")
diceoutcome=random.choice(dice)
print("The result of the dice is",diceoutcome)
print("The no. of steps moved by the turtle is",20*diceoutcome)
playrone.fd(20*diceoutcome)
playrtwoturn=input("Press the enter key to start the game")
d=random.choice(dice)
print("The result of the dice is",d)
print("The no.of steps moved by the turtle is",20*d)
playrtwo.fd(20*d)
|
# pygameBaseClass.py
# by David Simon (dasimon@andrew.cmu.edu)
# Nov 2014
#
# Changes:
# - Added EXIT condition to allow game to exit
# - Created runAsChild method to allow for nested game objects (menu, game)
import pygame
from pygame.locals import *
class PygameBaseClass(object):
"""Provides a framework for games based on Pygame"""
def __init__(self, name='PygameBase', width=1280, height=768):
self.name = name
self.width = width
self.height = height
def createDisplay(self):
"""Creates the display surface"""
dimensions = (self.width, self.height)
self.display = pygame.display.set_mode(dimensions)
pygame.display.set_caption(self.name)
def onKeyDown(self, event): pass
def onKeyUp(self, event): pass
def onMouseMotion(self, event): pass
def onMouseButtonDown(self, event): pass
def onMouseButtonUp(self, event): pass
def redrawAll(self): pass
def initGraphics(self): pass
def initGame(self): pass
def quit(self):
self.EXIT = True
def mainloop(self):
"""Handles events"""
self.EXIT = False
while self.EXIT == False:
self.clock.tick(60) # limits the game to 60 frames per second
for event in pygame.event.get():
if event.type == QUIT:
return
elif event.type == KEYDOWN:
self.onKeyDown(event)
elif event.type == KEYUP:
self.onKeyUp(event)
elif event.type == MOUSEMOTION:
self.onMouseMotion(event)
elif event.type == MOUSEBUTTONDOWN:
self.onMouseButtonDown(event)
elif event.type == MOUSEBUTTONUP:
self.onMouseButtonUp(event)
def run(self):
"""Run the game"""
# Set up pygame and the game window
pygame.init()
self.createDisplay()
# Initialize stuff
self.initGraphics()
self.initGame()
self.clock = pygame.time.Clock()
pygame.display.flip()
# Call the main loop
self.mainloop()
# Clean up
pygame.quit()
def runAsChild(self):
"""Allow this class to be run within an already-established object.
This allows for a parent object (game menu) and child object
(gamemode)"""
# Get the display
self.display = pygame.display.get_surface()
# Initialize stuff
self.initGraphics()
self.initGame()
self.clock = pygame.time.Clock()
pygame.display.flip()
# Call the main loop
self.mainloop()
if self.EXIT == False:
# if this instance is forced to quit, exit out of the parent
# instance as well
return 1
|
# 6.00 Problem Set 8
#
# Name:
# Collaborators:
# Time:
import numpy as np
import random
import matplotlib.pyplot as plt
from ps7 import *
#
# PROBLEM 1
#
class ResistantVirus(SimpleVirus):
"""
Representation of a virus which can have drug resistance.
"""
def __init__(self, maxBirthProb, clearProb, resistances, mutProb):
"""
Initialize a ResistantVirus instance, saves all parameters as attributes
of the instance.
maxBirthProb: Maximum reproduction probability (a float between 0-1)
clearProb: Maximum clearance probability (a float between 0-1).
resistances: A dictionary of drug names (strings) mapping to the state
of this virus particle's resistance (either True or False) to each drug.
e.g. {'guttagonol':False, 'grimpex',False}, means that this virus
particle is resistant to neither guttagonol nor grimpex.
mutProb: Mutation probability for this virus particle (a float). This is
the probability of the offspring acquiring or losing resistance to a drug.
"""
SimpleVirus.__init__(self, maxBirthProb, clearProb)
self.resistances = resistances
self.mutProb = mutProb
def isResistantTo(self, drug):
"""
Get the state of this virus particle's resistance to a drug. This method
is called by getResistPop() in Patient to determine how many virus
particles have resistance to a drug.
drug: The drug (a string)
returns: True if this virus instance is resistant to the drug, False
otherwise.
"""
if drug in self.resistances:
return self.resistances[drug]
else:
return False
def reproduce(self, popDensity, activeDrugs):
"""
Stochastically determines whether this virus particle reproduces at a
time step. Called by the update() method in the Patient class.
If the virus particle is not resistant to any drug in activeDrugs,
then it does not reproduce. Otherwise, the virus particle reproduces
with probability:
self.maxBirthProb * (1 - popDensity).
If this virus particle reproduces, then reproduce() creates and returns
the instance of the offspring ResistantVirus (which has the same
maxBirthProb and clearProb values as its parent).
For each drug resistance trait of the virus (i.e. each key of
self.resistances), the offspring has probability 1-mutProb of
inheriting that resistance trait from the parent, and probability
mutProb of switching that resistance trait in the offspring.
For example, if a virus particle is resistant to guttagonol but not
grimpex, and `self.mutProb` is 0.1, then there is a 10% chance that
that the offspring will lose resistance to guttagonol and a 90%
chance that the offspring will be resistant to guttagonol.
There is also a 10% chance that the offspring will gain resistance to
grimpex and a 90% chance that the offspring will not be resistant to
grimpex.
popDensity: the population density (a float), defined as the current
virus population divided by the maximum population
activeDrugs: a list of the drug names acting on this virus particle
(a list of strings).
returns: a new instance of the ResistantVirus class representing the
offspring of this virus particle. The child should have the same
maxBirthProb and clearProb values as this virus. Raises a
NoChildException if this virus particle does not reproduce.
"""
reproduceProb = self.maxBirthProb * (1 - popDensity)
ResistBool = True
OffspringResistances = {}
for drug in activeDrugs:
ResistBool = ResistBool and self.isResistantTo(drug)
if not ResistBool:
raise NoChildException()
elif random.random() > reproduceProb:
raise NoChildException()
else:
for drug in self.resistances.keys():
if random.random() < self.mutProb:
OffspringResistances[drug] = not self.resistances[drug]
else:
OffspringResistances[drug] = self.resistances[drug]
return ResistantVirus(self.maxBirthProb, self.clearProb, OffspringResistances, self.mutProb)
class Patient(SimplePatient):
"""
Representation of a patient. The patient is able to take drugs and his/her
virus population can acquire resistance to the drugs he/she takes.
"""
def __init__(self, viruses, maxPop):
"""
Initialization function, saves the viruses and maxPop parameters as
attributes. Also initializes the list of drugs being administered
(which should initially include no drugs).
viruses: the list representing the virus population (a list of
SimpleVirus instances)
maxPop: the maximum virus population for this patient (an integer)
"""
SimplePatient.__init__(self, viruses, maxPop)
self.drugsUsing = []
def addPrescription(self, newDrug):
"""
Administer a drug to this patient. After a prescription is added, the
drug acts on the virus population for all subsequent time steps. If the
newDrug is already prescribed to this patient, the method has no effect.
newDrug: The name of the drug to administer to the patient (a string).
postcondition: list of drugs being administered to a patient is updated
"""
# should not allow one drug being added to the list multiple times
if self.drugsUsing.count(newDrug) == 0:
self.drugsUsing.append(newDrug)
def getPrescriptions(self):
"""
Returns the drugs that are being administered to this patient.
returns: The list of drug names (strings) being administered to this
patient.
"""
return self.drugsUsing
def getResistPop(self, drugResist):
"""
Get the population of virus particles resistant to the drugs listed in
drugResist.
drugResist: Which drug resistances to include in the population (a list
of strings - e.g. ['guttagonol'] or ['guttagonol', 'grimpex'])
returns: the population of viruses (an integer) with resistances to all
drugs in the drugResist list.
"""
ResistPop = 0
for virus in self.viruses:
AllResistance = True
for drug in drugResist:
AllResistance = AllResistance and virus.isResistantTo(drug)
if AllResistance:
ResistPop += 1
return ResistPop
def update(self):
"""
Update the state of the virus population in this patient for a single
time step. update() should execute these actions in order:
- Determine whether each virus particle survives and update the list of
virus particles accordingly
- The current population density is calculated. This population density
value is used until the next call to update().
- Determine whether each virus particle should reproduce and add
offspring virus particles to the list of viruses in this patient.
The list of drugs being administered should be accounted for in the
determination of whether each virus particle reproduces.
returns: the total virus population at the end of the update (an
integer)
"""
survived_viruses = []
for virus in self.viruses:
if not virus.doesClear():
survived_viruses.append(virus)
self.viruses = survived_viruses
popDensity = len(survived_viruses) / float(self.maxPop)
offsprings = []
for virus in survived_viruses:
try:
offspring = virus.reproduce(popDensity, self.drugsUsing)
offsprings.append(offspring)
except NoChildException:
pass
self.viruses = survived_viruses + offsprings
return self.getTotalPop()
#
# PROBLEM 2
#
def generateResistVirusesList(viruses_num, maxBirthProb, clearProb, resistances, mutProb):
viruses_list = []
for _ in xrange(viruses_num):
viruses_list.append(ResistantVirus(maxBirthProb, clearProb, resistances, mutProb))
return viruses_list
def simulationWithDrug():
"""
Runs simulations and plots graphs for problem 4.
Instantiates a patient, runs a simulation for 150 timesteps, adds
guttagonol, and runs the simulation for an additional 150 timesteps.
total virus population vs. time and guttagonol-resistant virus population
vs. time are plotted
"""
viruses_num = 100
maxBirthProb = 0.1
clearProb = 0.05
maxPop = 1000
timesteps1 = 150
timesteps2 = 150
num_trials = 100
mutProb = 0.005
resistances = {'guttagonol': False}
virusesPopsum = 0
ResistPopsum = 0
for i in xrange(num_trials):
viruses_list = generateResistVirusesList(viruses_num, maxBirthProb, clearProb, resistances, mutProb)
virusesPop = []
ResistPop = []
PatientA = Patient(viruses_list, maxPop)
for time in xrange(timesteps1):
virusesPop.append(PatientA.update())
ResistPop.append(PatientA.getResistPop(['guttagonol']))
PatientA.addPrescription('guttagonol')
for time in xrange(timesteps2):
virusesPop.append(PatientA.update())
ResistPop.append(PatientA.getResistPop(['guttagonol']))
virusesPopArray = np.array(virusesPop)
ResistPopArray = np.array(ResistPop)
if type(virusesPopsum) == int:
virusesPopsum = virusesPopArray
ResistPopsum = ResistPopArray
else:
virusesPopsum += virusesPopArray
ResistPopsum += ResistPopArray
virusesPopAverage = list(virusesPopsum / float(num_trials))
ResistPopAverage = list(ResistPopsum / float(num_trials))
plt.plot(xrange(timesteps1 + timesteps2), virusesPopAverage, 'b-', label="Total")
plt.plot(xrange(timesteps1 + timesteps2), ResistPopAverage, 'r-', label="ResistantViruses")
plt.xlabel('Elapsed time steps')
plt.ylabel('The population of the virus in the patient')
plt.title('Virus grows in the patient')
plt.legend(loc="best")
plt.show()
# simulationWithDrug()
#
# PROBLEM 3
#
def simulationDelayedTreatment():
"""
Runs simulations and make histograms for problem 5.
Runs multiple simulations to show the relationship between delayed treatment
and patient outcome.
Histograms of final total virus populations are displayed for delays of 300,
150, 75, 0 timesteps (followed by an additional 150 timesteps of
simulation).
"""
delays = [300, 150, 75, 0]
viruses_num = 100
maxBirthProb = 0.1
clearProb = 0.05
maxPop = 1000
timesteps = 150
num_trials = 300
mutProb = 0.005
resistances = {'guttagonol': False}
virusesPop = [[0 for _ in xrange(num_trials)] for _ in xrange(4)]
for k in xrange(4):
delay = delays[k]
for i in xrange(num_trials):
viruses_list = generateResistVirusesList(viruses_num, maxBirthProb, clearProb, resistances, mutProb)
PatientA = Patient(viruses_list, maxPop)
for time in xrange(delay + timesteps):
if time == delay:
PatientA.addPrescription('guttagonol')
virusesPop[k][i] = PatientA.update()
for num in xrange(4):
plt.subplot(2, 2, num+1)
plt.title("delay: " + str(delays[num]))
plt.xlabel("final viruses number")
plt.ylabel("number of trials")
plt.hist(virusesPop[num], bins=12, range=(0, 600))
plt.show()
# simulationDelayedTreatment()
#
# PROBLEM 4
#
def simulationTwoDrugsDelayedTreatment():
"""
Runs simulations and make histograms for problem 6.
Runs multiple simulations to show the relationship between administration
of multiple drugs and patient outcome.
Histograms of final total virus populations are displayed for lag times of
150, 75, 0 timesteps between adding drugs (followed by an additional 150
timesteps of simulation).
"""
delays = [300, 150, 75, 0]
viruses_num = 100
maxBirthProb = 0.1
clearProb = 0.05
maxPop = 1000
timesteps = 300
num_trials = 300
mutProb = 0.005
resistances = {'guttagonol': False, 'grimpex': False}
virusesPop = [[0 for _ in xrange(num_trials)] for _ in xrange(4)]
for k in xrange(4):
delay = delays[k]
for i in xrange(num_trials):
viruses_list = generateResistVirusesList(viruses_num, maxBirthProb, clearProb, resistances, mutProb)
PatientA = Patient(viruses_list, maxPop)
for time in xrange(delay + timesteps):
if time == 150:
PatientA.addPrescription('guttagonol')
elif time == 150 + delay:
PatientA.addPrescription('grimpex')
virusesPop[k][i] = PatientA.update()
for num in xrange(4):
plt.subplot(2, 2, num+1)
plt.title("time interval: " + str(delays[num]))
plt.xlabel("final viruses number")
plt.ylabel("number of trials")
plt.hist(virusesPop[num], bins=12, range=(0, 600))
plt.show()
# simulationTwoDrugsDelayedTreatment()
#
# PROBLEM 5
#
def simulationTwoDrugsVirusPopulations():
"""
Run simulations and plot graphs examining the relationship between
administration of multiple drugs and patient outcome.
Plots of total and drug-resistant viruses vs. time are made for a
simulation with a 300 time step delay between administering the 2 drugs and
a simulations for which drugs are administered simultaneously.
"""
delays = [300, 0]
viruses_num = 100
maxBirthProb = 0.1
clearProb = 0.05
maxPop = 1000
timesteps = 300
num_trials = 100
mutProb = 0.005
resistances = {'guttagonol': False, 'grimpex': False}
virusesPopAverage = [[], []]
guttagonolResistPopAverage = [[], []]
grimpexResistPopAverage = [[], []]
bothPopResistAverage = [[], []]
for k in xrange(2):
delay = delays[k]
virusesPopsum = 0
guttagonolResistPopsum = 0
grimpexResistPopsum = 0
bothResistPopsum = 0
for i in xrange(num_trials):
virusesPop = []
guttagonolResistPop = []
grimpexResistPop = []
bothResistPop = []
viruses_list = generateResistVirusesList(viruses_num, maxBirthProb, clearProb, resistances, mutProb)
PatientA = Patient(viruses_list, maxPop)
for time in xrange(timesteps + delay):
if time == 150:
PatientA.addPrescription('guttagonol')
if time == 150 + delay:
PatientA.addPrescription('grimpex')
virusesPop.append(PatientA.update())
guttagonolResistPop.append(PatientA.getResistPop(['guttagonol']))
grimpexResistPop.append(PatientA.getResistPop(['grimpex']))
bothResistPop.append(PatientA.getResistPop(['guttagonol', 'grimpex']))
virusesPopArray = np.array(virusesPop)
guttagonolResistPopArray = np.array(guttagonolResistPop)
grimpexResistPopArray = np.array(grimpexResistPop)
bothResistPopArray = np.array(bothResistPop)
if type(virusesPopsum) == int:
virusesPopsum = virusesPopArray
guttagonolResistPopsum = guttagonolResistPopArray
grimpexResistPopsum = grimpexResistPopArray
bothResistPopsum = bothResistPopArray
else:
virusesPopsum += virusesPopArray
guttagonolResistPopsum += guttagonolResistPopArray
grimpexResistPopsum += grimpexResistPopArray
bothResistPopsum += bothResistPopArray
virusesPopAverage[k] = list(virusesPopsum / float(num_trials))
guttagonolResistPopAverage[k] = list(guttagonolResistPopsum / float(num_trials))
grimpexResistPopAverage[k] = list(grimpexResistPopsum / float(num_trials))
bothPopResistAverage[k] = list(bothResistPopsum / float(num_trials))
plt.subplot(1, 2, k + 1)
plt.plot(xrange(timesteps + delay), virusesPopAverage[k], 'b-', label="Total")
plt.plot(xrange(timesteps + delay), guttagonolResistPopAverage[k], 'r-', label="Guttagonol-resistant Viruses")
plt.plot(xrange(timesteps + delay), grimpexResistPopAverage[k], 'g-', label="Grimpex-resistant Viruses")
plt.plot(xrange(timesteps + delay), bothPopResistAverage[k], 'm-', label="Both drugs resistant Viruses")
plt.xlabel('Elapsed time steps')
plt.ylabel('The population of the virus in the patient')
plt.title('Virus grows in the patient with %d time delay between drugs' % delay)
plt.legend(loc="upper right", fontsize="x-small")
plt.show()
simulationTwoDrugsVirusPopulations()
|
import sys
import math
name=input("Please enter your name")
while name.isalpha()==False or len(name)<4 :
if ' ' in name :
break
else:
print("THE NAME YOU ENTERED IS INCORRECT")
name=input('Enter name again')
print("WELCOME! NOW YOU ARE READY TO USE CALCULATOR \n YOU HAVE FOLLOWING OPTIONS")
doagain='yes'
while doagain=='yes':
print("Select operation")
print("1.Add 2.Subtract")
print("3.Multiply 4.Modulous")
print("5.square root 6. Square")
print("7.division")
select=int(input("your choice operation 1/2/3/4/5/6/7 "))
if select==1:
num1=int(input("Enter your number"))
addagain='yes'
while addagain=='yes':
num2=int(input("Enter your number again"))
result=num1+num2
addagain=input("do you want to add more number")
print("The sum of the given number is ",result)
elif select==2:
a=int(input("Enter your first number"))
subtractagain='yes'
a=0
b=0
while subtractagain=='yes':
b=int(input("Enter the number you want to subtract"))
c=a-b
subtractagain=input('Do you want to subtract more number')
print("The resulrt is",c)
elif select==3:
num1 = int(input("Enter the first number"))
mulagain='yes'
while mulagain=='yes':
num2=int(input("Enter your number "))
product=num1*num2
mulagain=input("do you want to multiply more number")
print("the product of the given number is",product)
elif select==4:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
rem=num1%num2
print("The remainder of the given division number is",rem)
elif select==5:
num1 = int(input("Enter the number"))
sqroot=math.sqrt(num1)
print("The square root of the given number is ",sqroot)
elif select==6:
num1 = int(input("Enter the number"))
square=num1*num1
square=int(square)
print("The square of the given number is ",square)
elif select==7:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
quoitent=num1/num2
print("The Quoitent of the given number is",float(quoitent))
else:
sys.exit("OPERATION OUT OF THE RANGE")
doagain=input("\nYou want to do other calculation:(yes/no) ")
|
"""
This file presents how to create a SATModel, add variables, add constraints and solve the model using the SolveEngine python interface
"""
from pysolveengine import SATModel, SEStatusCode, SolverStatusCode
######################################
# create SAT model
#
# the token
token = "#2prMEegqCAFB5eqmfuXmGufyJ+PcMzJbZaQcvqrhtx4="
# the name of the file being used when uploading the problem file
# (to be able to find the file in the webinterface of the SolveEngine easier)
# default: model
file_name = "special_model"
# the time (in seconds) the model class waits before checking the server if the result is ready
# the smaller the number the shorter the intervals
sleep_time = 3
# with/without debug printout
# this does not print debug information for the solvers
debug = True
#if True, messages will be printed to keep updated on the status of the solving
interactive_mode = True
#web connection works by default with grpc, which is faster
#if http connections desired set it to True
http_mode = False
model = SATModel(token, model_name=file_name, sleep_time=sleep_time,
debug=debug, interactive_mode=interactive_mode,
http_mode=http_mode)
######################################
######################################
#BUILDING STEP BY STEP
######################################
# Creating Variables
#
#an integer id is automatically given to each variable
#the id is the smallest available integer
x1 = model.add_variable("x1")
x2 = model.add_variable("x2")
#you can define an id yourself, but it is not advised
x3 = model.add_variable("x3", id_=3)
# if a variable is lost, you can use get_variable
x3 = model.get_variable_with_id(id_=3)
# or
x3 = model.get_variable_with_name(name="x3")
# Building expressions
#
# -x1 means negative(x1)
# when expression displayed, will show !x1
expr = -x1
# | is used for 'OR'; & is used for 'AND'
expr = (x1 | x2) & x3
# ^ is used for 'XOR' (equivalent to (x1 | x2) & -(x1 & x2)
expr = x1 ^ x2
# (==, !=, <=) are used to express equivalence, non equivalence and implication
expr = (x1 == x2) <= (x1 != x3)
# Add constraint
model.add_constraint_expr(expr)
######################################
######################################
#BUILDING WITH A LIST
######################################
# This way uses only the integer ids
# You cannot use the id 0
# no need to build the variables first
#they will be automatically added to the model with a generated name
#Add a constraint (only linked by 'OR') (equivalent to : x1 | -x5 | x2)
model.add_constraint_vector([1, -5, 2])
#You can also add several constraints in once
#there can be expression as well as vectors
lst_constraints = []
lst_constraints.append([1,-2,5])
lst_constraints.append(expr)
model.add_list_constraints(lst_constraints=lst_constraints)
######################################
######################################
#BUILDING WITH A FILE
######################################
# You can also easily build the model
# using a file
# The file must contained a problem written
# in a cnf format, starting with p cnf
file_path = '/.../filename.cnf'
model.build_from_file(file_path=file_path)
######################################
######################################
# check the model
#
print(model.build_str_model())
model.print_constraints()
print(model.file_name)
# You can know the index for each constraint by printing them
model.print_constraints()
# You can remove constraint knowing its index
model.remove_constraint_with_index(index=-1)
# At all time you can reinitialise the model's status/cosntraints/variables
#
model.reinit()
# solving the model
#
model.solve()
######################################
# checking the result status and getting the result
#
# there are two different status values
# print SolveEngine status
print("status=", model.se_status)
# if solve was successful
if model.se_status == SEStatusCode.COMPLETED:
# print solver status
print("solver status:", model.solver_status)
# status codes with solution
if model.solver_status in [SolverStatusCode.SATISFIABLE]:
# print variable values : 1 if True, -1 if False
print("x1=", x1.value)
#or
print("x1=", model.var_results[1])
#or
print("x1=", model.var_name_results["x1"])
#or
for key, value in model.var_name_results.items():
print(key, "=", value)
#or
#print summary
model.print_results()
# status codes without solution
elif model.solver_status in [SolverStatusCode.UNSATISFIABLE]:
print("the solver returned that the problem is unsatisfiable")
# status codes for an unsuccessful run
if model.se_status in [SEStatusCode.FAILED,
SEStatusCode.STOPPED,
SEStatusCode.INTERRUPTED]:
print("something went wrong")
if model.se_status in [SEStatusCode.TIMEOUT]:
print("time limit has been reached")
|
#!/usr/bin/env python
user_choice = "1"
amount_of_choices = 1
def showMenu():
while True:
print("What sorting algorithm do you want to use?")
print("[1] Bubble Sort")
# user_choice = input()
if (user_choice == "1"):
return "bubble"
break
|
entrada = int(input("Entrada:"))
p = int(input("p:"))
q = int(input("q:"))
n = int(input("n:"))
e = int(input("e:"))
d = int(input("d:"))
c = (entrada ** e) % n
print(entrada ** e)
print("RSA: {}".format(c))
d = (c ** d) % n
print(c ** d)
print("Des-RSA: {}".format(d))
|
import matplotlib.pyplot as plt
import numpy as np
import pandas as ps
# load data 人口与收入的关系
path = 'resource/all_work_code/exerise1/ex1data1.txt'
data = ps.read_csv(path, header=None, names=['Population', 'Profit'])
# print(data.head())
# 绘图
data.plot(kind='scatter', x='Population', y='Profit', figsize=(12, 8))
plt.show()
data.insert(0, 'Ones', 1)
# init x y theta
cols = data.shape[1]
# 第一列和第二列
x = data.iloc[:, 0:cols - 1]
# print(x.head())
# 第三列,输出
y = data.iloc[:, cols - 1:cols]
# print(y.head())
# init matrix
x = np.matrix(x.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0, 0]))
# 计算平均误差
def computeCost(x, y, theta):
inner = np.power(((x * theta.T) - y), 2)
return (1 / (2 * len(x))) * np.sum(inner)
print('误差=', computeCost(x, y, theta))
# 梯度下降, x,y theta初始猜测值,alpha学习速率,iters学习次数
def grandientDecline(x, y, theta, alpha, iters):
tmp = np.matrix(np.zeros(theta.shape))
# 求解的参数个数
parameters = int(theta.ravel().shape[1])
# 构建学习次数个数组
cost = np.zeros(iters)
for i in range(iters):
error = (x * theta.T) - y
for j in range(parameters):
term = np.multiply(error, x[:, j])
tmp[0, j] = theta[0, j] - ((alpha / len(x)) * np.sum(term))
theta = tmp
cost[i] = computeCost(x, y, theta)
return theta, cost
alpha = 0.01
iters = 1000
g, cost = grandientDecline(x, y, theta, alpha, iters)
print(type(g))
print(g)
print("新误差=", computeCost(x, y, g))
# 绘制函数图 100个样本
x = np.linspace(data.Population.min(), data.Population.max(), 100)
# f = theta0 + theta1 * x
f = g[0, 0] + (g[0, 1] * x)
fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(x, f, 'r', label='Prediction')
ax.scatter(data.Population, data.Profit, label='Traning Data')
ax.legend(loc=4) # 显示标签位置
ax.set_xlabel('Population')
ax.set_ylabel('Profit')
ax.set_title('Prediction Profit vs Population Size')
plt.show()
# 绘制收敛数据图
fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(np.arange(iters), cost, 'r')
ax.set_xlabel('Iterations')
ax.set_ylabel('iter')
ax.set_title('Error cs . Training Epoch')
plt.show()
|
#!/usr/bin/env python3
import cards
import sys
import random
import time
deck = cards.Cards()
turn = "user"
faceCards = ['K', 'Q', 'J', 'A']
regCards = [2, 3, 4, 5, 6, 7, 8, 9, 10]
numStrings = ['two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
faceStrings = ['King', 'Queen', 'Jack', 'Ace']
faceCard = 0
#Determine the type of card
def processInput(user_input):
cardType = -1
try:
if ' ' in user_input:
cardType = -2 #invalid format
elif user_input.upper() in (card.upper() for card in faceCards):
cardType = 1 #face card
elif user_input.upper() in (card.upper() for card in faceStrings):
cardType = 1 #face card
elif user_input.upper() in (card.upper() for card in numStrings):
cardType = 0 #number card
elif int(user_input) in regCards:
cardType = 0 #number card
return cardType
except ValueError: #catch exceptions
cardType = -2; #invalid format
return cardType
#Return either a number (2-10) or J, Q, K, A for display
def adjustCard(cardType, user_input):
if cardType == 0: #number card - return int value
if user_input.upper() in (card.upper() for card in numStrings):
return int(regCards[numStrings.index(user_input)])
else:
return int(user_input)
else: #face card - return first letter (K, Q, J, A)
return user_input[0].upper()
#Handle an incorrect guess
def guessWrong(turn):
deck.drawCard(turn)
deck.checkForSet(turn)
if turn == 'user':
print("Go Fish!")
deck.printHand()
else:
print("Went Fishing...Your Turn!")
time.sleep(1) #Delay 1 second for user to view output
#Handle a correct guess
def guessRight(turn, card, count, cardType):
if cardType == 0: #number card
index = regCards.index(card)
cardString = numStrings[index] #word version of number
else: #face card
index = faceCards.index(card)
cardString = faceStrings[index] #word version of face card
if count > 1:
cardString = cardString + "s" #add s if there were multiples
if turn == 'user':
print("I had " + str(count) + " " + cardString)
print("You get to go again!")
else:
print("Thanks for the " + cardString)
updateHand(count, card, turn) #update user and comp hands
#Update user and comp hands after a correct guess
def updateHand(count, card, turn):
if turn == 'user': #set the opponent
opp = 'comp'
else:
opp = 'user'
while count > 0: #for however many of a particular card player had
deck.remove(opp, card) #remove from opponent
deck.append(turn, card) #give to player
count = count - 1
deck.checkForSet(turn)
time.sleep(1)
#Game play continues until a player runs out of cards or the deck is empty
while len(deck.userhand) > 0 and len(deck.comphand) > 0 and len(deck.deck) > 0:
if turn == "user": #users turn
print("\n")
deck.printHand() #print the users hand
#ask user to guess and process input
user_input = input("Which card would you like to ask me for?: ")
cardType = processInput(user_input)
if cardType == -1: #provide error message
print("Invalid input, please ask for a valid card (i.e. 2 - 10, J, Q, K, A)")
elif cardType == -2: #provide error message
print("Invalid input, please type only a single card")
else:
card = adjustCard(cardType, user_input)
count = deck.comphand.count(card) #get number of times card appears in hand
if count == 0: #not in hand
guessWrong(turn)
turn = "comp" #change turns
else: #was in opponents hand
guessRight(turn, card, count, cardType)
turn = "user" #turn remains here
if turn == "comp": #computeres turn
print("\n")
card = random.choice(deck.comphand) #select random card from hand to request
cardType = processInput(str(card))
print("Do you have any " + str(card) + "s")
count = deck.userhand.count(card) #number of times card appears in users hand
time.sleep(1)
if count == 0: #not in users hand
guessWrong(turn)
turn = "user" #change turns
else:
guessRight(turn, card, count, cardType)
turn = "comp" #turn remains here
#Once while loop terminates handle the end of the game
print("\n")
print("GAME OVER...OUT OF CARDS")
numCompSets = len(deck.compsets)
numUserSets = len(deck.usersets)
print("You made " + str(numUserSets) + " sets")
print("I made " + str(numCompSets) + " sets")
#determine winner based on number of sets
if numCompSets > numUserSets:
print("I WIN!")
elif numUserSets > numCompSets:
print("YOU WIN!")
else:
print("WE TIED!")
|
import pickle
class STUDENT:
def __init__(self):
self.RNO=0
self.NAME=""
self.STREAM=""
self.PERCENT=0.0
def ACCEPT(self):
self.RNO=input("Enter Roll no:")
self.NAME=raw_input("Enter Name:")
self.STREAM=raw_input("Enter Stream:")
self.PERCENT=input("Enter Percentage:")
def DISPLAY(self):
print self.RNO,self.NAME,self.STREAM,self.PERCENT
def RET_STREAM(self):
return(self.STREAM)
n=int(input("Enter the number of records:"))
L=[]
for i in range(n):
O=STUDENT()
O.ACCEPT()
L.append(O)
with open("Student.dat","wb") as mf:
pickle.dump(L,mf)
with open("Student.dat","rb") as mf:
x=pickle.load(mf)
for record in x:
if(record.RET_STREAM()=="HUMANITIES"):
record.DISPLAY()
|
while True:
a=int(input("Enter a Number:"))
b=int(input("Enter the multiplying limit:"))
for i in range(1,b+1,1):
print a,"x",i,"=",a*i
|
L=[]
m=int(input("Rows:"))
n=int(input("Columns:"))
for i in range(m):
l=[]
for j in range(n):
x=int(input("Element:"))
l.append(x)
L.append(l)
s=0
for l in L:
for x in l:
s+=x
print "The sum of elements of a matrix is:",s
|
while True:
L1=[]
L2=[]
L3=[]
m=int(input("Enter the number of rows for Matrix 1:"))
n=int(input("Enter the number of columns for Matrix 1:"))
print
p=int(input("Enter the number of rows for Matrix 2:"))
q=int(input("Enter the number of columns for Matrix 2:"))
for i in range(m):
l=[]
for j in range(n):
x=int(input("Enter the element for Matrix 1:"))
l.append(x)
L1.append(l)
print "Matrix 1 is:"
for l in L1:
for x in l:
print x,
print
for i in range(p):
l=[]
for j in range(q):
y=int(input("Enter the element for Matrix 2:"))
l.append(y)
L2.append(l)
print "Matrix 2 is:"
for l in L2:
for y in l:
print y,
print
if (n==p):
for i in range(m):
l3=[]
for j in range(q):
l=0
for k in range(n):
l=l+L1[i][k]*L2[k][j]
l3.append(l)
L3.append(l3)
print "Resultant Matrix is:"
for l in L3:
for y in l:
print y,
print
else:
print "Sorry Multiplication is not possible because columns of Matrix 1 should be equal to rows of Matrix 2."
|
while True:
dict1={'jayant':7860372413,'suryansh':9837407901,'yohen':8527247495,}
name=raw_input("Enter the name of the Customer:")
print dict1[name.lower()],"is the telephone number of",name
|
import matplotlib.pyplot as plt
"""
Function: plotLoss
==============
Plots the loss and save it at the location given.
==============
input:
data: loss data
save_location: location to save figure
output:
None
"""
def plotLoss(data, save_location):
fig, ax = plt.subplots(nrows=1, ncols=1)
ax.plot(data, 'o')
plt.title('Training Loss')
plt.xlabel('Iteration')
fig.savefig(save_location)
plt.close(fig)
"""
Function: plotLoss
==============
Plots the loss and save it at the location given.
==============
input:
acc_train: accuracy of training data
acc_val: accuracy of validation data
save_location: location to save figure
output:
None
"""
def plotAccuracy(acc_train, acc_val, save_location):
fig, ax = plt.subplots(nrows=1, ncols=1)
ax.plot(acc_train, '-o', label='train')
ax.plot(acc_val, '-o', label='val')
ax.plot([0.5] * len(acc_val), 'k--')
plt.title('Accuracy')
plt.xlabel('Epoch')
plt.legend(loc='lower right')
fig.savefig(save_location)
plt.close(fig)
|
def maximum(dice, faces):
return dice * faces
def avg(dice, faces):
mode = float((dice / 2)) + float((dice * faces) / 2)
if mode % 1 == 0:
return int(mode)
else:
mode -= 0.5
average = f"{int(mode)} or {int(mode + 1)}"
return average
def permutation_count(dice, faces):
return faces ** dice
|
import math
import numpy as np
import matplotlib.pyplot as plt
##########################################################################
# Some Class Definitions
#########################################################################
class Neuron:
def __init__(self, weights, bias, layer, previous, final = False):
self.weights = weights
self.bias = bias
self.layer = layer
self.previous = previous
self.FINAL = final
def calculate(self):
prevresult = []
for item in self.previous:
prevresult.append(item.calculate())
temp = sum([a*b for a,b in zip(self.weights,prevresult)])
if self.FINAL:
self.calculated_value = np.tanh(temp + self.bias)
else:
self.calculated_value = np.tanh(temp + self.bias)
return self.calculated_value
def relu(self,x):
if x>0:
return x
return 0
def sigmoid(self,x):
return 1 / (1 + math.exp(-x))
class InputNeuron:
def setvalue(self,x):
self.x = x
def calculate(self):
return self.x
##########################################################################
# Here the actual fun starts,
# we create a neural network with two inner nodes called z1, and z2
# we show that this (with the correct parameters) can create a decision
# boundary such that when we run the whole network, it produces
# output values such that when they get rounded to -1, or 1, the -1
# correlates to a logic 0, and 1 to a logic 1 in the xor function.
# That is the network is expected to produce the following:
##########################################
# ....x1.x2....Y....XOR..
# -----------|-----------
# --| 0 0 | -1 | 0 |
# --| 0 1 | 1 | 1 |
# --| 1 0 | 1 | 1 |
# --| 1 1 | -1 | 0 |
# -----------------------
###########################################
##########################################################################
if __name__ == '__main__':
#construct a neural network with two inner nodes
#input layer
x1 = InputNeuron()
x2 = InputNeuron()
inputLayer = [x1,x2]
#hidden layer
weightshidden1 = [4,4]
weightshidden2 = [-3,-3]
z1 = Neuron(weightshidden1,-2,1,inputLayer)
z2 = Neuron(weightshidden2,5,1,inputLayer)
hiddenLayer = [z1,z2]
#output layer
weightsoutput = [5,5]
y = Neuron(weightsoutput,-5,2,hiddenLayer,final=True)
##########################################
#We try all the possible input combinations
##########################################
# x1 and x2 are the possible inputs, and y is the expected result
result_list = []
#expect y=1
x1.setvalue(0)
x2.setvalue(0)
result_list.append(y.calculate())
#expect y=1
x1.setvalue(0)
x2.setvalue(1)
result_list.append(y.calculate())
#expect y=1
x1.setvalue(1)
x2.setvalue(0)
result_list.append(y.calculate())
#expect y=-1
x1.setvalue(1)
x2.setvalue(1)
result_list.append(y.calculate())
print(result_list) # [-1,1,1,-1]
#########################################
# Plot the result as a decision boundary
########################################
x1list = np.linspace(-1,2,100)
x2list = np.linspace(-1,2,100)
resultlist = []
for item in x1list:
templist = []
for item2 in x2list:
x1.setvalue(item)
x2.setvalue(item2)
templist.append(y.calculate())
resultlist.append(templist)
#contour plot
plt.imshow(resultlist, extent=[0, 5, 0, 5], origin='lower',
cmap='RdGy', alpha=0.5)
plt.colorbar();
plt.show()
#########################################################
# We plot the intermediate values of the hidden layer
# as (x1,x2) -> (z1,z2), because they demonstrate
# why the neural network can solve this particular problem.
#########################################################
#z1
x1list = np.linspace(-1,2,100)
x2list = np.linspace(-1,2,100)
resultlist = []
for item in x1list:
templist = []
for item2 in x2list:
x1.setvalue(item)
x2.setvalue(item2)
temp = z1.calculate()
templist.append(temp)
resultlist.append(templist)
#contour plot
plt.imshow(resultlist, extent=[0, 5, 0, 5], origin='lower',
cmap='RdGy', alpha=0.5)
plt.colorbar();
plt.show()
#z2
x1list = np.linspace(-1,2,100)
x2list = np.linspace(-1,2,100)
resultlist = []
for item in x1list:
templist = []
for item2 in x2list:
x1.setvalue(item)
x2.setvalue(item2)
temp = z2.calculate()
templist.append(temp)
resultlist.append(templist)
#contour plot
plt.imshow(resultlist, extent=[0, 5, 0, 5], origin='lower',
cmap='RdGy', alpha=0.5)
plt.colorbar();
plt.show()
##################################################################
# In order to demonstrate that we need at least 2 inner neurons
# We take a look at what happens when we only use a single neuron.
#################################################################
#construct a neural network with 1 inner node
#input layer
x1 = InputNeuron()
x2 = InputNeuron()
inputLayer = [x1,x2]
#hidden layer
weightshidden1 = [4,4]
zsingle = Neuron(weightshidden1,-2,1,inputLayer)
hiddenLayer = [zsingle]
#output layer
weightsoutput = [5]
y = Neuron(weightsoutput,-5,2,hiddenLayer,final=True)
##########################################
# Single hidden Node
# We try all the possible input combinations
##########################################
# x1 and x2 are the possible inputs, and y is the expected result
result_list = []
#expect y=1
x1.setvalue(0)
x2.setvalue(0)
result_list.append(y.calculate())
#expect y=1
x1.setvalue(0)
x2.setvalue(1)
result_list.append(y.calculate())
#expect y=1
x1.setvalue(1)
x2.setvalue(0)
result_list.append(y.calculate())
#expect y=-1
x1.setvalue(1)
x2.setvalue(1)
result_list.append(y.calculate())
print(result_list) # [-1,0,0,0]
x1list = np.linspace(-1,2,100)
x2list = np.linspace(-1,2,100)
resultlist = []
for item in x1list:
templist = []
for item2 in x2list:
x1.setvalue(item)
x2.setvalue(item2)
temp = zsingle.calculate()
templist.append(temp)
resultlist.append(templist)
#contour plot
plt.imshow(resultlist, extent=[0, 5, 0, 5], origin='lower',
cmap='RdGy', alpha=0.5)
plt.colorbar();
plt.show()
|
# Print lines from file
try:
with open(r"e:\classroom\python\june11\names.txt", "rt") as f:
print(type(f))
for n in f.readlines():
print(n, len(n))
except:
print("Sorry! Could not read file!")
|
def iseven(n):
return n % 2 == 0
nums = [10, 11, 15, 20]
evennums = filter(iseven, nums)
oddnums = filter(lambda n: n % 2 == 1, nums)
for n in evennums:
print(n)
for n in oddnums:
print(n)
|
def add(*nums, display = False ):
sum = 0
for n in nums:
if display:
print(n)
sum += n
return sum
print(add(10, 20, 1, 2, 3, display=True))
print(add(10, 20, 1, 2, 3))
|
def add(n1, n2 = 0):
return n1 + n2
print(add(10, 20))
print(add(10))
# print(add())
print ( add (10,n2 = 100))
print ( add (n2 = 100,n1 = 10))
|
# This program says hello and asks for my name.
print('Hello World!')
print('What is your favorite food?')
food=input()
print("Same here! I love " +food)
|
from common.iterable_tools import IterableHelper
list01 = [62, 3, 9, 33, 56, 12, 332, 395]
def find01():
for item in list01:
print(item % 2)
# find01()
def find02():
for item in list01:
if item % 3 == 0 or item % 5 == 0:
yield item
def cond01(num):
return num % 2 != 0
def cond02(num):
return num % 3 == 0 or num % 5 == 0
def find_all(func):
for item in list01:
if func(item):
yield item
for i in find_all(lambda a: a % 2 != 0):
print(i)
for i in find_all(lambda num: num % 3 == 0 or num % 5 == 0):
print(i)
IterableHelper.find_all(list01, lambda a: a % 2 != 0)
|
import wikipedia
# https://github.com/goldsmith/Wikipedia
def search_wikipedia(query):
results = []
keyword = query['keyword']
wiki_pages_names = wikipedia.search(keyword)
if (len(wiki_pages_names)):
for wiki_page_name in wiki_pages_names:
try:
summary = wikipedia.summary(wiki_page_name)
wiki_page = wikipedia.page(wiki_page_name)
results.append(
{
"summary": summary,
"title": wiki_page.title,
"url": wiki_page.url,
"images": wiki_page.images
})
except wikipedia.exceptions.DisambiguationError as e:
a=1
# print e.options
return results
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 3 23:15:42 2020
@author: aaron
"""
# To run code in PyCharm console, highlight and press ⌥⇧E (option shift E)
# Data Preprocessing
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('FILE')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
# Taking Care of missing data
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import Imputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_x = LabelEncoder()
X[:, 0] = labelencoder_x.fit_transform(X[:, 0])
onehotencoder = OneHotEncoder(categorical_features=[0])
X = onehotencoder.fit_transform(X).toarray()
# Enconding dependent variable
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)
# Splitting dataset into training and test data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# Feature Scaling, after splitting the train and test to prevent information leakage between them
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)"""
|
# To run code in PyCharm console, highlight and press ⌥⇧E (option shift E)
# Data Preprocessing
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Section 5 - Multiple Linear Regression/50_Startups.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_x = LabelEncoder()
X[:, 3] = labelencoder_x.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features=[3])
X = onehotencoder.fit_transform(X).toarray()
# Avoiding the dummy variable trap, don't take the first column
X = X[:, 1:]
# Splitting dataset into training and test data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# Feature Scaling: Not necessary here because the library will take care of it for us
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)"""
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
y_pred = regressor.predict(X_test)
# Build the optimal model using backwards elimination, SL = 0.05
import statsmodels.api as sm
X = np.append(np.ones((50, 1)).astype(int), X, axis=1)
X_opt = X[:, [0, 1, 2, 3, 4, 5]]
regressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()
regressor_OLS.summary()
X_opt = X[:, [0, 1, 3, 4, 5]]
regressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()
regressor_OLS.summary()
X_opt = X[:, [0, 3, 4, 5]]
regressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()
regressor_OLS.summary()
X_opt = X[:, [0, 3, 5]]
regressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()
regressor_OLS.summary()
X_opt = X[:, [0, 3]]
regressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()
regressor_OLS.summary()
regressor_opt = LinearRegression()
regressor_opt.fit(X_opt)
|
# Operation for sorting whole numbers
def countingSort(arry):
# O(n) time and space operation
outputArray = arry.copy()
# O(n) time operation
maxNum = max(arry)
# O(max(arry) time and space operation)
countArray = [0] * (maxNum + 1)
# O(n) time and space operation
cumulativeArray = countArray.copy()
# O(n) time operation
for element in arry:
countArray[element] += 1
# O(n) time operation
for index in range(maxNum + 1):
if index == 0:
cumulativeArray[index] = countArray[index]
else:
cumulativeArray[index] = cumulativeArray[index - 1] + countArray[index]
#O(n) time operation
print(cumulativeArray)
for element in arry:
outputArray[cumulativeArray[element] - 1] = element
cumulativeArray[element] -= 1
return outputArray
print(countingSort([10, 9, 8, 7, 6, 5, 4, 3, 5, 5, 5]))
# Analysis: This algorithm appears to be useful for highly repetitive arrays that consist only
# of whole numbers and where the max of the array is relatively small. This algorithm is
# O(max(input array)) in terms of both space and time complexity.
# Time complexity can be changed to O(len(arry) + range(arry)) with slight change in implementation.
|
# Author: Fionn O'Reilly
# Filename: Bank_System.py
# Description: Presenting the user with a menu to create/close a bank account,
# withdraw or deposit from/to account, or print details of all accounts.
# Program reads current bank account details from a file and separates them into lists.
# Lists are then edited based on user actions, the updated information is then sent back to the file.
# All user input is validated.
from random import randint
# Reading all bank account details from file
def read_file():
number_list = []
balance_list = []
fname_list = []
lname_list = []
bank_details = open('bank.txt', 'r')
bank_details = bank_details.readlines()
# Separating file information into lists of account numbers, account balance, first name, and surname
for line in bank_details:
line = line.split()
number_list.append(int(line[0]))
balance_list.append(float(line[1]))
fname_list.append(line[2])
lname_list.append(line[3])
return number_list, balance_list, fname_list, lname_list
# Checking that the user entered a number from 1 to 6
def validate_menu_choice(prompt):
valid_input = False
while valid_input is False:
try:
user_input = int(input(prompt))
if user_input < 1 or user_input > 6:
print('ERROR - Please enter a number from 1 to 6')
else:
valid_input = True
except:
print('ERROR - Please enter a number from 1 to 6')
return user_input
# Checking that the account number assigned to a newly opened account does not already exist
def check_for_existing_number(number, number_list):
valid_number = False
while valid_number is False:
# Generating a new random 5 digit account number if the previous account number already exists
if number in number_list:
number = '{:05}'.format(randint(0, 99999))
else:
account_number = number
valid_number = True
return account_number
# Checking that first name and surname are letters and are at least 2 characters long
def validate_name(prompt):
valid_fname = False
while valid_fname is False:
name = input(prompt)
name = name.replace(' ', '\'')
length = len(name)
if not name.isalpha():
# Allowing for apostrophes in surnames
if '\'' in name and length >= 2:
valid_fname = True
else:
print('ERROR - Name must be letters only')
elif length < 2:
print('ERROR - Name must be at least two characters long')
else:
valid_fname = True
return name
# Checking that the account number given by the user exists when withdrawing/depositing money or closing an account
def check_account_number(prompt, number_list):
valid_number = False
while valid_number is False:
try:
account_number = int(input(prompt))
if account_number not in number_list:
print('ERROR - Account number does not exist')
else:
valid_number = True
except:
print('ERROR - Invalid account number')
return account_number
# Checking that withdrawal amount entered by user contains numbers only and isn't larger than account balance
def check_withdrawal_amount(prompt, acc_num_position, balance_list):
withdrawal_amount = 0
MIN_WITHDRAWAL = 10
valid_withdrawal = False
while valid_withdrawal is False:
# noinspection PyBroadException
try:
account_balance = balance_list[acc_num_position]
withdrawal_amount = int(input(prompt))
if withdrawal_amount > account_balance:
print('Insufficient funds')
elif withdrawal_amount < MIN_WITHDRAWAL:
print('ERROR - Withdrawal amount cannot be less than €10')
else:
valid_withdrawal = True
except Exception:
print('ERROR - Please enter numbers only')
return withdrawal_amount
# Checking that deposit amount entered by user is a number and does not exceed deposit limit
def validate_deposit(prompt):
deposit_amount = 0
MAX_LIMIT = 20000
MIN_DEPOSIT = 10
valid_deposit = False
while valid_deposit is False:
# noinspection PyBroadException
try:
deposit_amount = int(input(prompt))
if deposit_amount > MAX_LIMIT:
print('ERROR - Deposit cannot exceed €20,000')
elif deposit_amount < MIN_DEPOSIT:
print('ERROR - Deposit amount cannot be below €10')
else:
valid_deposit = True
except Exception:
print('ERROR - Please enter numbers only')
return deposit_amount
# Displaying main menu and taking user's menu choice
def menu_select(prompt):
menu = '\n1. Open an account \
\n2. Close an account \
\n3. Withdraw money \
\n4. Deposit money \
\n5. Generate a report for management \
\n6. Quit\n'
print(menu)
menu_choice = validate_menu_choice(prompt)
print()
return menu_choice
# Generating new five digit account number, taking account holder's name, and appending new details to lists
def open_account(number_list, balance_list, fname_list, lname_list):
account_number = check_for_existing_number('{:05}'.format(randint(0, 99999)), number_list)
print('Your new account number: ', account_number)
number_list.append(account_number)
balance_list.append(0.0)
account_holder_fname = validate_name('Enter your first name: ')
fname_list.append(account_holder_fname)
account_holder_lname = validate_name('Enter your surname: ')
lname_list.append(account_holder_lname)
print('Account created')
return_to_menu = True
return return_to_menu
# Getting account number from user and deleting correpsonding details from all lists
def close_account(number_list, balance_list, fname_list, lname_list):
account_number = check_account_number('Enter account number: ', number_list)
acc_num_position = number_list.index(account_number)
number_list.remove(number_list[acc_num_position])
balance_list.remove(balance_list[acc_num_position])
fname_list.remove(fname_list[acc_num_position])
lname_list.remove(lname_list[acc_num_position])
print('Account closed')
return_to_menu = True
return return_to_menu
# Getting account number and withdrawal amount from user,
# subtracting amount from balance associated with account,
# and replacing old balance in list with new balance
def withdraw_money(number_list, balance_list):
account_number = check_account_number('Enter account number: ', number_list)
acc_num_position = number_list.index(account_number)
withdrawal_amount = check_withdrawal_amount('Enter amount to withdraw: ', acc_num_position, balance_list)
old_balance = balance_list[acc_num_position]
new_balance = balance_list[acc_num_position] - withdrawal_amount
balance_list[balance_list.index(old_balance)] = new_balance
print('Withdrawal successful')
return_to_menu = True
return return_to_menu
# Getting account number and deposit amount from user,
# adding deposit amount to balance associated with account,
# and replacing old balance in list with new balance
def deposit_money(number_list, balance_list):
account_number = check_account_number('Enter account number: ', number_list)
acc_num_position = number_list.index(account_number)
deposit_amount = validate_deposit('Enter amount to deposit: ')
old_balance = balance_list[acc_num_position]
new_balance = balance_list[acc_num_position] + deposit_amount
balance_list[balance_list.index(old_balance)] = new_balance
print('Deposit successful')
return_to_menu = True
return return_to_menu
# Printing details of all accounts, total on deposit in the bank, and highest balance
def generate_report(number_list, balance_list, fname_list, lname_list):
print('Acc No.\t\t' + 'Balance\t\t', ' Name')
length = len(number_list)
position = 0
while position < length:
print(str(number_list[position]) + '\t\t' + '€' + str(
'{:<10}'.format(balance_list[position])) + '\t' + '{:<20}'.format(
fname_list[position] + ' ' + lname_list[position]))
position += 1
print('\nTotal on deposit: ', '€' + str(sum(balance_list)))
max_balance_position = balance_list.index(max(balance_list))
max_balance_holder = fname_list[max_balance_position].rstrip() + ' ' + lname_list[max_balance_position].rstrip()
print('Max balance is', '€' + str(max(balance_list)), 'held by', max_balance_holder)
return_to_menu = True
return return_to_menu
# Writing account details from lists to file
def update_file(menu_choice, number_list, balance_list, fname_list, lname_list):
bank_details = open('bank.txt', 'w')
length = len(number_list)
position = 0
while position < length:
account_details = str(number_list[position]), str(balance_list[position]), fname_list[position], lname_list[
position]
account_details = ' '.join(account_details)
bank_details.write(account_details)
bank_details.write('\n')
position += 1
bank_details.close()
return_to_menu = True
# Ending the program if the user chooses to quit
if menu_choice == 6:
print('Exiting...thank you!')
exit()
return return_to_menu
# Executing menu choice selected by user
def execute_choice(menu_choice, number_list, balance_list, fname_list, lname_list):
if menu_choice == 1:
open_account(number_list, balance_list, fname_list, lname_list)
elif menu_choice == 2:
close_account(number_list, balance_list, fname_list, lname_list)
elif menu_choice == 3:
withdraw_money(number_list, balance_list)
elif menu_choice == 4:
deposit_money(number_list, balance_list)
elif menu_choice == 5:
generate_report(number_list, balance_list, fname_list, lname_list)
elif menu_choice == 6:
update_file(menu_choice, number_list, balance_list, fname_list, lname_list)
return menu_choice
def main():
# Returning user to menu until they choose to quit
return_to_menu = True
while return_to_menu is True:
number_list, balance_list, fname_list, lname_list = read_file()
menu_choice = menu_select('Please choose a menu option by entering the corresponding number: ')
execute_choice(menu_choice, number_list, balance_list, fname_list, lname_list)
update_file(menu_choice, number_list, balance_list, fname_list, lname_list)
main()
|
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
while val in nums:
nums.remove(val)
int_len = len(nums)
# This is for check!
print(nums)
print(int_len)
return int_len
|
import unittest
import binaryLCA
# inherited Node from binaryLCA to avoid typing binaryLCA again and again. Additionally it was an excuse to practice inheritance.
class Node(binaryLCA.Node):
def __init__(self, value):
super().__init__(value)
class TestLCA(unittest.TestCase):
def test_BasicTree(self):
#print("Test1: Test Basic Tree:")
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
# visualising the data
#print(root)
self.assertEqual(3, binaryLCA.findLCA(root, 6, 7), "3 should be the lowest common ancestor of 6 and 7")
def test_EmptyTree(self):
#print("Test2: Test Empty Tree:")
root = None
self.assertEqual(-1, binaryLCA.findLCA(root, 6, 7), " The output should be -1 since the tree is empty")
def test_BothNodesNotPresent(self):
#print("Test3: testBothNodesNotPresent:")
root = Node(1)
self.assertEqual(-1, binaryLCA.findLCA(root, 6, 7), " The output should be -1 both nodes are missing")
def test_OneNodeNotPresent(self):
#print("Test4: testOneNodeNotPresent:")
root = Node(1)
root.left = Node(6)
self.assertEqual(-1, binaryLCA.findLCA(root, 6, 7), " The output should -1 since one of the nodes is missing")
def test_CommonAncestorIsTarg(self):
#print("Test5: commonAncestorIsTarget")
root = Node(1)
root.left = Node(3)
root.right = Node(5)
root.left.left = Node(6)
root.left.right = Node(8)
self.assertEqual(1, binaryLCA.findLCA(root, 1, 3),
"The output should be 1 since it is both the ancestor node and the target node")
self.assertEqual(1, binaryLCA.findLCA(root, 1, 5),
"The output should be 1 since it is both the ancestor node and the target node")
self.assertEqual(3, binaryLCA.findLCA(root, 3, 6),
"The output should be 3 since it is both the ancestor node and the target node")
self.assertEqual(3, binaryLCA.findLCA(root, 3, 8),
"The output should be 3 since it is both the ancestor node and the target node")
def test_MissingNode(self):
#print("Test6: testMissingNode")
root = Node(1)
root.left = Node(2)
root.right = Node(31)
root.left.left = Node(4)
root.left.right = Node(10)
root.right.left = Node(16)
root.right.right = Node(7)
root.left.left.left = Node(24)
self.assertEqual(-1, binaryLCA.findLCA(root, 10, 9), "Missing node should return -1")
def test_DuplicateNodesLucky(self):
#print("Test7: duplicateNodesLucky")
root = Node(1)
root.left = Node(1)
root.right = Node(2)
root.left.left = Node(4)
root.left.right = Node(10)
root.right.left = Node(50)
root.right.right = Node(7)
root.left.left.left = Node(24)
self.assertEqual(1, binaryLCA.findLCA(root, 1, 2), "Both the common ancestor and target are separate nodes both"\
"storing the value 1")
def test_DuplicateNodes(self):
# print("Test8: duplicateNodes:")
root = Node(1)
root.left = Node(3)
root.right = Node(2)
root.left.left = Node(4)
root.left.right = Node(6)
root.right.left = Node(6)
root.right.right = Node(7)
root.left.left.left = Node(24)
self.assertEqual(1, binaryLCA.findLCA(root, 7, 6),
"There are two instances of the value 6 in the tree, 1 should be returned as it is the common"
"ancestor for both values of 6")
#Example of visualization
print("Test 8: test_DuplicateNodes")
print(root)
def test_Single(self):
# print("Test9: testSingle")
root = Node(1)
assert binaryLCA.findLCA(root, 1, 1) == 1, \
"Should be 1 but got: " + str(binaryLCA.findLCA(root, 1, 1))
def test_CharsInNumberTree(self):
root = Node(1)
root.left = Node(2)
root.right = Node(31)
root.left.left = Node(4)
root.left.right = Node(10)
root.right.left = Node(16)
root.right.right = Node(7)
root.left.left.left = Node(24)
self.assertEqual(-1, binaryLCA.findLCA(root, 'a', 'b'),
"Should be -1 but got: " + str(binaryLCA.findLCA(root, 'a', 'b')))
def test_CharsInCharTree(self):
root = Node('a')
root.left = Node('b')
root.right = Node('c')
root.left.left = Node('d')
root.left.right = Node('e')
root.right.left = Node('f')
root.right.right = Node('g')
root.left.left.left = Node('h')
self.assertEqual('b', binaryLCA.findLCA(root, 'd', 'e'),
"Should be b but got: " + str(binaryLCA.findLCA(root, 'd', 'e')))
#Reminder if you don't put the word test in python functions they won't work!!
if __name__ == '__main__':
unittest.main()
|
### Mortgage Calculator App ###
print("|~~~~~~~~~~Mortgage Calculator App~~~~~~~~~|")
print('\n')
interest =(float(input('Enter your present loan interest rate: %'))/100)/12
years =float(input('Enter the term of loan (years): '))*12
amount =float(input('Enter the amount of loan after put down-payment: $'))
numerator = interest*((1+interest)**years)
denominator = (1+interest)**years-1
f = float("{0:.2f}".format(amount*numerator/denominator))
print('\n')
print("Principal Borrowed:%7.2f"% amount)
print("Monthly Mortgage Payment: $",f)
print("\nThank you for using the app ^.^")
|
# --------------
# Code starts here
class_1=['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2=['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove( 'Carla Gentry')
print(new_class)
# Code ends here
# --------------
# Code starts here
courses={'Math': 65,'English':70,'History':80,'French':70,'Science':60}
print(courses)
total=(65+70+80+70+60)
print(total)
percentage=total*100/500
print(percentage)
# Code ends here
# --------------
# Code starts here
mathematics={'Geoffrey Hinton':78,'Andrew Ng':95,'Sebastian Raschka':65,'Yoshua Benjio':50,'Hilary Mason':70,'Corinna Cortes':66,'Peter Warden':75}
print(mathematics)
topper=max(mathematics,key=mathematics.get)
print(topper)
# Code ends here
# --------------
# Given string
topper = 'andrew ng'
# Code starts here
# Create variable first_name
first_name = (topper.split()[0])
print (first_name)
# Create variable Last_name and store last two element in the list
last_name = (topper.split()[1])
print (last_name)
# Concatenate the string
full_name = last_name + ' ' + first_name
# print the full_name
print (full_name)
# print the name in upper case
certificate_name = full_name.upper()
print (certificate_name)
# Code ends here
|
'''
List 특징
- 1차원 배열 구조
형식) 변수 = [값1, 값2, ...]
- 다양한 자료형 저장 가능(R의 벡터는 한 벡터 내에 하나의 자료형만 저장 가능했음)
- index 사용, 순서 존재
형식) 변수[index], index=0부터 시작
- 값 수정(추가, 삽입, 수정, 삭제)
'''
# 1. 단일 list
lst = [1,2,3,4,5]
print(lst, type(lst), len(lst))
for i in lst :
# print(i, end=' ') # 1 2 3 4 5
print(lst[i-1:]) # 변수[start:stop]
# [1, 2, 3, 4, 5]
# [2, 3, 4, 5]
# [3, 4, 5]
# [4, 5]
# [5]
for i in lst :
print(lst[:i]) # stop-1까지
# [1]
# [1, 2]
# [1, 2, 3]
# [1, 2, 3, 4]
# [1, 2, 3, 4, 5]
'''
처음/마지막 데이터 추출
'''
x = list(range(1,101))
print(x)
print(x[:5]) # 처음 다섯개 원소
print(x[-5:]) # 마지막 다섯개 원소
'''
index 형식
변수[start:stop-1:step]
'''
print(x[:]) # 전체 데이타
print(x[1:5]) # [2, 3, 4, 5]
print(x[0:10:2]) # [1, 3, 5, 7, 9]
print(x[::10]) # [1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
print(x[9::10]) # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
print(x[1::2]) # 짝수
print(x[7:1:-1]) # [8, 7, 6, 5, 4, 3]
# 2. 중첩 list : [[], []] -> 1 dimension
a = ['a', 'b', 'c']
b = [10, 20, 5, True, 'hong'] # 서로 다른 type 저장 가능
print(b)
b = [10, 20, 5, a, True, 'hong']
print(b) # [10, 20, 5, ['a', 'b', 'c'], True, 'hong'] : 중첩 리스트
print(b[3]) # ['a', 'b', 'c']
print(b[3][2]) # c
print(b[3][1:]) # ['b', 'c']
print(type(a), type(b)) # <class 'list'> <class 'list'>
print(id(a), id(b)) # 2469897016968 2469897016584
print(id(b[3])) # 2469897016968 : same as a's
# 3. 값 수정(추가, 삽입, 수정, 삭제)
num = ['one', 'two', 'three', 'four']
print(len(num)) # 4
'''
object.method()
'''
num.append('five')
print(num) # ['one', 'two', 'three', 'four', 'five']
num.sort()
print(num) # ['five', 'four', 'one', 'three', 'two']
num.remove('five')
print(num) # ['four', 'one', 'three', 'two']
num = ['one', 'two', 'three', 'four']
num.insert(0, 'zero')
print(num) # ['zero', 'one', 'two', 'three', 'four']
num[4] = 4
print(num) # ['zero', 'one', 'two', 'three', 4]
# 4. list 연산
# 1) list 결합
x = [1,2,3,4,5]
y = [1.5, 2.5]
z = x + y # new object. auch list
print(z) # [1, 2, 3, 4, 5, 1.5, 2.5]
print(type(z)) # <class 'list'>
# 2) list 확장
x.extend(y) # 기존 object에 추가.
print(x) # [1, 2, 3, 4, 5, 1.5, 2.5] - 단일 list
# 3) list 추가
x.append(y) # 기존 object에 추가.
print(x) # [1, 2, 3, 4, 5, 1.5, 2.5, [1.5, 2.5]] - 중첩 list
# 5. list 곱셈(*) : 반복
lst = [1,2,3,4]
result = lst * 2
print(result) # [1, 2, 3, 4, 1, 2, 3, 4]
# 6. list 정렬
result
result.sort()
print(result) # [1, 1, 2, 2, 3, 3, 4, 4]
result.sort(reverse=True)
print(result) # [4, 4, 3, 3, 2, 2, 1, 1]
'''
scala 변수 : 한 개의 상수(값)을 갖는 변수(크기)
vector 변수 : 다수의 값을 갖는 변수(크기, 방향)
'''
dataset = [] # 빈 list
size = int(input("vector size : ")) # scala 변수
for i in range(size) : # range(5) : 0 ~ 4
dataset.append(i+1) # vector 변수
print(dataset) # [1, 2, 3, 4, 5]
# 7. list에서 원소 찾기
'''
if 값 in list :
참 실행문
else :
거짓 실행문
'''
if 5 in dataset :
print("5가 있음")
else :
print("5가 없음")
def func(lst):
lst[0] = 99
values = [0,1,1,2,3,5,8]
print(values)
func(values)
print(values)
|
'''
문2-1) 다음 벡터(emp)는 '입사년도이름급여'순으로 사원의 정보가 기록된 데이터 있다.
이 벡터 데이터를 이용하여 사원의 이름만 추출하는 함수를 정의하시오.
# <출력 결과>
names = ['홍길동', '이순신', '유관순']
'''
from re import findall, sub
# <Vector data>
emp = ["2014홍길동220", "2002이순신300", "2010유관순260"]
'''
# 함수 정의
def name_pro(emp):
names = [sub('\\d{3,}','', emp)]
return names
'''
# 답 : 길게
def name_pro(emp) :
names = []
for e in emp :
tmp = findall('[가-힣]{3,}', e)
if tmp :
names.append(tmp[0])
return names
def name_pro(emp) :
names = [findall('[가-힣]{3,}', e)[0] for e in emp]
return names
# 함수 호출
names = name_pro(emp)
print('names =', names)
|
'''
재귀호출(recursive call)
- 함수 내에서 자신의 함수를 반복적으로 호출하는 기법
- 반복적으로 변수의 값을 조정해서 연산 수행
ex) 1~n (1+2+3+4+...n)
- 반드시 종료조건이 필요하다.
'''
# 1.카운터 : 1~n
def Counter(n):
if n == 0 : # 종료조건
print("프로그램 종료")
return 0
else :
Counter(n-1) # 재귀호출
Counter(0)
def Counter(n):
if n == 0 : # 종료조건
#print("프로그램 종료")
return 0 # 함수 종료
else :
Counter(n-1) # 재귀호출
'''
1. stack : [5(first), 4(5-1) ... 0(1-1)종료조건이므로 재귀를 멈추고 종료함
stack의 특징은 가장 처음 저장한 변수를 꺼낼 때는 가장 나중에 꺼내는 변수.
'''
print(n, end=' ') # 카운트
print(Counter(0))
# 프로그램 종료
# 0
Counter(5) # 1 2 3 4 5
def Counter(n):
if n == 0 : # 종료조건
#print("프로그램 종료")
return 0 # 함수 종료
else :
print(n, end=' ')
Counter(n-1) # 재귀호출
Counter(5) # 5 4 3 2 1 아니 뭐여.....왜 거꾸로나와
# 2. 누적(1+2+3+...+n)
def Adder(n) :
if n ==1 : # 종료조건
return 1
else :
result = n + Adder(n-1) # 재귀호출
'''
stack : LIFO (후입선출)
1. stack [5(first), 4(5-1), 3(4-1), 2(3-1), 1(2-1) : 종료조건이므로 stack역에 저장안됨]
2. stack 역순으로 값 누적 :1 + [2+3+4+5] = 15
'''
print(result, end=' ')
return result
print(Adder(1)) # 1
print(Adder(5)) # 15
|
'''
제어문 : 조건문(if), 반복문(while, for)
python 블럭 : 콜론과 들여쓰기
형식1)
if 조건식 :
실행문
실행문
'''
var = 10
if var>= 10 :
print("var =", var)
print("var는 10보다 크거나 같다.")
print("항상 실행되는 영역")
'''
형식2)
if 조건식:
실행문1
else :
실행문2
'''
var = 2
if var >= 5 :
print("var는 5보다 크거나 같다.")
else :
print("var는 5보다 작다.")
# var는 5보다 작다.
# 키보드 점수 입력 -> 60점 이상 : 합격, 미만 : 불합격
score=int(input("점수 입력 : "))
if score>=60 :
print("합격")
else :
print("불합격")
# 합격
import datetime # module 임포트
datetime.datetime.now() # module.class.method() : datetime.datetime(2020, 4, 7, 11, 8, 13, 348434)
today = datetime.datetime.now()
print(today) # 2020-04-07 11:09:31.316521
# 요일 반환
week = today.weekday()
print(week) # 1 : 화요일 (0~4는 평일, 5~6 주말)
if week >= 5 :
print("오늘은 주말이다.")
else :
print("학원 가야 한다.")
'''
if 조건식1 :
실행문1
elif 조건식2:
실행문2
else :
실행문3
'''
# 문2) 키보드 score입력: A(100-90), B(89-80), C(79-70), D, F(59-...)
score = int(input("점수 입력 : "))
if score>=90 and score<=100 :
print("A")
elif score>=80 and score <=89 :
print("B")
elif score>=70 and score <= 79 :
print("C")
elif score>=60 and score <= 69 :
print("D")
else :
print("F")
score = int(input("점수 입력 : "))
# 전역변수 : score, grade
# grade = ""
if score>=90 and score<=100 :
grade = "A"
elif score>=80 and score <=89 :
grade = "B"
elif score>=70 and score <= 79 :
grade = "C"
elif score>=60 and score <= 69 :
grade = "D"
else :
grade = "F"
print("당신의 점수는 %d점이고, 등급은 %s이다." %(score, grade)) # 파이썬은 if문 블록에서 만들어진 변수 블록 밖에서도 사용 가능
# 블럭 if vs 라인 if
# 블럭 if
num = 9
if num >= 5 :
result = num*2
else :
result = num+2
print(result) # 18
# 라인 if
# 형식) 변수 = 참 if 조건문 else 거짓
result = num*2 if num >= 5 else num + 2
print(result) # 18
|
'''
<급여 계산 문제>
문) Employee 클래스를 상속하여 Permanent와 Temporary 클래스를 구현하시오.
<조건> pay_pro 함수 재정의
'''
# 부모클래스
class Employee :
name = None
pay = 0
def __init__(self,name):
self.name = name
# 원형 함수 : 급여 계산 함수
def pay_pro(self):
pass
# 자식클래스 - 정규직
class Permanent(Employee):
# name = None
# pay = 0
gi = bonus = 0
# 함수 재정의 : 인수+내용 추가
def pay_pro(self, gi, bonus):
self.gi = gi
self.bonus = bonus
self.pay = gi + bonus
def display(self):
print("="*30)
print("고용 형태 : 정규직\n이름 : {}\n급여 : {}".format(self.name, self.pay))
print("=" * 30)
name = input("이름을 입력하세요 :")
gi = int(input("기본 급여를 입력하세요 :"))
bonus = int(input("보너스를 입력하세요 :"))
permanent = Permanent(name)
permanent. pay_pro(gi, bonus)
permanent.display()
# 자식클래스 - 임시직
class Temporary(Employee):
# name = None
# pay = 0
time = tpay = 0
# 함수 재정의 : 인수+내용 추가
def pay_pro(self, time, tpay):
self.time = time
self.tpay = tpay
self.pay = time * tpay
def display(self):
print("="*30)
print("고용 형태 : 임시직\n이름 : {}\n급여 : {}".format(self.name, self.pay))
print("="*30)
name = input("이름을 입력하세요 :")
time = int(input("작업 시간을 입력하세요 :"))
tpay = int(input("시급을 입력하세요 :"))
temporary =Temporary(name)
temporary. pay_pro(time, tpay)
temporary.display()
#################################################### 원래 함수에서 self.time=time과같이 time변수 적역변수로 안만들어줘도도미
# 자식클래스 - 정규직
class Permanent(Employee):
# name = None
# pay = 0
def __init__(self, name):
super().__init__(name)
# 함수 재정의 : 인수+내용 추가
def pay_pro(self, gi, bonus):
self.pay = gi + bonus
def display(self):
print("="*30)
print("고용 형태 : 정규직\n이름 : {}\n급여 : {}".format(self.name, self.pay))
print("=" * 30)
name = input("이름을 입력하세요 :")
gi = int(input("기본 급여를 입력하세요 :"))
bonus = int(input("보너스를 입력하세요 :"))
permanent = Permanent(name)
permanent. pay_pro(gi, bonus)
permanent.display()
|
'''
step2 관련 문제
A형 문) vector 수를 키보드로 입력 받은 후, 입력 받은 수 만큼
임의 숫자를 vector에 추가하고, vector의 크기를 출력하시오.
<출력 예시>
vector 수 : 3
4
2
5
vector 크기 : 3
B형 문) vector 수를 키보드로 입력 받은 후, 입력 받은 수 만큼
임의 숫자를 vector에 추가한다.
이후 vector에서 찾을 값을 키보드로 입력한 후
해당 값이 vector에 있으면 "YES", 없으면 "NO"를 출력하시오.
<출력 예시>
vector 수 : 5
1
2
3
4
5
3
YES
vector 수 : 3
1
2
4
3
NO
'''
# A형 문제
size = int(input('vector 수 : ')) # vector 크기 입력
lst = []
import random
for i in range(size) :
lst.append(int(input()))
print('vector 크기 :', len(lst))
# B형 문제
size = int(input('vector 수 : '))
vector = []
for i in range(size) :
vector.append(int(input()))
if int(input()) in vector :
print("YES")
else :
print("NO")
# 내장함수 + 리스트 내포
print('sum =', sum(x)) # sum = 17
data4 = [[1,3,5],[4,5],[7,8,9]] # 중첩리스트
result = [print('sum =', sum(d), end=', ') for d in data4] # sum = 9, sum = 9, sum = 24,
|
'''
문제2) 서울 지역을 대상으로 '동' 이름만 추출하여 다음과 같이 출력하시오.
단계1 : 'ooo동' 문자열 추출 : 예) '개포1동 경남아파트' -> '개포1동'
단계2 : 중복되지 않은 전체 '동' 개수 출력 : list -> set -> list
<출력 예시>
서울시 전체 동 개수 = 797
'''
try :
file = open("../data/zipcode.txt", mode='r', encoding='utf-8')
lines = file.readline() # 첫줄 읽기
dongs = [] # 서울시 동 저장 list
cnt=0
while lines :
cnt += 1
addr = lines.split('\t')
if addr[1] == '서울' :
dong = addr[3].split() # 공백으로 split
dongs.append(dong[0])
lines = file.readline()
dongs = (set(dongs)) # set으로 중복제거 >> list로 변환
print('주소 개수 :', cnt)
print('서울시 전체 동 개수 =', len(dongs))
print('-'*50)
print(dongs)
print('-'*50)
# 내용채우기
file.close()
except Exception as e :
print('예외발생 :', e)
finally:
print('종료!!!!!!!!') |
class Dog:
def __init__(self):
self.nombre = ""
self.edad = None
self.peso = None
def ladrar(self):
if self.peso == None:
print("Soy un fantasma")
return
if self.peso >=8: print("GUAU, WOOF")
else: print("guau, woof")
class Perro:
def __init__(self, nombre, edad, peso):
self.nombre = nombre
self.edad = edad
self.peso = peso
def ladrar(self):
if self.peso >=8: print("GUAU, WOOF")
else: print("guau, woof")
def __str__(self):
return "Perro {}, edad: {}, peso: {}".format(self.nombre, self.edad, self.peso)
class PerroAsistencia(Perro):
__trabajando = False
def __init__(self, nombre, edad, peso, amo):
Perro.__init__(self, nombre, edad, peso)
self.amo = amo
def __str__(self):
return Perro.__str__(self) + ", asiste a {}".format(self.amo)
def pasear(self):
print("Soy {}, ayudo a mi dueño {} a pasear.".format(self.nombre, self.amo))
def ladrar(self):
if self.__trabajando: print("Shhhh, no puedo ladrar")
else: Perro.ladrar(self)
def trabajando(self, valor=None):
if valor == None: return self.__trabajando
else: self.__trabajando = valor
class Timido:
def __init__(self, nombre):
self.__nombre = nombre
def preguntarNombreConCuidado(self):
return self.__nombre |
from turtle import Turtle
START_X_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class Snake:
def __init__(self):
self.snake_segments = []
"""Each snake chunk (yummy). Increases by one segment for every food piece eaten."""
self.create_snake()
"""Creates snake in main file using the function below."""
self.head = self.snake_segments[0]
"""Attribute sets up the controls for the snake segment direction and the front of the snake."""
def create_snake(self):
for position in START_X_POSITIONS:
self.add_segment(position)
def add_segment(self, position):
snake_segment = Turtle(shape="square")
snake_segment.color("green")
snake_segment.penup()
snake_segment.goto(position)
self.snake_segments.append(snake_segment)
def extend(self):
self.add_segment(self.snake_segments[-1].position())
"""Extends snake by appending a snake segment to the end of the self.snake_segments list."""
def move(self):
for seg_num in range(len(self.snake_segments) - 1, 0, -1):
"""Range from last snake segment in list to first, decreasing by 1."""
new_x_cor = self.snake_segments[seg_num - 1].xcor()
new_y_cor = self.snake_segments[seg_num - 1].ycor()
self.snake_segments[seg_num].goto(new_x_cor, new_y_cor)
"""Moves each segment to the position of the next segment."""
self.snake_segments[0].forward(MOVE_DISTANCE)
def up(self):
if self.head.heading() != DOWN:
"""So the snake can't turn around 180 degrees."""
self.head.setheading(UP)
def down(self):
if self.head.heading() != UP:
self.head.setheading(DOWN)
def left(self):
if self.head.heading() != RIGHT:
self.head.setheading(LEFT)
def right(self):
if self.head.heading() != LEFT:
self.head.setheading(RIGHT)
|
import random
# HERO class. Stores the hero abilities, armors, calculates attack and defense values, how to deal damage, adding of kills
class Hero:
def __init__(self, name, health = 100):
self.abilities = list()
self.name = name
self.armors = list()
self.start_health = health
self.health = health
self.deaths = 0
self.kills = 0
# Add abilities into HERO.abilities. Will later be prompted for names by user and random values picked.
def add_ability(self, ability):
self.abilities.append(ability)
# Adds total attack based on abilities given. Will later be prompted for names by user and random values picked.
def attack(self):
total_attack = 0
for add_attack in self.abilities:
total_attack += add_attack.attack()
return total_attack
# Adds total defense based on armors given. Will later be prompted for names by user and random values picked.
def defend(self):
total_defense = 0
for add_defense in self.armors:
total_defense += add_defense.defend()
if self.health == 0:
total_defense = 0
return total_defense
# Damage calculation. If health <= 0, death counter + 1
def take_damage(self, damage_amt):
self.health -= damage_amt
if self.health <= 0:
self.deaths += 1
# function to add kills
def add_kill(self, num_kills):
self.kills += num_kills
#Not in tutorial
def add_armor(self, armor):
self.armors.append(armor)
# ABILITY class. Updates attack strength based on abilities given
class Ability:
def __init__(self, name, attack_strength):
self.name = name
self.attack_strength = attack_strength
# generates random value for attack damage range (lowest, highest)
def attack(self):
self.lowest_attack = self.attack_strength // 2
self.highest_attack = random.randint(self.lowest_attack, self.attack_strength)
return self.highest_attack
def update_attack(self, attack_strength):
self.attack_strength = attack_strength
class Weapon(Ability):
def attack(self):
return random.randint(0, self.attack_strength)
# TEAM class. Creates teams of heroes and their attack powers
class Team:
def __init__(self, team_name):
self.name = team_name
self.heroes = list()
def add_hero(self, Hero):
self.heroes.append(Hero)
def remove_hero(self, name):
for hero in self.heroes:
if hero.name == name:
self.heroes.remove(hero)
return 0
def find_hero(self, name):
for hero in self.heroes:
if hero.name == name:
return hero
return 0
def view_all_heroes(self):
for index in self.heroes:
print(index.name)
# calculates total attack power of all heroes and calculates deaths
def attack(self, other_team):
total_attack_power = 0
for hero in self.heroes:
total_attack_power += hero.attack()
deaths = other_team.defend(total_attack_power)
for hero in self.heroes:
hero.add_kill(deaths)
# calculates total defense of all heroes and returns excess as damage to next hero
# Ex: Hero1 has 100 health and takes 101 damage. Hero2 takes the extra 1 damage
def defend(self, damage_amt):
total_defense_power = 0
for hero in self.heroes:
total_defense_power += hero.defend()
total_excess = damage_amt - total_defense_power
if total_excess > 0:
return self.deal_damage(total_excess)
else:
return 0
def deal_damage(self, damage):
total_damage = damage // len(self.heroes)
total_deaths = 0
for hero in self.heroes:
hero.take_damage(total_damage)
#does not update total damage?
if hero.health <= 0:
total_deaths += 1
return total_deaths
def revive_heroes(self, health = 100):
for hero in self.heroes:
hero.health = hero.start_health
def stats(self):
for hero in self.heroes:
print(hero + "Kill/Death Ratio:")
print(hero.deal_damage()/hero.take_damage())
def update_kills(self):
for hero in self.heroes:
if hero.add_kill:
print(hero + " has killed another hero!")
class Armor:
def __init__(self, name, defense):
self.name = name
self.defense = defense
def defend(self):
return random.randint(0, self.defense)
class Arena:
def __init__(self):
self.team_one = None
self.team_two = None
# Not in tutorial. function for gathering all the user inputs for the heroes and gives them random powers solely for less user input
def create_hero(self):
prompt_hero = input("What hero would you like to add to Team One?")
hero = Hero(prompt_hero)
prompt_weapon = input("What weapon does " + prompt_hero + " have?")
weapon = Weapon(prompt_weapon, random.randint(1,20))
prompt_ability = input("What ability does " + prompt_hero + "have?")
ability_power = random.randint(1,20)
ability = Ability(prompt_ability, ability_power)
prompt_armor = input("What armor does " + prompt_hero + " have?")
armor_power = random.randint(1,20)
armor = Armor(prompt_armor, armor_power)
# self.add_hero_to_team(hero)
hero.add_ability(ability)
hero.add_ability(weapon)
hero.add_armor(armor)
return hero
def add_hero_to_team(self, team, hero):
print("Team:")
print(team)
print("Hero: ")
print(hero)
team.add_hero(hero)
def build_team_one(self):
self.team_one = Team(input("What would you like Team One to be called?"))
count = 0
while count < 3:
hero = self.create_hero()
self.add_hero_to_team(self.team_one, hero)
print(self.team_one.heroes)
# self.team_one.add_hero(hero)
count += 1
# if len(self.team_one) < 3:
# for index, hero in enumerate(self.team_one):
# if index < 3:
# prompt_hero = input("What hero would you like to add to Team One?")
# print(prompt_hero + "has been added to Team One")
# hero.team_one.add_hero(prompt_hero)
# prompt_ability = input("Alright what abilities should this hero have?")
# print("{} now has the ability {}".format(prompt_hero, prompt_ability))
# hero.team_one.add_ability(prompt_ability)
def build_team_two(self):
self.team_two = Team(input("What would you like Team One to be called?"))
count = 0
while count < 3:
hero = self.create_hero()
self.add_hero_to_team(self.team_two, hero)
print(self.team_two.heroes)
# self.team_one.add_hero(hero)
count += 1
# self.team_two = Team(input("What would you like Team Two to be called?"))
# for hero in range(0,3):
# prompt_hero = input("What hero would you like to add to Team Two?")
# print(prompt_hero + "has been added to Team Two")
# hero.team_two.add_hero(prompt_hero)
# prompt_ability = input("Alright what abilities should this hero have?")
# print("{} now has the ability {}".format(prompt_hero, prompt_ability))
# hero.team_two.add_ability(prompt_ability)
def team_battle(self):
turn_order = random.randint(0,1)
if turn_order == 0:
# team_one.initialize()
print("Team One will start!")
for i in range(0,len(self.team_one.heroes)):
print(self.team_one.heroes)
print(self.team_one.heroes[i].abilities)
while self.team_one.heroes[i].health > 0 and self.team_two.heroes[i].health > 0:
self.team_one.attack(self.team_two)
self.team_two.defend(self.team_one)
self.team_one.update_kills()
self.team_two.update_kills()
# for hero in team_one.heroes:
# while self.team_one.isAlive() == True and self.team_two.isAlive() == True:
# hero.attack(team_two)
# hero.defend(team_one)
# self.team_one.update_kills()
# self.team_two.update_kills()
else:
print("Team Two will start!")
for i in range(0,len(self.team_two.heroes)):
print(self.team_one.heroes)
print(self.team_one.heroes[i].abilities)
while self.team_one.heroes[i].health > 0 and self.team_two.heroes[i].health > 0:
self.team_two.attack(self.team_one)
self.team_one.defend(self.team_two)
self.team_one.update_kills()
self.team_two.update_kills()
# team_two.initialize()
# print("Team Two will start!")
# for hero in team_one.heroes:
# while self.team_one.isAlive() == True and self.team_two.isAlive() == True:
# hero.attack(team_two)
# hero.defend(team_one)
# self.team_one.update_kills()
# self.team_two.update_kills()
"""
This method should continue to battle teams until
one or both teams are dead.
"""
def show_stats(self):
for hero in self.team_one.heroes:
hero.stats()
for hero in self.team_two.heroes:
hero.stats()
"""
This method should print out the battle statistics
including each heroes kill/death ratio.
"""
# def initialize():
if __name__ == "__main__":
game_running = True
arena = Arena()
arena.build_team_one()
arena.build_team_two()
while game_running:
arena.team_battle()
arena.show_stats()
play_again = input("Play Again? Y or N: ")
if play_again.lower() == "n":
game_running = False
else:
arena.team_one.revive_heroes()
arena.team_two.revive_heroes()
# initialize()
if __name__ == "__main__":
hero = Hero("Wonder Woman")
print(hero.attack())
ability = Ability("Divine Speed", 300)
hero.add_ability(ability)
print(hero.attack())
new_ability = Ability("Super Human Strength", 800)
hero.add_ability(new_ability)
print(hero.attack())
# team = Team("yo")
# jodie = Hero("Jodie Foster")
# batman = Hero("Batman")
# ww = Hero("Wonder Woman")
# team.add_hero(jodie)
# team.add_hero(batman)
# team.add_hero(ww)
# print(len(team.heroes))
# team.remove_hero(jodie)
# print(len(team.heroes))
|
from copy import copy
class Vehicle(object):
def __init__(self, ID=0, vType=0, zipcode=00000, availability=True):
self.ID = ID
self.vType = vType
self.zipcode = zipcode
self.availability = availability
def relocate(self, newZipcode):
self.zipcode = newZipcode
return
class Request(object):
def __init__(self, ID, vType, zipcode):
self.ID = ID
self.vType = vType
self.zipcode = zipcode
class Distance(object):
def __init__(self, zip1, zip2, distance):
self.zip1 = zip1
self.zip2 = zip2
self.distance = distance
class EmerVehicles(object):
def __init__(self, emergencyVehicles, distances, requests):
emergencyVehiclesFile = open(emergencyVehicles)
distancesFile = open(distances)
requestsFile = open(requests)
self.vehicles = self.getVehicles(emergencyVehiclesFile)
self.distances = self.getDistances(distancesFile)
self.requests = self.getRequest(requestsFile)
def printOutput(self):
file = open("ProcessedRequests.txt", "r")
for line in file:
print(line)
def processRequests(self):
'''Processes requests and stores them in a .txt file'''
output = open("ProcessedRequests.txt", "w+")
for r in self.requests:
j = self.findClosest(r)
closest, dist = j[0], j[1]
string = "{} {} {} {} {} \n".format(r.ID, r.vType, r.zipcode, closest.ID, dist)
output.write(string)
closest.relocate(r.zipcode)
def getVehicles(self, file):
'''Returns list of vehicles from provided file'''
vehicleList = []
for vehicle in file:
info = vehicle.split()
try:
vehicleList.append(Vehicle(int(info[0]), int(info[1]), int(info[2])))
except IndexError:
pass
return vehicleList
def getDistances(self, file):
'''Returns list of distances from provided file'''
distanceList = []
for distance in file:
info = distance.split()
try:
distanceList.append(Distance(int(info[0]), int(info[1]), int(info[2])))
except IndexError:
pass
return distanceList
def getRequest(self, file):
'''Returns list of requests from provided file'''
requestList = []
for request in file:
info = request.split()
try:
requestList.append(Request(int(info[0]), int(info[1]), int(info[2])))
except IndexError:
pass
return requestList
def findClosest(self, request):
'''Returns closest vehicles to given request'''
lowestDist = Vehicle()
for vehicle in self.vehicles:
if vehicle.vType == request.vType:
newDist = self.calcDist(vehicle.zipcode, request.zipcode)
oldDist = self.calcDist(lowestDist.zipcode, request.zipcode)
if (newDist < oldDist):
lowestDist = vehicle
if (self.calcDist(lowestDist.zipcode, request.zipcode)) == 0:
return [lowestDist, 0]
finalDistance = self.calcDist(lowestDist.zipcode, request.zipcode)
return [lowestDist, finalDistance]
def calcDist(self, location1, location2):
'''Returns the distance between two zipcodes'''
if (location1 == 00000 or location2 == 00000):
return 500
elif location1 == location2:
return 0
elif location1 > location2:
temp = copy(location2)
location2 = copy(location1)
location1 = copy(temp)
distance = 0
t = copy(location1)
for loc in self.distances:
if loc.zip1 == t:
if loc.zip2 == location2:
distance = distance + loc.distance
return distance
distance = distance + loc.distance
t = copy(loc.zip2)
|
print("---Python Basic Data Type---")
print("---number---")
x = 3
print(type(x))
print(x)
print(x ** 2)
#没有x++ x--这种操作符
y = 2.5
print(type(y))
print(x, y)
print("---boolean---")
t = True
f = False
print(type(t))
print(t and f)
print(t != f)
print(f)
print("---string---")
hello = 'hello'
world = "world"
print(hello)
print(len(world))
hw = hello + ' ' + world
print(hw)
hw233 = '%s %s %d' % (hello, world, 233)
print(hw233)
print("---string methods---")
s = "hello"
print(s.capitalize()) #首字母大写
print(s.upper()) #capitalize/uppercase
print(s.rjust(7)) #right justify右对齐,限制长度,用空格填充
print(s.center(7)) #居中,跟rjust同类型的效果
print(s.replace('l', '(ell)')) #替换所有的
print(' world '.strip()) #删除所有前导和后缀空格
#容器
print("---Container---")
print("---list---")
#python的列表list就是其他语言的数组array,但是长度可变resizeable且可存不同类型
xs = [3, 1, 2]
print(xs, xs[2])
print(xs[-1]) #从后往前数,1开始计数
xs[2] = 'foo'
print(xs)
xs.append('bar')
print(xs)
x = xs.pop() #移除并返回最后一个元素
print(x, xs)
print("---list sclicing(切片)---") #concise(brief) syntax来获取子列表sublists
nums = list(range(5)) #用list转换range对象,还不懂为什么,具体的都忘记了
print(nums)
print(nums[2:4]) #后面的总是不被包含,老外习惯[,)区间
print(nums[2:])
print(nums[:2])
print(nums[:])
print(nums[:-1])
nums[2:4] = [8, 9]
print(nums)
print("---list loops---")
animals = ['cat', 'dog', 'monkey']
for animal in animals:
print(animal)
for idx, animal in enumerate(animals): #enumerate枚举,这样可以获得index,序号从零计数(是指针?)
print('#%d: %s' % (idx + 1, animal))
print("---list comprehensions(列表推导)---") #很强的一个syntax
nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
squares.append(x ** 2)
print(squares) #用循环是这么写的
nums = [0, 1, 2 ,3 ,4]
squares = [x ** 2 for x in nums] #用列表推导就可以极度简化
print(squares)
squares = [x ** 2 for x in nums if x % 2 == 0] #可以加条件
print(squares)
print("---dictionary---")
#python的字典很像其它语言的map或者JavaScript里面的object,是(key, value)的键值对
d = {'cat': 'cute', 'dog': 'furry'}
print(d['cat']) #得到一条entry,entry理解为词条/条目
print('cat' in d) #check if dictionary d has a given key, return True of False
d['fish'] = 'wet' #C++里面有类似的写法
print(d['fish'])
#print(d['monkey']) #KeyError,所以不能这么写,最好用get
print(d.get('monkey', 'N/A')) #N/A是获取默认值,没有就打印N/A
print(d.get('fish', 'N/A'))
del d['fish'] #删除一个entry
print(d.get('fish', 'N/A'))
print("---dictionary loops---")
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
legs = d[animal]
print("A %s has %d legs" % (animal, legs))
for animal, legs in d.items(): #这样可以获取key和对应value(corresponding)
print("A %s has %d legs" % (animal, legs))
#这个用法没搞懂
#关于d.items()的作用:以列表形式返回可遍历的(键, 值) 元组数组。
#示例,详解:
D = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com', 'taobao': 'www.taobao.com'}
print("字典值 : %s" % D.items())
print("转换为列表 : %s" % list(D.items()))
for key, value in D.items():#遍历字典列表,这里的key和value分别对应D.items()生成的元组tuple里的两个元素。
print(key, value)
print("---dictionary comprehensions")
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0} #even number偶数,字典推导和列表推导的形式差不多
print(even_num_to_square)
print("---set---") #直观上跟其他语言中的set就很像了
animals = {'cat', 'dog'}
print('cat' in animals) #data in container的句子是返回是否在其中
print('fish' in animals)
animals.add('fish')
print('fish' in animals)
print(len(animals)) #有几个元素
animals.add('cat') #does nothing
animals.remove('cat')
print(len(animals))
print("---set loops")
animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals): #enumerate(container)返回一个由(序号,元素)元组构成的列表
print('#%d: %s' % (idx + 1, animal)) #可以发现,无序,无法做顺序的假设,无论加入的顺序如何
print("---set comprehensions---")
from math import sqrt
nums = {int(sqrt(x)) for x in range(30)} #满足后面条件的x全都要被遍历
print(nums)
print("---tuples---")
#元组是一个值的有序列表(不可改变!)。从很多方面来说,元组和列表都很相似。
#和列表最重要的不同在于,
#1.元组可以在字典中用作键,
#2.还可以作为集合的元素,
#而列表不行。例子如下:
d = {(x, x + 1): x for x in range(10)}
t = (5, 6)
tt = (5, 6, 7)
print(tt, type(t))
print(d[t]) #是个比较神奇的用法
print(d[(1, 2)]) |
'''
handles direct communication with the server
loggin in, fetching api data, downloading images etc.
'''
import urllib
import urllib2
from urllib2 import URLError, HTTPError
import json
import settings
class Request:
def __init__(self, persistence_data):
pass
def connect_to_server(self, username, password):
request_data = {
'username': username,
'password': password,
'computer_name': settings.COMPUTER_NAME,
'computer_username': settings.COMPUTER_USERNAME,
'app_version': settings.VERSION,
'app_name': settings.APP_NAME,
}
try:
response = urllib2.urlopen(settings.API_URL, urllib.urlencode(request_data))
except URLError, error:
print 'Connection Error: %s' % (error.code)
return False
except:
print 'Unknown error during server connection'
return False
try:
data = json.loads(response.read())
except:
print 'Unable to parse server response'
return False
if data['success']:
#print 'Login Successful!'
return data
else:
print 'Login Failure:'
print 'Error: %s' % (data['error'])
return False
def download_image(self, src_uri, dest_uri):
print 'downloading image from %s to %s' % (src_uri, dest_uri)
try:
image = urllib.urlopen(src_uri).read()
except:
print 'Unbale to open image @ %s' % (src_uri)
return False
try:
mfile = open(dest_uri, 'wb')
mfile.write(image)
mfile.close()
except:
print 'Error writing image to file'
return False
return True |
import random
guesses_left = 10
list_word = ["gucci", "polo", "versace", "armani", "obey", "nike", "jordan", "supreme", "stussy", "bape", "addidas"]
random_word = random.choice(list_word)
letters_guessed = []
ranged_word = len(random_word)
print(random_word)
guess = ""
correct = list(random_word)
guess = ""
while guess != "quit":
output = []
for letter in random_word:
if letter in letters_guessed:
output.append(letter)
else:
output.append("*")
print(" ".join(list(output)))
guess = input("Guess a letter: ")
letters_guessed.append(guess)
print(letters_guessed)
if guess not in random_word:
guesses_left -= 1
print(guesses_left)
if output == correct:
print("You win")
exit(0)
if guesses_left == 0:
print("you loose")
Guesses = input("Guesses a letter:")
print("These are your letter %s" % letters_guessed)
lower = Guesses.lower()
letters_guessed.append(lower)
|
def fact(n):
if n == 0:
f = 1
else:
f = 1
for i in range(1, n + 1):
f *= i
yield f
for el in fact(5):
print(el)
# |
'''SnakeGame.py
By Tenzin Dophen, Adapted from Jed Yang 2017-03-15
This class contains objects which draws a body like a snake with a tail, which
can be moved around by a user, using the arrows on the keyboards for direction. The snake
can eat any objects(circles, supposed to be apples) also drawn in the class snake on the way which will increase
the user's score but also grows the snake's tail by 1 each time it eats. The user loses(the game ends and the window closes) if
the snake goes touches the boundaries of the window or the head of the snake touches any of its tails.
Happy Gaming'''
from graphics import *
import sys
from random import randint
class Snake(GraphWin):
def __init__(self,color, bgcolor):
"""Assign these numbers to instance variables."""
GraphWin.__init__(self, 'Snake Module snake', 1000, 900)
self.setBackground(color_rgb(0,0,225))
self.x = 10
self.y = 10
self.dx = 5 # the number by which the snake should move
self.dy = 0
self.a = 0 # position of the apple
self.b = 0 # position of the apple
self.score = 0
self.color = color
self.bgcolor = bgcolor
self.total = 0
self.bodyParts = [] #list to store the body of the snake(i.e head and the tails)
self.makeHead()# class the function to make the head of the snake
self.make_Tail()# class the function to make the tail of the snake
self.apple()# class the function to make the apple
self.draw()
# binds all the keys, i.e. arrow keys on the keyboard
self.bind_all('<Up>', self.upHandler)
self.bind_all('<Down>', self.downHandler)
self.bind_all('<Left>', self.leftHandler)
self.bind_all('<Right>', self.rightHandler)
def stepsnake(self):
"""Step one time unit. Use move() based on dx, dy"""
self.move_snake(self.dx, self.dy) # calls the move_snake fucntion to move the snake
if self.x < 0 or self.x > self.width or self.y < 0 or self.y > self.height:
#the game ends if the snake's head touches the boundaries of the window
sys.exit()
for i in range(1, len(self.bodyParts)-1):
if self.bodyParts[0].getP1().getX() - self.bodyParts[i+1].getP1().getX() == 0 and self.bodyParts[0].getP1().getY() - self.bodyParts[i+1].getP1().getY() == 0:
sys.exit()
# the game ends and the window closes if the head of the tail touches any of its tails that is created after it eats the apple
'''This fucntion is called everytime the snake takes a step ad is used eat the apples
on the way as well as call the relvant function to add the tail'''
def eat(self):
d = abs(self.x - self.a) # checks the distance between the apple and the snake's x coordinate of head
e = abs(self.y - self.b)#checks the distance between the apple and the snake's head y coordinate of head
if d < 20 and e < 20: # checks if the distance between the snake and the head is within 20
self.apple.undraw() # remove the apple
self.a = randint(0,self.width -100) # generates random number within the window, but not too close to the boundary
self.b = randint(0,self.height-100)# generates random number within the window, but not too close to the boundary
self.apple = Circle(Point (self.a , self.b ), 10) # set up an apple
self.apple.setFill("white")
self.apple.draw(self) # draw a new apple in a random place
self.total = self.total + 1 # keeps track of the apples the snake eats
self.make_Tail() # class the function to add a new tail
def move_snake(self, dx, dy):
"""Move the snake upwards/downwards by dy and right and left by dx."""
self.eat() # calls the eat function to check if the snake eats any apple
self.bodyParts[0].move(dx,dy) # move the head of the snake
''' The for loop runs through the list of the snake bodyparts, starting from the item on the end of the list
to the second item on the list, basically all the tails and just not the head.
In the for loop, starting from the last tail in the list, it moves and switches its place to the one above it,
using the x and y coordinate to help cover the distance. The getP1() returns the points of the tail while the getX() and get Y returns the x and y corrdinates of the tail'''
for i in range(len(self.bodyParts)-1, 0, -1):
self.bodyParts[i].move(self.bodyParts[i-1].getP1().getX() - self.bodyParts[i].getP1().getX(),self.bodyParts[i-1].getP1().getY() - self.bodyParts[i].getP1().getY() )
self.x = self.x + dx # updates the location fo the snake
self.y = self.y + dy # updates the location of the snake
def upHandler(self, event):
self.dy= -10 - self.total*2 #moves the snake upwards and increases the step it should take everytime it eats an apple, updated by the value of self.total
self.dx = 0
def downHandler(self, event):
self.dy = 10 + self.total*2 #moves the snake downwards and increases the step it should take everytime it eats an apple, updated by the value of self.total
self.dx = 0
def rightHandler(self, event):#moves the snake to the right and increases the step it should take everytime it eats an apple, updated by the value of self.total
self.dx = 10 + self.total*2
self.dy = 0
def leftHandler(self, event):
self.dx = -10 - self.total*2 #moves the snake to the left and increases the step it should take everytime it eats an apple, updated by the value of self.total
self.dy = 0
def draw(self):
#Draw the head and the apple in the window.
self.head.draw(self)
self.apple.draw(self)
def makeHead(self):
#Set up head.
self.head = Rectangle(Point(self.x, self.y ), Point(self.x -20, self.y + 20 ))
self.headColor = color_rgb(200, 200, 20)
self.head.setFill(self.headColor)
self.bodyParts.append(self.head) # add the head to the list bodyParts
def apple(self):
a = randint(0,self.width - 100) # generate random number within the window
b = randint(0,self.height - 100)# generate random number within the window
self.a = a
self.b = b
self.apple = Circle(Point (self.a , self.b ), 10) # make the apple
self.apple.setFill("white")
def make_Tail(self):
self.score = 5 * self.total #updates the score the user earns
print("SCORE = ", self.score) #prints the score
#draws the tail so that its right behind the head with different colour
self.tail = Rectangle(Point(self.x + (self.total *(-20)), self.y ), Point(self.x +(self.total +1) *(-20), self.y + 20))
self.tailColor = color_rgb(100, 200, 20)
self.tail.setFill(self.tailColor)
self.tail.draw(self)
self.bodyParts.append(self.tail) # adds the tail to the list
def snakeModule():
snake = Snake(color_rgb(255,255,0), color_rgb(0,0,0)) # class the Snake Class
while snake.winfo_exists():
snake.stepsnake() # class the stepsnake function everytime
update(24)
# pause for roughly 1/24 of a second
if __name__ == '__main__':
snakeModule() #Only runs snakeModule() if the program is not being called by another
|
def word_break(s: str, word_dict: [str]) -> bool:
ok = [False] * (len(s)+1)
ok[0] = True
for i in range(1, len(s)+1):
for w in word_dict:
if i-len(w)>=0 and s[i-len(w):i] == w:
ok[i] = ok[i-len(w)]
if ok[i]:
break
return ok[-1]
#######
print(word_break("catsandog", ["cats","dog","sand","and","cat"]))
print(word_break("applepenapple", ["apple","pen"]))
print(word_break("leetcode", ["leet","code"]))
print(word_break("a", ["c","bbbbb"]))
|
def threeSumClosest(nums: [int], target: int) -> int:
n = len(nums)
nums.sort()
minDist = float('inf')
res = float('inf')
for i in range(0, n-2):
start, end = i+1, n-1
while start < end:
tmp = target - (nums[i]+nums[start]+nums[end])
if abs(tmp) < minDist:
res = nums[i]+nums[start]+nums[end]
minDist = abs(tmp)
if tmp > 0:
start += 1
elif tmp < 0:
end -= 1
else:
return target
return res
print(threeSumClosest([-1,2,1,-4], 1), "should be 2")
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
def visitTree(target: int, root: TreeNode) -> []:
if not root:
return None
if not root.left and not root.right and target == root.val:
return [[root.val]]
paths = []
if root.left:
left = visitTree(target-root.val, root.left)
for l in left:
k = [root.val]
k.extend(l)
paths.append(k)
if root.right:
right = visitTree(target-root.val, root.right)
for r in right:
k = [root.val]
k.extend(r)
paths.append(k)
return paths
return visitTree(targetSum, root)
|
# 322. Coin Change
# Solution 1 - wrong answer
# not valid when we don't need the biggest number to be divided first
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
coins = sorted(coins,reverse=True)
count = 0
for coin in coins :
if amount//coin >= 1:
count += amount//coin
amount = amount % coin
if amount != 0:
return -1
else:
return count
# Solution 2 - Time Limit Exceeded
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
dp = [float('inf')] * (amount +1)
dp[0] = 0
for coin in coins:
for x in range(coin, amount+1):
min = float('inf')
i,rem = 0, x
while (rem-coin*i)>=0:
if min > dp[rem-coin*i] + i:
min = dp[rem-coin*i]+i
i+=1
dp[x] = min
if dp[amount] != float('inf'):
return dp[amount]
else:
return -1
# Solution 3 - Accepted
#
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
dp = [float('inf')] * (amount +1)
dp[0] = 0
for coin in coins:
for x in range(coin, amount+1):
dp[x] = min(dp[x], dp[x-coin]+1)
if dp[amount] != float('inf'):
return dp[amount]
else:
return -1
|
# 973. K Closest Points to Origin
# Solution 1
# Time Complexity : O(n + nlogn) = O(nlogn)
# 1, figure out each distance between origin and point.and make index & distance into dictionary.
# 2, sort dictionary with values.
# 3, Only pop k elements in the distance.
# Beat 84.76%
class Solution(object):
def kClosest(self, points, K):
"""
:type points: List[List[int]]
:type K: int
:rtype: List[List[int]]
"""
dist,i = {},0
for point in points:
dist[i] = point[0]*point[0] + point[1]*point[1]
i+=1
dist = sorted(dist.items(),key = lambda x:x[1])
res = []
for i in range(K):
res.append(points[dist[i][0]])
return res
# Solution 2 (** need to do **)
# Divide and conquer solution
|
# 435.Non-overlapping Intervals
#class Solution(object):
# def eraseOverlapIntervals(self, intervals):
def eraseOverlapIntervals(intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
if intervals == []:
return 0
intervals = sorted(intervals, key=lambda i:i[1])
res,cnt,tmp = [],0,0
end = float('-inf')
for i in range((len(intervals))):
if end <= intervals[i][0]:
end = intervals[i][1]
else :
cnt +=1
return cnt
arr =[[0,2],[1,3],[1,3],[2,4],[3,5],[3,5],[4,6]]
print eraseOverlapIntervals(arr)
arr = [[1,100],[11,22],[1,11],[2,12]]
print eraseOverlapIntervals(arr)
arr = [[1,2],[1,2],[1,2]]
print eraseOverlapIntervals(arr)
arr = [[1,2],[2,3]]
print eraseOverlapIntervals(arr)
|
def perm(list, start):
if start == len(list)-1:
#print("before append = ", perm_list)
temp = []
for i in range(len(list)):
temp += list[i]
perm_list.append(temp)
#print(list)
#print("perm_list = ", perm_list)
return
for i in range(start, len(list)):
list[start], list[i] = list[i], list[start]
perm(list, start+1)
list[start],list[i] = list[i],list[start]
perm_list = []
perm([1,2,3,4],0)
print(perm_list) |
# Two Sum
"""
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
"""
def twoSum(nums, target):
res = []
for idx,num in enumerate(nums):
for j in range(idx+1,len(nums),1):
if num + nums[j] == target:
res.append(idx)
res.append(j)
return res
nums = [2,7,11,15]
target = 9
print twoSum(nums,target)
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
def heapAdjust(arr, s, length):
temp = arr[s]
child = 2 * s + 1
while child < length:
if child + 1 < length and arr[child+1] < arr[child]:
child = child+1
if arr[child] < arr[s]:
arr[s] = arr[child]
s = child
child = s * 2 + 1
else:
break
arr[s] = temp
return arr
def heapBuild(arr, length):
a = list(range(0, (length - 1) // 2 + 1))
a = a[::-1]
for index in a:
arr = heapAdjust(arr, index, length)
return arr
def heapSort(arr, length):
arr = heapBuild(arr, length)
a = list(range(0, length))[::-1]
for index in a:
temp = arr[index]
arr[index] = arr[0]
arr[0] = temp
arr = heapAdjust(arr, 0, index)
print(arr)
return arr
heapSort([1, 5, 0, 10, 8, 20], 6) |
import sys
def main():
# get user input
while True: # repeat while input is negative
input_number = input("Enter a card number: ")
length = len(input_number)
if length >= 13 and length <= 16: # if input has a valid length break
break
elif length < 13: # length is too short exit
print("INVALID")
sys.exit(0)
# convert input_number from string to an array of integer numbers
number = [int(digit) for digit in input_number]
validate_card(number)
def validate_card(number):
num2 = []
num = []
for idx, digit in enumerate(reversed(number)):
if idx % 2 != 0:
digit = 2 * digit
if digit > 9:
num2.append(get_digit(digit, 0))
num2.append(get_digit(digit, 1))
else:
num2.append(digit)
else:
num.append(digit)
# calculate sum of numbers which have to be multiplied by two
sum2_number = sum(num2)
# calculate sum of the rest of numbers
sum_number = sum(num)
# calculate checksum
check_sum = sum_number + sum2_number
check_manufacturer(check_sum, number)
def check_manufacturer(check_sum, number):
# check if checksum is valid
if get_digit(check_sum, 0) != 0:
print("INVALID")
# check which card company it is
else:
if number[0] == 3 and (number[1] == 4 or number[1] == 7):
print("AMEX")
elif number[0] == 4:
print("VISA")
elif number[0] == 5 and (number[1] == 1 or number[1] == 2 or number[1] == 3 or number[1] == 4 or number[1] == 5):
print("MASTERCARD")
else:
print("INVALID")
def get_digit(number, n):
return number // 10**n % 10
if __name__ == "__main__":
main() |
# Created by:
# Forrest W. Parker
# 01/06/2017
#
# Version 1.0
# 01/06/2017
#####
import math
# Returns True if the string 'string' matches the pattern string 'patstring'
# and returns False otherwise.
#
# Note that distinct characters of 'patstring' must correspond to
# distinct substrings of 'string'.
# (e.g. "a" and "b" in 'patstring' cannot both correspond to the
# substring "one" in 'string')
#
# Examples:
# >>> checkPattern("onetwothreefourcowcowcowcow","abcdeeee")
# True
# >>> checkPattern("onetwothreefourcowcowcowcow","abcdeeff")
# False
# >>> checkPattern("onetwothreefourcowcowcowcow","abcdeef")
# True
#
# Note that neither 'string' nor 'patstring' are restricted
# to alphabetical characters.
def checkPattern (string, patstring):
return checkPatternRecursive(string, patstring, {})
# Used by checkPattern.
# See the notes throughout for details about how it works.
def checkPatternRecursive (string, patstring, patdict):
# First check if either 'string' or 'patstring' is empty.
# If either is empty, go to the elif statement far below.
#
# Otherwise both are nonempty, do the following.
if len(string) != 0 and len(patstring) != 0:
# Take the first character in 'patarray'.
patletter = patstring[0]
# If this character is already assigned to a string in 'patdict',
# do the following.
if patletter in patdict.keys():
# Get the string assigned to 'patletter'.
sub = patdict[patletter]
# If 'sub' is longer than 'string' or
# if string does not start with sub,
# the current set of character substitutions
# has failed, so return False.
if len(string) < len(sub) or sub != string[:len(sub)]:
return False
# Else the character substitution made earlier
# is still acceptable, so call checkPatternRecursive
# again with 'sub' removed from the the beginning of
# 'string' and 'patletter' removed from the beginning
# of 'patstring' and return the result.
else:
return checkPatternRecursive(string[len(sub):], patstring[1:], patdict)
# Else 'patletter' is not assigned to a string in 'patdict',
# so initialize 'fitsPattern', 'subLength', and 'maxLength'.
else:
fitsPattern = False
subLength = 0
maxLength = math.floor((len(string)-len(patstring)+patstring.count(patletter))
/patstring.count(patletter))
# Incrementally increase 'subLength' by one and let 'sub'
# be the substring formed by the first 'subLength' characters
# of 'string' with a maximum length of 'maxLength'.
#
# Note that the calculation of 'maxLength' determines the longest
# substring of 'string' that can be substituted for 'patletter'
# before the substitution cannot be valid.
#
# If during any iteration 'fitsPattern' is set to True, cease
# future iterations.
while subLength < maxLength and not fitsPattern:
subLength += 1
sub = string[:subLength]
# If 'sub' is already assigned to a different character in
# 'patdict', skip it.
#
# Otherwise, create a new entry in 'patdict' to record the
# new substitution, assign 'fitsPattern' to be the result
# of calling checkPatternRecursive again with 'sub'
# removed from the the beginning of 'string' and
# 'patletter' removed from the beginning of 'patstring',
# and finally remove the 'patletter'-'sub' pairing from
# 'patdict'.
#
# Note that the last step is necessary since dictionaries
# are passed into functions by reference, not by value. Not
# removing the pairing may cause errors to future calls
# of checkPatternRecursive as 'patdict' would contain entries
# made in earlier iterations, leading to incorrect results.
if not sub in patdict.values():
patdict[patletter] = sub
fitsPattern = checkPatternRecursive(string[subLength:], patstring[1:], patdict)
patdict.pop(patletter)
# Once finished considering substitutions for 'patletter'
# (whether successful or not), return 'fitsPattern'.
return fitsPattern
# Else either 'string' or 'patstring' is an empty string.
# If both are empty, then a successful set of substitutions
# has been found, so return True.
elif len(string) == 0 and len(patstring) == 0:
return True
# Else only one of 'string' and 'patstring' is empty.
# This indicates that the current set of substitutions
# is not valid, so return False.
else:
return False
#####
# Returns with an array of stringpattern classes which contain all
# patternArrays and corresponding patternDictionaries for the string
# 'string'.
#
# WARNING: This function would use an exponential amount of memory
# proportional to the length of 'string'. It has been artificially
# capped to run properly only when 'string' has no more than eight
# characters.
def findAllPatterns(string):
if len(string) > 8:
return []
else:
return findAllPatternsRecursive(string, {}, {})
# Used by findAllPatterns.
# Functionality is left to the reader to determine.
def findAllPatternsRecursive(string, patdict, valdict):
patarray = []
if len(string) == 0:
patarray.append(stringpattern(patdict))
else:
for i in range(0,len(string)):
n = len(string)-i
sub = string[:n]
if sub in valdict.keys():
patnum = valdict[sub]+1
isNewNum = False
else:
patnum = len(patdict.keys())+1
patdict[str(patnum)] = sub
valdict[sub] = patnum
isNewNum = True
getpatarray = findAllPatternsRecursive(string[n:], patdict.copy(), valdict.copy())
for j in getpatarray:
j.patternArray.insert(0,patnum)
patarray.extend(getpatarray)
if isNewNum:
patdict.pop(str(patnum))
valdict.pop(sub)
return patarray
# Class used by findAllPatterns
class stringpattern:
def __init__(self, patdict):
self.patternArray = []
self.patternDictionary = patdict.copy()
def makeString(self):
string = ""
for i in self.patternArray:
string += self.patternDictionary[str(i)]
return string
|
import time
def recursive_find(number, cur):
if number > cur.value and cur.right != None:
return recursive_find(number, cur.right)
elif number < cur.value and cur.left != None:
return recursive_find(number, cur.left)
if number == cur.value:
return True
return False
def find_r(number, cur):
if type(number) != int:
return False
if number == cur.root.value:
return True
try:
return recursive_find(number, cur.root)
except:
return False
def doTree():
temp = BinaryTree(4)
temp.insert(1)
temp.insert(2)
temp.insert(6)
temp.insert(11)
temp.insert(12)
temp.insert(3)
temp.insert(5)
temp.insert(8)
temp.insert(7)
return temp
# In retrospect I should of made this function a method of the BinaryTree class as it would of been easier to do
# from an implementation and logic point of view.
def remove(target, tree):
if not find_r(target, tree):
print("Value not found in tree")
return
cur = tree.root
# Path variable memorises the path that is taken to the target, and is used when we modify the tree
path = ''
# This while searches the target is
while cur is not None:
if target == cur.value:
break;
elif target > cur.value:
cur = cur.right
path += '.right'
elif target < cur.value:
cur = cur.left
path += '.left'
if cur.value != target:
print("Number has not been found")
return tree
# Case 4: We are removing the root, as there are no children
if cur.left is None and cur.right is None and path == '':
cur.root = None
print("You have just removed the root from the tree. Assign a new root to continue")
tree.root = None
return tree
# Case1: If there is no child
elif cur.left is None and cur.right is None:
exec('tree.root' + path + '=None')
# Case3: Both in left and right there is a child found. I chose to do Case3 before Case2 because its simpler
# to think about the conditionals
elif cur.left is not None and cur.right is not None:
removePath = ''
cur = cur.right
while cur.left is not None:
cur = cur.left
removePath += '.left'
exec('tree.root' + path + '.value = cur.value')
exec('tree.root' + path + '.right' + removePath + '= cur.right')
# Case 2: only one child is found
elif cur.left is None:
exec('tree.root' + path + ' = ' + 'tree.root' + path + '.right')
exec('tree.root' + path + 'right = None')
elif cur.right is None:
exec('tree.root' + path + ' = ' + 'tree.root' + path + '.left')
exec('tree.root' + path + 'left = None')
return tree
# My main issue with my code is that it heavily relies on the exec() function, and
# I fear it's not that efficient.
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree(object):
def find_i(self, number):
try:
cur = tree.root
while cur is not None:
if cur.value == number:
return True
elif number < cur.value:
cur = cur.left
else:
cur = cur.right
return False
except TypeError:
return False
print("Please pass an integer")
def __init__(self):
self.root = None
def __init__(self, root):
self.root = Node(root)
"""DISPLAY FUNCTION FROM AULA"""
def display(self, cur_node):
if self.root == None:
return
lines, _, _, _ = self._display(cur_node)
for line in lines:
print(line)
def _display(self, cur_node):
"""Returns list of strings, width, height, and horizontal coordinate of the root."""
# No child.
if cur_node.right is None and cur_node.left is None:
line = '%s' % cur_node.value
width = len(line)
height = 1
middle = width // 2
return [line], width, height, middle
# Only left child.
if cur_node.right is None:
lines, n, p, x = self._display(cur_node.left)
s = '%s' % cur_node.value
u = len(s)
first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s
second_line = x * ' ' + '/' + (n - x - 1 + u) * ' '
shifted_lines = [line + u * ' ' for line in lines]
return [first_line, second_line] + shifted_lines, n + u, p + 2, n + u // 2
# Only right child.
if cur_node.left is None:
lines, n, p, x = self._display(cur_node.right)
s = '%s' % cur_node.value
u = len(s)
first_line = s + x * '_' + (n - x) * ' '
second_line = (u + x) * ' ' + '\\' + (n - x - 1) * ' '
shifted_lines = [u * ' ' + line for line in lines]
return [first_line, second_line] + shifted_lines, n + u, p + 2, u // 2
# Two children.
left, n, p, x = self._display(cur_node.left)
right, m, q, y = self._display(cur_node.right)
s = '%s' % cur_node.value
u = len(s)
first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s + y * '_' + (m - y) * ' '
second_line = x * ' ' + '/' + (n - x - 1 + u + y) * ' ' + '\\' + (m - y - 1) * ' '
if p < q:
left += [n * ' '] * (q - p)
elif q < p:
right += [m * ' '] * (p - q)
zipped_lines = zip(left, right)
lines = [first_line, second_line] + [a + u * ' ' + b for a, b in zipped_lines]
return lines, n + m + u, max(p, q) + 2, n + u // 2
"""INSERT FUNCTION FROM AULA"""
def insert(self, value):
if value is None:
self.root = Node(value)
else:
self._insert(value, self.root)
def _insert(self, value, cur_node):
if value < cur_node.value:
if cur_node.left is None:
cur_node.left = Node(value)
else:
self._insert(value, cur_node.left)
elif value > cur_node.value:
if cur_node.right is None:
cur_node.right = Node(value)
else:
self._insert(value, cur_node.right)
else:
print("Value already present in tree")
def insert(self, value):
if self.root is None:
self.root = Node(value)
else:
self._insert(value, self.root)
def _insert(self, value, cur_node):
if value < cur_node.value:
if cur_node.left is None:
cur_node.left = Node(value)
else:
self._insert(value, cur_node.left)
elif value > cur_node.value:
if cur_node.right is None:
cur_node.right = Node(value)
else:
self._insert(value, cur_node.right)
else:
print("Value already present in tree")
tree = BinaryTree(4)
tree.insert(4)
tree.insert(1)
tree.insert(2)
tree.insert(6)
tree.insert(11)
tree.insert(12)
tree.insert(3)
tree.insert(5)
tree.insert(8)
tree.insert(7)
#
print(tree.find_i(3))
print(tree.find_i(6))
print(tree.find_i("Hello"))
print(tree.find_i(15.443))
print(tree.find_i(99))
print(tree.find_i(tree.root.value))
print()
print(find_r(7, tree))
print(find_r(tree.root.value, tree))
print(find_r(143434, tree))
print(find_r("Hello", tree))
print()
tree.display(tree.root)
print("We remove 1 then add it. Then print to see the difference")
tree = (remove(1, tree))
tree.insert(1)
tree.display(tree.root)
print("We remove 11 to see the difference. Then print")
tree = (remove(11, tree))
tree.display(tree.root)
print("We remove 6 and 8 to see the difference. Then print and we check to see if 6 still exists")
tree = (remove(6, tree))
tree = (remove(8, tree))
tree.display(tree.root)
print(tree.find_i(6))
print(find_r(6, tree))
print("We remove twice in a row the root too see what happens. Print twice")
tree = (remove(4, tree))
tree.display(tree.root)
tree = (remove(5, tree))
tree.display(tree.root)
print("We remove all the elements from the tree")
tree = remove(7, tree)
tree = remove(12, tree)
tree.display(tree.root)
tree = remove(2, tree)
tree = remove(1, tree)
tree = remove(3, tree)
tree.display(tree.root) # Doesnt print
print()
if input("Additionally, would you like to se a comparison between recursive and iterative searches?(y/n) ") == "y":
nrOfLoops = int(input("Input your number of runs for each algorithm. It should be around the magnitudes of 10^5-6 "))
start = time.time()
tree = doTree()
for i in range(nrOfLoops):
tree.find_i(6)
stop = time.time()
time1 = stop - start
start = time.time()
for i in range(nrOfLoops):
find_r(6, tree)
stop = time.time()
time2 = stop - start
print(f"Iterative search time is about {round(time1,4)}, and recursive search time is about {round(time2,4)}.")
print(f"This means that Iterative search is roughly {round((time1 / time2) * 100, 2)}% faster then recursive search")
|
#Estructuras de Control
#Autor: Javier Arturo Hernández Sosa
#Fecha: 1/Sep/2017
#Descripcion: Curso Python FES Acatlán
#sentencia IF,ELSE y ELIF
edad = 10
if(edad<18):
print("Eres un niño todavía")
elif(edad>=18 and edad<40):
print("Eres un adulto")
elif(edad>=40 and edad<70):
print("Ya estas viejo")
else:
print("Ya te pasaste de maduro")
#sentencia WHILE
x = 0
while(True):
x = x + 1
if(x==3):
print("Nos brincamos el 3")
continue
elif(x==8):
print("En el 8 rompemos el ciclo")
break
print(x)
'''Función RANGE
range(inicio,final,incremento) Genera una progreción aritmética
range(10) 0 a 9
range(5,10) 5 a 9
range 5,10,2) 5 a 9 de 2 en 2
'''
#sentencia FOR
for i in range(1,10,1):
if(i==3):
print("Se brinca el 3")
continue
elif(i==8):
print("Rompiendo for")
break
print(i)
#FOR y WHILE pueden tener una cláusula ELSE
'''En el caso del for la cláusula se ejecuta cuando finaliza el el for pero no cuando termina por un break
En el caso de while la cláusula se ejecuta cuando la condición se vuelve false
'''
for i in "Hola":
print(i)
else:
print("Termino la iteración del for")
y = 3
while(y<10):
y = y + 1
if(y==8):
print("Se rompe el ciclo")
break
print(y)
else:
print("La condición se rompio")
|
#Manejo de Archivos
#Autor: Javier Arturo Hernández Sosa
#Fecha: 24/Sep/2017
#Descripcion: Curso Python FES Acatlán
'''
Los errores de sintaxis, también conocidos como errores de interpretación.
'''
# prinCt("Hola") Ocurren cuando escribimos mal algo dentro del código
'''
Excepciones, son errores que ocurren durante la ejecución aunque
la sintaxis sea correcta, pero estos se pueden manejar para que
el programa no termine inesperadamente.
'''
'''
Algunas excepciones comunes:
ZeroDivisionError: división por cero
NameError: Variable no definida
TypeError: Error de conversion de tipo implicita
ImportError: Error cuando carga una libreria
IndexError: Cuando una secuencia esta fuera de rango
OverflowError: Cuando una operación aritmética es demaciado grande para representarla
KeyboardInterrupt: Cuando el usuario interrumpe con 'control-c' para windows
OSError: Ocurre cuando la función de sistema regresa un error, como
no poder abrir un archivo o el disco de escritura esta lleno
ETC...
'''
#Manejando Excepciones
#Una excepción
try:
x = int(input("Dame un número"))
except ValueError:
print("El valor que ingresaste no es un número.")
#Multiples excepciones
try:
x = int(input("Dame un número"))
resultado = 5/x
except ValueError:
print("El valor que ingresaste no es un número.")
except ZeroDivisionError:
print("División entre cero.")
#También pueden colocarse varios errores en un solo except
'''
except (ValueError,ZeroDivisionError):
print("Ocurrio un error, pruebe a ingresar un valor que no sea un cero , una letra o un signo.")
'''
#De igual manera podemos usar except sin parámetros
try:
x = int(input("Dame un número"))
resultado = 5/x
except:
print("Ocurrio un error")
'''
Aquí podemos capturar cualquier error que ocurrar pero no sabremos de que tipo
y esto podría ocultar errores de programación.
'''
#bloque ELSE
'''
Este bloque es opcional y se ejecuta cuando no se genera una excepción dentro del try
'''
try:
x = int(input("Dame un número"))
resultado = 5/x
except:
print("Ocurrio un error")
else:
print("El resultado de la operación es: ",resultado)
#Cláusula finally
'''
Esta se ejecuta si no hay error en try
si hay un bloque ELSE también se ejecuta, después del bloque else
si ocurre un error manejado por except se ejecuta
si ocurre un error que no es manejado por except también se ejecuta
Y como podrás ver siempre se ejecuta, esto es útil para liberar recursos externos
sin importar si el suo del recurso fue exitoso o no.
(cerrar archivos o conexiones de red (DB))
'''
try:
x = int(input("Dame un número"))
resultado = 5/x
except:
print("Ocurrio un error")
else:
print("El resultado de la operación es: ",resultado)
finally:
del(x)
del(resultado)
print("Liberando espacio ocupado por las variables.")
#Levantando excepciones RAISE
'''
También podemos levantar excepciones usando la sentencia raise
debemos indicar el tipo de error y un mensaje opcional
raise ZeroDivisionError
raise ZeroDivisionError("!Dividiste entre cero¡")
Esto cortara el flujo del programa
'''
print("Hola antes de la excepcion")
raise ZeroDivisionError("!Dividiste entre cero¡")
print("Hola después de la excepción")
#Podemos usar raise sin parámetros dentro de un except para re-lanzar la excepción ocurrida
try:
x = int(input("Dame un número"))
resultado = 5/x
except:
print("Ocurrio un error")
raise
|
#Ejercicios 1
#Autor: Javier Arturo Hernández Sosa
#Fecha: 6/Sep/2017
#Descripcion: Curso Python FES Acatlán
#Ver si un número es par o impar
numero = int(input("Dame un número: "))
if((numero%2) == 0):
print("El numero ingresado es par.")
else:
print("El número ingresado es impar")
#Saber si una cadena es Palíndromo
cadena = input("Dame una cadena: ")
nCadena = cadena.replace(" ","")
for i in range(len(nCadena)):
if(nCadena[i]==nCadena[-(i+1)]):
pass
else:
print("No es paíndromo")
break
else:
print("Si es palíndromo")
#Multiplicación de vectores
tam = int(input("Ingresa la dimención de los vectores: "))
vec1 = []
vec2 = []
for i in range(2):
x = 0
while(x<tam):
if(i==0):
valor = int(input("Dame los valores del vector 1: "))
vec1.append(valor)
elif(i==1):
valor = int(input("Dame los valores del vector 2: "))
vec2.append(valor)
x = x+1
m = 0
for i in range(tam):
m = m + (vec1[i] * vec2[i])
print(f"El resultado de la multiplicación de los vectores es: {m}")
#Multiplicación de matrices 2x2
lista1 = [[1,2],[2,3]]
lista2 = [[3,3],[3,3]]
lista3 = [[0,0],[0,0]]
print("Matriz 1")
print(lista1)
print("Matriz 2")
print(lista2)
for i in range(2):
for j in range(2):
for k in range(2):
lista3[i][j] = lista3[i][j]+(lista1[i][k] * lista2[k][j])
else:
print("Resultado de la multiplicación: ")
print(lista3)
|
from config.db import BASE
'''
opcion = 1
usuarios = []
while opcion !=0:
print('Selecciona una opción:')
print('1. Registrar usuario')
print('2. Inicio de sesión')
print('0. Salir')
opcion = int(input())
if opcion == 1:
nombre = input('Ingrese nombres del usuario: ')
apellido = input('Ingrese apellidos del usuario: ')
correo = input('Ingrese el correo del usuario:
contrasena = input('Ingrese contraseña, mínimo 8 caracteres, una mayúscula y un carácter especial: ')
')
contactos.append({
'nombre': nombre,
'apellido': apellido,
'correo': correo,
'contrasena': contrasena,
})
input('Usuario guardado correctamente. Presione enter para continuar')
elif opcion ==2:
correo = input('Ingrese el correo del usuario: ')
correos = [correo]
for correo in correos:
print("Probando si '{}' es válido...{}".format(correo, es_correo_valido(correo)))
contrasena = input('Ingrese contraseña: ')
def validarContrasena(contrasena):
if 8 <= len(contrasena) <= 16:
if re.search('[a-z]', contrasena) and re.search('[A-Z]', contrasena):
if re.search('[0-9]', contrasena):
if re.search('[$@#]', contrasena):
return True
return False
print(validarContrasena(clave))
'''
def ingresoValidar(info):
dato =""
bandera = 1
while bandera!=0:
dato = input('Ingrese '+info+': ')
if not dato:
print("Porfavor ingrese")
else:
print("Se registro "+info)
return dato
#_______________________________________________________
def crearUsuario(usuario):
#print(usuario)
#dato = ['mama','meme','mimi']
cursor=BASE.cursor()
cursor.execute('''
insert into usuarios(nombre,email,contrasena)
values (%s,%s,%s)''',
(usuario['nombre'],
usuario['email'],
usuario['contrasena']))
''' cursor.execute(' insert into usuarios(nombre,email,contrasena) values (%s,%s,%s)', (dato)) '''
BASE.commit()
cursor.close()
def crear():
newUser ={
'nombre' : ingresoValidar('nombre'),
'email' : ingresoValidar('email'),
'contrasena' : ingresoValidar('contrasena')
}
crearUsuario(newUser) |
#!/usr/local/bin/python3.9
def convert(T):
t=T[:-2] #enlève les 2 derniers caractères donc la lettre
T=T.lower()
if T[-1] =="f": #récupére le dernier caractère de T
c=(5/9)*(int(t)-32)
print("la température est de "+str(c)+ " °C")
else:
f=int(t)*(9/5)+32
print("la température est de "+str(f) + " °F")
# test
test=input("Tapez une température avec son unité (°C/°F): ")
convert(test)
|
class GameClock(object):
"""Manages time in a game."""
def __init__(self, game_ticks_per_second=20):
"""Create a Game Clock object.
game_ticks_per_second -- The number of logic frames a second.
"""
self.game_ticks_per_second = float(game_ticks_per_second)
self.game_tick = 1. / self.game_ticks_per_second
self.speed = 1.
self.clock_time = 0.
self.virtual_time = 0.
self.game_time = 0.
self.game_frame_count = 0
self.real_time_passed = 0.
self.real_time = self.get_real_time()
self.started = False
self.paused = False
self.between_frame = 0.0
self.fps_sample_start_time = 0.0
self.fps_sample_count = 0
self.average_fps = 0
def start(self):
"""Starts the Game Clock. Must be called once."""
if self.started:
return
self.clock_time = 0.
self.virtual_time = 0.
self.game_time = 0.
self.game_frame_count = 0
self.real_time_passed = 0.
self.real_time = self.get_real_time()
self.started = True
self.fps = 0.0
self.fps_sample_start_time = self.real_time
self.fps_sample_count = 0
def set_speed(self, speed):
"""Sets the speed of the clock.
speed -- A time factor (1 is normal speed, 2 is twice normal)
"""
assert isinstance(speed, float), "Must be a float"
if speed < 0.0:
raise ValueError("Negative speeds not supported")
self.speed = speed
def pause(self):
"""Pauses the Game Clock."""
self.pause = True
def unpause(self):
"""Un-pauses the Game Clock."""
self.pause = False
def get_real_time(self):
"""Returns the real time, as reported by the system clock.
This method may be overriden."""
import time
return time.clock()
def get_fps(self):
"""Retrieves the current frames per second as a tuple containing
the fps and average fps over a second."""
return self.fps, self.average_fps
def get_between_frame(self):
"""Returns the interpolant between the previous game tick and the
next game tick."""
return self.between_frame
def update(self, max_updates = 0):
"""Advances time, must be called once per frame. Yields tuples of
game frame count and game time.
max_updates -- Maximum number of game time updates to issue.
"""
assert self.started, "You must call 'start' before using a GameClock."
real_time_now = self.get_real_time()
self.real_time_passed = real_time_now - self.real_time
self.real_time = real_time_now
self.clock_time += self.real_time_passed
if not self.paused:
self.virtual_time += self.real_time_passed * self.speed
update_count = 0
while self.game_time + self.game_tick < self.virtual_time:
self.game_frame_count += 1
self.game_time = self.game_frame_count * self.game_tick
yield (self.game_frame_count, self.game_time)
if max_updates and update_count == max_updates:
break
self.between_frame = ( self.virtual_time - self.game_time ) / self.game_tick
if self.real_time_passed != 0:
self.fps = 1.0 / self.real_time_passed
else:
self.fps = 0.0
self.fps_sample_count += 1
if self.real_time - self.fps_sample_start_time > 1.0:
self.average_fps = self.fps_sample_count / (self.real_time - self.fps_sample_start_time)
self.fps_sample_start_time = self.real_time
self.fps_sample_count = 0
if __name__ == "__main__":
import time
t = GameClock(20) # AI is 20 frames per second
t.start()
while t.virtual_time < 2.0:
for (frame_count, game_time) in t.update():
print "Game frame #%i, %2.4f" % (frame_count, game_time)
virtual_time = t.virtual_time
print "\t%2.2f%% between game frame, time is %2.4f"%(t.between_frame*100., virtual_time)
time.sleep(0.2) # Simulate time to render frame
|
def cities_graph():
dict_graph = {}
with open('data.txt', 'r') as f:
for line in f:
city_a, city_b, cost = line.strip().split(',')
cost = int(cost)
if city_a not in dict_graph:
dict_graph[city_a] = {city_b: cost}
else:
dict_graph[city_a][city_b] = cost
if city_b not in dict_graph:
dict_graph[city_b] = {city_a: cost}
else:
dict_graph[city_b][city_a] = cost
return dict_graph
cities_and_paths = cities_graph()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.