text
stringlengths 37
1.41M
|
---|
# Lucia Saura 17/02/2018
# Collaz Conjeture
# https://en.wikipedia.org/wiki/Collatz_conjecture
i = 17
while i > 1:
if i % 2 == 0:
print(i//2)
i = i//2
else:
print (i * 3 + 1)
i = i * 3 + 1
|
'''Esta é uma tarefa de demonstração.
Escreva uma função:
def solution(A)
que, dada uma matriz A de N números inteiros, retorna o menor número inteiro positivo (maior que 0) que não ocorre em A.
Por exemplo, dado A = [1, 3, 6, 4, 1, 2], a função deve retornar 5.
Dado A = [1, 2, 3], a função deve retornar 4.
Dado A = [−1, −3], a função deve retornar 1.
Escreva um algoritmo eficiente para as seguintes suposições:
N é um número inteiro dentro do intervalo [1..100.000];
cada elemento da matriz A é um número inteiro dentro do intervalo [-1.000.000..1.000.000].'''
A = [-10,0, 2, 3,4,9,8,7,6,5,10,11,12,13,141]
def solution(A):
a = set(A)
cont = 0
if not 0 in A:
cont = 1
for num in a:
if num != cont:
return cont
if num == cont:
cont += 1
return cont
print(solution(A))
|
#!/usr/bin/env python
# From the Census Incorporated place CSV, create an optimized JS lookup that
# will return a place based on the following procedure:
#
# 1. Choose a random number in the range of [0, Population of the US)
# 2. Return the place that person would live in
#
# Output:
# {
# // Whoa. A _bunch_ of people don't live in incorporated places!
# totalPopulation: 192213590,
# placeData: [
# [population counter, "Place name", state code (0--49)],
# ...
# [population counter, "Place name", state code (0--49)]
# ],
# stateNames: ["Alabama", "Alaska", ..., "Wyoming"]
# }
# where population counter is the beginning of the US population that lives there
import csv
import json
import sys
def cleanup_name(name):
# Remove the last uncapitalized words
words = name.split()
words.reverse()
last_index = 0
for i, word in enumerate(words):
if not word.islower():
# We've found the last uncapitalized word
last_index = len(words) - i
break
# Back to normal
words.reverse()
words = words[0:last_index]
return " ".join(words)
def main():
if len(sys.argv) < 3:
sys.exit("Usage: ./places.py IN_CSV OUT_JSON")
places_reader = csv.DictReader(open(sys.argv[1], 'r'))
pop_counter = 0
place_data = []
state_names = []
for row in places_reader:
name = cleanup_name(row['name'])
state_name = row['STATENAME']
if state_name not in state_names:
state_names.append(state_name)
state_code = state_names.index(state_name)
place_data.append([pop_counter, name, state_code])
pop_counter += int(row['POP_2009'])
to_json = {}
to_json["totalPopulation"] = pop_counter
to_json["placeData"] = place_data
to_json["stateNames"] = state_names
json.dump(to_json, open(sys.argv[2], 'w'))
if __name__ == '__main__':
main()
|
"""A camera library for projection."""
import json
import numpy as np
try:
import google3
from google3.pyglib import gfile
from cvx2 import latest as cv2
GOOGLE3 = True
except:
import cv2
GOOGLE3 = False
class Camera():
"""A simple camera class."""
def __init__(self,
rvec=np.zeros(3),
tvec=np.zeros(3),
matrix=np.eye(3),
dist=np.zeros(5),
name=None,
size=(None, None)):
"""Camera constructor.
Args:
rvec: The rotation vector of the camera in Rodrigues' rotation formula.
An `np.array` with the shape of `(3,)`.
tvec: The translation vector of the camera. An `np.array` with the
shape of `(3,)`.
matrix: The intrinsic of the camera. An `np.array` with the
shape of `(3,)`.
dist: The distorion coefficients (k1, k2, p1, p2, k3). An `np.array` with
the shape of `(5,)`.
name: A string indicates the name of this camera.
size: A tuple `(width, height)` indicates the size of the captured image.
"""
self.rvec = rvec
self.tvec = tvec
self.matrix = matrix
self.dist = dist
self.name = name
self.size = size
def project(self, points3d):
"""Project a set of 3D points to 2D for this camera.
This function uses cv2.projectPoints to calculate 2D points from 3D points.
Args:
points3d: The 3D point coordinates in the world system. An `np.array`
with the shape of `(N1, N2, ..., Nm, 3)`.
Returns:
The 2D point coordinates in the image plane. An `np.array` with the
shape of `(N1, N2, ..., Nm, 2)`.
"""
shape = points3d.shape
points3d = points3d.reshape(-1, 1, 3)
points2d, _ = cv2.projectPoints(points3d, self.rvec, self.tvec,
self.matrix.astype('float64'),
self.dist.astype('float64'))
return points2d.reshape(*shape[:-1], 2)
class CameraGroup():
"""A simple multi camera class."""
def __init__(self, cams=None):
self.cams = cams
def project(self, points3d):
"""Project a set of 3D points to 2D for all cameras.
Args:
points3d: The 3D point coordinates in the world system. An `np.array`
with the shape of `(N1, N2, ..., Nm, 3)`.
Returns:
The 2D point coordinates in the image plane. An `np.array` with the
shape of `(#cams, N1, N2, ..., Nm, 2)`.
"""
points2d = np.stack([cam.project(points3d) for cam in self.cams])
return points2d
@classmethod
def load(cls, path):
"""Load data from json file."""
if '/cns/' in path:
with gfile.Open(path, 'r') as f:
data = json.load(f)
else:
with open(path, 'r') as f:
data = json.load(f)
keys = sorted(data.keys())
cams = []
for key in keys:
if key == 'metadata':
continue
else:
name = data[key]['name']
size = data[key]['size']
matrix = np.array(data[key]['matrix'])
dist = np.array(data[key]['distortions'])
rvec = np.array(data[key]['rotation'])
tvec = np.array(data[key]['translation'])
cams.append(Camera(rvec, tvec, matrix, dist, name, size))
return cls(cams)
|
class Company:
def __init__(self):
self.name = None
self.country_code = None
self.identifier = None
self.address = None
self.exists_since = None
self.exists_until = None
def __str__(self):
return 'Company {self.name} ({self.country_code}, {self.identifier})'.format(self=self)
|
# Harker Russell
#J Fausto
# Steve Sharp
def is_vowel(word):
word_lenght = len(word)
position = 0
while position < word_lenght:
if(word[position] == 'A') or (word[position] == 'E') or(word[position] == 'I') or (word[position] == 'O') or (word[position] == 'U') or (word[position] == 'a') or (word[position] == 'e') or (word[position] == 'i') or (word[position] == 'o') or (word[position] == 'u'):
return position
position = position + 1
return -1
def ammend_consonant(word):
index = is_vowel(word)
newWord = word[index:]
finalWord = newWord + word[0:index] +'ay'
return finalWord
inputString = input("Type some words (no punctuation, please!): ")
wordsList = inputString.split()
newWordsList = []
for n in range(len(wordsList)):
word = wordsList[n]
k = is_vowel(word)
if(k == 0):
word += 'ay'
else:
word = ammend_consonant(word)
newWordsList.append(word)
print(newWordsList)
|
from collections import namedtuple
Chest = namedtuple("Chest", ["open", "contains"])
class Problem:
def __init__(self, startkeys, chests)
self.keys = startkeys[:]
self.chests = chests[:]
def clone(self):
return Problem(self.keys, self.chests)
def open_chest(self, index):
self.keys.remove(self.chests[index].open)
self.keys.extend(self.chests[index].contains)
del self.chests[index]
def is_done(self):
return len(self.chests) == 0
def open_all(self):
"""If have N chests needing key type k and >=N keys of that type then open all chests"""
opened = True
while opened:
opened = False
keyshave = set( self.keys )
for key in keyshave:
numberhave = sum( k == key for k in self.keys )
numberneeded = sum( chest.open == key for chest in self.chests )
if numberhave >= numberneeded:
index = 0
while index < len(self.chests):
if self.chests[index].open == key:
self.open_chest(index) # Modifies self.chests !!
else:
index += 1
opened = True
break
def do_chain(self, length):
"""Returns True if there is a "chain" of `length`, which is also performed."""
num_cases = int(input())
for case in range(1, num_cases+1):
num_start_keys, num_chests = [int(x) for x in input().split()]
start_keys = [int(x) for x in input().split()]
chests = []
for _ in range(num_chests):
data = [int(x) for x in input().split()]
chests.append( Chest(data[0], data[2:]) )
print("Case #{}: {}".format(case, output))
|
class Ken:
def __init__(self, weights):
self.weights = weights[:]
self.weights.sort()
def play(self, other_weight):
"""Implements Ken's optimal strategy, based on `other_weight` being played by
Naomi. Returns weight which Ken will play."""
if other_weight > self.weights[-1]:
# Can't win so play smallest weight
ken_play = self.weights[0]
del self.weights[0]
else:
# Can win, so play least weight which wins
index = len(self.weights) - 1
while index > 0 and self.weights[index - 1] > other_weight:
index -= 1
ken_play = self.weights[index]
del self.weights[index]
return ken_play
def War(kweights, nweights):
"""Returns number of points Ken wins."""
k = Ken(kweights)
kwins = 0
for x in nweights:
ken_play = k.play(x)
if ken_play > x:
kwins += 1
return kwins
def DWar(kweights, nweights):
"""Return number of points Ken wins in deceitful war."""
n = nweights[:]
n.sort() # So n now increasing
k = Ken(kweights)
kwins = 0
while len(n) > 0:
# Can n cheat and win?
if n[-1] > k.weights[0]:
index = next( i for i, w in enumerate(n) if w > k.weights[0] )
k_play = k.play(k.weights[-1] + 1)
if k_play > n[index]:
raise Exception("Shouldn't happen")
del n[index]
else:
n_play = n.pop()
k_play = k.play(n_play)
if k_play < n_play:
raise Exception("Really shouldn't happen")
else:
kwins += 1
return kwins
num_cases = int(input())
for case in range(1, num_cases+1):
num_blocks = int(input())
nblocks = [float(x) for x in input().split()]
kblocks = [float(x) for x in input().split()]
print("Case #{}: {} {}".format(case, num_blocks - DWar(kblocks, nblocks),
num_blocks - War(kblocks, nblocks)))
|
import sys
radius = input("enter radius")
print(radius * radius * 3.14 )
|
def threeNumber(x,y,z):
addition = x + y+ z
print addition
if x==y==z:
print addition * addition * addition
threeNumber(2,2,2)
|
#!usr/bin/python
import re
match = re.search(r'iii','piiiiiig') => found, match.group() == "iii"
match = re.search(r'iii' , 'piiiiig') => not found, match == None
|
# -*- coding: utf-8 -*-
# @Time : 2020/10/7 15:32
# @Author : Evan
# @Email : [email protected]
# @File : train_regression_model.py
# @Software: PyCharm
# @Description: train a regression model
import numpy as np
from sklearn.linear_model import LinearRegression
import data_preparation
from sklearn.metrics import mean_squared_error
# train a linearRegression model
lin_reg = LinearRegression()
housing_prepared = data_preparation.housing_prepared
print("housing_prepared", housing_prepared)
housing_labels = data_preparation.housing_labels
print("housing_labels", housing_labels)
housing = data_preparation.housing
lin_reg.fit(housing_prepared, housing_labels)
# use the first 5 rows data to test this model
some_data = housing.iloc[:5]
print("some data")
print(some_data)
# use the first 5 rows of housing_labels as the test labels
some_labels = housing_labels.iloc[:5]
some_data_prepared = data_preparation.full_pipeline.transform(some_data)
# predict
print("Predictions:\t", lin_reg.predict(some_data_prepared))
# compare
print("Labels:\t\t", list(some_labels))
# use mean_squared_error method to test regression model's RMSE in all the data set
housing_predictions = lin_reg.predict(housing_prepared)
lin_mse = mean_squared_error(housing_labels, housing_predictions)
lin_rmse = np.sqrt(lin_mse)
print(lin_rmse)
|
#!/usr/bin/env python3
# Write a program that computes the GC% of a DNA sequence
# Format the output for 2 decimal places
# Use all three formatting methods
dna = 'ACAGAGCCAGCAGATATACAGCAGATACTAT' # feel free to change
gc = 0
for i in range(0, len(dna)):
if dna[i] == 'G' or dna[i] == 'C': gc += 1
else: gc += 0
gc_percent = gc / len(dna)
# formating options
print(round(gc_percent, 2))
print('%.2f' % gc_percent)
print('{:.2f}'.format(gc_percent))
print(f'{gc_percent:.2f}')
# print(f'{gc_percent}) I dont know
"""
0.42
0.42
0.42
"""
|
t = int(raw_input())
while t > 0:
a = int(raw_input())
while a >= 10:
suma = 0
while a != 0:
b = a % 10
a = a / 10
suma = suma + b
a = suma
print a
t= t -1
|
# Definir dos funciones que reciban una cantidad variable de argumentos: a) una función que
# puede llegar a recibir hasta 30 números como parámetros y debe devuelva la suma total de
# los mismos; b) otra función que reciba un número variable de parámetros nombrados (usar
# **kwargs), e imprima dichos parámetros. De antemano no se sabe cuáles de los siguientes tres
# posibles parámetros se reciben:
# nombre
# apellido
# sexo
def sumador(*num):
sum = 0
for n in num:
sum = sum + n
print("Suma: ",sum)
sumador(3,5)
sumador(4,5,6,7)
sumador(1,2,3,5,6)
def imprimir(**dato):
print("\nTipo de datos de argumento:",type(dato))
for key, value in dato.items():
print("{} es {}".format(key,value))
imprimir(Nombre="Sita", Apellido="Sharma", Edad=22, Telefono=1234567890)
imprimir(Nombre="John", Apellido="Wood", Email="[email protected]", Pais="Wakanda", Edad=25, Telefono=9876543210) |
# Dada una frase donde las palabras pueden estar repetidas e indistintamente en mayúsculas
# y minúsculas, imprimir una lista con todas las palabras sin repetir y en letra minúscula.
frase = """Si trabajás mucho CON computadoras, eventualmente encontrarás que te
gustaría automatizar alguna tarea. Por ejemplo, podrías desear realizar una
búsqueda y reemplazo en un gran número DE archivos de texto, o renombrar y
reorganizar un montón de archivos con fotos de una manera compleja. Tal vez quieras
escribir alguna pequeña base de datos personalizada, o una aplicación especializada
con interfaz gráfica, o UN juego simple."""
# convierto las palabras en minusculas y luego las separo por espacio en una lista eliminando los saltos de linea
lista_palabras = frase.lower().rsplit()
#convierto la lista de palabras en un conjunto para eliminar las palabras repetidas y agarro el conjunto y los transformo a lista
print(list(set(lista_palabras))) |
# Dada una lista de strings con el siguiente formato:
# tam = ['im1 4,14', 'im2 13,15', 'im3 6,34', 'im4 410,134']
# Donde im1, im2, etc son los nombres de las imágenes y la parte de números representa el valor
# de una coordenada (x, y). Se solicita que arme dos listas que contengan, nombre y luego una
# tupla de las coordenadas en formato de números. Una de las listas debe contener los datos en
# las cuales el valor de x es mayor o igual a un número ingresado por teclado y la otra, contendrá
# los datos de las imágenes cuyo valor de coordenada sea menor al número ingresado. Tener en
# cuenta que los datos de la lista original son strings y que los números de la lista generada deben
# ser enteros. Se espera que se muestre el siguiente resultado, si el dato ingresado por el teclado
# fuera 30:
# lista1 = ['im2', (33, 15), 'im4', (410, 134)]
# lista2 = ['im1', (4, 14), 'im3', (6, 34)]
# Nota: puede utilizar la función string.partition que permite separar un string y asignar a
# variables. Investigue su utilización.
# def crearLista():
# iter = int(input("ingrese la cantidad de imagenes a insertar\n"))
# lista = []
# for item in range(iter):
# name = input("ingrese nombre de image\n")
# coord = input("coordernada ej: 32,45\n")
# lista.append(name+' '+coord)
# return lista
# def imprimirResultado(aux = []):
# print("="*30)
# print(aux)
# print("="*30)
# lista = crearLista()
# imprimirResultado(lista)
tam = ['im1 4,14', 'im2 33,15', 'im3 6,34', 'im4 410,134']
numb = int(input("ingrese un numero\n"))
menor = []
mayor = []
for item in tam:
img,coord=item.split(' ')
x,separator,y = coord.partition(',')
tupla = (int(x),int(y))
if(int(x) > numb):
mayor.append(img)
mayor.append(tupla)
else:
menor.append(img)
menor.append(tupla)
print("a continuación se vana a imprimir las listas \n")
print("="*30)
print('lista 1 = {}'.format(mayor))
print('lista 2 = {}'.format(menor))
print("="*30+'\n') |
import math
CONSt= 17.31
d1 = float( input("ingrese la distancia_1 (en metros)\n"))
d2 = float(input("ingrese la distancia_2 (en metros)\n"))
f = float(input("ingrese la frecuencia en Mhz \n"))
R = 17.31 * math.sqrt( ((d1*d2)/(f*(d1+d2))) )
print("===="*30 )
print("el radio de fresnel es : {:.2f} mts".format(R) )
print("===="*30 )
enter = input("presion enter para finalizar \n") |
# -*- encoding:utf-8 -*-
# 循环
flag = True
count = 1
'''
while flag:
print(count)
count = count + 1
if count > 100:
flag = False
while count <= 100:
print(count)
count = count + 1
'''
s = 'aksldfj'
for i in s:
print(i)
s = 'fsadf苍井空fklsadf'
if '苍井空' in s:
print('非法字符') |
# 无序列表 不会有重复的元素
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6}
print(set1 - set2) # 求差集 {1,2,3}
print(set2 - set1) # {6}
print(set1 & set2) # 求交集 {4,5}
print(set1 | set2) # 求合集 {1,2,3,4,5}
# 定义一个空集合
set3 = set()
print(type(set3), len(set3)) # 'set' 0 |
# 装饰器进阶
# 复习
def wrapper(f):
def inner(*args, **kwargs):
print('被装饰的函数执行之前做的事')
result = f(*args, **kwargs)
print('被装饰的函数执行之后做的事')
return result,1 # 这个才是func1的真正返回值
return inner
@wrapper
def func1(*args, **kwargs):
print(args, kwargs)
return 111 # 这个不是func1的返回值
result = func1(1, a=2)
|
# 函数
def greet_user():
'''简单的问候语'''
print('hello python')
greet_user()
def greet(msg):
print(msg)
greet('hello python')
# 位置实参
def describe_pet(animal_type, pet_name):
'''显示宠物信息'''
print('\nI have a ' + animal_type + '.')
print('My ' + animal_type + '"s name is' + pet_name.title() + '.')
describe_pet('hamster', 'harry')
# 关键字实参
def describe_pet1(animal_type, pet_name):
'''显示宠物信息'''
print('\nI have a ' + animal_type + '.')
print('My ' + animal_type + '"s name is' + pet_name.title() + '.')
describe_pet1(animal_type='hamster', pet_name='harry')
# 默认值 这里注意形参的顺序,先是位置形参,然后是默认形参)
def describe_pet2(animal_type, pet_name='john'):
'''显示宠物信息'''
print('\nI have a ' + animal_type + '.')
print('My ' + animal_type + '"s name is' + pet_name.title() + '.')
describe_pet2('hamster')
# 传递列表
def greet_users(names):
for name in names:
print(name)
greet_users(['lee', 'zhang'])
# 在函数中修改列表
list = [1, 2, 3]
def changeList(list):
if list:
list.pop()
return list
while list:
print(list)
print('del is not completed')
changeList(list)
# 传递任意数量的实参
def anything(*item):
print(item)
anything(1)
anything(1, 24)
def anything1(name, *item):
print(name)
print(item)
anything1('lee', '1', 'zhang')
# 使用任意数量的关键字实参
def build_profile(first, last, **user_info):
'''创建一个字典,其中包含我们知道的有关用户的一切'''
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein',
location="princeton")
print(user_profile)
|
# 只有内置方法里面有__iter__方法的数据类型才可以被for循环
list = []
print(list.__iter__())
# 查看list的所有方法
# print(dir([]))
# 获取list1的迭代器
list1 = [1]
list1.__iter__() # 得到迭代器, 迭代器才有__next__方法
print(list1.__iter__().__next__()) # 获取list1的下一个, 和JS的迭代器类似
# 只要含有__iter__方法的都是可迭代的 --可迭代协议
# 内部含有__next__ 和__iter__方法的就是迭代器
# example
from collections.abc import Iterable
from collections.abc import Iterator
print(isinstance([], Iterable)) # True []是一个可迭代数据类型
print(isinstance([], Iterator)) # False []不是迭代器
# 迭代器的好处:
# 遍历取值
# 节省内存空间
# 迭代器并不会在内存中在占用一大块内存,而是随着循环每次生成一个,不是一次性生成
# practice 模拟for循环
l = [1, 2, 3, 4]
iterator = l.__iter__()
while True:
print(iterator.__next__())
|
# 类型判断
isinstance('1', str) # True
isinstance('1', (int, str, float)) # True 如果是元祖中其中一种,返回True
# 身份运算符 is
# 关系运算符 ==
# isinstance
# 最好使用isinstance , 可以判断子类的类型
|
# 类基础
# 创建和使用
#### 创建类
class Dog:
'''一次模拟小狗的简单尝试'''
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name.title() + 'is now sitting!')
def roll_over(self):
print(self.name.title() + ' rolled over!')
#### 创建实例
my_dog = Dog('willie', 6)
print(my_dog.name.title() + '.')
print(str(my_dog.age) + ' years old.')
my_dog.sit()
my_dog.roll_over()
#### 使用类和实例
class Car:
'''一次模拟汽车的简单尝试'''
def __init__(self, make, model, year):
'''初始化汽车属性'''
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
# 给属性指定默认值
class Car1:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 这里设置了默认值,形参里就不需要传入了
def get_descriptive_name(self):
pass
def read_odometer(self):
print(str(self.odometer_reading) + ' miles on it.')
my_new_car1 = Car1('audi', 'a4', '2016')
print(my_new_car1.read_odometer())
# 修改属性的值(修改的是实例的属性)
my_new_car1.odometer_reading = 23
my_new_car1.read_odometer() # 23
my_new_car11 = Car1('bmw', 'm3', 2018)
my_new_car11.read_odometer() # 0
# 通过方法修改属性的值
class Car2:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 这里设置了默认值,形参里就不需要传入了
def get_descriptive_name(self):
pass
def read_odometer(self):
print(str(self.odometer_reading) + ' miles on it.')
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print('You can not roll back an odometer!')
my_new_car2 = Car2('audi', 'a4', 2018)
print(my_new_car2.odometer_reading) # 0
my_new_car2.update_odometer(10)
print(my_new_car2.odometer_reading) # 10
# 通过方法对属性的值进行递增
class Car3:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 这里设置了默认值,形参里就不需要传入了
def get_descriptive_name(self):
pass
def read_odometer(self):
print(str(self.odometer_reading) + ' miles on it.')
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print('You can not roll back an odometer!')
def increment_odometer(self, miles):
self.odometer_reading += miles
my_new_car3 = Car3(' fararri', '458', 2019)
my_new_car3.increment_odometer(100)
print(my_new_car3.odometer_reading) # 100
my_new_car3.increment_odometer(100)
print(my_new_car3.odometer_reading) # 200
|
# -*- coding: utf-8 -*-
"""
Created on Sat May 14 20:58:35 2016
@author: Sofia
"""
from tkinter import* #Import necessary libraries
from tkinter.ttk import*
import math
from tkinter import messagebox
import numpy as np
win1=Tk() #Create first window which takes user's input
win1.title('GRAPHING CALCULATOR PROGRAM')
frame1=Frame(win1).grid(row=0, column=0) #('Setting up the Grid')
frame2=Frame(win1).grid(row=1, column=0) #('Function Options')
frame3=Frame(win1).grid(row=2, column=0) #('Table of Values')
#Inputted values from entry fields are all float values, combobox is a string value and checkbutton is integer.
Xmin=DoubleVar()
Xmax=DoubleVar()
Xscl=DoubleVar()
Ymin=DoubleVar()
Ymax=DoubleVar()
Yscl=DoubleVar()
sel=StringVar()
ab=IntVar()
a_var=DoubleVar()
b_var=DoubleVar()
c_var=DoubleVar()
d_var=DoubleVar()
st_x=DoubleVar()
end_x=DoubleVar()
step=DoubleVar()
lin='f(x)=ax+b'
quad='f(x)=ax^2+bx+c'
cub='f(x)=ax^3+bx^2+cx+d'
sin='f(x)=a*sin[b(x-d)]+c'
cos='f(x)=a*cos[b(x-d)]+c'
tan='f(x)=a*tan[b(x-d)]+c'
#list of possible function choices is created
functions=[lin, quad, cub, sin, cos, tan]
#function which calculates and draws graph and outputs table of values
def funs():
global a
global b
global c
global d
global x
global x_range
try:
a=float(a_var.get()) #gets a,b,c,d values from entry fields and combobox celection
b=float(b_var.get())
c=float(c_var.get())
d=float(d_var.get())
selection=sel.get()
except:
messagebox.showwarning("Error", "Invalid input") #if entries are not float or integer values, a message box lets the user know
coords=[]
y_list=[]
x_range=np.linspace(float(xmin), float(xmax), 10000)
txt=Text(win2, wrap=WORD, height=43, width=45) #text box which shows the table of values, intercepts and max/min values
txt.grid(row=0, column=1)
txt.insert(0., '\n\n'+selection+'\n\nX , f(x)\n\n\n')
for x in x_range: #calculates f(x) depending on the function chosen
if selection==functions[0]:
y=(a*x)+b
elif selection==functions[1]:
y=(a*(x**2))+(b*x)+c
elif selection==functions[2]:
y=(a*(x**3))+(b*(x**2))+(c*x)+d
elif selection==functions[3]:
y=a*math.cos(b*(x-d))+c
elif selection==functions[4]:
y=a*math.sin(b*(x-d))+c
elif selection==functions[5]:
y=a*math.tan(b*(x-d))+c
if int(ab.get())==1: #absolute option for tan function
y=abs(y)
if y>=ymin and y<=ymax:
coords.append((x0+(x*x_unit),y0-(y*y_unit)))
y_list.append(y)
elif len(coords)>1:
canvas.create_line(coords, smooth=1, arrow=BOTH)
coords.clear()
if selection not in functions:
messagebox.showwarning("Error", "Invalid function selection")
#inserts x and f(x) for table of values, intercepts and min/max values.
txt.insert(END, str(x)+' , '+str(y)+'\n')
if round(x,2)==0:
txt.insert(0., '\nY-intercept: '+str(y))
if round(y,2)==0:
txt.insert(0., '\nX-intercept: '+str(x))
txt.insert(0., "\nY max: "+str(max(y_list)))
txt.insert(0., "\nY min: "+str(min(y_list)))
if len(coords)>1:
canvas.create_line(coords, smooth=1, arrow=BOTH)
mainloop()
#main function, summoned by the 'submit' button
def main():
global win2
global xmin
global xmax
global xscl
global ymin
global ymax
global yscl
try:
xmin=Xmin.get()
xmax=Xmax.get()
xscl=Xscl.get()
ymin=Ymin.get()
ymax=Ymax.get()
yscl=Yscl.get()
except:
messagebox.showwarning("Error", "Invalid input")
#X and Y min always have to be negative
#X and Y max always have to be positive
#X and Y scl always have to be positive
try:
if xmin>=0:
xmin=-1*xmin
if xmax<=0:
xmax=-1*xmax
if xscl<=0:
xscl=-1*xscl
if ymin>=0:
ymin=-1*ymin
if ymax<=0:
ymax=-1*ymax
if yscl<=0:
yscl=-1*yscl
except:
messagebox.showwarning("Error", "Invalid input")
try:
global x_unit
global y_unit
global canvas
global x0
global y0
x_unit=900/(xmax-xmin)
y_unit=600/(ymax-ymin)
win2=Tk() #new graph window is created
win2.title("GRAPH AND TABLE OF VALUES")
canvas=Canvas(win2, width=1000, height=700, bg='light yellow') #graph is drawn on the canvas
canvas.grid(row=0, column=0)
y0=650+(y_unit*ymin) #ymin is negative
x0=50-(x_unit*xmin) #this brings the (0,0) coordinates from top left to the origin of the graph
canvas.create_line(50, y0, 950, y0, fill='blue', arrow=BOTH) #x axis is drawn
canvas.create_line(x0, 50, x0, 650, fill='blue', arrow=BOTH) #y axis is drawn
for i in range(int(xmin*x_unit), int(xmax*x_unit)+int(xscl*x_unit), int(xscl*x_unit)):
canvas.create_text(x0+i, y0+10, text=str(round(i/x_unit, 3)), fill='dark blue') #x axis is labeled, rounded to 3 decimal places
for i in range(0, int(ymax*y_unit)-int(ymin*y_unit) +int(yscl*y_unit), int(yscl*y_unit)):
canvas.create_text(70-int(x_unit*xmin), 650-i, text=str(round(i/y_unit+ymin, 3)), fill='dark blue') #y axis is labeled, rounded to 3 decimal places
except ValueError:
messagebox.showwarning("Error", "Invalid input")
funs() #function program is called
#Setting up the grid
sL1=ttk.Style()
sL1.configure('Kim.TButton', foreground='maroon')
#all entry fields and labels are created, also combobox and checkbutton
blank1=Label(frame1, text=' ').grid(column=0, row=0, columnspan=8)
labX1=Label(frame1, text='Xmin: ', style='Kim.TButton').grid(column=1, row=1)
entX1=Entry(frame1, width=10, textvar=Xmin).grid(column=2, row=1)
labX2=Label(frame1, text='Xmax: ', style='Kim.TButton').grid(column=3, row=1)
entX2=Entry(frame1, width=10, textvar=Xmax).grid(column=4, row=1)
labX3=Label(frame1, text='Xscl: ', style='Kim.TButton').grid(column=5, row=1)
entX3=Entry(frame1, width=10, textvar=Xscl).grid(column=6, row=1)
labY1=Label(frame1, text='Ymin: ', style='Kim.TButton').grid(column=1, row=2)
entY1=Entry(frame1, width=10, textvar=Ymin).grid(column=2, row=2)
labY2=Label(frame1, text='Ymax: ', style='Kim.TButton').grid(column=3, row=2)
entY2=Entry(frame1, width=10, textvar=Ymax).grid(column=4, row=2)
labY3=Label(frame1, text='Yscl: ', style='Kim.TButton').grid(column=5, row=2)
entY3=Entry(frame1, width=10, textvar=Yscl).grid(column=6, row=2)
blank2=Label(frame1, text=' ').grid(row=3, column=0, columnspan=8)
#Function options
global entA
global entB
global entC
global entD
sel_fun=Combobox(frame2, textvariable=sel, values=functions).grid(column=0, row=4, columnspan=8)
sel.set(functions[0])
sCh=ttk.Style()
sCh.configure("Red.TCheckbutton", foreground="orange")
absolute=Checkbutton(frame2, text='Absolute', variable=ab, style='Red.TCheckbutton').grid(column=0, row=5, columnspan=8)
blank3=Label(frame2, text=' ').grid(row=6, column=0, columnspan=8)
labA=Label(frame2, text=' '*10+'a', width=10).grid(column=0, row=7)
entA=Entry(frame2, width=10, textvar=a_var).grid(column=1, row=7)
labB=Label(frame2, text='b').grid(column=2, row=7)
entB=Entry(frame2, width=10, textvar=b_var).grid(column=3, row=7)
labC=Label(frame2, text='c').grid(column=4, row=7)
entC=Entry(frame2, width=10, textvar=c_var).grid(column=5, row=7)
labD=Label(frame2, text='d').grid(column=6, row=7)
entD=Entry(frame2, width=10, textvar=d_var).grid(column=7, row=7)
blank4=Label(frame2, text=' ').grid(row=8, column=0, columnspan=8)
sB=ttk.Style()
sB.configure('green/black.TButton', foreground='green', background='red', relief=RAISED)
submit=Button(frame3, text='Submit', command=main, style='green/black.TButton')
submit.grid(column=0, row=9, columnspan=8)
blank5=Label(frame2, text=' ').grid(row=10, column=0, columnspan=8)
blank6=Label(win1, text=' ', width=2).grid(row=0, column=8, rowspan=8)
mainloop() |
def alphabet_position(letter):
"""Receives a letter (that is, a string with only one alphabetic character) and returns the 0-based
numerical position of that letter within the alphabet. Example: a -> 0, A -> 0"""
return ord(letter.upper()) - ord("A")
def rotate_character(char, rot):
"""Receives a character char (that is, a string of length 1), and an integer rot. Return a new string of
length 1, the result of rotating char by rot number of places to the right. """
if not(char.isalpha()):
return char
rotated_char = chr(ord("A") + (alphabet_position(char) + rot) % 26)
if not char.isupper():
return rotated_char.lower()
return rotated_char
def encrypt(text, rot):
"""Receives as input a string and an integer. Returns the result of rotating each letter in the text
by rot places to the right."""
result = ""
for letter in text:
result += rotate_character(letter, rot)
return result
def main():
msg = input("Type a message: ")
rot = int(input("Rotate by:"))
print(encrypt(msg, rot))
if __name__ == "__main__":
main()
|
#! -*- coding: utf-8 -*-
# 创建一个Thread的实例,传给它一个函数
import threading
from time import sleep, time
loops = [4, 2]
def loop(nloop, nsec, lock):
print('start loop %s at: %s' % (nloop, time()))
sleep(nsec)
print('loop %s done at: %s' % (nloop, time()))
# 每个线程都会被分配一个事先已经获得的锁,在 sleep()的时间到了之后就释放 相应的锁以通知主线程,这个线程已经结束了。
def main():
print('starting at:', time())
threads = []
nloops = range(len(loops))
for i in nloops:
t = threading.Thread(target=loop, args=(i, loops[i]))
threads.append(t)
for i in nloops:
# start threads
threads[i].start()
for i in nloops:
# wait for all
# join()会等到线程结束,或者在给了 timeout 参数的时候,等到超时为止。
# 使用 join()看上去 会比使用一个等待锁释放的无限循环清楚一些(这种锁也被称为"spinlock")
threads[i].join() # threads to finish
print('all DONE at:', time())
if __name__ == '__main__':
main() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 单线程telnet
import telnetlib
import string
import sys,os
# 调用telnet,输出结果True/False+字符串
def check_port(ip,port):
address = 'telnet ' + ip + ' '+ port
try:
tn = telnetlib.Telnet(ip, port, timeout=10)
result = (True,address + ' ---Passed\n')
except:
result = (False,address + ' ---Failed\n')
finally:
print("check_port: ",result)
return result
# 分析ip文件,输出ip+端口的list
def ana_ip(iplist):
address_list=[]
try:
f=open(iplist)
for line in f:
ip=line.split()[0]
port_list=line.split()[-1].split('/')
for port in port_list:
address_list.append((ip,port))
except:
print("ana_ip error!")
finally:
# print("ana_ip\n",address_list)
return address_list
def main():
result_list=[]
address_list=ana_ip('ip_biglist')
for i in address_list:
result=check_port(i[0],i[1])
result_list.append(result)
# # 写log文件
# if ( not os.path.exists("ip_result")):
# os.mknod("ip_result")
try:
f=open('ip_result','w')
# 记录telnet失败地址
f.write('\n---Telnet Failed--------------------------\n')
for line in result_list:
if line[0] == False:
f.write(line[1])
# 记录telnet通过地址
f.write('---Telnet Passed--------------------------\n')
for line in result_list:
if line[0]==True:
f.write(line[1])
except:
print("main error!")
finally:
f.close()
if __name__ == "__main__":
main() |
import re
#The following function calculate the normalized counts.
def normalized_count(tWord,tFind):
count = (tFind / tWord) * 100
return count
#The following sets up variables and lists
pronouns = ["I", "you", "he", "she", "it", "we", "they", "me", "him", "her", "us", "them"]
modals = ["must", "shall", "will", "should", "would", "can", "could", "may", "might"]
num_of_word_1 = 0
num_of_word_2 = 0
num_of_findings_1 = 0
num_of_findings_2 = 0
#The following prompts ask for two texts
text_1 = input("Please paste the first text here:\n")
text_2 = input("Please paste the second text here:\n")
#Split the texts
text_1 = text_1.lower().split()
text_2 = text_2.lower().split()
#Find the prnouns, contraction, and modals in the first text
#print("text 1 begins...")
for word_1 in text_1:
word_1 = word_1.strip()
num_of_word_1 += 1
if re.findall(r"([\'\’][msdt|ll|ve|re|all])", word_1) or word_1 in pronouns or word_1 in modals:
#print(word_1)
num_of_findings_1 += 1
# Find the prnouns, contraction, and modals in the second text
#print("\ntext 2 begins...")
for word_2 in text_2:
word_2 = word_2.strip()
num_of_word_2 += 1
if re.findall(r"([\'\’][msdt|ll|ve|re|all])", word_2) or word_2 in pronouns or word_2 in modals:
#print(word_2)
num_of_findings_2 += 1
#The following prints various results
print("The total number of words in the first text: " + str(num_of_word_1))
print("The total number of words in the second text: " + str(num_of_word_2))
print("The total number of findings in the first text: " + str(num_of_findings_1))
print("The total number of findings in the second text: " + str(num_of_findings_2))
#The following uses the normalized_count function
first_text = normalized_count(num_of_word_1,num_of_findings_1)
second_text = normalized_count(num_of_word_2,num_of_findings_2)
#Print out the normalized counts for each text
print("The normalized count for the first text: " + str(round(first_text,2)))
print("The normalized count for the second text: " + str(round(second_text,2)))
'''
------------------------Report----------------------------
Actual findings that are correct for text 1 = 44
Actual findings that are correct for text 2 = 35
----------------------------------------------------------
| Precision | recall |
----------------------------------------------------------
1st text | 44/52 = 85% | 44/44 = 100% |
2nd text | 35/48 = 73% | 35/35 = 100% |
----------------------------------------------------------
''' |
#%%
s=input('請輸入一句英文句子 ')
s1=s.title()
s2=s.capitalize()
s3=s.upper()
s4=s.swapcase()
a=s1.split(' ')
print(a[::-1])
print(s2)
print(s3)
print(s4)
# s5=s.replace([0],'pig')
# print(s5)
#%%
全班學生 = set(['john','mary','tina','fiona','claire','eva','ben','bill','bert'])
英文及格 = set(['john','mary','fiona','claire','ben','bill'])
數學及格 = set(['mary','fiona','claire','eva','ben'])
print(英文及格&數學及格)
print(全班學生-數學及格) #全^數
print(英文及格&(全班學生-數學及格)) #英-數
#%%
a='「紅豆生南國,春來發幾枝?願君多采擷,此物最相思。」<作者:王維>'
b='「春眠不覺曉,處處聞啼鳥。夜來風雨聲,花落知多少。」<作者:孟浩然>'
aa=set(a)
bb=set(b)
aa.remove(',')
aa.remove('?')
aa.remove('。')
aa.remove('「')
aa.remove('」')
aa.remove(':')
aa.remove('<')
aa.remove('>')
print(aa)
bb.remove(',')
bb.remove('。')
bb.remove('「')
bb.remove('」')
bb.remove(':')
bb.remove('<')
bb.remove('>')
print(bb)
print(aa&bb)
#%%
S1=str(input('請輸入第一首詩 '))
S2=str(input('請輸入第二首詩 '))
ss1=set(S1)
ss2=set(S2)
ss1.remove(',')
ss1.remove('?')
ss1.remove('。')
ss1.remove('「')
ss1.remove('」')
ss1.remove(':')
ss1.remove('<')
ss1.remove('>')
ss2.remove(',')
ss2.remove('。')
ss2.remove('「')
ss2.remove('」')
ss2.remove(':')
ss2.remove('<')
ss2.remove('>')
print(ss1&ss2)
#%%
n=[]
e=[]
name=input('請輸入姓名? ')
n.append(name) #append是針對n的set 所以是n.append ()內中是新增的資料name
email=input('請輸入email? ')
e.append(email)
name=input('請輸入姓名? ')
n.append(name)
email=input('請輸入email? ')
e.append(email)
name=input('請輸入姓名? ')
n.append(name)
email=input('請輸入email? ')
e.append(email)
serch={'查詢姓名':n,'查詢信箱':e} #再設一個新的set
q=input('請輸入要查詢信箱的姓名?')
姓名=n.index(q)
print(serch['查詢信箱'][姓名])
#姓名 成績 學號
#%%
number=[]
name=[]
score=[]
a=input('輸入學號?')
number.append(a)
b=input('輸入姓名?')
name.append(b)
c=input('輸入成績?')
score.append(c)
a=input('輸入學號?')
number.append(a)
b=input('輸入姓名?')
name.append(b)
c=input('輸入成績?')
score.append(c)
a=input('輸入學號?')
number.append(a)
b=input('輸入姓名?')
name.append(b)
c=input('輸入成績?')
score.append(c)
final={'aa':number,'bb':name,'cc':score}
q=input('請輸入學生學號進行查詢')
serch=number.index(q) #q是number這個set裡面的index序列幾
print(final['bb'][serch],final['cc'][serch])
for
# pass
# def __init__(self,a,b,c):
# self.a = a
# self.b = b
# self.c = c
|
import os
import pandas as pd
def csv_to_df(file_name, csv_data):
'''
Salva um arquivo .csv e retorna um dataframe
Params:
file_name (str): nome do arquivo .csv
csv_data (str): dados no farmato de csv
Returns:
(DataFrame): objeto DataFrame com os dados
'''
df = None
# salvar o arquivo
with open(file_name, 'w', encoding='utf-8') as f:
try:
f.write(csv_data.decode('utf-8'))
except UnicodeDecodeError:
f.write(csv_data.decode('latin-1'))
# ler como dataframe
df = pd.read_csv(file_name, sep=';')
# remover arquivo
os.remove(file_name)
return df
|
def divisors():
'''
this function prints all the divisors of a number
:return:
'''
num = int(input("enter a number"))
list = []
for i in range(2,num):
if(num % i == 0):
list.append(i)
print list
if __name__ == '__main__':
divisors()
|
# -*- coding: utf-8 -*-
line = '+++++++++++++++++++++++++++++++++++++++'
laptop = ['sony', 'ibm', 'hp', 'dell', 'apple']
print(len(laptop), laptop)
print('I like %s thinkpad! :)' % laptop[1])
print('But I don\'t like %s xps :(' % laptop[-2])
print(line)
laptop.append('compaq') # append one element to last position
laptop.insert(3, 'lenovo') # insert to the designated position
print(laptop)
laptop.pop() # delete the last one
print(laptop)
laptop.pop(3) # delete the designated position
print(laptop)
laptop[0] = 'asus' # replace [0] with new value
print(laptop)
print(line)
bag = ['iphone', 7, True, laptop] # a list can store data of different types
print(len(bag), bag)
print('%s%d is a product from %s: %s' % (bag[0], bag[1], bag[3][-1], bag[2])) # bag是一个二维数组
print(line)
game = ('doom', 'diablo', 23, laptop)
print(game)
game[3][0] = 'compaq'
print(game)
one = (1)
specialone = (1,) # , is mandatory to define a tuple with element 1
print(one, 'is not a tuple.', specialone, 'is a tuple')
|
box = '''
--------------
| example |
--------------
'''
print(box)
result = 1024*768
# \n\t are string, \n means a new line, \t means a table, \a is a beep sound
print("1024 * 768 =\n\t", -result, '\n\a')
# print a \, a new line, and a \
print('\\\n\\', '\n')
# use r" to ignore \
print(r'\\\n\\')
print()
# \r means an 'return' at current line
print('abc\rdef')
print('''line1
line2
line3''')
|
# -*- coding: utf-8 -*-
line = '#################'
# %s字符 %f浮点数 %d整数 %x十六进制整数
print('Hello, %s' % 'world')
print('Hello, %s is %s' % ('world', 'ok'))
# 1000.99被%d取整, %.2f指定小数点位数
print('Hello %s, you have $%d and $%.2f bonus!' % ('Leo', 99.12345, 99.12845))
print(line)
# the 5 below means %d starting from 5th (4 spaces before)
print('%5d+%d' % (3, 62))
print(line)
a = 72
b = 85
c = (b - a) / a * 100
print('the improvement is %.1f%s ' % (c, '%'))
print('the improvement is %.1f%%' % c) # %% means the 2nd % is string
def info(name, *, gender, city='beijing', age):
print('Personal Info')
print('----------------')
print(' Name: %s' % name)
print('%9s %s' % ('Gender:', gender))
print(' City: %s' % city)
print(' Age: %s' % age)
print()
info('bob', gender='male', age=20)
args = ('ag', 'be', 'cs')
print('%s, %s!' % ('hello', ','.join(args)))
print('%s, %s!' % ('hello', ', '.join(args)))
|
class User: # here's what we have so far
def __init__(self, name, email):
self.name = name
self.email = email
def printUser(self):
print(self.name)
class BankAccount(User):
def __init__ (self, name, email, acc_name='Checking'):
User.__init__(self, name, email)
self.int_rate = 0.01
self.balance = 50
self.acc_name = acc_name
print(f'Name: {self.name}, Account Type: {self.acc_name}, Balance: ${self.balance}')
def deposit(self, amount):
self.balance += amount
self.display_account_info()
return self
def withdrawal(self, amount):
if self.balance >= amount:
self.balance -= amount
self.display_account_info()
else:
self.balance -= 5
print("Sorry you have insufficient funds and will be charged $5")
self.display_account_info()
return self
def display_account_info(self):
print(f"Name: {self.name}, Account Type: {self.acc_name}, Balance: ${self.balance}")
return self
def yield_interest(self):
interest = self.balance * self.int_rate
print(f"Interest: ${interest}")
return self
# Test to see if the Class Inheritance is set up correctly
print(issubclass(BankAccount, User))
# Set up a new User
guido = User('Guido', '[email protected]')
# Set up two new Accounts using the properties from User class
guidoCheck = BankAccount('Guido', '[email protected]')
guidoSave = BankAccount('Guido', '[email protected]', acc_name = 'Savings')
# Test out methods
guidoSave.deposit(50)
guidoCheck.withdrawal(25)
guidoSave.display_account_info()
guidoSave.yield_interest()
guidoSave.withdrawal(80)
# Chained
guidoSave.deposit(50).display_account_info().yield_interest().withdrawal(80)
|
#import Python test framework
import unittest
#import libraries
import math
# our 'unit'
# this is what we are running our test on
def reverseList(revArray):
loopCount = math.floor(len(revArray)/2)
for i in range(loopCount):
revArray[i], revArray[-1-i] = revArray[-1-i], revArray[i]
return revArray
# our "unit tests"
# initialized by creating a class that inherits from unittest.TestCase
class reverseListTests(unittest.TestCase):
def testPositiveInt(self):
self.assertEqual(reverseList([1,2,3,4]), [4,3,2,1])
def testNegativeInt(self):
self.assertEqual(reverseList([-1,-2,-3,-4]), [-4,-3,-2,-1])
def testMixInt(self):
self.assertEqual(reverseList([-1,0,2,3]), [3,2,0,-1])
def setUp(self):
# add the setUp tasks
print("running setUp")
# any task you want run after the tests are executed, put them in the tearDown method
def tearDown(self):
# add the tearDown tasks
print("running tearDown tasks")
def isPalindrome(paliString):
if type(paliString) != str:
print(f'Sorry, "{paliString}" is not a string!')
elif type(paliString) == str and len(paliString.split()) > 1:
print(f'Sorry, "{paliString}" is more than 1 word!')
else:
looper = math.floor(len(paliString)/2)
for i in range(looper):
if paliString[i] != paliString[-1-i]:
return False
else:
return True
class isPalindromeTests(unittest.TestCase):
def testTrue(self):
self.assertTrue(isPalindrome('racecar'))
self.assertTrue(isPalindrome('kayak'))
def testFalse(self):
self.assertFalse(isPalindrome('Was it a cat I saw'))
self.assertFalse(isPalindrome('racing'))
def testInt(self):
self.assertFalse(isPalindrome(1))
def testList(self):
self.assertFalse(isPalindrome([1,2,3]))
def testDict(self):
self.assertFalse(isPalindrome({1,2,3}))
def setUp(self):
print("running setUp")
# any task you want run after the tests are executed, put them in the tearDown method
def tearDown(self):
# add the tearDown tasks
print("running tearDown tasks")
def coins(money):
if money == 0:
print("That is the exact amount so there is no change!")
return False
elif money < 0:
balance = money * -1
print(f'Ummm, well this is awkward - you still owe me 0.{balance} cents ...')
return False
else:
newList = []
if money % 25 == 0:
q = math.floor(money / 25)
newList.extend((q,0,0,0))
else:
q = math.floor(money / 25)
newList.append(q)
money %= 25
if money % 10 == 0:
d = math.floor(money / 10)
newList.extend((d,0,0))
else:
d = math.floor(money / 10)
newList.append(d)
money %= 10
if money % 5 == 0:
n = math.floor(money / 5)
newList.extend((n,0))
else:
n = math.floor(money / 5)
newList.append(n)
money %= 5
newList.append(money)
return newList
class coinsTest(unittest.TestCase):
def testCalculations(self):
self.assertEqual(coins(87), [3,1,0,2])
self.assertEqual(coins(30), [1,0,1,0])
self.assertEqual(coins(1267), [50,1,1,2])
self.assertEqual(coins(20), [0,2,0,0])
self.assertEqual(coins(1), [0,0,0,1])
def testExceptions(self):
self.assertFalse(coins(0))
self.assertFalse(coins(-43))
def setUp(self):
print("running setUp")
# any task you want run after the tests are executed, put them in the tearDown method
def tearDown(self):
# add the tearDown tasks
print("running tearDown tasks")
def factorial(max):
if max == 0:
fact = 1
elif max < 0:
print('You cannot have a negative factorial')
return False
else:
fact = max
for i in range(1,max):
fact *= i
return fact
class factorialTest(unittest.TestCase):
def testTrue(self):
self.assertEqual(factorial(5), 120)
self.assertEqual(factorial(10), 3628800)
def testZero(self):
self.assertEqual(factorial(0), 1)
def testNegativeInt(self):
self.assertFalse(factorial(-5))
def setUp(self):
print("running setUp")
# any task you want run after the tests are executed, put them in the tearDown method
def tearDown(self):
# add the tearDown tasks
print("running tearDown tasks")
def fibonacci(n):
fibList = [0,1]
if n == 0:
return 0
elif n < 0:
print('I need a positive number!')
return False
else:
for i in range(1,n-1):
fibList.append(fibList[i] + fibList[i-1])
return fibList[-1]
# Using recursion
# def fibonacci(first, second):
# print(first)
# if first > 100:
# return first
# return fibonacci(first + second, first)
class fibonacciTest(unittest.TestCase):
def testCorrect(self):
self.assertEquals(fibonacci(5), 3)
self.assertEquals(fibonacci(9), 21)
self.assertEquals(fibonacci(20), 4181)
self.assertEquals(fibonacci(0), 0)
def testIncorrect(self):
self.assertNotEqual(fibonacci(4), 3)
self.assertNotEqual(fibonacci(8), 21)
self.assertNotEqual(fibonacci(19), 4181)
self.assertNotEqual(fibonacci(7), 0)
def testExceptions(self):
self.assertFalse(fibonacci(-5))
def setUp(self):
print("running setUp")
def tearDown(self):
print("running tearDown tasks")
if __name__ == '__main__':
unittest.main() # this runs our tests
|
i=1
while i<=1000:
if 3%i==0:
print("nav")
if 7%i==0:
print("gurukul")
if 21%i==0:
print("navgurukul")
else:
print(i)
i=i+1
|
from enum import Enum
class Suits(Enum):
DIAMONDS = unichr(0x2666)
HEARTS = unichr(0x2665)
CLUBS = unichr(0x2663)
SPADES = unichr(0x2660)
class Card(object):
def __init__(self, suit, number):
self.suit = suit.value
self.number = number
self.val = self.get_val_from_number()
def get_val_from_number(self):
face_cards = {
'J': 11,
'Q': 12,
'K': 13,
'A': 14
}
if self.number == '2':
return int(self.number) + 13
elif self.number <= '9' or self.number == '10':
return int(self.number)
elif self.number in face_cards:
return face_cards[self.number]
else:
return ''
def get_ascii_front(self):
# Generate top, blank middle and bottom rows
top = unichr(0x250C)
bottom = unichr(0x2514)
empty_mid = left = suit_left = middle = face = twomid = right = suit_right = unichr(0x2502)
for i in range(0, 19):
top += unichr(0x2500)
bottom += unichr(0x2500)
empty_mid += u' '
top += unichr(0x2510)
bottom += unichr(0x2518)
empty_mid += unichr(0x2502)
# Generate Single Middle and Face Cards
for i in range(0, 9):
middle += u' '
face += u' '
middle += u'{}'.format(self.suit)
face += u'{}'.format(self.number)
for i in range(0, 9):
middle += u' '
face += u' '
middle += unichr(0x2502)
face += unichr(0x2502)
# Generate Double Middle Symbol
twomid += u' '
twomid += u'{}'.format(self.suit)
for i in range(0, 13):
twomid += u' '
twomid += u'{}'.format(self.suit)
twomid += u' '
twomid += unichr(0x2502)
# Generate card-specific lines
left += u'{}'.format(self.number)
suit_left += u'{}'.format(self.suit)
if self.number == '10':
for i in range(0, 17):
left += u' '
right += u' '
else:
for i in range(0, 18):
left += u' '
right += u' '
for i in range(0, 18):
suit_left += u' '
suit_right += u' '
right += u'{}'.format(self.number)
suit_right += u'{}'.format(self.suit)
left += unichr(0x2502)
right += unichr(0x2502)
suit_left += unichr(0x2502)
suit_right += unichr(0x2502)
lines = [top, left, suit_left, suit_right, right, bottom]
if self.number in ['J', 'Q', 'K', 'A']:
if self.number == 'A':
lines.insert(3, middle)
else:
lines.insert(3, face)
for i in range(0, 4):
lines.insert(3, empty_mid)
lines.insert(len(lines) - 3, empty_mid)
elif self.number == '2':
lines.insert(3, middle)
for i in range(0, 7):
lines.insert(3, empty_mid)
lines.insert(3, middle)
elif self.number == '3':
lines.insert(3, empty_mid)
lines.insert(4, middle)
for i in range(0, 2):
lines.insert(5, middle)
lines.insert(5, empty_mid)
lines.insert(5, empty_mid)
lines.insert(len(lines) - 3, empty_mid)
elif self.number == '4':
lines.insert(3, twomid)
for i in range(0, 7):
lines.insert(4, empty_mid)
lines.insert(len(lines) - 3, twomid)
elif self.number == '5':
lines.insert(3, twomid)
lines.insert(3, middle)
lines.insert(3, twomid)
for i in range(0, 3):
lines.insert(4, empty_mid)
lines.insert(len(lines) - 4, empty_mid)
elif self.number == '6':
lines.insert(3, twomid)
for i in range(0, 2):
lines.insert(3, twomid)
lines.insert(4, empty_mid)
lines.insert(4, empty_mid)
lines.insert(4, empty_mid)
elif self.number == '7':
lines.insert(3, twomid)
lines.insert(4, empty_mid)
lines.insert(5, middle)
lines.insert(6, empty_mid)
lines.insert(7, twomid)
lines.insert(8, empty_mid)
lines.insert(8, empty_mid)
lines.insert(8, empty_mid)
lines.insert(len(lines) - 3, twomid)
elif self.number == '8':
lines.insert(3, twomid)
lines.insert(4, empty_mid)
lines.insert(5, middle)
lines.insert(6, empty_mid)
lines.insert(7, twomid)
lines.insert(8, empty_mid)
lines.insert(9, middle)
lines.insert(10, empty_mid)
lines.insert(11, twomid)
elif self.number == '9':
lines.insert(3, twomid)
lines.insert(4, empty_mid)
lines.insert(5, empty_mid)
lines.insert(6, twomid)
lines.insert(7, middle)
lines.insert(8, twomid)
lines.insert(9, empty_mid)
lines.insert(10, empty_mid)
lines.insert(11, twomid)
elif self.number == '10':
lines.insert(3, empty_mid)
lines.insert(4, twomid)
lines.insert(5, middle)
lines.insert(6, twomid)
lines.insert(7, empty_mid)
lines.insert(8, twomid)
lines.insert(9, middle)
lines.insert(10, twomid)
lines.insert(11, empty_mid)
return lines
|
import sys
import pdb
import argparse
def main_two(args):
pass
def main_one(args):
with open(args.filename) as file_open:
data = file_open.readlines()
count = 0
for row_w in data:
row = [int(i) for i in row_w.split()]
max_i = row[0]
min_i = row[0]
if not args.second:
for i in row:
min_i = min(min_i, i)
max_i = max(max_i, i)
else:
for i in row:
for x in row:
if i == x:
continue
if x % i == 0:
min_i = i
max_i = x
print "%d/%d" % (max_i, min_i)
def one(x, y):
return x - y
def two(x, y):
return x / y
add = one
if args.second:
add = two
count += add(max_i, min_i)
print count
parser = argparse.ArgumentParser()
parser.add_argument('filename')
parser.add_argument('-s', '--second', required=False, action='store_true')
args = parser.parse_args()
main_one(args)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 19 21:20:41 2020
@author: katherinefilpolopez
"""
import re
def transponMethod(seq, transSeq):
n = len(transSeq)
n = int(n/2)
trans1 = transSeq[:n]
trans2 = transSeq[n+1:]
tracker = 0
for i in range(n-2):
for j in range(n-2):
if(trans1[i] == trans2[j]):
tracker = tracker +1
j= j+1
i = i +1
if tracker > 3:
print("It's a transpon")
regexObj = re.compile(transSeq)
matchObj = regexObj.search(seq)
transTable = str.maketrans("ATCG", "TAGC")
comp = seq.translate(transTable)
reverse = comp[::-1]
regexObj2 = re.compile(transSeq)
matchObj2 = regexObj2.search(reverse)
if matchObj or matchObj2:
print("The transpon has been inserted")
else:
print("The transpon has not been inserted")
if tracker < 3:
raise Exception("It's not a transpon")
return seq
seq1 = 'ATGCAGTTTTTTT'
seq2 = 'ATATGGGGGATAT'
seq3 = 'ATATGGGGG'
seq4 = 'ATGCAGTTTTTTTATATGGGGGATAT'
print(transponMethod(seq1,seq2))
print(transponMethod(seq4,seq2))
|
import sqlite3
class DB_class:
conn = None
cursor = None
def __init__(self):
self.conn = sqlite3.connect('test.db')
self.cursor = self.conn.cursor()
cmd = 'CREATE TABLE IF NOT EXISTS products (name TEXT, description TEXT)'
self.cursor.execute(cmd)
cmd = 'CREATE TABLE IF NOT EXISTS history (user TEXT, request TEXT)'
self.cursor.execute(cmd)
cmd = 'CREATE TABLE IF NOT EXISTS users (user TEXT, passwd TEXT)'
self.cursor.execute(cmd)
def insert_users(self, user, passwd):
cmd = 'INSERT INTO users VALUES (\'%s\', \'%s\')' % (user, passwd)
print(cmd)
self.cursor.execute(cmd)
self.conn.commit()
def get_users(self):
cmd = 'SELECT * FROM users'
self.cursor.execute(cmd)
res = self.cursor.fetchall()
print(res)
my_db = DB_class()
my_db.insert_users('user1', '111111')
my_db.get_users()
|
card_rank = int(input())
if card_rank == 1:
card_name = 'Ace'
elif card_rank == 11:
card_name = 'Jack'
elif card_rank == 12:
card_name = 'Queen'
elif card_rank == 13:
card_name = 'King'
else:
card_name = card_rank
print('Drew a ' + str(card_name))
|
from deck import print_card, draw_card, print_header, draw_starting_hand, print_end_turn_status, print_end_game_status
from deck_test_helper import get_print, mock_random
import unittest
from unittest.mock import patch
class TestBlackjack(unittest.TestCase):
"""
Class for testing Blackjack.
There are two helper functions, get_print and mock_random, that can help you.
get_print: returns the printed statements from running a provided function with provided arguments
mock_random: use this if code calls randint. mock_random takes in a list of numbers that randint should
be using and runs the provided function with provided arguments accordingly
Example of calling print_card, which takes an argument and prints out card rank:
get_print(print_card, 2) - returns string that gets printed out when print_card function gets called with 2
To check whether the above printed correctly - self.assertEqual(get_print(print_card, 3), "Drew a 2\n")
Example of calling draw_card(), which takes no arguments but uses randint:
mock_random([3], draw_card)) - runs draw_card with 3 as the randint
To check whether the above returned correctly - self.assertEqual(mock_random([3], draw_card)), 3)
If the function takes in an argument, pass that as the last argument into mock_random()
mock_random([3, 5], draw_starting_hand), "DEALER") - runs draw_starting_hand with 3 as first randint, 5 as secnd
To check whether the above returned correctly - self.assertEqual(mock_random([3, 5], draw_starting_hand), "DEALER")
"""
def test_print_card(self):
"""
Example of a test to compare printed statements with expected
This does not count as one of your tests
"""
self.assertEqual(get_print(print_card, 2), "Drew a 2\n")
def test_mock_randint(self):
"""
Example of a test to compare output for a function that calls randint
This does not count as one of your tests
"""
self.assertEqual(mock_random([3], draw_card), 3)
self.assertEqual(mock_random([3, 5], draw_starting_hand, "DEALER"), 8)
# WRITE YOUR TESTS BELOW
def test_print_card(self):
self.assertEqual(get_print(print_card, 3), "Drew a 3\n")
self.assertEqual(get_print(print_card, 7), "Drew a 7\n")
self.assertEqual(get_print(print_card, 10), "Drew a 10\n")
self.assertEqual(get_print(print_card, 1), "Drew a Ace\n")
self.assertEqual(get_print(print_card, 11), "Drew a Jack\n")
self.assertEqual(get_print(print_card, 12), "Drew a Queen\n")
self.assertEqual(get_print(print_card, 13), "Drew a King\n")
def test_print_header(self):
self.assertEqual(get_print(print_header, "YOUR TURN"), "-----------\nYOUR TURN\n-----------\n")
self.assertEqual(get_print(print_header, "DEALER TURN"), "-----------\nDEALER TURN\n-----------\n")
self.assertEqual(get_print(print_header, "GAME RESULT"), "-----------\nGAME RESULT\n-----------\n")
self.assertEqual(get_print(print_header, "DEALER"), "-----------\nDEALER\n-----------\n")
self.assertEqual(get_print(print_header, "USER"), "-----------\nUSER\n-----------\n")
def test_print_end_turn_status(self):
self.assertEqual(get_print(print_end_turn_status, 11), "Final hand: 11.\n")
self.assertEqual(get_print(print_end_turn_status, 19), "Final hand: 19.\n")
self.assertEqual(get_print(print_end_turn_status, 20), "Final hand: 20.\n")
self.assertEqual(get_print(print_end_turn_status, 21), "Final hand: 21.\nBLACKJACK!\n")
self.assertEqual(get_print(print_end_turn_status, 25), "Final hand: 25.\nBUST.\n")
self.assertEqual(get_print(print_end_turn_status, 28), "Final hand: 28.\nBUST.\n")
def test_print_end_game_status(self):
self.assertEqual(get_print(print_end_game_status, 19, 20), "-----------\nGAME RESULT\n-----------\nDealer wins!\n")
self.assertEqual(get_print(print_end_game_status, 18, 21), "-----------\nGAME RESULT\n-----------\nDealer wins!\n")
self.assertEqual(get_print(print_end_game_status, 26, 21), "-----------\nGAME RESULT\n-----------\nDealer wins!\n")
self.assertEqual(get_print(print_end_game_status, 24, 19), "-----------\nGAME RESULT\n-----------\nDealer wins!\n")
self.assertEqual(get_print(print_end_game_status, 19, 18), "-----------\nGAME RESULT\n-----------\nYou win!\n")
self.assertEqual(get_print(print_end_game_status, 21, 20), "-----------\nGAME RESULT\n-----------\nYou win!\n")
self.assertEqual(get_print(print_end_game_status, 21, 23), "-----------\nGAME RESULT\n-----------\nYou win!\n")
self.assertEqual(get_print(print_end_game_status, 15, 25), "-----------\nGAME RESULT\n-----------\nYou win!\n")
self.assertEqual(get_print(print_end_game_status, 19, 19), "-----------\nGAME RESULT\n-----------\nTie.\n")
self.assertEqual(get_print(print_end_game_status, 21, 21), "-----------\nGAME RESULT\n-----------\nTie.\n")
self.assertEqual(get_print(print_end_game_status, 23, 23), "-----------\nGAME RESULT\n-----------\nTie.\n")
self.assertEqual(get_print(print_end_game_status, 22, 25), "-----------\nGAME RESULT\n-----------\nTie.\n")
def test_draw_card(self):
self.assertEqual(mock_random([3], draw_card), 3)
self.assertEqual(mock_random([8], draw_card), 8)
self.assertEqual(mock_random([1], draw_card), 11)
self.assertEqual(mock_random([11], draw_card), 10)
self.assertEqual(mock_random([12], draw_card), 10)
self.assertEqual(mock_random([13], draw_card), 10)
def test_draw_starting_hand(self):
self.assertEqual(mock_random([3, 5], draw_starting_hand, "DEALER"), 8)
self.assertEqual(mock_random([4, 5], draw_starting_hand, "DEALER"), 9)
self.assertEqual(mock_random([1, 5], draw_starting_hand, "DEALER"), 16)
self.assertEqual(mock_random([11, 12], draw_starting_hand, "DEALER"), 20)
self.assertEqual(mock_random([13, 1], draw_starting_hand, "DEALER"), 21)
self.assertEqual(mock_random([12, 5], draw_starting_hand, "DEALER"), 15)
self.assertEqual(mock_random([3, 4], draw_starting_hand, "USER"), 7)
self.assertEqual(mock_random([9, 10], draw_starting_hand, "USER"), 19)
self.assertEqual(mock_random([13, 11], draw_starting_hand, "USER"), 20)
self.assertEqual(mock_random([12, 11], draw_starting_hand, "USER"), 20)
self.assertEqual(mock_random([13, 1], draw_starting_hand, "USER"), 21)
self.assertEqual(mock_random([12, 5], draw_starting_hand, "USER"), 15)
if __name__ == '__main__':
unittest.main()
|
#server
# TCP Server Code
#host="127.0.0.1" # Set the server address to variable host
host="127.168.2.75" # Set the server address to variable host
port=4446 # Sets the variable port to 4444
from socket import * # Imports socket module
s=socket(AF_INET, SOCK_STREAM)
s.bind((host,port)) # Binds the socket. Note that the input to
# the bind function is a tuple
s.listen(1) # Sets socket to listening state with a queue
# of 1 connection
print "Listening for connections.. "
q,addr=s.accept() # Accepts incoming request from client and returns
# socket and address to variables q and addr
data=raw_input("Enter data to be send: ") # Data to be send is stored in variable data from
# user
q.send(data) # Sends data to client
s.close()
# End of code
#Client
# TCP Client Code
#host="127.0.0.1" # Set the server address to variable host
host = "127.168.2.75"
port=4446 # Sets the variable port to 4444
from socket import * # Imports socket module
s=socket(AF_INET, SOCK_STREAM) # Creates a socket
s.connect((host,port)) # Connect to server address
msg=s.recv(1024) # Receives data upto 1024 bytes and stores in variables msg
print ("Message from server : " + msg.strip().decode('ascii'))
s.close() # Closes the socket
# End of code
|
memo = {0: 0, 1: 1} # base case
def fib3(n):
if n not in memo:
memo[n] = fib3(n-1) + fib3(n-2) # memoization
return memo[n]
if __name__ == "__main__":
print(fib3(20))
|
# python doe not require an else block at the end of an if-elif chain
# sometimes an else block is useful
# or sometime times it is clearer to use an additional elif statement that catches a specific condition of interest
age = 24
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65: # the elif block now check to make sure a person is less than 65 before assigning a price of 10
price = 10
elif age >= 65: #
price = 6
print("Your admission cost is $" + str(price)+ ".") |
# every attribute in a class needs an initial value, even if that value is 0 or an empty string
# in some cases, such as when setting a default value, it makes since to specify this initial in the ...
# ... body of the init method
# if you do this you do this for an attribute you don't have to include a parameter for that attribute
# in this example we will add odometer_reading that starts with a value of 0
# and we will add a method to read each cars odometer
class Car():
"""Represents a car"""
def __init__(self, make, model, year):
"""Attributes to describe car"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # new attribute added, default is 0
def get_descriptive_name(self):
"""Return a nearly formatted descriptive name"""
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self): # function makes it easier to read odometer
"""Shows car mileage"""
print("This car has " + str(self.odometer_reading) + " miles on it.")
my_new_car = Car("Audi", "A4", 2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_new_car = Car("Land Rover", "Defender", 1969)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer() |
print("\t\t\t - PIZZA TOPPINGS -")
pizza = "Please type your prefer pizza topping: "
pizza += "\n\tType 'quit' to cancel program"
while True:
topping = input(pizza)
if topping != "quit":
print(" Adding " + topping)
else:
break
print("\n\t\t\t - MOVIE TICKETS -")
# create a a loop that asks a person their age and outputs how much a ticket ...
# ... would cost
# Under 3 is free
# 3 to 12 is £10
# Over 12 is £15
prompt = "Age : "
prompt += "\n\tEnter 'quit' once you are finished."
while True:
age = input(prompt)
if age == "quit":
break
age = int(age)
if age < 3:
print("Cost = £0")
elif age < 13:
print("Cost = £10")
else:
print("Cost = £15")
print = ("\n\t\t\t - THREE EXITS - ") |
# often you'll want to take one action when a conditional test passes and different one action in all other cases
# an if-else allows you to define an action or set of actions that are executed when the conditional test fails
# here is the same code from 4.12 but will a message for anyone who is not old enough to vote
age = 17
if age >= 18: # if the conditional test passes the indented print statement below is executed
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else: # if the test evaluates False the else block is executed
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!") |
# reverse() can be used to print a list in reverse order
cars =["bmw", "audi", "toyota", "sabaru"]
print(cars)
cars.reverse()
print(cars) # note reverse does not sort() the list instead just reverses it |
# you can nest a dictionary inside another dictionary, but can get complicated quicky when doing so
users = {
"a-einstein" : {
"first" : "albert",
"last" : "einstein",
"location" : "princeton",
},
"m-curie" : {
"first" : "marie",
"last" : "curie",
"location" : "paris",
}
}
for username, user_info in users.items(): # loop through users in dictionary, variables stored as "username" ...
# ... each value associated with each username goes into the variable "user_info"
print("\nUsername:" + username) # once since the dictionary loop the username is printed
full_name = user_info["first"] + " " + user_info["last"] # inside user_info to access the first and last name
location = user_info["location"]
print ("\tFull name: " + full_name.title()) # use full name from line 19 to generate full name
print("\tLocation: " + location.title())
# in the dictionary users are defined with two keys, the usernames being a-einstein and m-curie
# the value associated with each key is the first name, last name and the location
|
# an assumption made about every list so far is that it has at least one value in it
# here we will check if the a list is empty before running a loop
requested_toppings = [] # started with an empty list
if requested_toppings: # if the list contains at least one item list turns up as true
for x in requested_toppings: # if the list is empty it evaluates to false
print("Adding " + x + ".")
print("\nFinished making your pizza!")
else: # if the conditional test fails we print the message below
print("Are you sure you want to make a plain pizza?") |
# you may need to check for multiple conditions
# for example if you want two conditions to be true to take an action
# here is a code to check if both people are over 21
age_0 = 22
age_1 = 18
print((age_0 >=21) and (age_1 >=21)) # check whether both ages are equal to or over 21
|
# motorcycles = ["honda","yamaha","suzuki"]
# print(motorcycles[3]) # one common error is asking for non-existant values. i.e. asking for a forth item when there are only 3 values
motorcycles = ["honda","yamaha","suzuki"]
print(motorcycles[-1])
# when the index is -1 it always returns the last item |
# an if statement is an expression that can be evaluated as True or False and is ...
# ... called a conditional test. if the if statement is True python executes the code ...
# ...following the if statement. if the test evaluates to false python ignores the following ...
# ... if statement
# most conditional test compare the current value to the variable to a specific ...
# value of interest. python uses the values True or False
x = 2 # the line sets the value x to equal 2
print("Does x equal 2?")
print(x == 2) # the line checks whether x is equal to 2 using the double equals sign (==)
print("\nDoes x equal 3?")
print(x == 3) # this check whether x is qual to 3
|
# If the value's position you wan't to remove is unknown, the remove() fucntion can be use to remove using just the value
motorcycles = ["honda","yamaha","suzuki","ducati"]
print(motorcycles)
motorcycles.remove("ducati") # remove() removes the value "dacati" without giving the position i.e motorcylces.pop(3)
print(motorcycles)
print("\n") # \n starts a new line
bicycles = ["trek","cannondale","redline","specialised"]
print(bicycles)
too_expensive = "specialised"
bicycles.remove(too_expensive)
print(bicycles)
print("\nA " + too_expensive.title() + " is too expensive for me.") # \n starts a new line, ducati is stored as "too_expensive",
# remove() removes the value "ducati" from the list but is still stored as the variable "too expensive" allowing me to print a statement about ducati
# remove() only the first occurrence of the value specified
|
# when modeling something from the real world code, you may find that you are adding more detail to the class
# you'll find that you have a growing list of attributes and that your files are becoming lengthy
# in this situation you might recognise that part of one class can be written as a separate class
# you can break large classes into smaller classes
# for example if we continue adding detail to ElectricCar class we might notice that we are adding a lot of attributes
# in previous examples we where adding attributes and methods specific to the cars battery
# an entire class could be made dedicated to said battery
class Car():
"""Represents a car"""
def __init__(self, make, model, year):
"""Attributes to describe car"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a nearly formatted descriptive name"""
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def read_odometer(self):
"""Shows car mileage"""
print("This car has " + str(self.odometer_reading) + " miles on it.\n")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You cant roll back an odometer")
def increment_odometer(self,miles):
self.odormeter_reading += miles
class Battery(): # define new class that doesnt inherit from any other class
"""Simple model for battery for electric car"""
def __init__(self, battery_size = 70):
"""Initialise battery attributes"""
self.battery_size = battery_size
def describe_battery(self): # option parameter that sets battery size to 70 if not value is given
"""Print statement describe battery size"""
print("This car has a " + str(self.battery_size) + "kWh Battery")
def get_range(self):
"""Print statement about range battery provides"""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
class ElectricCar(Car):
"""Represents aspects of a car, specifgic to eletric vehicles"""
def __init__(self,make,model,year):
"""Initialise attributes of parent class"""
super().__init__(make,model,year)
self.battery = Battery() # add attribute called self.battery and tells python to create new instance ...
# ... of battery and store it in self.battery
# this means any time ElectricCar is called the battery instance is created automatticlly
my_tesla = ElectricCar("tesla", "model s", 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
|
# previously I have been working thorough all the elements in a list
# a specific group in a list is called a slice
# to make a slice you specify the index of the first and last elements you want to work with
# similar to the range() function python stops one item before the second index you specify
# for example to out the first 3 elements in a list you would request indicies 0 through 3
# this would return element 0, 1, and 2
# for example
players = ["charles", "martina", "martina", "micheal", "florence", "eli"]
print(players[0:3]) # the code prints a slice of the list, which includes the first 3 players
# you can print any subset in a list
print(players[1:4])
# to omit the first index in a slice, python automatically starts your slice at the beginning of a list
print(players[:4]) # this prints from the start of the list to the index position 4
# without a starting index, python starts at the beginning of the list
# a similar syntax works that in cludes the end of a list
print(players[2:]) # this prints from index position 2 to the last item
# this syntax allows you to output from all the elements from any point in the list regardless the length of the list
# a negative index returns elements a certain distance from the end of a list
# for example to out the last three players we can use players[-3:]
print(players[-3:0]) |
# sometimes people will ask for anything in their lists
# below are two lists
# the first is a list of available topping and second is a list the user has requested
# each time each time request_toppings is checked against the list of available_toppings
available_toppings = ["mushrooms", "olives", "green peppers", # list of availiable toppings is defined
"pepperoni", "pineapple", "extra cheese"]
requested_toppings = ["mushrooms", "french fries", "extra cheese"] # toppings the customer requested note ...
# note french fries is not in the list of available_toppings
for topping in requested_toppings: # python loops through the list of requested toppings to see if items are available
if topping in available_toppings: # if it is it is added to the pizza
print("Adding " + topping + ".")
else: # the else block prints a message tell which are unavailable
print("Sorry, we don't have " + topping + ".")
print("Finished making your pizza!") |
# dictionaries allow you to connect simple pieces of related information
# in this lesson we will learn how to access information once its in a dictionary and how to modify that information
# consider a game featuring aliens that can have different colours and point values
# a dictionary stores that information about that alien
alien_0 = { "colour" : "green", "points" : 5 }
print(alien_0["colour"])
print(alien_0["points"]) |
# here is how to change the label type and graph thickness
import matplotlib.pyplot as plt
squares = [1, 4, 9, 16, 25]
# set linewidth
plt.plot(squares, linewidth = 5)
# set title and label axes
plt.title("Square Numbers", fontsize=24) # .title() to gives a title
plt.xlabel("Value", fontsize =14) # .xlabel() gives title for x axis
plt.ylabel("Square of Value", fontsize=14) # /ylabel() gives title for y axis
# set size of tick labels
plt.tick_params(axis="both", labelsize=14) # .tick_params() styles the tick marks, effect tick marks
# on both tick marks on x and y axis
plt.show()
|
# a function can return any kind of value you need it to
# including data structures like lists and dictionaries
# for example the following function takes parts of a name and returns a dictionary representing a person
def build_person(first_name, last_name, age=""):
"""Return a doctopmary of information about a person."""
person = {"first": first_name, "last": last_name} # build person takes first and last name and puts in dictionary
# value first_name stored as first, value last_name stored as last
if age:
person["age"] = age
return person # dictionary representing the person is returned
musician = build_person("jimi", "hendrix", age=27)
print(musician) |
class Restaurant():
""" About restaurants or whatever"""
def __init__(self, restaurant_name, restaurant_type):
self.restaurant_name = restaurant_name
self.restaurant_type = restaurant_type
self.number_served = 0
def open_restaurant(self):
print(self.restaurant_name + " which serves " +
self.restaurant_type + " is open for business.")
def set_number_served(self):
print("This restaurant has served " + str(self.number_served) + " customers.\n") |
# Siraj Raval: Build a Neural Net in 4 Minutes
# https://www.youtube.com/watch?v=h3l4qz76JhQ
import numpy as np
# Sigmoid, a function that will map any value to a value between zero and one
# will be run at every neuron of our network when data hits it
# useful for creating probabilities out of numbers
def nonlin(x,deriv=False):
if(deriv==True):
return x*(1-x)
return 1/(1+np.exp(-x))
# input data as a matrix
# each row is a different training example
# each column represents a different neuron
# so we have four training examples with three input neurons each
X = np.array([[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]])
# Create output data set
# output data set, which is four examples, with one output neuron each
y= np.array([[0],
[1],
[1],
[0]])
# Seed the Random Numbers.
# We'll be generating random numbers soon.
# So here we'll seed those numbers to be deterministic.
# This means giving the randomly generated numbers the same starting point
# so we'll get the same sequence of generated numbers every time we run our
# program. NOTE: Seeding like this is is useful for debugging.
np.random.seed(1)
# Create synapse matricies
# Synapses are connections between each neuron in one layer to every neuron in
# the next layer.
# Since we'll have three layers in our neural network, we need two synapse matricies.
# Each synampse has a random weight given to it.
syn0 = 2*np.random.random((3,4)) - 1
syn1 = 2*np.random.random((4,1)) - 1
# Training step
# NOTE: in python3, this is: for j in range(100000)
for j in xrange(100000):
# first layer is just the input data
l0 = X
# prediction step
# here we perform matrix multiplication between each layer and its synapse
# then we run the sygmoid function on all the values in the matrix to create
# the next layer.
l1 = nonlin(np.dot(l0, syn0))
# This layer contains the prediction of the output data
# We do th e same stypes on this layer to get the next layer.
# This is a more refined prediction
l2 = nonlin(np.dot(l1, syn1))
# Now that we have a prediction of the output value in layer two
# Let's compare it to the expected output data using subtraction to get the
# error rate.
l2_error = y - l2
# Print out the average error rate at a set interval to make sure it goes
# down every time!
if(j % 10000) == 0:
print "Error:" + str(np.mean(np.abs(l2_error)))
# Next, we multiply the error rate by the result of the sigmoid function.
# The function is used to get the derivative of our output prediction from
# layer two. This will give us a delta, which we'll use to reduce the error
# rate of our predictions when we update our synapses EVERY ITERATION
l2_delta = l2_error * nonlin(l2, deriv=True)
# Then we'll want to see how much layer one contributed to the error in
# layer two. This is called BACKPROPAGATION. We'll get this error by
# multiplying layer two's delta by synapse one's transpose
l1_error = l2_delta.dot(syn1.T)
# Then we'll get synapse one's delta by multiplying layer one's error by
# by the result of our sigmoid function. The function is used to get the
# derivative of layer one.
l1_delta = l1_error * nonlin(l1, deriv=True)
# Update Weights
# Now we have deltas for each of our layers, we can use them to update our
# synapse weights to reduce our error weight MORE AND MORE each iteration.
# This is an algorithm called GRADIENT DESCENT.
# To do this, we'll just multiply each layer by a delta.
syn1 += l1.T.dot(l2_delta)
syn0 += l0.T.dot(l1_delta)
print "Output after training"
print l2
|
from Utility import *
class BinarySearch:
utility=Utility()
print("enter the number of words for binary search : ")
var_input = utility.input_int_data()
if (var_input <= 0):
print("please check the input : ")
else:
my_array=[None]*var_input
print(" enter values ")
for x in range(0,var_input):
my_array[x]=raw_input()
my_array.sort()
print(" your array after sorting: ")
for x in range(0,var_input):
print(my_array[x]),
print("\n")
var_key = raw_input(" enter a key to search : ")
utility.binary_search(my_array,0,len(my_array)-1,var_key)
|
from Utility import *
class Annagram:
utility=Utility()
var_str_1=raw_input("please enter first string : ")
var_str_2 = raw_input("please enter second string : ")
var_result = utility.annagram(var_str_1,var_str_2)
if(var_result):
print("it is a annagram ")
else:
print("it is not a annagram ") |
from Utility import *
class Gambler:
utility = Utility()
print("Please enter a number_of_times : ")
number_of_times = utility.input_int_data()
if number_of_times <= 0:
print("check the input")
else:
loss = 0
wins = 0
x = 1
# for x in range(1, number_of_times + 1):
while x <= number_of_times :
print("Please enter a stake : ")
stake = utility.input_int_data()
print("Please enter a goal : ")
goal = utility.input_int_data()
if (stake <= 0) or (goal <= 0) :
print("please check the input")
elif goal== stake or goal < stake:
print("you already reached goal")
else:
amount = stake
while (amount > 0) and (amount < goal):
rand_num = random.random()
if (rand_num > 0.5):
amount = amount + 1
else:
amount = amount - 1
if (amount == goal):
wins = wins + 1
print("win")
else:
loss = loss + 1
print("loss")
x +=1
print("total number of wins " + str(wins))
print("percentage of win " + str((100.0 * wins) / number_of_times))
print("percentage of loss " + str((100.0 * loss) / number_of_times)) |
from Node import *
class LinkedList:
def __init__(self):
self.head=None
def add(self,data):
obj_node=Node(data)
if(self.head == None):
self.head=obj_node
else:
temp = self.head
while(temp.next_node != None):
temp = temp.next_node
temp.next_node=obj_node
def delete(self,data):
temp = self.head
prev = None
if temp is None:
print(" it is empty ")
elif (temp.data == data):
temp = self.head
self.head = temp.next_node
temp = None
else:
temp2 = self.head
while(temp2 != None):
if temp2.data == data :
prev.next_node = temp2.next_node
temp2 = None
break
else:
prev = temp2
temp2 = temp2.next_node
prev = None
def search(self,data):
temp = self.head
while(temp != None):
if (temp.data == data):
return True
temp = temp.next_node
return False
def display(self):
temp = self.head
while(temp != None):
print temp.data
temp = temp.next_node
def get_data(self):
my_list = []
temp = self.head
while(temp != None):
my_list.append(temp.data)
temp = temp.next_node
return my_list
def print_list(self,f,head):
file = open(f,"w+")
if(head is None):
print("it is empty")
elif (head.next_node is None):
file.write(head.data),
file.write(" ")
else:
while(head != None):
file.write(str(head.data)+" ")
head = head.next_node
def add_order(self,data):
try:
obj_node = Node(data)
temp_node = None
temp = self.head
key = int(data)
temp_data = int(temp.data)
if (self.head == None):
self.head = obj_node
elif(temp_data > key):
temp_node = obj_node
temp_node.next_node = temp
self.head = obj_node
else:
while (temp.next_node != None):
temp_data = int(temp.data)
temp_node_data = int(temp.next_node.data)
if(temp_data < key and temp_node_data > key):
temp_node = obj_node
temp_node.next_node = temp.next_node
temp.next_node = temp_node
break
temp = temp.next_node
temp.next_node = obj_node
except ValueError :
print("value error...please check the input")
|
import math
class Utility:
def input_int_data(self):
while True:
try:
var_input = int(input())
return var_input
break
except NameError:
print("please enter a integer...try again")
except NameError:
print("please enter integer value")
except SyntaxError:
print("Check the entered input and try again")
except MemoryError:
print("Check the entered input and try again")
except OverflowError:
print("Entered number is very high")
except Exception:
print("exception...something went wrong")
def input_str_data(self):
while True:
try:
var_input = raw_input()
return var_input
break
except NameError:
print("please enter a string...try again")
except NameError:
print("please enter integer value")
except SyntaxError:
print("Check the entered input and try again")
except MemoryError:
print("Check the entered input and try again")
except OverflowError:
print("Entered number is very high")
except Exception:
print("exception...something went wrong")
def input_float_data(self):
while True:
try:
var_input = float(input())
return var_input
break
except NameError:
print("please enter a string...try again")
except NameError:
print("please enter integer value")
except SyntaxError:
print("Check the entered input and try again")
except MemoryError:
print("Check the entered input and try again")
except OverflowError:
print("Entered number is very high")
except Exception:
print("exception...something went wrong")
def annagram(self,var_str1,var_str2):
var_nospace_str1=var_str1.replace(" ","")
var_nospace_str2=var_str2.replace(" ","")
if(len(var_nospace_str1) != len(var_nospace_str2)):
return False
else:
var_lower_str1=var_nospace_str1.lower()
var_lower_str2=var_nospace_str2.lower()
char_array_1=list(var_lower_str1)
char_array_2=list(var_lower_str2)
char_array_1.sort()
char_array_2.sort()
for x in range(0,len(char_array_1)):
if(char_array_1[x]!= char_array_2[x]):
return False
return True
def primenumber(self,var_range):
my_array = [None] * var_range
index=0
for x in range(1,var_range+1):
count=0
for num in range(1,x+1):
if(x % num == 0):
count=count+1
if(count == 2):
my_array[index] = x
index = index+1
return my_array
def extend_annagram(self,prime_array):
var_size=0
var_j=0
for x in range(0,len(prime_array)):
if(prime_array[x]!=None):
var_size=var_size+1
my_array=[None]*var_size
for x in range(0,len(prime_array)):
if (prime_array[x] != None):
my_array[var_j]=prime_array[x]
var_j=var_j+1
print(str(prime_array[x])+" "),
print ("\n")
var_str1=""
var_str2=""
for x in range(0,len(my_array)-1):
for y in range(x+1,len(my_array)):
var_str1=my_array[x]
var_str2=my_array[y]
flag=self.annagram(str(var_str1),str(var_str2))
if(flag):
print(str(my_array[x])+" "+str(my_array[y]))
def palindrome(self,prime_array):
var_size = 0
var_j = 0
for x in range(0, len(prime_array)):
if (prime_array[x] != None):
var_size = var_size + 1
my_array = [None] * var_size
for x in range(0, len(prime_array)):
if (prime_array[x] != None):
my_array[var_j] = prime_array[x]
var_j = var_j + 1
print(str(my_array[x]) + " "),
print ("\n")
for x in range(0,len(my_array)):
# var_remainder=0
# var_sum=0
# var_temp=my_array[x]
# while(my_array[x]>0):
# var_remainder == my_array[x]%10
# print(var_remainder)
# var_sum = (var_sum * 10) + var_remainder
# print(var_sum)
# my_array[x] = my_array[x]/10
# print(my_array[x])
var_temp=str(my_array[x])
if int(var_temp) > 10:
if(var_temp == var_temp[::-1]):
if var_temp > 10:
print(str(var_temp)+" palindrome")
else:
print(str(var_temp)+" is not a palindrome")
def guessing(self,var_low,var_high):
var_mid=(var_low+var_high)/2
if(var_mid == var_high):
return var_mid
if( 1 == var_mid) or ((var_mid + 1) == var_high):
print( str(var_mid) + " then enter '1' \n " + str(
var_high) + " then enter '2'")
else:
print(" 1 - "+str(var_mid)+" then enter '1' \n "+str(var_mid + 1)+" - "+str(var_high)+" then enter '2'")
var_option=self.input_int_data()
if(var_option == 1):
return self.guessing(var_low,var_mid)
elif(var_option == 2):
return self.guessing(var_mid+1,var_high)
else:
print(" please enter valid option : ")
return self.guessing(var_low,var_high)
def binary_search(self,my_array, var_low, var_high, var_key):
if(var_low <= var_high):
var_mid = var_low+(var_high-var_low)/2
if(my_array[var_mid] == var_key):
print(" key found at : "+str(var_mid+1))
elif(my_array[var_mid] > var_key):
self.binary_search(my_array, var_low, var_mid-1, var_key)
elif(my_array[var_mid] < var_key):
self.binary_search(my_array, var_mid+1, var_high, var_key)
else:
print(" key not found ")
def insertion_sort(self,my_array):
for index in range(1,len(my_array)):
var_key = my_array[index]
prev_index = index-1
while prev_index >= 0:
if(var_key < my_array[prev_index]):
my_array[prev_index+1] = my_array[prev_index]
my_array[prev_index] = var_key
prev_index -= 1
else:
break
return my_array
def bubble_sort(self,my_array):
for x in range(0,len(my_array)):
for y in range(0, len(my_array)-1 ):
if(my_array[y] > my_array[y+1]):
var_temp = my_array[y]
my_array[y] = my_array[y+1]
my_array[y+1] = var_temp
return my_array
def merge_sort(self,my_array):
# if given number is only one integer or nothing then it will return.
if (len(my_array) <= 1):
return my_array
# dividing length into half.
var_mid = len(my_array)/2
left_array = [None]*var_mid
right_array=[]
if (len(my_array) % 2 == 0):
right_array = [None]*var_mid
else:
var_len=var_mid+1
right_array = [None]*var_len
# collecting in left array.
for x in range(0,var_mid):
left_array[x] = my_array[x]
# collecting in right array.
var_x=0
for y in range(var_mid,len(my_array)):
if(var_x < len(right_array)):
right_array[var_x] = my_array[y]
var_x=var_x+1
left_array = self.merge_sort(left_array)
# print(" left_array "+str(left_array))
right_array = self.merge_sort(right_array)
# print(" right_array " + str(right_array))
result_array = self.merge_arrays(left_array,right_array)
print(" result_array " + str(result_array))
return result_array
def merge_arrays(self,left_array,right_array):
# taking length to initialize arrays
var_length = len(left_array)+len(right_array)
result_array = [None]*var_length
var_left_index = 0
var_right_index = 0
var_result_index = 0
while (var_left_index<len(left_array)) or (var_right_index < len(right_array)):
if(var_left_index < len(left_array)) and (var_right_index < len(right_array)):
if(left_array[var_left_index] <= right_array[var_right_index]):
result_array[var_result_index] = left_array[var_left_index]
var_left_index += 1
var_result_index += 1
else:
result_array[var_result_index] = right_array[var_right_index]
var_right_index += 1
var_result_index += 1
elif (var_left_index < len(left_array)):
result_array[var_result_index] = left_array[var_left_index]
var_left_index = var_left_index + 1
var_result_index = var_result_index + 1
elif (var_right_index < len(right_array)):
result_array[var_result_index] = right_array[var_right_index]
var_right_index = var_right_index + 1
var_result_index = var_result_index + 1
return result_array
def counting_notes(self,var_amount):
my_array=[2000,1000,500,100,50,10,5,2,1]
var_note=0
for x in range(0,len(my_array)):
var_number = var_amount/my_array[x]
padding = format(""," <4s")
print(" "+str(my_array[x])+""+str(padding)+"x"+str(padding)+""+str(var_number))
var_amount = var_amount % my_array[x]
var_note = var_note + var_number
return var_note
def day_of_week(self,var_day,var_month,var_year):
var_yo = var_year - (14-var_month) / 12
var_x = var_yo + var_yo / 4 - var_yo / 100 + var_yo / 400
var_mo = var_month + 12 * ((14-var_month)/12) -2
var_d = (var_day + var_x + 31 * var_mo/12)%7
return var_d
def is_leap_year(self,year):
if (year % 4 == 0) :
if (year % 100 == 0) :
if (year % 400 == 0) :
return True
else :
return False
else :
return True
else :
return False
def celsius(self):
print("enter fahrenheit temperature : ")
var_fahrenheit = self.input_int_data()
var_celsius = (var_fahrenheit - 32) * 5 / 9;
print(" In celsius : "+str(var_celsius))
def fahrenheit(self):
print("enter celsius temperature : ")
var_celsius = self.input_int_data()
var_fahrenheit = (var_celsius * 9 / 5) + 32
print(" In farenheit : "+str(var_fahrenheit))
def calculation(self,var_principle,var_interest,var_year):
var_n = 12 * var_year
if(var_interest == 0):
var_payment = (var_principle/(var_year*12))
else:
var_r = var_interest / (12*100)
var_payment = (var_principle * var_r) / (1 - math.pow((1+var_r),(-var_n)))
print(" monthly payment : "+str(var_payment))
def calculate_sqrt(self,var_input):
var_temp = var_input
var_epsilon = 1e-15
while (abs(var_temp - (var_input / var_temp)) > (var_epsilon * var_temp)):
var_temp = (((var_input / var_temp) + var_temp) / 2.0)
print("The square root of "+str(var_input)+" is "+str(var_temp))
def to_binary(self,var_decimal):
var_binary = ""
var_rem = 0
while (var_decimal > 0) :
var_rem = var_decimal % 2
var_binary = str(var_rem) + var_binary
var_decimal = var_decimal / 2
while (len(var_binary) < 8) :
var_binary = str(0) + var_binary
return var_binary
def swap_nibbles(self,var_binary):
var_temp = ""
var_mid = len(var_binary) / 2
var_temp = var_temp + var_binary[var_mid:]
var_temp = var_temp + var_binary[:var_mid]
return var_temp
def to_decimal(self,var_binary):
var_sum = 0
var_temp = ""
char_array = list(var_binary)
var_power = len(char_array)-1
print(" ")
for x in range(0,len(char_array)):
var_index_value =char_array[x]
var_sum = var_sum + (int(var_index_value) * math.pow(2,var_power))
var_power = var_power-1
var_temp = var_temp + str(var_sum)
return var_temp |
from Utility import *
class WindChill:
utility=Utility()
print("please enter the temperature t (in Fahrenheit) below '50'")
var_t = utility.input_int_data()
print("please enter the wind speed v (in miles per hour) between '3' and '120'")
var_v = utility.input_int_data()
if ((var_t <= 50) and (var_v <= 120) and (var_v >= 3)):
utility.weather(var_t, var_v)
else:
print("please enter input as mention in range") |
from Utility import *
class DeckOfCards:
def deck_of_cards(self):
suit_list = ["Clubs", "Diamonds", "Hearts", "Spades"]
rank_list = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]
deck_arr = [None] * 52
# storing total cards
for i in range(0, len(rank_list)):
for j in range(0, len(suit_list)):
deck_arr[len(suit_list) * i + j] = str(rank_list[i])+ " of "+ str(suit_list[j])
# shuffling the cards
for i in range(0, len(deck_arr)):
rand = i + int(random.random() * (len(deck_arr) - i))
temp = deck_arr[rand]
deck_arr[rand] = deck_arr[i]
deck_arr[i] = temp
return deck_arr
# sorting for each person
def sort_cards(self,deck_arr):
char_arr = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '1', 'J', 'Q', 'K']
index = 0
sort_arr = []
for column in range(4):
sort_arr.append([])
for x in range(len(char_arr)):
for y in range(9):
temp = deck_arr[column][y][0]
if (char_arr[x] == temp):
sort_arr[column].append(deck_arr[column][y])
# index = index + 1
return sort_arr
|
from Stack import *
from Utility import *
class BalancedParanthesis:
utility = Utility()
stack = Stack()
# var_input = "((5+6)*(7+8)/(4+3)(5+6)*(7+8)/(4+3))"
print("please enter expression")
var_input = utility.input_str_data()
my_array = list(var_input)
open_para = "("
close_para = ")"
for x in range(0 ,len(my_array)):
if(my_array[x] == open_para) :
stack.push(my_array[x])
elif(my_array[x] == close_para) :
result = stack.pop()
if(result == 0):
print(" Unbalanced paranthesis..... ")
exit(0)
flag1 = stack.is_empty()
if (flag1):
pass
# print("Balanced Paranthesis '()'")
# exit(0)
else:
print("Unbalanced Paranthesis '()'")
exit(0)
for x in range(0 ,len(my_array)):
if (my_array[x] == "{") :
stack.push(my_array[x])
elif (my_array[x] == "}") :
result = stack.pop()
if(result == 0):
print(" Unbalanced paranthesis..... ")
exit(0)
flag2 = stack.is_empty()
if(flag2):
pass
# print("Balanced Paranthesis '{}'")
else:
print("Unbalanced Paranthesis '{}'")
for x in range(0 ,len(my_array)):
if (my_array[x] == "[") :
stack.push(my_array[x])
elif (my_array[x] == "]") :
result = stack.pop()
if(result == 0):
print(" Unbalanced paranthesis..... ")
exit(0)
flag3 = stack.is_empty()
if(flag3) and flag1 and flag2:
print("Balanced Paranthesis ")
else:
print("Unbalanced Paranthesis ")
|
from collections import defaultdict
def update_allergens(allergenDB, allergen):
for key in allergenDB:
if key != allergen and len(allergenDB[key]) > 1:
allergenDB[key].difference_update(allergenDB[allergen])
if len(allergenDB[key]) == 1:
update_allergens(allergenDB, key)
def match_food_items(foods):
ingredientDB = defaultdict(int)
allergenDB = {}
for food in foods:
ingredients, allergens = [items.split(" ") for items in food]
for allergen in allergens:
allergenDB[allergen] = set(ingredients) if allergen not in allergenDB else allergenDB[allergen].intersection(ingredients)
if len(allergenDB[allergen]) == 1:
update_allergens(allergenDB, allergen)
for ingredient in ingredients:
ingredientDB[ingredient] += 1
return allergenDB, ingredientDB
with open("Day_21/input.txt", "r") as fin:
foods = [line.rstrip(")").replace(",", "").split(" (contains ") for line in fin.read().split("\n")]
# Day 21.1
allergenDB, ingredientDB = match_food_items(foods)
dangerous_ingredients = [next(iter(allergenDB[key])) for key in sorted(allergenDB.keys())]
print(sum([count for ingredient, count in ingredientDB.items() if ingredient not in dangerous_ingredients]))
# Day 21.2
print(",".join(dangerous_ingredients))
|
def console_execution(instructions):
visited = set()
acc = 0
line = 0
while line not in visited and line < len(instructions):
visited.add(line)
command, value = instructions[line]
if command == "acc":
acc += int(value)
line += int(value) if command == "jmp" else 1
return (line >= len(instructions), acc)
def repaired_console_acc(instructions):
for line in instructions:
command = line[0]
if command == "acc":
continue
line[0] = "nop" if command == "jmp" else "jmp"
is_executable, acc = console_execution(instructions)
if is_executable:
return acc
line[0] = command
with open("Day_08/input.txt", "r") as fin:
instructions = [(line.strip().split(" ")) for line in fin]
print(console_execution(instructions)[1]) # Day 8.1
print(repaired_console_acc(instructions)) # Day 8.2
|
#Compilation of Object oriented stuff in python
class first_class:
var1=3 #this is a variable of a class atrribute
def __init__(self,name,breed): #this initializes the constructor
self.name="rocky"
self.breed="blsck labrodor"
def class_function(self,var): #this is a class method
print(var*2)
new_object=first_class("h","g")
print(new_object.breed)
print(new_object.var1)
var2="random string"
print(new_object.class_function(var2)) #please add a self in the class function without fail
#Inheritance
class second_class(first_class):
def use1stmethod(self):
print()
|
# print prime numbers between 1 to 100
#count=0
#for n in range(2,100):
#for i in range(1,n+1):
#if n%i == 0:
#count+=1
#if count==2:
#print "%d" %n
#count=0
ints=[32,45,67,78]
for iv,key in enumerate(ints):
print "the index is %d, the element is %d "%(iv,key)
|
# problem in output
def func(*a,**keyword):
for key in keyword:
print keyword[key]
func(1,2,3,4,5,6,b=1,a=0,c=2,d=9)
|
#create the name of the states
states ={
"uttarpradesh":"up",
"delhi":"dl",
"andhrapradesh":"ap",
"rajasthan":"rj"
}
#create the name of the cities in the states
cities ={
"up":"agra",
"dl":"noida",
"ap":"hyderabad",
"rj":"kota"
}
print "some cities name :"
print "up has %s" %cities["up"]
print "rj has %s" %cities["rj"]
print "some states name :"
print "the short name is %s" %states["uttarpradesh"]
print "the short name is %s" %states["andhrapradesh"]
print "some cities name using states:"
print "the name of city is %s" % cities[states["uttarpradesh"]]
print "the name of city is %s" % cities[states["rajasthan"]]
print "the name of city is %s" % cities[states["delhi"]]
#print every state name with abbreviation
print'*'*10
for state,abbrev in states.items():
print "%s has this %s abbreviation " %(state,abbrev)
# print every city name with abbreviation
print'-' *10
for city,abbrev in cities.items():
print "%s has this %s abbreviation " %(city,abbrev)
# print every city in the state
print '+' *10
for state,abbrev in states.items():
print "%s has %s abbreviation and has %s city" %(state,abbrev,cities[abbrev])
|
print "whats ur name :"
x = raw_input()
print "whats ur height:"
h = raw_input()
print "wats ur weight :"
w = raw_input()
print "so ur name is %s ur height is %s ur weight is %s" %(x,h,w)
|
from sys import argv
script,user_name = argv
pr = ">>>>>>>>>>" #it is just a string variable
print "my script name is %s,my user name is %s" %(script,user_name)
print "what do you lke %s" %(user_name)
like =raw_input(pr)
print "where do you live %s" %(user_name)
live = raw_input(pr)
print "whats ur favourite food %s" %(user_name)
food = raw_input(pr)
print '''
i like %r i live in %r.
my favourite good is %r.
''' %(like,live,food)
|
def compute_mongo_age(birthYear, birthMonth, birthDay, currentYear, currentMonth, currentDay):
ageInYears = (currentYear-birthYear) + (currentMonth-birthMonth)/15 + (currentDay-birthDay)/(15*26)
return ageInYears
print(compute_mongo_age(2879,8,11,2892,2,21))
|
from tkinter import *
from tkinter import messagebox
import random
class MinesweeperCell(Label):
'''represents a Minesweeper cell'''
def __init__(self,master):
'''MinesweeperCell(master) -> MinesweeperCell
creates a new Minesweeper cell'''
Label.__init__(self,master,height=1,width=2,text='',\
relief = 'raised',bg='white',font=('Arial',18))
self.coord = (-1,-1) # (row,column) coordinate tuple
self.adjBombs = -1
self.bomb = False
self.exposed = False
self.flagged = False
# set up listeners
self.bind('<Button-1>',self.expose)
self.bind('<Button-2>',self.flag)
def expose(self,event):
'''MinesweeperCell.expose(event)
handler method for left mouse click
exposes cell'''
colormap = ['','blue','darkgreen','red','purple','maroon','cyan','black','dim gray'] # colors for different numbers
if not self.flagged and not self.exposed: # only acts on cells that are not flagged and not exposed
if not self.bomb:
self.exposed = True
self['bg'] = 'silver'
self['relief'] = 'sunken'
self.adjBombs = self.master.find_adj_bombs(self.coord) # find number of adjacent bombs
# display colored number of adjacent bombs if there are any
if self.adjBombs > 0:
self['text'] = self.adjBombs
self['fg'] = colormap[self.adjBombs]
# otherwise auto-expose adjacent cells
else:
self.master.auto_expose(self.coord,'<Button-1>')
self.master.exposedCount += 1
# check for win
if self.master.find_win():
messagebox.showinfo('Minesweeper','Congratulations -- you won!',parent=self)
self.master.end_game()
# player loses if exposed cell contains bomb
else:
messagebox.showerror('Minesweeper','KABOOM! You lose.',parent=self)
self.master.display_bombs()
self.master.end_game()
def flag(self,event):
'''MinesweeperCell.flag(event)
handler method for right mouse click
flags cell'''
if not self.exposed: # only acts on cells that are not exposed
# flags not flagged cells
if not self.flagged:
self.flagged = True
self['text'] = '*'
self.master.dec_rem_bombs() # decreases bombs remaining count by 1
# removes flag from flagged cells
else:
self.flagged = False
self['text'] = ''
self.master.inc_rem_bombs() # increases bombs remaining count by 1
class MinesweeperUnit:
'''represents a Minesweeper unit (a square of 9 cells)'''
def __init__(self,unit):
'''MinesweeperUnit(unit) -> Minesweeper Unit
creates a new Minesweeper unit with MinesweeperCells in dict unit'''
self.unit = unit # store dict of MinesweeperCell
def get_cell_list(self):
'''MinesweeperUnit.get_cell_list() -> list
returns list of MinesweeperCells'''
return list(self.unit.values())
class MinesweeperGrid(Frame):
'''object for Minesweeper grid'''
def __init__(self,master,width,height,numBombs):
'''MinesweeperGrid(master,width,height,numBombs)
creates a new Minesweeper grid with given numbers of columns, rows, and bombs'''
# initialize a new Frame
Frame.__init__(self,master,bg='black')
self.grid()
self.numColumns = width
self.numRows = height
self.numBombs = numBombs
self.remBombsCount = self.numBombs
self.exposedCount = 0 # create a counter for number of exposed cells
# create label for number of remaining bombs
self.bombLabel = Label(self,bg='white',text=str(self.numBombs),font=('Arial',24))
self.bombLabel.grid(row=self.numRows+1,column=0,columnspan=self.numColumns)
# create cells
self.cells = {} # set up dict for cells
for row in range(self.numRows):
for column in range(self.numColumns):
coord = (row,column)
newCell = MinesweeperCell(self)
newCell.coord = coord
self.cells[coord] = newCell
self.cells[coord].grid(row=row,column=column)
cellList = [cell for cell in self.cells.values()]
# randomly assign given number of bombs to cells
for b in range(self.numBombs):
cell = random.choice(cellList)
cell.bomb = True
cellList.remove(cell)
# create units
self.units = {}
for coord in self.cells:
unitCells = {}
for i in range(-1,2):
for j in range(-1,2):
# add cell to unit dict if coord valid
if 0<=coord[0]+i<self.numRows and 0<=coord[1]+j<self.numColumns:
unitCells[(coord[0]+i,coord[1]+j)] = self.cells[(coord[0]+i,coord[1]+j)]
self.units[coord] = MinesweeperUnit(unitCells) # add unit to dict of units with center cell coord as key
def find_adj_bombs(self,coord):
'''MinesweeperGrid.find_adj_bombs(coord) -> int
returns number of bombs adjacent to cell with given coord'''
adjBombCount = 0
# count number of adjacent cells with bombs
for cell in self.units[coord].get_cell_list():
if cell.bomb:
adjBombCount += 1
return adjBombCount
def auto_expose(self,coord,event):
'''MinesweeperGrid.auto_expose(coord,event)
exposes cells adjacent to cell with given coord'''
for cell in self.units[coord].get_cell_list():
cell.expose(event)
def dec_rem_bombs(self):
'''MinesweeperGrid.dec_rem_bombs()
decreases remaining bombs count by 1'''
self.remBombsCount -= 1
self.bombLabel['text'] = str(self.remBombsCount)
def inc_rem_bombs(self):
'''MinesweeperGrid.inc_rem_bombs()
increases remaining bombs count by 1'''
self.remBombsCount += 1
self.bombLabel['text'] = str(self.remBombsCount)
def display_bombs(self):
'''MinesweeperGrid.display_bombs()
displays not flagged bombs'''
for cell in self.cells.values():
if cell.bomb and not cell.flagged:
cell['bg'] = 'red'
cell['text'] = '*'
def find_win(self):
'''MInesweeperGrid.find_win() -> bool
returns True if all cells without bombs are exposed'''
if self.exposedCount == self.numRows*self.numColumns-self.numBombs:
return True
def end_game(self):
'''MinesweeperGrid.end_game()
makes all cells unable to be exposed'''
for cell in self.cells.values():
cell.exposed = True
def play_minesweeper(width,height,numBombs):
'''play_minesweeper(width,height,numBombs)
plays Minesweeper on a width by height board with given number of bombs'''
root = Tk()
root.title('Minesweeper')
mg = MinesweeperGrid(root,width,height,numBombs)
root.mainloop()
print(play_minesweeper(12,10,15))
|
import random
class Die:
'''Die class'''
def __init__(self,sidesParam=6):
'''Die([sidesParam])
creates a new Die object
int sidesParam is the number of sides
(default is 6)
-or- sidesParam is a list/tuple of sides'''
# if an integer, create a die with sides
# from 1 to sides
if isinstance(sidesParam,int):
sidesParam = range(1,sidesParam+1)
self.sides = list(sidesParam)
self.numSides = len(self.sides)
# roll the die to get a random side on top to start
self.roll()
def __str__(self):
'''str(Die) -> str
string representation of Die'''
return 'A ' + str(self.numSides) + '-sided die with ' + \
str(self.get_top()) + ' on top'
def roll(self):
'''Die.roll()
rolls the die'''
# pick a random side and put it on top
self.top = random.choice(self.sides)
def get_top(self):
'''Die.get_top() -> object
returns top of Die'''
return self.top
def set_top(self,value):
'''Die.set_top(value)
sets the top of the Die to value
Does nothing if value is illegal'''
if value in self.sides:
self.top = value
def flip(self):
index = self.sides.index(self.top)
self.sides.reverse()
self.top = self.sides[index]
def europadice():
diceList = []
sides = [1,2,3,4,'W']
dice = Die(sides)
for d in range(10):
dice.roll()
top = dice.get_top()
diceList.append(top)
greatestNum = 0
for side in sides[:4]:
count = diceList.count(side)
if count > greatestNum:
greatestNum = count
mostCommonSide = side
diceString = ''
for d in diceList:
diceString += str(d) + ' '
print(diceString)
print("We're going for all " + str(mostCommonSide) + 's')
unwantedSides = [s for s in diceList if s not in (mostCommonSide,'W')]
for s in unwantedSides:
diceList.remove(s)
print(diceList)
reroll = 1
while unwantedSides != [] and reroll <= 3:
input('Reroll #' + str(reroll) + '. Press enter to reroll. ')
length = len(unwantedSides)
unwantedSides = []
for d in range(length):
dice.roll()
top = dice.get_top()
unwantedSides.append(top)
for t in unwantedSides:
if t in (mostCommonSide,'W'):
unwantedSides.remove(t)
diceList.append(t)
diceString = ''
for dice in diceList:
diceString += str(dice) + ' '
print(diceString)
reroll += 1
if unwantedSides == []:
print('Yay, you win!')
else:
print('Sorry, only got ' + str(10-len(unwantedSides)))
|
import turtle
wn = turtle.Screen ()
hongweiBigPig = turtle.Turtle ()
for i in range(8):
for j in range(4):
hongweiBigPig.forward(-50)
hongweiBigPig.left(90)
hongweiBigPig.penup()
hongweiBigPig.forward(50)
hongweiBigPig.pendown()
wn.mainloop()
|
n = int(input('Enter a positive integer n >= 3: '))
fiboOne = 1
fiboTwo = 1
for i in range(3,n + 1):
fibo = fiboOne + fiboTwo
fiboOne = fibo
fiboTwo = fibo - fiboTwo
print(fibo)
|
def compute_mongo_age(birthYear, birthMonth, birthDay, currentYear, currentMonth, currentDay):
assert 0 <= birthMonth & birthMonth < 15, 'birthMonth: illegal argument'
ageInYears = (currentYear-birthYear) + (currentMonth-birthMonth)/15 + (currentDay-birthDay)/(15*26) # computes the age of the Mongo resident in years
return ageInYears
print(compute_mongo_age(2879, 16, 11, 2892, 2, 21))
|
f = open('africa.txt','r')
text = f.read()
f.close()
eightLetterWords = []
wordList = text.split()
for word in wordList:
if len(word) == 8:
eightLetterWords.append(word)
print(len(eightLetterWords))
|
def rot13(string):
encodedString = ''
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
for character in string:
if character in alphabet:
number = ord(character)
if number < 78 or 96 < number < 110:
newNumber = number + 13
else:
newNumber = number - 13
newCharacter = chr(newNumber)
encodedString += newCharacter
else:
encodedString += character
return encodedString
print(rot13('Hello, World!!'))
|
s = input()
count_upper = 0
count_lower = 0
for c in s:
if c.isupper():
count_upper += 1
if c.islower():
count_lower += 1
if count_upper > count_lower:
print(s.upper())
else:
print(s.lower()) |
#Breaking out of while loops
import random
class Enemy:
hp = 200
def __init__(self, attack_low, attack_high):
self.attack_low = attack_low
self.attack_high = attack_high
def get_attack(self):
print(self.attack_low)
def get_hp(self):
print("Hp is", self.hp)
enemy1 = Enemy(40, 50)
enemy1.get_attack()
enemy1.get_hp()
enemy2 = Enemy(70, 90)
enemy2.get_attack()
enemy2.get_hp()
'''
class Enemy:
def __init__(self, attack_low, attack_high):
self.attack_low = attack_low
self.attack_high = attack_high
def get_attack(self):
print(self.attack_low)
enemy1 = Enemy(40, 50)
enemy1.get_attack()
enemy2 = Enemy(70, 90)
enemy2.get_attack()
'''
'''Class Practice
class Enemy:
attackLow = 60
attackHigh = 80
def get_Attack(self):
print(self.attackLow)
enemy1 = Enemy()
enemy1.get_Attack()
enemy2 =Enemy()
enemy2.get_Attack()
'''
'''
playerHp = 260
enemyAttackLow = 60
enemyAttackHigh = 80
#Use Continue in while loop
while playerHp > 0:
dmg = random.randrange(enemyAttackLow, enemyAttackHigh)
playerHp = playerHp - dmg
if playerHp <= 30:
playerHp = 30
print("Enemy Strikes for", dmg, "points of damage. Current hp is", playerHp)
if playerHp > 30:
continue
print("You have low health. You've been teleported to nearest location")
break
'''
#breaking from the while loop
'''while playerHp > 0:
dmg = random.randrange(enemyAttackLow, enemyAttackHigh)
playerHp = playerHp - dmg
if playerHp <= 0:
playerHp = 0
print("Enemy Strikes for", dmg, "points of damage. Current hp is", playerHp)
if playerHp == 0:
print("You have died.")
#stop while loop by break keyword
while playerHp > 0:
dmg = random.randrange(enemyAttackLow, enemyAttackHigh)
playerHp = playerHp - dmg
if playerHp <= 30:
playerHp = 30
print("Enemy Strikes for", dmg, "points of damage. Current hp is", playerHp)
if playerHp == 30:
print("You have low health. You've been teleported to nearest location")
break '''
|
binary_num = input("Please enter a binary number")
i = 0
integer = 0
power = len(binary_num) - 1
while i < len(binary_num)-1:
if binary_num[i] == "1":
integer = integer + 2**power
i = i + 1
power = power - 1
print(integer)
|
class MyClass (object):
def method1(self, param_tuple):
self.local_list = []
for element in param_tuple:
if element > 10:
self.local_list.append(element)
def method2(self):
self.sum_int = 0
for element in self.local_list:
self.sum_int += element
return self.sum_int
inst1 = MyClass()
inst2 = MyClass()
inst1.method1([1, 2, 3])
print(inst1.local_list) # Line 1
inst1.method1([10, 11, 12])
print(inst1.local_list) # Line 2
print(inst1.method2()) # Line 3
# inst2.method2() # Line 4
|
def acronym ():
str1 = input("What is your string?")
str2 = str1.split("")
firstlet = ""
for i in str2:
firstlet.append(i[0])
print(firstlet.upper())
acronym()
|
def grades ():
i = int(input("Enter your grade: "))
if i >=90 and i <= 100:
print ("A")
if i >=80 and i <= 89:
print ("B")
if i >=70 and i <=79:
print ("C")
if i >=60 and i<=69:
print ("D")
if i <60:
print ("F, drop the boyfriend. hes lowering your grades.")
grades () |
# MARLA ANDERSON
# LAB 3
# got some help from Juan Pablo
from random import randint
# global variable of chutes and ladders
# remenber to let your function know you're using this variable with 'global'
chutes_ladders = {4 : 7,
8 : 15,
12 : 2,
14: 6}
# Rolls a die of six sides and returns the result
def roll_die():
roll = randint(1,6)
return roll
# makes a game (just a list) of the given dimensions
def makeGame(w, l):
list= range(1,(w*l)+1)
#This also works.
#for i in range(1,(w*1)+1):
# list.append(i)
return list
# checks if given square is a chutes or ladders
def is_chutes_ladders(d):
global chutes_ladders
if d in chutes_ladders:
return True
else:
return False
# function to make and play a game
def play_game(w,l,mode):
global chutes_ladders
#i was using this but its uneccesary for my code
mode = int(input("Who's playing? 1:pc or 2:user? "))
won = 0
if mode == 2:
game = makeGame(w,l)
players = int(input("How many players?"))
state = []
for i in range(players):
player= input("What is player's %s name?" %(i+1))
state.append({'player': player, 'state': 1,'moves': 0})
#This should be a list of dictionaries of each player's state
while won == 0:
for i in range(players):
state[i]["moves"]+=1
input("%s, Press ENTER to roll the die."%(state[i]["player"]))
roll = roll_die()
print ("%s, you rolled a %s."%(state[i]["player"],roll))
#for debugging purposes
#print(state[i]['state'])
placement = state[i]['state']+roll
#for debugging purposes
#print (placement)
# this is checking before you add the roll to the position
if is_chutes_ladders(placement):
state[i]['state'] = chutes_ladders[placement]
print ("%s, you are now in square %s." %(state[i]["player"],state[i]['state']))
else:
state[i]['state'] = placement
print ("%s, you are now in square %s." %(state[i]["player"],placement))
if (state[i]['state'] >= len(game)):
won = 1
winner = state[i]["player"]
break
print("Congratulations, %s, you win. You took %s moves."%(winner,state[i]["moves"]))
elif mode == 1:
game = makeGame(w,l)
players = int(input("How many players?"))
state = []
for i in range(players):
state.append({'player': "", 'state': 1,'moves': 0})
#This should be a list of dictionaries of each player's state
won = 0
while won == 0:
for i in range(players):
state[i]["moves"]+=1
roll = roll_die()
#for debugging purposes
#print(state[i]['state'])
placement = state[i]['state']+roll
#for debugging purposes
#print (placement)
# this is checking before you add the roll to the position
if is_chutes_ladders(placement):
state[i]['state'] = chutes_ladders[placement]
else:
state[i]['state'] = placement
if (state[i]['state'] >= len(game)):
won = 1
break
print("It took %s moves."%(state[i]["moves"]))
else:
print ("Please enter an integer: 1 or 2.")
play_game(6,6,2)
# Runs the game as a simulation and keeps track of the number of moves it takes to win and returns average
def simulate_game():
w = int(input("Enter a width for your game board?: "))
l = int(input("Enter a length for your game board?: "))
simulations = int(input("Enter how many simulations of the game you want: "))
listx =[]
for i in range(simulations):
listx.append(play_game(w,l,2))
return listx
average_moves =sum(listx)/len(listx)
print("Average moves: %s" %s(average_moves))
simulate_game()
|
import time
import math
from binary_search_tree import BSTNode
start_time = time.time()
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
duplicates = [] # Return the list of duplicates in this data structure
# BST
# root = None
# for name in names_1:
# if root is None:
# root = BSTNode(name)
# else:
# root.insert(name)
# for name in names_2:
# if root.contains(name):
# duplicates.append(name)
# STRETCH
names_1.sort()
def binary_search(names, search_value):
left = 0
right = len(names) - 1
while left <= right:
mid = math.floor((left + right) / 2)
if names[mid] < search_value:
left = mid + 1
elif names[mid] > search_value:
right = mid - 1
else:
return True
return False
for name in names_2:
if binary_search(names_1, name):
duplicates.append(name)
# set (to see best time)
# names_1_set = set(names_1)
# names_2_set = set(names_2)
# duplicates = names_1_set.intersection(names_2_set)
end_time = time.time()
print (f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print (f"runtime: {end_time - start_time} seconds")
# ---------- Stretch Goal -----------
# Python has built-in tools that allow for a very efficient approach to this problem
# What's the best time you can accomplish? Thare are no restrictions on techniques or data
# structures, but you may not import any additional libraries that you did not write yourself.
|
import unittest
from sorting import DictionarySorting
from operator import itemgetter
class TestSorting(unittest.TestCase):
instance = None
def setUp(self):
self.instance = DictionarySorting()
def test_convertToList(self):
x = {"aman": 23, "Tom": 35}
self.assertEqual(id(self.instance.convertToList(x)), id(zip(x.keys(), x.values())),
{"There is some problem with the convert method"})
def test_convertToDictionary(self):
x = self.instance.convertToList({"aman": 23, "Tom": 35})
self.assertEqual(self.instance.convertToDictionary(x), {"aman": 23, "Tom": 35},
{"There is something wrong with the convertDictonary method"})
def test_sorting(self):
self.assertEqual(self.instance.sorting({"Tom": 35, "aman": 23}), {"aman": 23, "Tom": 35},
{"There is something wrong with the sorting method"})
def test_sortingLists(self):
# Note not the actual stock prices just a sample dataset
list = [{'name': 'Goog', 'price': 879},
{'name': 'FB', 'price': 579},
{'name': 'Apple', 'price': 579},
{'name': 'Samsung', 'price': 679}]
self.assertListEqual(self.instance.sortingList(list, 'name'), sorted(list, key=itemgetter('name')),
msg="There was some problem with the sortingList method")
self.assertListEqual(self.instance.sortingList(list, 'price'), sorted(list, key=itemgetter('price')),
msg="There was some problem with the sortingList method")
self.assertEqual(self.instance.sortingList(list, 'name', 'price'), sorted(list, key=itemgetter('name', 'price')),
msg="There was some problem with the sortingList method")
self.assertEqual(self.instance.sortingList(list, 'name', 'price', 'desc'), sorted(list, key=itemgetter('name', 'price'), reverse=True),
msg="There was some problem with the sortingList method")
def test_max(self):
self.assertEqual(self.instance.max({"aman": 23, "Tom": 35}, "value"), {"Tom": 35},
{"There was something wrong with the max method"})
self.assertEqual(self.instance.max({"aman": 23, "Tom": 35}, "key"), {"aman": 23},
{"There was something wrong with the max method when using orderBy"})
def test_min(self):
self.assertEqual(self.instance.min({"aman": 23, "Tom": 35}, "value"), {"aman": 23},
{"There was something wrong with the min method"})
self.assertEqual(self.instance.min({"aman": 23, "Tom": 35}, "key"), {"Tom": 35},
{"There was something wrong with the min method when using orderBy"})
if __name__ == '__main__':
unittest.main() |
low = 1
high = 1000
print('think of a number between 1 and 1000')
input('Press ENTER to start')
count = 0
# guess = high//2
while low != high:
count = count + 1
guess = low + (high - low) // 2
high_low = input(f'My guess is {guess}. Should i guess higher or lower? '
'Enter h for higher, l for lower and c for correct: ')
if high_low == 'h':
# guess = guess // 2
low = guess + 1
elif high_low == 'l':
# guess = guess + (guess // 2)
high = guess - 1
elif high_low == 'c':
print(f'I got it in {count} guesses')
else:
print('Enter h, l or c')
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.