text stringlengths 37 1.41M |
|---|
# CN_Mobile=['131','132','133','134'] #移动
# CN_Unicorn=['147','199','188'] #联通
# CN_telecon=['156','158','157'] #电信
#
# mobile=input('请输入11位的手机号码:')#输入11位手机号码
# mobile_s = mobile[:3] #截取前三位手机号码
# if mobile.isdigit():
# if len(mobile)!=11:
# print('号码位数不对')
# else:
# if mobile_s in CN_Mobile:
# print('这是移动号码段')
# elif mobile_s in CN_Unicorn:
# print('这是联通号码段')
# elif mobile_s in CN_telecon:
# print('这是电信号码段')
# else:
# print('非电话号码段')
# else:
# print('非法字符!')
telno=input("请输入手机号码:")
if not telno.isdigit():
print("输入内容有非法字符")
elif len(telno) !=11:
print("输入的手机号码位数不对!")
else:
telno3=telno[:3]
print("手机号前3位:"+telno3)
if telno3 in ('130','131','132','145','155','156','166','171','175','176','185','186','166'):
print ("联通号段")
elif telno3 in('134','135','136','137','138','139','147','150','151','152','157','158','159','172','178','182','183','184','187','188','198'):
print("移动号段")
elif telno3 in('133','149','153','173','177','180','181','189','199'):
print("电信号段")
else:
print("未知号段!")
|
# author:JinMing time:2020-05-16
# -*- coding: utf-8 -*-
import threading
import time
def foo(something, num): # 定义每个线程要执行的函数
for i in range(num):
print("CPU 正在", something)
time.sleep(1)
# 创建线程实例,target 指向任务函数,args 为 target 指向的函数传参
t1 = threading.Thread(target=foo, args=("看电影", 2)) # 生成了一个线程实例
t2 = threading.Thread(target=foo, args=("听音乐", 5)) # 生成了另一个线程实例
# 启动线程
t1.start()
t2.start() |
#Ingresar nombres en una lista, luego buscar un nombre y de encontrarlo decir en qué posición está.
lista_nombres = []
nombre = input("\nIngresar nombre (0 para finalizar): ")
while (nombre != "0"):
lista_nombres.append(nombre)
nombre = input("\nIngresar nombre (0 para finalizar): ")
print("\n -------- LISTA COMPLETA -----------\n")
nombre = input("Ingrese un nombre para encontrar su posición en la lista: ")
if nombre in lista_nombres:
print("El nombre se encuentra en la posición: " + str(lista_nombres.index(nombre)))
else:
print("Nombre no encontrado.") |
#Dada una lista cargada con 7 números enteros, obtener el promedio. Mostrar por pantalla dicho promedio y los números de la lista que sean mayores que él.
lista_numeros = [0 for x in range(7)]
print("A continuación, se calculará el promedio de siete números")
# numero = int(input("\nIngresar número: "))
for i in range(len(lista_numeros)):
lista_numeros[i] = int(input("\nIngresar número: "))
suma=0
for i in range(len(lista_numeros)):
suma = suma + lista_numeros[i]
res = suma / len(lista_numeros)
print("\nEl promedio es: " + str(res))
|
#Transformar la cadena "River vuelve a las copas", en la cadena "River vuelve a la copa". Resolverlo recorriendo la cadena original como si fuera una lista.
cadena = 'River vuelve a las copas'
cadena3 = cadena.replace("s", "")
# print(cadena2)
print(cadena3)
cadena2 = cadena.split('s')
for i in range(len(cadena2)):
print(cadena2[i], end="")
print("\n")
|
#Determinar cuál es la vocal que aparece con mayor frecuencia.
s = "Quiero comer manzanas, solamente manzanas."
# s = s.replace(",", "")
# s = s.replace(".", "")
# lista_s = s.split()
s.lower()
# cantidad_a = s.count("a")
# cantidad_e = s.count("e")
# cantidad_i = s.count("i")
# cantidad_o = s.count("o")
# cantidad_u = s.count("u")
lista_cantidades = [s.count("a"), s.count("e"), s.count("i"), s.count("o"), s.count("u")]
lista_vocales = ["a", "e", "i", "o", "u"]
cantidad_mayor = 0
for i in range(len(lista_cantidades)):
if lista_cantidades[i] > cantidad_mayor:
cantidad_mayor = lista_cantidades[i]
if lista_cantidades.index(cantidad_mayor) == 0:
print("La vocal que aparece con mayor frecuencia es: a")
elif lista_cantidades.index(cantidad_mayor) == 1:
print("La vocal que aparece con mayor frecuencia es: e")
elif lista_cantidades.index(cantidad_mayor) == 2:
print("La vocal que aparece con mayor frecuencia es: i")
elif lista_cantidades.index(cantidad_mayor) == 3:
print("La vocal que aparece con mayor frecuencia es: o")
elif lista_cantidades.index(cantidad_mayor) == 4:
print("La vocal que aparece con mayor frecuencia es: u")
for i in range(len(lista_cantidades)):
print(lista_vocales[i] + " = " + str(lista_cantidades[i]) + " veces.")
|
##Nombre de alumno: Leonardo Roman Leonhardt
#Pedir un nombre y una opción ('>' o '<') y según esta mostrar por ejemplo.: Juan es menor de edad
nombre = input("\n Ingrese un nombre: ")
opcion = input("\n Ingrese un signo mayor que ( > ) o menor que ( < ) para definir si " + nombre + " es mayor o menor de edad : ")
if (opcion == ">"):
print("\n" + nombre + " es mayor de edad. \n")
elif (opcion == "<"):
print("\n" + nombre + " es menor de edad. \n")
else:
print("\n ¡Operación no válida! \n") |
#Pedir el ingreso de 10 números. Contar los mayores de 23. Mostrar el resultado.
datos = [0 for x in range(10)]
for i in range(0,len(datos)):
datos[i] = int( input( "Ingrese número {}: ".format(i+1) ))
print ("Los números mayores que 23 son: ")
for i in range(0, len(datos)):
if datos[i] > 23:
print( datos[i], end= ' ')
cantidad_Numeros = 0
for i in range(0, len(datos)):
if datos[i] > 23:
cantidad_Numeros = cantidad_Numeros + 1
print("\nLa cantidad de números mayores a 23 es: " + str(cantidad_Numeros)) |
test_string = "I am a NOUN "
test_string = test_string.replace("NOUN","Rafeeq")
print test_string |
from datetime import datetime
class Node:
def __init__(self, name, date, clickCount):
"""Represents a generic object in the bookmark manager
Keyword Args:
name -- name of the node
date -- date the node was added
clickCount -- frequency of node clicks
"""
self.parent = None
self.name = name
self.date = date
self.clickCount = clickCount
class Folder(Node):
def __init__(self, name, children = None, date = datetime.now(), clickCount = 0):
"""Represents a folder in the manager
Keyword Args:
name -- name of folder
children -- list of children (None by default)
date -- date folder was added (current time by default)
clickCount -- number of times folder has been clicked (0 by default)
"""
Node.__init__(self, name, date, clickCount)
if children is None:
self.children = []
else:
self.children = list(children)
for child in children:
child.parent = self
class Bookmark(Node):
def __init__(self, name, url, date = datetime.now(), clickCount = 0):
"""Represents a bookmark in the manager
Keyword Args:
name -- user-defined name of bookmark
url -- url the bookmark points to
date -- date bookmark was added (current time by default)
clickCount -- number of times bookmark has been clicked (0 by default)
"""
Node.__init__(self, name, date, clickCount)
self.url = url
|
a = int(input("성적을 입력하세요 : "))
if a>= 90 :
print("A")
elif a>=80:
print("B")
elif a>=70:
print("C")
elif a>=60:
print("D")
else :
print("F") |
# a1에 한행씩 리스트 생성해서 a2로 한줄씩 통째로 복사하는 다중리스트
a1 = [] # 1줄 (행)용 리스트
a2 = [] # 최종목표인 다중리스트(이차원)
# 다중리스트 생성
v = 1
for i in range(0, 3): # 3행
for j in range(0, 4): # 4열
a1.append(v)
v += 1
print(a1)
a2.append(a1) # 배열 <- 배열
print(a2)
a1 = []
# 다중리스트 출력
for i in range(0, 3): # 3행
for j in range(0, 4): # 4열
print("$3d" % a2[i][j], end=" ")
print() |
print(2**3)
print(pow(2,3))
print(100 ** 100)
print(9/2)
print(9//2) #몫 구하기
print(9%2) #나머지 구하기
print(3.14E5)
print(0xff, 0o77, 0b1111) #16/8/2진수를 10진수로 변환
print(hex(255), oct(63), bin(15)) #10진수를 다른진수로 변환
print()
a = (100 == 100)
print(a) #True
b = "파이썬\n만세"
print(b)
b = """파이썬
만세"""
#"""(겹따옴표 세개) -> 화면에 보이는 그대로 출력
print(b)
b = "파이썬\
만세"
print(b) |
import re
import nltk
nltk.download('stopwords')
nltk.download('punkt')
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
def clean_text(text_string):
text_string = text_string.lower()
text_string = re.sub(r'[^\w\s]', '', text_string) # Removes punctuations from test query.
# text_string = re.sub(r'\b\d+\b', '', text_string) # Removes numbers from test query. Works for: ashwin 124. Doesn't work for: Ashwin124.
text_string = text_string.strip() # Strip unwanted character
stop_words = set(stopwords.words('english')) # English stop words.
tokens = word_tokenize(text_string) # Tokenized input query.
filtered_words = [word for word in tokens if word not in stop_words] # Removing stop words from the input test query
return filtered_words |
__author__ = 'dario'
def main():
pass
def print_columns(data):
print "\nCOLUMNS IN DATA SET ARE:"
for x in data.columns:
print x
def append_squared_value_for_columns(data, columns_to_square):
added_column_names = []
for column in columns_to_square:
squared = data[column] * data[column]
new_column_name = '{}_squared'.format(column)
added_column_names.append(new_column_name)
data[new_column_name] = squared # append the squared value of the column
#print_columns(data)
return added_column_names
def append_cubed_value_for_columns(data, columns_to_cube):
added_column_names = []
for column in columns_to_cube:
squared = data[column] * data[column] * data[column]
new_column_name = '{}_cubed'.format(column)
added_column_names.append(new_column_name)
data[new_column_name] = squared # append the squared value of the column
#print_columns(data)
return added_column_names
def append_specific_combined_features(data, features_src, features_dest):
for column in features_src:
for other_column in features_dest:
combined_column = data[column] * data[other_column]
data["{}_and_{}_comb".format(column, other_column)] = combined_column
def append_features_combined_with_each_other(data, features_to_combine):
for column_index in range(0, len(features_to_combine)):
column = features_to_combine[column_index]
for other_column_index in range(0, len(features_to_combine)):
if column_index < other_column_index:
other_column = features_to_combine[other_column_index]
combined_column = data[column] * data[other_column]
data["{}_and_{}_comb".format(column, other_column)] = combined_column # append the squared value of the column
#print_columns(data)
def show_some_stats(df):
# take a look at the dataset
# It prints the first 5 rows
print df.head()
print "\nCOLUMNS:"
for x in df.columns:
print x
# summarize the data
print "\nDATA SUMMARY:"
print df.describe()
# take a look at the standard deviation of each column
print "\nVARIABLES STDDEV:"
print df.std()
if __name__ == "__main__":
main() |
# -*- coding: utf-8 -*-
"""Collecting multiple drivers in a database."""
import json
from .driver import Driver
class DriverDB(list):
"""Representing the database (inherits from ``list``)."""
def __init__(self):
"""Create an empty database.
Take a look at ``from_file`` for loading an existing database file.
"""
list.__init__(self)
self.manufacturers = set()
def load_from_disk(self, filename):
"""Load a database from file.
Args:
filename : file to load database from
"""
self.clear()
self.manufacturers.clear()
with open(filename, 'r') as f:
driver_list = json.load(f)
for entry in driver_list:
driver = Driver.from_dict(entry)
self.manufacturers.add(driver.manufacturer)
self.append(driver)
def write_to_disk(self, filename):
"""Write database to disk.
Args:
filename : file in which to store database
"""
driver_list = []
for driver in self:
driver_list.append(driver.dict_representation())
with open(filename, 'w') as f:
json.dump(driver_list, f, indent=4, sort_keys=True)
@classmethod
def from_file(cls, filename):
"""Create a new database from existing file.
Args:
filename : file from which to initialize database
Example:
>>> mydatabase = DriverDB.from_file("mypersonaldb.json")
"""
driver_db = cls()
driver_db.load_from_disk(filename)
return driver_db
|
animals = [
{'name':'cow', 'size':'large'},
{'name':'bird', 'size':'small'},
{'name':'fish', 'size':'small'},
{'name':'rabbit', 'size':'medium'},
{'name':'pony', 'size':'large'},
{'name':'squirrel', 'size':'medium'},
{'name':'fox', 'size':'medium'}]
import itertools
from operator import itemgetter
sorted_animals = sorted(animals, key=itemgetter('size'))
for key, group in itertools.groupby(sorted_animals, key=lambda x:x['size']):
print (key),
print (list(group)) |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 13 10:05:21 2018
@author: souravg
To do : Accept First and Last name and print them in reverse order.
"""
fname = input("Enter your First Name : ")
lname = input("Enter your Last Name : ")
print("Your FullName is %s and the reverse order of your FullName is %s" %(fname+' '+lname,lname+' '+fname))
|
DECREASING_POWER_OF_10 = [1000, 100, 10, 1]
ROMAN_TO_NUMERAL = {1000: 'M', 500: 'D', 100: 'C', 50: 'L', 10: 'X', 5: 'V', 1: 'I'}
def convert(number):
assert isinstance(number, int) and 0 < number < 3000
decreasing_remain_list = [int(number % (power_of_10 * 10) / power_of_10) for power_of_10 in DECREASING_POWER_OF_10]
roman_array = [_convert_power_of_ten_to_roman(power_of_10, digit) for power_of_10, digit in
zip(DECREASING_POWER_OF_10, decreasing_remain_list)]
return ''.join(roman_array)
def _convert_power_of_ten_to_roman(power_of_10, quotient):
if quotient <= 3:
roman = ROMAN_TO_NUMERAL[power_of_10] * quotient
elif quotient == 4:
roman = ROMAN_TO_NUMERAL[power_of_10] + ROMAN_TO_NUMERAL[power_of_10 * 5]
elif quotient == 5:
roman = ROMAN_TO_NUMERAL[power_of_10 * 5]
elif 6 <= quotient <= 8:
roman = ROMAN_TO_NUMERAL[power_of_10 * 5] + ROMAN_TO_NUMERAL[power_of_10] * (quotient - 5)
else:
roman = ROMAN_TO_NUMERAL[power_of_10] + ROMAN_TO_NUMERAL[power_of_10 * 10]
return roman
|
import random
DESCRIPTION = "Answer yes if given number is prime. Otherwise answer no."
RANDOM_NUMBER_MIN = 2
RANDOM_NUMBER_MAX = 100
def get_question_answer():
"""Function to create random number and return result(prime or no)"""
question = random.randint(RANDOM_NUMBER_MIN, RANDOM_NUMBER_MAX)
answer = 'yes' if is_prime(question) else 'no'
return question, answer
def is_prime(number):
"""Checking if number is prime or not"""
if number < 2:
return False
max_divider_possible = number // 2
for divider in range(2, max_divider_possible):
if number % divider == 0:
return False
return True
|
class Board(object):
def __init__(self, boardSize, playerNum):
self.__boardSize = boardSize
self.__playerNum = playerNum
self.__gameBoard = []
self.__CandLmap = {}
self.__player_loc = {}
self.__delimeter = '-'
self.__initBoard()
# PROPERTIES
@property
def gameBoard(self):
return self.__gameBoard
@property
def CandLmap(self):
return self.__CandLmap
@property
def PlayerLoc(self):
return self.__player_loc
# PRIVATE METHODS
# initialize the game board and players
def __initBoard(self):
cellLength = 4 + self.__playerNum
self.__gameBoard = [[self.__delimeter*cellLength] * self.__boardSize for x in range(self.__boardSize)]
# set players off the board
for i in range(self.__playerNum):
self.__player_loc[i] = 0
self.__CandLmap = {1:38, 4:14, 9:31, 16:6, 21:42, 28:84, 36:44,
48:26, 49:11, 51:67, 56:53, 62:19, 64:60,
71:91, 80:100, 87:24, 93:73, 95:75, 98:78}
# make Chutes and Ladder labels and place on board
ladderCount = chuteCount = 0
delimString = self.__delimeter*(cellLength-3)
for item in self.__CandLmap:
key = item
value = self.__CandLmap[item]
if key > value:
labelKey = 'CT'+str(chuteCount)+delimString
labelValue = 'CB'+str(chuteCount)+delimString
chuteCount += 1
else:
labelKey = 'LB'+str(ladderCount)+delimString
labelValue = 'LT'+str(ladderCount)+delimString
ladderCount += 1
self.__placeOnBoard(key, labelKey)
self.__placeOnBoard(value, labelValue)
# convert position into grid coordinates and update gameBoard
def __placeOnBoard(self,position,label,isNewPos=False):
gridCoord = self.__posToGrid(position)
y = gridCoord[0]
x = gridCoord[1]
# if updating previous player position, look for player number to replace,
# else for new player position replace right most '-' with player number
if str(label).isnumeric():
if isNewPos:
delimeter = self.__delimeter
else:
delimeter = str(label)
label = self.__delimeter
labelCur = self.__gameBoard[y][x]
playerFound = False
cellLength = 4 + self.__playerNum
while(not(playerFound)):
if labelCur[cellLength-1] == delimeter:
label = labelCur[:cellLength-1] + str(label) + labelCur[cellLength:]
playerFound = True
else:
cellLength-=1
self.__gameBoard[y][x] = label
# convert position into grid coordinates and update gameBoard
def __posToGrid(self,position):
# convert position to grid coordinates (remember board starts at (9,0), moves Left to Right and Up
# and then Right to Left and Up
y = self.__boardSize - 1 - int((position-1) / self.__boardSize)
x = (position-1) % self.__boardSize if y%2 else self.__boardSize - 1 - ((position-1) % self.__boardSize)
return [y, x]
# PUBLIC METHODS
# Compute the location for current move and move player
def makeMove(self, turn, spin):
# get player pos
pos_current = self.__player_loc[turn]
pos_new = 100 if pos_current + spin > 100 else pos_current + spin
# check for chute or ladder
pos_new = self.__CandLmap.get(pos_new,pos_new)
# remove old player location
if pos_current > 0:
self.__placeOnBoard(pos_current, turn, False)
# update player location
self.__player_loc[turn] = pos_new
self.__placeOnBoard(pos_new, turn, True)
# check for winner
def checkWinner(self,turn):
return self.__player_loc[turn] == 100
# Print out game board
def printBoard(self):
for row in self.__gameBoard:
print(' '.join([str(s) for s in row]))
print("\n")
|
# Simple finite while loops
n = 5
while n > 0:
n -= 1
print(n)
a = ["foo", "bar", "baz"]
while a: # != ['']
print(a.pop(-1))
# while loop with an else statement
# while <expr>:
# <statement(s)>
# else:
# <additional_statement(s)>
n = 5
while n > 0:
n -= 1
print(n)
else:
print("Loop done.")
|
def quick_sort(arr):
"""[3, 8, 2, 5, 1, 4, 7, 6]
pick pivot, put smaller on the left, larger on the right,
keep doing these for the subset of the array:left, right
"""
if len(arr) <= 1:
return arr
k = choose_pivot(arr)
left, right = partition(arr, k)
l = quick_sort(left)
r = quick_sort(right)
return l + r
def partition(arr, k):
middle = arr[k]
i = 0
for j, ele in enumerate(arr, 0):
if ele <= middle:
if j >= i:
switch(i, j, arr)
i += 1
switch(k, i-1, arr)
return arr[:i], arr[i:]
def choose_pivot(arr):
return 0
def switch(idx, idy, arr):
arr[idx], arr[idy] = arr[idy], arr[idx]
arr = [3, 8, 2, 5, 1, 4, 7, 6]
print arr
print quick_sort(arr)
import random
arr2 = range(10000)
random.shuffle(arr2)
print arr2
print quick_sort(arr2)
|
class Node(object):
def __init__(self, val):
self.val = val
self.next_ = None
def __repr__(self):
val = str(self.val)
if self.next_ is None:
return val
return val + ',' + str(self.next_)
def _is_head(pre):
return pre is None
def _is_tail(cur):
return cur is None
class LinkedList(object):
def __init__(self, *args):
self.head = None
self.tail = None
if args:
map(lambda val: self.append(val), args)
def __repr__(self):
return str(self.head)
def delete(self, idx):
prev = self._find_pre(idx)
cur = prev.next_
if prev is None:
del cur
return
prev.next_ = cur.next_
def append(self, val):
node = Node(val)
if self.head is None:
self.head = self.tail = node
return
self.tail.next_ = node
self.tail = node
def sort(self):
cur = self.head
swapped = True
while swapped:
cur = self.head
swapped = False
while cur:
succ = cur.next_
if succ and cur.val > succ.val:
cur.val, succ.val = succ.val, cur.val
swapped = True
cur = succ
def sorted_insert(self, val):
cur = self.head
node = Node(val)
pre = None
while cur:
if cur.val >= val:
if pre is None:
self.head = node
else:
pre.next_ = node
node.next_ = cur
return
pre, cur = cur, cur.next_
if self.head is None:
self.head = node
return
self.tail.next_, self.tail = node, node
def insert(self, idx, val):
node = Node(val)
pre = self._find_pre(idx)
if pre is None:
self.head, node.next_ = node, self.head
else:
pre.next_, node.next_ = node, pre.next_
if node.next_ is None:
self.tail = node
def _find_pre(self, idx):
def helper(pre, cnt):
if cnt == idx:
return pre
cur = self.head if pre is None else pre.next_
if cur is None:
if idx == cnt + 1:
return pre
else:
raise ValueError('invalid index')
return helper(cur, cnt+1)
return None if self.head is None else helper(None, 0)
def reverse_recursive(self):
def helper(head):
parent = head.next_
if parent is None:
return head
rest = helper(parent)
rest.next_ = head
head.next_ = None
return head
head = self.head
helper(head)
self.head, self.tail = self.tail, self.head
def test():
lis = LinkedList(3, 2, 4, 9, 10)
print lis
lis.reverse_recursive()
print 'lis reversed'
print lis
lis.insert(3, 12)
print 'inserted(3, 12)'
print lis
lis.insert(0, 100)
lis.insert(6, 9)
lis.insert(8, 88)
lis.sort()
lis.sorted_insert(0)
lis.sorted_insert(111)
print lis
if __name__ == '__main__':
exit(test())
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input());
A = set()
B = set()
sum1=0;
A = input();
#print(A)
A = A.split(" ");
#print(A)
for i in range(n):
A[i]=int(A[i]);
A = set(A)
#print(A)
#print(A);
op = int(input());
for i in range(op):
a = input().split(' ');
B = input();
B = B.split(" ");
for i in range(int(a[1])):
B[i]=int(B[i]);
B = set(B)
#print(B)
#print(a);
b=a[0];
if( b == "intersection_update"):
A.intersection_update(B);
elif(b == "update"):
A.update(B);
elif(b == "symmetric_difference_update"):
A.symmetric_difference_update(B);
else:
A.difference_update(B);
#print(A)
for i in range(len(A)):
#sum = sum + int(A[i])
sum1 = sum(A);
print(sum1);
|
# 32ms/98.63%
class Solution:
def countSegments(self, s: str) -> int:
count = 0
flag = True
for i in s:
if i == " ":
flag = True
else:
if flag:
count += 1
flag = False
|
# 36ms/94.95%
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for symbol in s:
if symbol == "(" or symbol == "[" or symbol == "{":
stack.append(symbol)
else:
if stack == []:
return False
char = stack.pop()
if ord(symbol) - ord(char) < 1 or ord(symbol) - ord(char) > 2:
return False
if stack == []:
return True
else:
return False |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 56ms/100%
class Solution:
def findTilt(self, root: TreeNode) -> int:
# return sum and tilt simutaneously
def _findTilt(root):
if root.left is None:
if root.right is None:
return root.val, 0
else:
right_sum, right_tilt = _findTilt(root.right)
return root.val + right_sum, abs(right_sum) + right_tilt
if root.right is None:
left_sum, left_tilt = _findTilt(root.left)
return root.val + left_sum, abs(left_sum) + left_tilt
left_sum, left_tilt = _findTilt(root.left)
right_sum, right_tilt = _findTilt(root.right)
return left_sum + root.val + right_sum, abs(right_sum - left_sum) + left_tilt + right_tilt
if root is None:
return 0
else:
return _findTilt(root)[1]
# simplify version
# 68ms/91.45%
class Solution1:
def findTilt(self, root: TreeNode) -> int:
# return sum and tilt simutaneously
def _findTilt(root):
if root is None:
return 0, 0
left_sum, left_tilt = _findTilt(root.left)
right_sum, right_tilt = _findTilt(root.right)
return left_sum + root.val + right_sum, abs(right_sum - left_sum) + left_tilt + right_tilt
return _findTilt(root)[1] |
'''
When working with iterators, henerators, etc.
look at the documentation for the itertools module
'''
from itertools import islice, count
from itertools import chain
from list_comprehension import is_prime
def main():
thousand_primes=islice((x for x in count() if is_prime(x)), 1000)
print(thousand_primes, type(thousand_primes))
print("list of first 1K prime numbers:", list(thousand_primes))
print("sum of first 1K prime numbers:", sum(list(thousand_primes)))
# Note: if you need to use the object again, you need to re-generate it
thousand_primes = islice((x for x in count() if is_prime(x)), 1000)
print(thousand_primes, type(thousand_primes))
# Other built-ins use with itertools: any ("or"), or all ("and")
print(any([False, False, True]))
print(all([False, False, True]))
print("are there prime numbers between 1328 1361",
any(is_prime(x) for x in range(1328, 1362)),
list(x for x in range(1328, 1362) if is_prime(x))
# Check if all names in an iterable are in tiel form: First Letter capiatlize
names = ["London", "New york", "Ogden"]
print(all(name == name.title()for name in names))
# Another built-in: zip()
monday = [12, 14, 14, 15, 15, 16, 15, 13, 10, 9]
tuesday = [13, 14, 15, 15, 1, 17, 16, 16, 12, 12]
wednesday = [2, 3, 4, 5, 6, 7, 6, 5, 4, 6]
# (:6.1f) --6 char width, 1 decimal precision, floating point
for temps in zip(monday, tuesday, wednesday):
print("mine={:4.1f}, max={:4.1f}, avg={:4.1f}".format(
min(temps), max(temps), sum(temps)/len(temps)))
# chain
all_temps = chain(monday, tuesday, wednesday)
print("all temperatures>0", all(t>0 for t in all_temps))
|
rows = 'ABCDEFGHI'
cols = '123456789'
def cross(a, b):
return [x + y for x in a for y in b]
boxes = cross(rows, cols)
row_units = [cross(x, cols) for x in rows]
column_units = [cross(rows, y) for y in cols]
square_units = [cross(xs, ys) for xs in ['ABC', 'DEF', 'GHI'] for ys in ['123', '456', '789']]
unitlist = row_units + column_units + square_units
units = dict((box, [u for u in unitlist if box in u]) for box in boxes)
peers = dict((box, set(sum(units[box], [])) - {box}) for box in boxes)
def display(values):
"""Display the values as a 2-D grid.
Input: The sudoku in dictionary form
Output: None"""
if values is None:
print('illegal puzzle grid')
return
width = 1 + max(len(values[box]) for box in boxes) # should be 2
line = '+'.join(['-' * (width * 3)] * 3)
for r in rows:
print(''.join(values[r + c].center(width) + ('|' if c in '36' else '') for c in cols))
if r in 'CF': print(line)
print()
if __name__ == '__main__':
print(boxes)
print(row_units)
print(column_units)
print(square_units)
print(units)
print(peers)
display(dict((box, box[1:]) for box in boxes))
|
# Python program to find out
# Sum of elements at even and
# odd index positions separately
# Function to calculate Sum
def SumEvenOdd(a, n):
even = 0
odd = 0
for i in range(n):
# Loop to find even and odd Sum
if i % 2 == 0:
even += a[i]
else:
odd += a[i]
print ("Even index positions sum ", even)
print ("Odd index positions sum ", odd)
# main Function
arr = [9, 2, 3, 4, 0, 5 ]
n = len(arr)
SumEvenOdd(arr, n)
|
def postorder_traversal(root):
if root:
left = postorder_traversal(root.left)
right = postorder_traversal(root.right)
return left + right + [root.val]
else:
return []
def postorder_traversal_iteratively(root):
if not root:
return []
result, queue = [], [(root, False)]
while queue:
curNode, visited = queue.pop()
if curNode:
if visited:
result.append(curNode.val)
else:
queue.append((curNode, True))
queue.append((curNode.right, False))
queue.append((curNode.left, False))
return result
|
import unittest
from trees.treenode.treenode import TreeNode
from .postorder_traversal import postorder_traversal, postorder_traversal_iteratively
class PreorderTraversalTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
a = TreeNode('a')
b = TreeNode('b')
c = TreeNode('c')
d = TreeNode('d')
e = TreeNode('e')
f = TreeNode('f')
g = TreeNode('g')
h = TreeNode('h')
i = TreeNode('i')
f.left = b
f.right = g
b.left = a
b.right = d
d.left = c
d.right = e
g.right = i
i.left = h
cls.root = f
def test_postorder_traversal(self):
postorder = postorder_traversal(self.root)
self.assertListEqual(postorder, ['a', 'c', 'e', 'd', 'b', 'h', 'i', 'g', 'f'])
def test_postorder_traversal_iteratively(self):
postorder = postorder_traversal_iteratively(self.root)
self.assertListEqual(postorder, ['a', 'c', 'e', 'd', 'b', 'h', 'i', 'g', 'f'])
if __name__ == '__main__':
unittest.main()
|
"""
Write a Python program to print the following string in a specific format
Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high,
Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are" Output :
Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are
"""
print("Twinkle, twinkle, little star, \n\tHow I wonder what you are!\n\t\t Up above "
"the world so high,\n\t\t Like a diamond in the sky. \nTwinkle, twinkle, little star, \n\tHow I wonder what you are")
"""
Write a Python program to get the Python version you are using
"""
import sys
python_version = sys.version
print("The python version is: ",python_version)
python_version_info = sys.version_info
print("The python version info is: ",python_version_info)
"""
Write a Python program to display the current date and time.
Sample Output :
Current date and time :
2014-07-05 14:34:14
"""
import datetime
current_date = datetime.datetime.now()
print("The Current date is : ", current_date.strftime("%Y-%M-%H %H:%M:%S"))
"""
Write a Python program which accepts the radius of a circle from the user and compute the area.
Sample Output :
r = 1.1
Area = 3.8013271108436504
"""
import math
# Method 1
radius = 1.1
area_of_circle = math.pi*radius*radius
print("The Area of the Circle is : ", area_of_circle)
# Method 2
circle_radius = int(input("Enter the radius: "))
area_of_circle = math.pi*circle_radius*circle_radius
print("The Area of the Circle is : ", area_of_circle)
# Method 3
def circle_area(radius):
area_of_circle = math.pi * radius * radius
return area_of_circle
print("The area of the Circle is :",circle_area(3))
"""
Write a Python program which accepts the user's first and
last name and print them in reverse order with a space between them.
"""
user_first_name = input("Enter the first name: ")
user_last_name = input("Enter the last name: ")
print("User name is : ",user_last_name, " ", user_first_name)
|
# Tyler Hedegard 5/13/2016
# Thinkful.com Python Introduction Lesson 3
# Pirate Bartender
questions = {
"strong": "Do ye like yer drinks strong?",
"salty": "Do ye like it with a salty tang?",
"bitter": "Are ye a lubber who likes it bitter?",
"sweet": "Would ye like a bit of sweetness with yer poison?",
"fruity": "Are ye one for a fruity finish?",
}
ingredients = {
"strong": ["glug of rum", "slug of whisky", "splash of gin"],
"salty": ["olive on a stick", "salt-dusted rim", "rasher of bacon"],
"bitter": ["shake of bitters", "splash of tonic", "twist of lemon peel"],
"sweet": ["sugar cube", "spoonful of honey", "spash of cola"],
"fruity": ["slice of orange", "dash of cassis", "cherry on top"],
}
names = {
"adjective": ["Fluffy","Gallant","Rebellious","Sassy","Malicious"],
"noun": ["Sea-Dog","Batman","Knight","Nail","Doormat"],
}
def ask(questions):
"""Asks all questions in a dictionary and returns the answers in a dictionary"""
answers = {}
for question in questions:
reply = input(questions[question])
if reply.lower() == "yes" or reply.lower() == "y":
answers[question] = True
else:
answers[question] = False
return answers
def makeDrink(ingredients, preferences):
"""Takes preferences and ingredients, picks random ingredient from each preference and returns a drink (name and ingredients)"""
import random
drinkName = random.choice(names["adjective"]) + " " + random.choice(names["noun"])
drink = {
"name": drinkName,
"ingredients": [],
}
for preference in preferences:
if preferences[preference] == True:
drink["ingredients"].append(random.choice(ingredients[preference]))
return drink
if __name__ == '__main__':
done = False
while done == False:
drink = makeDrink(ingredients,ask(questions))
print("Here is your {} with {}.".format(drink["name"],drink["ingredients"]))
another = input("Would you like another drink (Y/N)? ")
if another.lower() == "n" or another.lower() == "no":
done = True
print("Thank you for coming in!") |
from random import shuffle
import itertools
palo = "C D P T".split()
rank = "2 3 4 5 6 7 8 9 10 J Q K A".split()
def shuffleDeck():
# Función para barajear y repartir
deck = list(itertools.product(rank, palo))
shuffle(deck)
return deck[:26], deck[26:]
def compareCards(card1, card2):
# Compare the cards. First cast them
cards = []
for value in [card1, card2]:
try:
cards.append(int(value[0]))
except ValueError:
if "J" in value[0]: cards.append(11)
elif "Q" in value[0]: cards.append(12)
elif "K" in value[0]: cards.append(13)
else: cards.append(14)
if cards[0] > cards[1]:
return 1
elif cards[0] < cards[1]:
return 2
else:
return 0
class Player:
def __init__(self, N, hand):
# Debe tener una mano este usuario
self.name = N
self.hand = hand
def remainingCards(self):
return len(self.hand)
def drawCard(self):
self.card = self.hand.pop(0)
return self.card
def draw3Cards(self):
self.card = [self.hand.pop(0) for i in range(3)]
return self.card[-1]
def addCards(self, card):
# Agrega cartas
if type(card) is tuple:
# En caso que solo sea una
self.hand.append(card)
else:
# Mas de una carta
self.hand.extend(card)
def currentCard(self):
return self.card
def giveCard(self):
card = self.card
self.card = None
return card
def turn(self):
return "{}: {} {}".format(self.name, self.card[0], self.card[1])
if __name__ == "__main__":
p1 = input("Dame el jugador 1: ")
p2 = input("Dame el jugador 2: ")
print("Revolviendo el deck...")
h1, h2 = shuffleDeck()
# Generando usuarios
P1 = Player(p1, h1)
P2 = Player(p2, h2)
while P1.remainingCards() > 10 and P2.remainingCards() > 10:
for player in [P1, P2]:
# if player.name == p1:
# input("presiona para sacar una carta: ")
player.drawCard()
result = compareCards(P1.currentCard(), P2.currentCard())
if result == 1:
# Gano el primero
print("Ganó {} {} {}".format(P1.name, P1.turn(), P2.turn()))
P1.addCards([P2.giveCard(), P1.giveCard()])
elif result == 2:
# Gano el segundo
print("Ganó {} {} {}".format(P2.name, P1.turn(), P2.turn()))
P2.addCards([P1.giveCard(), P2.giveCard()])
else:
#Empate
print(P1.turn() + " " + P2.turn())
input("Empate, hay que volver a sacar, presiona para continuar ")
result = compareCards(P1.draw3Cards(), P2.draw3Cards())
if result == 1:
# Gano el primero
print("Ganó {}".format(P1.name))
P1.addCards([P2.giveCard(), P1.giveCard()])
elif result == 2:
# Gano el segundo
print("Ganó {}".format(P2.name))
P2.addCards([P1.giveCard(), P2.giveCard()])
print("{}: {}, {}:{}".format(p1, P1.remainingCards(), p2, P2.remainingCards()))
|
# Import the random module so we can randomly generate numbers
# Import time module for dramatic pausing effect
import random
import time
# Create a Superhero class that will act as a template for any heroes we create
class Superhero():
# Initializing our class and setting its attributes
def __init__(self):
self.superName= superName
self.power = power
self.braun = braun
self.brains = brains
self.stamina = stamina
self.wisdom = wisdom
self.constitution = constitution
self.dexterity = dexterity
self.speed = speed
# Adding random values to each stat using the random() function
braun = random.randint(1,20)
brains = random.randint(1,20)
stamina = random.randint(1,20)
wisdom = random.randint(1,20)
constitution = random.randint(1,20)
dexterity = random.randint(1,20)
speed = random.randint(1,20)
# Creating a list of possible super powers
superPowers = ['Flying', 'Super Strength', 'Telepathy', 'Super Speed', 'Can Eat a Lot of Hot Dogs', 'Good at Skipping Rope']
# Randomly choosing a super power from the superPowers list
# and assigning it to the variable power
power = random.choice(superPowers)
# Creating lists of possible first and last names
superFirstName = ['Wonder', 'Whatta', 'Real', 'Incredible', 'Astonihing', 'Decent', 'Stupendous', 'Above-average', 'That Guy', 'Darth']
superLastName = ['Boy', 'Man', 'Dingo', 'Body', 'Girl', 'Woman', 'Guy', 'Hero', 'Max', 'Dream', 'Macho Man', 'Stallion']
# Randomizing Super Hero Name
# We do this by choosing one name from each of our two name lists
# And adding it to the variable superName
superName = random.choice(superFirstName)+ " " +random.choice(superLastName)
# Creating a subclass of Superhero named Mutate
# Mutate heroes will get a +10 bonus to their speed score.
class Mutate(Superhero):
def __init__(self):
Superhero.__init__(self)
print("You create a Mutate!")
self.speed = self.speed + 10
# Creating a subclass of Superhero named Robot
# Robot heroes will get a +10 bonus to their braun score.
class Robot(Superhero):
def __init__(self):
Superhero.__init__(self)
print("You created a robot!")
self.braun = self.braun + 10
# Introductory text
print("Are you ready to create a super hero with the Super Hero Generator 3000?")
# Ask the user a question and prompt them for an answer
# input() 'listens' to what they type on their keyboard
# We then use upper() to change the users answer to all uppercase letters
print("Enter Y/N:")
answer = input()
answer = answer.upper()
# While loop to check for the answer "Y"
# This loop will continue while the value of answer IS NOT "Y"
while answer != "Y":
print("I'm sorry, but you have to choose Y to continue!")
print("Choose Y/N:")
answer = input()
answer = answer.upper()
print("Great, let's get started!")
# Letting the user chooose which type of hero to create
print("Choose from the following hero options: ")
print("Press 1 for a Regular Superhero")
print("Press 2 for a Mutate Superhero")
print("Press 3 for a Robot Superhero")
answer2 = input()
if answer2=='1':
# Creating the Superhero object
hero = Superhero()
# We print out the result of the created object, including its parameters
print("You created a regular super hero!")
print("Generating stats, name, and super powers.")
# Creating dramatic effect
for i in range(1):
print("..........")
time.sleep(3)
print ("(nah...you wouldn't like THAT one...)")
for i in range(2):
print("..........")
time.sleep(3)
print("(almost there....)")
print(" ")
print("Your name is %s." % (hero.superName))
print("You super power is: ", hero.power)
print("Your new stats are:")
print("")
print("Brains: ", hero.brains)
print("Braun: ", hero.braun)
print("Stamina: ", hero.stamina)
print("Wisdom: ", hero.wisdom)
print("Constitution: ", hero.constitution)
print("Dexterity: ", hero.dexterity)
print("Speed: ", hero.speed)
print("")
elif answer2=='2':
# Creating a Mutate object
hero2 = Mutate()
print("Generating stats, name, and super powers.")
# Creating dramatic effect
for i in range(1):
print("..........")
time.sleep(3)
print("(nah...you wouldn't like THAT one...)")
for i in range(2):
print("..........")
time.sleep(3)
print("Your name is %s." % (hero2.superName))
print("You super power is: ", hero2.power)
print("Your new stats are:")
print("")
print("Brains: ", hero2.brains)
print("Braun: ", hero2.braun)
print("Stamina: ", hero2.stamina)
print("Wisdom: ", hero2.wisdom)
print("Constitution: ", hero2.constitution)
print("Dexterity: ", hero2.dexterity)
print("Speed: ", hero2.speed)
print("")
elif answer2=='3':
# Create a Robot character
hero3 = Robot()
print("Generating stats, name, and super powers.")
# Creating dramatic effect
for i in range(1):
print("..........")
time.sleep(3)
print("(nah...you wouldn't like THAT one...)")
for i in range(2):
print("..........")
time.sleep(3)
print("Your name is %s." % (hero3.superName))
print("You super power is: ", hero3.power)
print("Your new stats are:")
print("")
print("Brains: ", hero3.brains)
print("Braun: ", hero3.braun)
print("Stamina: ", hero3.stamina)
print("Wisdom: ", hero3.wisdom)
print("Constitution: ", hero3.constitution)
print("Dexterity: ", hero3.dexterity)
print("Speed: ", hero3.speed)
print("")
else:
print("You did not choose the proper answer! Program will now self-destruct")
|
import time
def PowSum(numbers):
Sum=0
New_list=iteration(numbers)
x=digits(numbers)
for n in range(0,x):
Sum=int(New_list[n])**x+Sum
return Sum
def flower(Numbers):
if PowSum(Numbers)==Numbers:
print(Numbers,'\n')
def iteration(numb):
# Origin_list=[]
# for i in range(0,times):
# Origin_list.append((numb//(10**(times-1-i)))%10)
# return Origin_list
return list(str(numb))
def digits(nu):
for i in range(0,100):
if nu//(10**i)==0:
return i
# return 4
start = time.clock()
for num in range(0,10000):
# x = digits(num)
# list1=iteration(num,int(x))
# list1=iteration(num,digits(num))
flower(num)
# flower(digits(num),num,digits(num))
elapsed = (time.clock() - start)
print("Time used:",elapsed)
|
# Create a function called calculate_avg_rating
# Parameters: the function should have one argument of type list of Review (i.e., the arg should be a list of Review objects)
# Returns: the function should return a float: the average of all review ratings that are given in the list as an argument to this function.
# The returned value should be rounded to the closest second decimal. Use the build-in round function: https://www.w3schools.com/python/ref_func_round.asp
#
# If the argument is an empty list, return 0.0
# for reference on exceptions, check the class notes here: https://github.com/FTEC-6v99/python-overview/blob/master/advanced/exceptions.py
#
# Make sure that you add type hints to the function paramter and return value
import typing as t
from app.src.Review import Review
def calculate_avg_rating(reviews: t.List[Review]) -> float:
if len(reviews) == 0:
return 0.0
sum = 0.0
for review in reviews:
sum += review.rating
return round(sum / len(reviews), 2) |
"""
1. Szukanie min i max [1,23] |
2. a = |0-1|/|1-23| = a = |0 - 1| / |min - max|
3. b = 1 - 1/22 * 23 = b = 1 - (a * max)
4. y = a*x + b -> 1/22*x - 1/22 | min - max
"""
def findMinimum(data):
return min(data)
def findMaximum(data):
return max(data)
def findExtrema(data):
return min(data), max(data)
def normalizeDataset(data, lowBorder=0, topBorder=1):
normalizedData = []
a = abs(lowBorder - topBorder) / abs(findMinimum(data) - findMaximum(data))
b = topBorder - (a * findMaximum(data))
for element in data:
# normalizacja liniowa aX + b
normalizedData.append(a * element + b)
return normalizedData
def printDataset(data):
for element in data:
print("%6.2f" % element, end= " ")
print()
data = [1 ,23 ,4 ,2 , 4, 5, 4, 11,22] # do znormalizowania od 0 -> 1
printDataset(data)
printDataset(normalizeDataset(data))
printDataset(normalizeDataset(data, -1, 1))
printDataset(normalizeDataset(data, lowBorder = -1, topBorder = 1))
findExtrema(data)
|
#CLI - command line interface
#GUI - graphical user interface
from d3_2_objects.p67_pwn.student_controller import StudentController
# utworzenie obiektu zawierającego metody obsługi dziekanatu
dziekanat = StudentController()
while(True):
menu = input("APLIKACJA DZIEKANAT\n"
"(D)-dodaj nowego studenta\n(U)-usuń studenta\n(Z)-zaktualizuj oceny\n"
"(O)-wyczyść listę ocen studenta\n(W)-wypisz listę studentów\n(Q)-wyjdź z programu")
if(menu.upper()=="D"):
name = input("podaj imię: ")
lastname = input("podaj nazwisko: ")
dziekanat.addStudent(name,lastname)
elif(menu.upper()=="U"):
print(dziekanat)
try:
index_no = int(input("podaj numer indeksu"))
dziekanat.deleteStudentByIndex(index_no)
except:
print("Numer indeksu musi być liczbą!")
elif(menu.upper()=="Z"):
try:
index_no = int(input("podaj numer indeksu"))
grades = input("Podaj listę ocen (po przecinku)")
grades = grades.split(",")
# konwersja ocen do liczb całkowitych
for i, grade in enumerate(grades):
grades[i] = int(grades[i])
# wywołanie metody dodającej oceny do wybranego studenta
dziekanat.addGradesToStudent(index_no,grades)
except:
print("Błąd danych! Nie można wykonać konwersji lub błędny numer indeksu")
elif(menu.upper()=="O"):
try:
index_no = int(input("podaj numer indeksu"))
dziekanat.deleteStudentGrades(index_no)
except:
print("Błędny numer indeksu")
elif(menu.upper()=="W"):
print(dziekanat)
elif(menu.upper()=="Q"):
# przerwanie pętli while
break
else:
print("Błędny wybór!") |
# P 55
# Woda zamarza przy 32 stopniach Fahrenheita, a wrze przy 212 stopniach Fahrenheita.
# Napisz program, który wyświetli tabelę przeliczeń stopni Celsjusza na stopnie Fahrenheita
# w zakresie od –20 do +40 stopni Celsjusza (co 5 stopni). Pamiętaj o wyświetlaniu znaku plus/minus przy temperaturze.
print(" C | F")
for temp_c in reversed(range(-20, 41, 5)):
print("%+3iC | %+3iF" % (temp_c, round((9 / 5) * temp_c + 32)))
print()
c_to_f = {}
for temp_c in reversed(range(-20, 45, 1)):
c_to_f[temp_c] = (9/5) * temp_c + 32
if(temp_c != 0):
print("%+4iC | %5.1fF" % (temp_c, c_to_f[temp_c]))
else:
print("%4iC | %5.1fF" % (temp_c, c_to_f[temp_c]))
print(c_to_f)
|
# Napisz program zliczający liczbę wartości unikatowych wprowadzonych przez użytkownika
# P44
slowo = input("Pdaj co kolwiek: ")
zbior = set(slowo)
print(sorted(zbior))
for index, element in enumerate(sorted(zbior)):
print(element + ":=", index, end=" ")
|
# P59
# Napisz funkcję, która wygeneruje losowe zdanie zawierające podaną liczbę (domyślnie 5) losowo wygenerowanych wyrazów.
from random import sample, choice, randint, random, randint, choices
names = ["Ala","Ola","Ela", "Andrij", "Agni", "Andrij"]
# print(sample(names, 5))
for element in sample(names, 5):
print("%s " % element, end=" ")
print()
def randSet(list):
for element in sample(names, 5):
print("%s " % element, end=" ")
print(randSet(names))
print()
##########################
# P 59
# Napisz funkcję, która wygeneruje losowe zdanie zawierające podaną liczbę (domyślnie 5) losowo wygenerowanych wyrazów.
content = "Ciąg został omówiony w roku 1202 przez Leonarda z Pizy, zwanego Fibonaccim, " \
"w dziele Liber abaci jako rozwiązanie zadania o rozmnażaniu się królików. " \
"Nazwę ciąg Fibonacciego spopularyzował w XIX w. Edouard Lucas"
"""
1. Podziel zdania na wyrazy
2. Losuj wyrazy i przypisów je do nowo wygenerowanego zdania
"""
# print(str.split(content))
# for slowo in content:
# print(slowo, end=" ")
# print()
def splitSentenceBySeparator(content, separator):
return content.split(separator)
def createSentenceByListOfWords(listOfWords):
sentence = ""
for word in listOfWords:
sentence += word + " "
return sentence + "."
def generateSentence(content, n = 5):
words = splitSentenceBySeparator(content, " ")
generatedSentence = choices(words, k = n)
return createSentenceByListOfWords(generatedSentence)
print(splitSentenceBySeparator(content, " "))
print(createSentenceByListOfWords(splitSentenceBySeparator(content, " ")))
print(generateSentence(content))
|
a = "sample text"
b = [1,2,3,1,1,2] # lista
c = (1,2,1,2,1) # krotka
d = {1,2,3,4,5} # zbiór
e = {'a':1,'b':2,'c':3} # Słownik
print()
############ Napisy
print("# napisy = Tekst")
a_tekst = "tekst"
print(a_tekst.capitalize())
print(a_tekst)
print(a_tekst[1])
print ('a' and 'b', "'a' and 'b‘# 'b'")
print ('a' or 'b'," 'a' or 'b' #'a'")
print()
############# Krotka Tuple
# krotka nie jest modyfikowalna nie możemy modyfikować i usuwać elementów krotek
print("# Krotka Tuple = () ")
a_tuple = (0, 1,2,3,4, 5, 6, 7, 8, 9, 10)
print(a_tuple)
print()
############## Listy
print("# Lista = [] ")
a_list = [0, 1,2,3,4, 5, 6, 7, 8, 9, 10]
a_list.append(6)
a_list.append(6)
print(a_list, "a_list.append(6) dodaje element x na koniec listy")
a_list.remove(6)
print(a_list, "a_list.remove(6) odnajduje pierwszy napotkany x i usuwa go z listy ")
a_list.insert(0,'x')
print(a_list, "a_list.insert(0,'x') dodaje do listy element x w miejsce o indeksie i")
a_list.pop(0)
print(a_list, "a_list.pop(0) zwraca i-ty element i usuwa go z listy.")
print(a_list[0])
print(a_list[0:5:1], "List[indeksStart : indeksStop]")
print(a_list[:5], "List[indeksStart : indeksStop]")
print(a_list[::3], "List[indeksStart :: wielokrotność]")
print(a_list[1::3], "List[indeksStart :: wielokrotność]")
print(9 in a_list )
print(9 not in a_list )
for elem in a_tekst:
print (elem)
print (a_tekst)
for i in range(3):
print("a_tekst\t")
print([a_tekst for i in a_tekst])
print()
print(a_tekst, end=' ')
############### Set zbiory = {1,2,3,4,5}'
# Zbiory zmienne nie mogą być ani kluczami w słownikach ani elementami innych zbiorów.
print('# Set zbiory = {1,2,3,4,5}')
a_set = {1, 2, 3,4,5,6,7,8,9,10}
a_set = frozenset(a_list)
a_set = set(a_list) # Nowy zbiór tworzymy używając słowa kluczowego set()
a_set.add('80')
a_set.add('99')
print (a_set, "a_set.add('80') dodanie do zbioru")
a_set.discard('99')
print (a_set, "a_set.discard('99') usunięcie z zbioru")
a_set.remove('80')
print (a_set, "a_set.remove('80') usunięcie z zbioru")
x = [1,2] + [3,4]
print(x)
print (2 in [1,2,3])
a_set = a_set ^ a_set
print(a_set)
print()
############## Dictionary (slownik)
print('# Dictionary (slownik)')
a_dict = { 'a':1,'b':2, 'c':3 , 'd':4}
# Dodawanie klucza i wartości do słownika
a_dict["e"] = 5
print(len(a_dict))
print (a_dict.keys())
print (a_dict.values())
print (a_dict.items())
print (a_dict['a'])
a_dict.pop("c")
print (a_dict, "a_dict.pop('c') Odczytuje i usuwa wartość ze słownika")
a_dict.popitem()
print (a_dict, "a_dict.popitem() Odczytuje i usuwa ostatnią wartość ze słownika")
a_dict.clear()
print (a_dict, "a_dict.clear() Czyści cały słownik")
a_dict = { 'a':1,'b':2, 'c':3 , 'd':4}
a_dict2 = a_dict
a_dict2 = a_dict.copy() # Nadpisuje całą zawartość Slownik2 do Slownik1
a_dict2.update(a_dict) #Aktualizuje Slownik1 w oparciu o Slownik2
print(a_dict2, "a_dict2")
'a' in a_dict.keys() #Sprawdza występowanie określonego klucza w słowniku
a_set = set(a_list)
a_list = list(a_set)
a_tuple = tuple(a_list)
print(" %2i %5.2f %d %e %s %c" % (11, 1, 1.01, 100, 'A', 'A'))
#################################
tekst = "tekst1 tekst2"
lista = list(tekst)
print(lista)
lista = tekst.split()
print(lista)
lista = sorted(lista, reverse = True)
print(lista)
lista.sort()
print(lista)
tekst.count('t')
print(tekst.count(""))
zbior = set([1,2,3])
tekst = str(zbior) + "}" +'3'
print(tekst)
zbior = set(tekst)
print(zbior)
sorted(zbior)
print(sorted(zbior, reverse = False))
print()
slownik = {1 : 'wartość1', 2 : 'wartośćN'}
print(slownik[1])
slownik[1] = 'wartość2'
print(slownik[1])
slownik2 = slownik.copy()
print(slownik)
print(slownik2)
print()
slownik[3] = "wartość3"
slownik[2] = "wartość2"
print(slownik)
print(slownik2)
print()
slownik2.update(slownik)
print(slownik2)
slownik2.update(slownik)
print(slownik2)
|
from math import exp, log
deltas = [0.41, 0.49, 0.55, 0.65, 0.73]
# for the first time we are calling get_diffs, we use 100. For the second stage, we use the calculated diff
def check_diff(diffs, diff):
if diff in diffs:
return diffs[diff]
return 100
def intermediate_func(delta, velocityOne, velocityTwo):
return delta * velocityOne * exp(velocityTwo - velocityOne)
def get_diffs(velocityToCompare, velocities, x=1, differences=None):
if differences is None:
differences = {}
diffs = {}
teVelocity, ltVelocity, vVelocity, stVelocity = velocities
if velocityToCompare < teVelocity:
diffs['teDiff'] = check_diff(differences, "teDiff") + x * (
deltas[0] * teVelocity * exp(teVelocity - velocityToCompare))
elif velocityToCompare < ltVelocity:
diffs['teDiff'] = check_diff(differences, "teDiff") - x * intermediate_func(deltas[1], teVelocity,
velocityToCompare)
elif velocityToCompare < vVelocity:
diffs['ltDiff'] = check_diff(differences, "ltDiff") - x * intermediate_func(deltas[2], ltVelocity,
velocityToCompare)
elif velocityToCompare < stVelocity:
diffs['vDiff'] = check_diff(differences, "vDiff") - x * intermediate_func(deltas[3], vVelocity,
velocityToCompare)
else:
diffs['stDiff'] = check_diff(differences, "stDiff") - x * intermediate_func(deltas[4], stVelocity,
velocityToCompare)
return diffs
def calculate_difficulties(currentVelocity, velocities):
# todo why so many diffs. floating around? get rid of them
teVelocity, ltVelocity, vVelocity, stVelocity = velocities
diffs = get_diffs(currentVelocity, velocities)
while len(diffs) < 4:
if 'teDiff' in diffs and 'ltDiff' not in diffs:
diffs['ltDiff'] = diffs['teDiff'] + intermediate_func(deltas[1], teVelocity, ltVelocity)
if 'ltDiff' in diffs and not ('teDiff' in diffs and 'vDiff' in diffs):
if 'teDiff' not in diffs:
diffs['teDiff'] = diffs['ltDiff'] - intermediate_func(deltas[1], teVelocity, ltVelocity)
if 'vDiff' not in diffs:
diffs['vDiff'] = diffs['ltDiff'] + intermediate_func(deltas[2], ltVelocity, vVelocity)
if 'vDiff' in diffs and not ('ltDiff' in diffs and 'stDiff' in diffs):
if 'ltDiff' not in diffs:
diffs['ltDiff'] = diffs['vDiff'] - intermediate_func(deltas[2], ltVelocity, vVelocity)
if 'stDiff' not in diffs:
diffs['stDiff'] = diffs['vDiff'] + intermediate_func(deltas[3], vVelocity, stVelocity)
if 'stDiff' in diffs and 'vDiff' not in diffs:
diffs['vDiff'] = diffs['stDiff'] - intermediate_func(deltas[3], vVelocity, stVelocity)
return diffs
def get_speed_difficulty(currentVelocity, targetVelocity, velocities):
diffs = calculate_difficulties(currentVelocity, velocities)
finalDiffs = get_diffs(targetVelocity, velocities, -1, diffs)
finalDiffsKeys = [*finalDiffs]
if len(finalDiffsKeys) == 1:
return finalDiffs[finalDiffsKeys[0]]
return 0
def get_estimated_twopointfour(currentVelocity, velocities, currentFitness):
diffs = calculate_difficulties(currentVelocity, velocities)
teVelocity, ltVelocity, vVelocity, stVelocity = velocities
if diffs['teDiff'] > currentFitness:
predicted_time = teVelocity - log((diffs['teDiff'] - currentFitness) / (deltas[0] * teVelocity))
if predicted_time < teVelocity:
return predicted_time
if currentFitness > diffs['teDiff']:
predicted_time = teVelocity + log((currentFitness - diffs['teDiff']) / (deltas[1] * teVelocity))
if predicted_time < ltVelocity:
return predicted_time
if currentFitness > diffs['ltDiff']:
predicted_time = ltVelocity + log((currentFitness - diffs['ltDiff']) / (deltas[2] * ltVelocity))
if predicted_time < vVelocity:
return predicted_time
if currentFitness > diffs['vDiff']:
predicted_time = vVelocity + log((currentFitness - diffs['vDiff']) / (deltas[3] * vVelocity))
if predicted_time < stVelocity:
return predicted_time
predicted_time = stVelocity + log((currentFitness - diffs['stDiff']) / (deltas[4] * stVelocity))
return predicted_time
|
#!/bin/python3
import math
import os
import random
import re
import sys
#import numpy as np
#
# Complete the 'numbersSquare' function below.
#
# The function accepts following parameters:
# 1. INTEGER n
# 2. INTEGER s
#
def numbersSquare(n, s):
# Write your code here
#rs = [[0,0],[0,0]]
rs = [[0 for j in range(n)] for i in range(n)]
#rs = np.zeros(n,n)
for i in range (0,n):
if i==0:
rs[0][0]=s
else:
data = rs[i-1][0]
for j in range (0,i+1):
data+=1
#rs[j][i].append(data)
rs[j][i]=data
for j in range(i-1,-1,-1):
rs[i][j] = rs[i][j+1]+1
for i in range(0,n):
str1 = ' '.join(map(str,rs[i])) #------> HOW TO PRINT LIST AS STRING
print(str1)
if __name__ == '__main__':
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
s = int(first_multiple_input[1])
numbersSquare(n, s)
|
# -*- coding: utf-8 -*-
"""
Created on Thu May 6 22:13:38 2021
@author: sh010
"""
class Node:
def __init__(self,elem, link = None):
self.data = elem
self.link = link
class LinkedList:
def __init__(self):
self.head = None
def isEmpty(self): return self.head == None
def clear(self): self.head = None
def size(self):
node = self.head
count = 0
while not node == None :
node = node.link
count += 1
return count
def display(self, msg='LinkedList'):
print(msg, end=' ')
if not self.isEmpty():
node = self.head
while node.link != None:
print(node.data, end ="->")
node = node.link
print(node.data)
def getNode(self, pos):
if pos < 0 : return None
node = self.head
while pos > 0 and node != None:
node = node.link
pos -= 1
return node
def getEntry(self, pos):
node = self.getNode(pos)
if node == None : return None
else : return node.data
def replace(self, pos, elem):
node = self.getNode(pos)
if node != None: node.data = elem
def find(self, data):
node = self.head;
while node is not None:
if node.data == data : return node
node = node.Link
return node
def insert(self, pos, elem):
before = self.getNode(pos-1)
if before == None:
self.head = Node(elem, self.head)
else:
node = Node(elem, before.link)
before.link = node
def delete(self, pos):
before = self.getNode(pos-1)
if before == None:
self.head = self.head.link
elif before.link != None:
before.link = before.link.link
def merge(self, l):
node = l.head
before = self.getNode(self.size()-1)
before.link = node
l.clear()
return l
A = LinkedList()
for i in range(5):
A.insert(i, i)
print("A의 길이는 ",A.size(),"이다.")
B = LinkedList()
for i in range(5):
B.insert(i, i)
print("B의 길이는 ",B.size(),"이다.")
A.merge(B)
print("merge 연산 후: A의 길이는 ",A.size(),"이다.")
print("merge 연산 후: B의 길이는 ",B.size(),"이다.")
A.display() |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 29 11:56:16 2021
@author: sh010
"""
class Node:
def __init__(self,elem, link = None):
self.data = elem
self.link = link
class LinkedList:
def __init__(self):
self.head = None
def isEmpty(self): return self.head == None
def clear(self): self.head = None
def size(self):
node = self.head
count = 0
while not node == None :
node = node.link
count += 1
return count
def display(self, msg='LinkedList'):
print(msg, end='')
if not self.isEmpty():
node = self.head
while node.link != None:
print(node.data, end ="->")
node = node.link
print(node.data)
def getNode(self, pos):
if pos < 0 : return None
node = self.head
while pos > 0 and node != None:
node = node.link
pos -= 1
return node
def getEntry(self, pos):
node = self.getNode(pos)
if node == None : return None
else : return node.data
def replace(self, pos, elem):
node = self.getNode(pos)
if node != None: node.data = elem
def find(self, data):
node = self.head;
while node is not None:
if node.data == data : return node
node = node.Link
return node
def insert(self, pos, elem):
before = self.getNode(pos-1)
if before == None:
self.head = Node(elem, self.head)
else:
node = Node(elem, before.link)
before.link = node
def delete(self, pos):
before = self.getNode(pos-1)
if before == None:
self.head = self.head.link
elif before.link!= None:
before.link = before.link.link
s = LinkedList()
n = int(input("노드의 개수 : "))
for i in range(n):
data = input(f"노드#{i+1} 데이터 : ")
s.insert(i, data)
s.display("생성된 연결 리스트: ")
"""s.display('단순연결리스트로 구현한 리스트(초기상태):')
s.insert(0,10); s.insert(0,20); s.insert(1,30)
s.insert(s.size(), 40); s.insert(2, 50)
s.display()
print(s.size())
s.reverse()
s.display()""" |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 13 15:46:22 2021
@author: sh010
"""
MAX_QSIZE = 10
class CircularQueue:
def __init__(self):
self.front = 0
self.rear = 0
self.items = [None] * MAX_QSIZE
def isEmpty(self):return self.front == self.rear
def isFull(self): return self.front == (self.rear+1)%MAX_QSIZE
def clear(self): self.front = self.rear
def enqueue(self, item):
if not self.isFull():
self.rear = (self.rear+1)%MAX_QSIZE
self.items[self.rear] = item
def dequeue(self):
if not self.isEmpty():
self.front = (self.front+1)%MAX_QSIZE
return self.items[self.front]
def peek(self):
if not self.isEmpty():
return self.items[(self.front + 1) % MAX_QSIZE]
def size(self):
return (self.rear - self.front +MAX_QSIZE) % MAX_QSIZE
def display(self):
out = []
if self.front < self.rear :
out = self.items[self.front+1:self.rear+1]
else:
out = self.items[self.front+1:MAX_QSIZE]\
+ self.items[0:self.rear+1]
print("[f=%s,r=%d] ==> "%(self.front, self.rear), out)
q = CircularQueue()
for i in range(8): q.enqueue(i)
q.display()
for i in range(5): q.dequeue()
q.display()
for i in range(8, 14): q.enqueue(i)
q.display() |
# Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento. salario + (salario*15/100)
salario = float(input("Informe o salário: "))
aumento = salario + (15 / 100)
novo_salario = salario + aumento
print(f"Seu salário com aumento é R${novo_salario}") |
# Faça um programa que receba um valor, e traga informações sobre esse valor, dizendo se é alfanumérico, numérico e etc.
num = input("Informe um valor: ")
if num.isalpha() and num.isupper():
msg = "é letra do alfabeto e está em maiúsculo"
elif num.isalpha() and num.islower():
msg = "é letra do alfabeto e está em minúsculo"
elif num.isalnum():
msg = "alfanumérico"
elif num.isnumeric():
msg = "número"
print(f"Status: {msg}") |
fruits = ["apple", "banana", "cherry", "guava"]
print(fruits)
print(type(fruits))
print(fruits[2])
print(fruits[-2])
print(fruits[0:])
if "banana" in fruits:
print("Exist!")
fruits[0] = "sev"
fruits[2] ="deshi"
print(fruits)
newfruits=["aam", "jamun", "amrood"]
print(fruits[0:2])
fruits[0:2] = newfruits
fruits.insert(-1, "watemenon")
fruits.append("kuchhnhi")
fruits.extend(newfruits)
fruits.remove("kuchhnhi")
fruits.pop(0)
del fruits[0]
print(fruits)
fruits.clear()
print(fruits) |
#x = 32
#txt = """My name is rohit and my age is {}
#Also i am leving in Pune since {} years"""
#print(txt.format(32,3))
#y = "welcom to \"Python\" world"
#print(y)
#y="Welcome to Python World.\n with Rohit Shukla" #for new line
#print(y)
#y="welcome"
#print(y.capitalize()) #Capitlize function in string
#y="welcome"
#print(y.count("e")) #count function in string
#y="welcome to the python world with rohit"
#print(y.find("rohit")) #find function in string
#y="welcome to the python world with rohit"
#print(y.index("rohit")) #index function in string
#y="welcome to the python world with rohit"
#print(y.islower()) #islower function in string
y="welcome to the python world with rohit"
print(y.isupper()) #isupper function in string
|
def solution(A):
"""
A sorted array has been rotated so that the elements might appear in the
order 3, 4, 5, 6, 7, 1, 2. How would you find the minimum element? You may
assume that the array has all unique elements.
>>> solution([3, 1, 2])
1
>>> solution([2, 3, 4, 6, 1])
1
>>> solution([2, 1])
1
"""
if len(A) == 1:
return A[0]
if len(A) == 2:
if A[0] < A[1]:
return A[0]
else:
return A[1]
middle, rest = divmod(len(A), 2)
if A[0] > A[middle + rest]:
min_elem = solution(A[:middle + rest])
elif A[-1] < A[middle]:
min_elem = solution(A[middle + rest:])
return min_elem
|
def solution(stairs):
"""
A child is running up a staircase with n steps, and can hop either 1 step,
2 steps, or 3 steps at a time. Implement a method to count how many
possible ways the child can run up the stairs.
>>> solution(5)
13
>>> solution(3)
4
>>> solution(7)
44
"""
map_solution = {1: 1, 2: 2, 3: 4}
def calculate(stairs):
try:
return map_solution[stairs]
except KeyError:
return (calculate(stairs - 1) + calculate(stairs - 2) +
calculate(stairs - 3))
return calculate(stairs)
|
# Real Mini Project
from selenium import webdriver
from bs4 import BeautifulSoup
import time
import tkinter as tk
from tkinter import ttk
import pandas as pd
# import requests
# from_city = input("Flying from: ")
# to_city = input("Flying to: ")
# day = input("What date (dd/mm/yyyy): ")
def popup(msg):
popup = tk.Tk()
popup.wm_title("Flights Data ")
NORM_FONT = ("Verdana", 20)
label = ttk.Label(popup, text=msg, font=NORM_FONT)
label.pack(side="top", fill="x", pady=10)
B1 = ttk.Button(popup, text="Ok", command = popup.destroy)
B1.pack()
popup.mainloop()
def search_flight():
try:
from_loc = e1.get()
to_loc = e2.get()
date = e3.get()
# print(from_loc)
# from_loc = "chennai" #input("Enter Source : ")
# to_loc = "bangalore" #input("Enter Destination : ")
# date = "30/09/2021" #input("")
#url = "https://www.expedia.ie/Flights-Search?trip=oneway&leg1=from:"+from_loc+",to:"+to_loc+",departure:"+date+"TANYT&passengers=adults:1,children:0,seniors:0,infantinlap:Y&options=cabinclass:economy&mode=search&origref=www.expedia.ie"
url = "https://www.expedia.co.in/Flights-Search?trip=oneway&leg1=from:" + from_loc + ",to:" + to_loc + ",departure:" + date + "TANYT&passengers=adults:1,children:0,seniors:0,infantinlap:Y&options=cabinclass:economy&mode=search"
print(f"URL: {url}")
print("The cheapest flights: \n")
# r = requests.get(url)
driver = webdriver.Safari()
driver.get(url)
time.sleep(5)
depa_time = driver.find_elements_by_xpath("//span[contains(@data-test-id,'departure-time')]")
departure_time_list = [a.text for a in depa_time]
arrival_departure = driver.find_elements_by_xpath("//div[contains(@data-test-id,'arrival-departure')]")
arrival_departure_list = [a.text for a in arrival_departure]
journey_duration = driver.find_elements_by_xpath("//div[contains(@data-test-id,'journey-duration')]")
journey_duration_list = [a.text for a in journey_duration]
price_column = driver.find_elements_by_xpath("//div[contains(@data-test-id,'price-column')]")
price_column_list = [a.text for a in price_column]
print(departure_time_list)
print(arrival_departure_list)
print(journey_duration_list)
print(price_column_list)
# fetching data using BeautifulSoup
#soup = BeautifulSoup(driver.page_source, 'html.parser')
# Getting all the data from the website using html elements and tags.
# departure_time = soup.find_all('span', attrs={'data-test-id': 'departure-time'})
# arrival_departure = soup.find_all('div', attrs={'data-test-id': 'arrival-departure'})
# journey_duration = soup.find_all('div', attrs={'data-test-id': 'journey-duration'})
# price_column = soup.find_all('div', attrs={'data-test-id': 'price-column'})
# Cleaning up the data, such as getting only text and removing whitespace. This all gets stored in list using list comprehension.
# departure_time_list = [a.getText().strip() for a in departure_time]
# arrival_departure_list = [a.getText().strip() for a in arrival_departure]
# journey_duration_list = [b.getText().strip() for b in journey_duration]
price_column_list = []
for pr in price_column:
p = str(pr.text)
price = p[p.find('Rs')+1 : p.find('Rs',p.find('Rs', p.find('Rs')+1))]
price_column_list.append('R'+price)
if len(departure_time_list) == 0 :
print("Flights are not available at this moment...... ")
return
driver.quit()
#Adding all data to Dictionary
flights = {"arrival - departure": arrival_departure_list,
"departure_time" : departure_time_list,
"journey_duration": journey_duration_list,
"price": price_column_list}
flights_data = pd.DataFrame(flights)
print("Current Cheapest Flight is = ")
# exporting the data into excel sheet
flights_data.to_excel("output.xlsx", index=None)
print(flights_data)
msg="Flights data downloaded successful !! \n"
popup(msg)
except Exception as e:
print(e)
popup("Error While Fetching Data....")
pass
root = tk.Tk()
text = tk.Text(root,bg='light blue')
text.grid(row=4,column=0,columnspan=2)
root.title('Mini Project Find Chepest Flights')
tk.Label(root,text="Enter Source : ").grid(row=0)
e1 = tk.Entry(root)
e1.grid(row=0,column=1)
tk.Label(root,text="Enter Destination : ").grid(row=1)
e2 = tk.Entry(root)
e2.grid(row=1, column=1)
tk.Label(root,text="Enter Date (dd/mm/YYYY) : ").grid(row=2)
e3 = tk.Entry(root)
e3.grid(row=2,column=1)
tk.Button(root,
text='Search', command=search_flight,anchor=tk.CENTER).grid(row=3,column=1,
sticky=tk.W,
pady=4)
print(e1.get())
root.mainloop()
# search_flight(from_city, to_city, day)
|
# search and count the words in file
count = 0
with open("/home/anil/Desktop/py_file.txt") as file_data:
file_content = file_data.read()
file_data.seek(0)
for line in file_data:
for s in line.rstrip().split(" "):
count += 1
# print(line.rstrip())
# for line in file_content:
# print(line)
# print(file_content)
# for s in file_content.split(" "):
# count += 1
print(count)
|
def sort_dict_list(dict):
values = []
sorted = []
for entry in dict:
for key, value in entry.items():
values.append(value)
values.sort(key=lambda x: x, reverse=True)
for number in range(len(values)):
for entry in dict:
for key, value in entry.items():
if value == values[number]:
sorted.append(entry)
break
return sorted |
import json
import csv
import io
'''
creates a .csv file using a Twitter .json file
the fields have to be set manually
'''
data_json = io.open('bigtweets_2.json', mode='r', encoding='utf-8').read()
#reads in the JSON file
data_python = json.loads(data_json)
csv_out = io.open('bigtweets_2_out_utf8.csv', mode='w', encoding='utf-8') #opens csv file
fields = u'created_at,text,screen_name,followers,friends,rt,fav' #field names
csv_out.write(fields)
csv_out.write(u'\n')
for line in data_python:
#writes a row and gets the fields from the json object
#screen_name and followers/friends are found on the second level hence two get methods
if line.get('text') != None:
row = [line.get('created_at'),
'"' + line.get('text').replace('"','').replace("'","") + '"', #creates double quotes
line.get('user').get('screen_name'),
(line.get('user').get('followers_count')),
(line.get('user').get('friends_count')),
(line.get('retweet_count')),
(line.get('favorite_count'))]
else:
row=""
print(str(row))
row_joined = (str(row).strip('[').strip(']'))
print(row_joined)
csv_out.write(row_joined)
csv_out.write(u'\n')
csv_out.close()
|
#!/usr/bin/python3
''' say_my_name function '''
def say_my_name(first_name, last_name=""):
'''
Print first and last name
Parameters:
first_name (str)
last_name (str)
Returns:
void
'''
if type(first_name) is not str:
raise TypeError("first_name must be a string")
elif type(last_name) is not str:
raise TypeError("last_name must be a string")
print("My name is {:s} {:s}".format(first_name, last_name))
|
#!/usr/bin/python3
''' write_file function '''
def append_write(filename="", text=""):
'''
write in a file and appends in file
'''
with open(filename, 'a', encoding="utf-8") as file:
return file.write(text)
|
#!/usr/bin/python3
""" pascal triangle"""
def pascal_triangle(n):
""" return pascal triangle """
pascal_list = []
new_list = []
pascal_number = 0
if n <= 0:
return pascal_list
for i in range(0, n):
pascal_number = 11 ** i
pascal_list.append(str(pascal_number))
for j in pascal_list:
new_list.append(j)
return new_list
|
#!/usr/bin/python3
for i in range(0, 90):
if i % 10 != i / 10 and i % 10 > i / 10:
print("{:02d}{}".format(i, ", " if i < 89 else '\n'), end='')
|
while True: #Taken if User Want to play game again
v=1 #Counter how many values are filled in board
board=[' ']*10 #Setting all values to blank in board
player='' #Will store which player is playing
val=False #For Checking if any player won or not
def printTable():
for i in range(1,10):
print(board[i],end=' ')
if(i%3==0 and i!=9):
print("\n",'-'*8)
elif i!=9:
print('|',end=' ')
print("\nWelcome to Tic Tac Toe Game :)\nHope you have pleasent experience ;)\n")
printTable()
while True:
val=input("\n\nEnter O or X ") #Taking 1st user value if its O or X
if val.lower()=='o' or val=='0': #Check if it is O
player='O' # set player to O
break;
elif val.lower()=='x': #Check if it is X
player='X' # set player to X
break;
else: #When neither O nor X entered
print("You are not entering O or X alphabet, try again")
#Function for win Situation Return True if player Win else False, Player is taken as parameter because by default blank is assigned to all
#on equating 2 blank it will return true even if that position are empty
def test(player):
if board[1]==board[2] and board[2]==board[3] and board[3]==player: #123 1st row
return True
elif board[4]==board[5] and board[5]==board[6] and board[6]==player: #456 2nd row
return True
elif board[7]==board[8] and board[8]==board[9] and board[9]==player: #789 rd row
return True
elif board[1]==board[5] and board[5]==board[9] and board[9]==player: #1st column
return True
elif board[3]==board[5] and board[5]==board[7] and board[7]==player: #2nd column
return True
elif board[1]==board[4] and board[4]==board[7] and board[7]==player: #3rd column
return True
elif board[2]==board[5] and board[5]==board[8] and board[8]==player: #Diagnal 1
return True
elif board[3]==board[6] and board[6]==board[9] and board[9]==player: #Diagnal 2
return True
else:
return False
while v!=10: #Will Run until whole board is filled
position=input('\nEnter position ') #Taken Position
while position not in ['1','2','3','4','5','6','7','8','9']: #if invalid position entered
print("You are not entering correct position, try natural numbers less than 10\n")
position=input('Enter position ') #taken position again
if(board[int(position)]==' '): #check position is empty
board[int(position)]=player #fill board with O/X at entered position
v=v+1 #Updating count of number of positions filled in board
printTable() #Print Table
if v>4: #Minimum 5 values is needed to be filled in order to Win (In Total of X and O )
if test(player): #If any player had won before filling the entire board it will break and Val becomes true, initially Declared false at top.
val=True
break
if player=='X': #Player will Swap after every turn
player='O'
else:
player='X'
else:
print("Position is already Occupied") #if position is already filled again position is asked , end of while loop
if val==True:
print("\n\n",player," Wins the game ;p\nThanks for playing with us")
else:
print("\nDraw\nThanks for playing with us ;p")
play=input("\nPress Y if you wanna play again\n") #Ask user if he want to play again
if play.lower()!='y': #Check if is any other value than Y or y then break, program will be terminated, if Y is enteree control will go to 1st line while loop
print("Come Back Soon :( ")
break
|
print(sorted([9, 1, 3, 2, 7, 5]))
# 使用sorted对字典进行排序
from random import randint
names = ['bruce', 'john', 'lili', 'cindy', 'tony']
d = {x: randint(60, 100) for x in names}
print(d)
# 1.转换成元祖
print(sorted(zip(d.values(), d.keys())))
# 2.
print(d.items())
print(sorted(d.items(), key=lambda x: x[1]))
|
import sqlite3
from sqlite3 import Error
import os
class Database:
"""Handles simple sqlite database to keep track of urls already visited.
We want to avoid having to check for changes on each individual listing
so urls visited can be stored with flags indicating whether the listing
has been visited or the location api has been used.
Parameters
----------
db_name : string
Use the spider name and it will store the database file in
./data/db_name.db
Database fields
---------------
is_deep_scraped
is_location_scraped
"""
def __init__(self, db_name):
""" Initialize connection to database.
:param db_name: database file (use spider name)
"""
self.__conn = self.__create_connection(db_name)
# Create listing data table if it doens't already exist
self.__create_listing_data_table()
def __create_connection(self, db_name):
""" create a database connection to the SQLite database
specified by db_name
:param db_name: database file (use spider name)
:return: Connection object or None
"""
os.makedirs("./data/db", exist_ok=True)
conn = None
try:
conn = sqlite3.connect("./data/db/" + db_name + ".db")
except Error as e:
print(e)
return conn
def close_connection(self):
""" Simply closed the database connection
:return: None
"""
self.__conn.close()
def __create_listing_data_table(self):
sql = """ CREATE TABLE IF NOT EXISTS listing_data (
listing_id INTEGER PRIMARY KEY,
url TEXT NOT NULL UNIQUE,
is_deep_scraped TEXT,
is_location_scraped TEXT
) """
cur = self.__conn.cursor()
cur.execute(sql)
self.__conn.commit()
def flag_listing_data(self, url, field):
""" flag listing data with true so we know it's been deep scraped
:param url: listing url
:param field: is_deep_scraped or is_location_scraped
:return: None
"""
# Uses 2 queries to upsert
sql = f""" UPDATE listing_data
SET {field} = "true"
WHERE url = '{url}' """
cur = self.__conn.cursor()
cur.execute(sql)
sql = f""" INSERT OR IGNORE INTO listing_data
(url, {field})
VALUES ( '{url}', 'true' ) """
cur.execute(sql)
self.__conn.commit()
def load_prev_visited(self):
""" Returns previously visited listings with flags to know if they have
been deep scraped or location scraped
:return: Dict with the listing url as the key and the flags set to
'true' or None.
flags are is_deep_scraped or is_location_scraped
"""
prev_visited_listings = {}
sql = """ SELECT * FROM listing_data """
# Returns dict rather than tuple
self.__conn.row_factory = sqlite3.Row
cur = self.__conn.cursor()
cur.execute(sql)
rows = cur.fetchall()
for row in rows:
prev_visited_listings[row['url']] = {
'is_deep_scraped': row['is_deep_scraped'],
'is_location_scraped': row['is_location_scraped']
}
return prev_visited_listings
|
# -*- coding: utf-8 -*-
"""
Model related functions defined on analysis
To train the best model on new data, add the data to the raw csv data and use train_model function
Otherwise, use predict to predict new data
@author: icaromarley5
"""
from sklearn.tree import DecisionTreeClassifier
from joblib import dump,load
import pandas as pd
random_state = 100
model_name = 'model.joblib'
raw_data_path = 'KaggleV2-May-2016.csv'
target = 'No-show'
# builds a training dataset from raw data
# if a row is passed, it transforms the row for prediction
def build_training_data(one_row=None):
df = pd.read_csv(raw_data_path,parse_dates=['ScheduledDay','AppointmentDay'])
# feature selection based on analysis
columns = ['Scholarship', 'last_no_show', 'age_lesser_45', 'days_lesser_10']
patient_id = None
if one_row is not None:
patient_id = one_row['PatientId']
df = df.copy()
# remove data that have ScheduledDay > AppointmentDay
df['days'] = (df['AppointmentDay'] - df['ScheduledDay']).dt.days
df = df[df['days'] >= 0]
# change no show values to int
df['No-show'].replace({'No':0,'Yes':1},inplace=True)
# get last appointment
df.sort_values('AppointmentDay',inplace=True)
groupby_patient = df.sort_values('AppointmentDay').groupby('PatientId')
df_last = groupby_patient.last()
def compute_last_no_show(groupby):
if groupby.shape[0] < 2:
return 0
return groupby['No-show'].shift(1).iloc[-1]
df_last['last_no_show'] = groupby_patient\
.apply(compute_last_no_show)
df = df_last.copy()
# feature engineering based on analysis
df['age_lesser_45'] = (df['Age'] <= 45).astype(int)
df['days_lesser_10'] = (df['days'] <= 10).astype(int)
result = df
if patient_id:
df.reset_index(inplace=True)
result = df[df['PatientId'] == patient_id]
result = result[columns + [target]]
return result
# creates untrained best model based on analysis
def create_best_model(class_weight):
return DecisionTreeClassifier(random_state=random_state,class_weight=class_weight)
def train_model():
df = build_training_data()
X = df[[column for column in df.columns if column != target]]
y = df[target]
class_weight = dict(1 - y.value_counts()/y.shape[0])
model = create_best_model(class_weight)
model.fit(X,y)
dump(model,model_name)
return model
def load_model():
return load(model_name)
def predict(data_row):
row = build_training_data(data_row)
if row.shape[0] > 0:
row = row[[column for column in row.columns if column != target]]
model = load_model()
return model.predict(row)[0]
return "invalid data. ScheduledDay > AppointmentDay" |
#write a function which take the given array and find and return the
#second biggest number
import time
start = time.time()
#write a function that takes two strings and returns True if they are reverse
def sum_array(list_array):
total=0
list_array=sum(list_array)
total+=list_array
return total
print(sum_array([100,100]))
#Write a function that take an array of string and convert it to uppercase
def upper_case(s1,s2):
return s1.upper() == s2.upper()
print(upper_case("abc","ABc"))
#Compute the time complexity
my_list=[]
for i in range(10):
my_list.append(i)
elapsed_time_lc=(time.time()-start)
print(my_list)
|
age = 31
if age>= 35:
print('You are old enough to be president!')
elif age >=30:
print('You are old enough to become Senator!')
else:
print('You are not old enough to be elected')
print('Have a nice day!!') |
"""
Basic implementation of a binary tree.
Author: Xavier Cucurull Salamero <xavier.cucurull@estudiantat.upc.edu>
"""
class Node:
""" Implementation of a binary tree to use with CART.
"""
def __init__(self, predicted_class, gini, data_idx=None):
self.predicted_class = predicted_class
self.gini = gini
self.data_idx = data_idx
self.split_point = None
self.right = None
self.left = None
def __str__(self):
str = []
self._str_aux(self, s=str)
return '\n'.join(str)
def _str_aux(self, node, depth=0, s=[]):
# If not a terminal node
if node.left:
# If feature is categorical
if type(node.split_point) == set:
s.append('{}[{} ∈ {}]'.format(depth*' ', node.feature, node.split_point))
# If feature is numerical
else:
s.append('{}[{} < {:.3f}]'.format(depth*' ', node.feature, node.split_point))
# Explore children
self._str_aux(node.left, depth+1, s)
self._str_aux(node.right, depth+1, s)
# Terminal node (leaf)
else:
s.append('{}[{}]'.format(depth*' ', node.predicted_class))
|
n = int(input("Enter Your Number :"))
for i in range(n):
for j in range(i+1):
print(" ",end = '')
for j in range(n-i ):
print(i+j+1,end = " ")
print("")
for p in range(n):
for q in range(n-p):
print(" ",end = '')
for q in range(p+1):
print(n-p+q,end = ' ')
print("")
|
#if we decide to do things locally check this out
#http://zetcode.com/db/mysqlpython/
#http://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html
import mysql.connector
from mysql.connector import errorcode
class users:
def __init__(self, dbname, username , password , host , connection = None ):
self.dbname = dbname
self.username = username
self.password = password
self.host = host
self.connection= connection
def connectToDB(self):
try:
cnx = mysql.connector.connect(user= self.username, password= self.password, host= self.host, database= self.dbname )
self.connection = cnx
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
def closeDB(self):
if self.connection == None:
print "you are not connecte dto databse"
else:
self.connection.close()
print "the connection has been closed"
def showhowtogetinfo():
print "must collect your login information to use Command LineInterface"
print "1.) go to the following website: http://onid.oregonstate.edu/ "
print "2.)Click Log in to ONID (to bypass: https://secure.onid.oregonstate.edu/cgi-bin/my?type=want_auth)"
print "3.) Type in user name and password amd click login"
print "4.) Click on Web Database"
print "5.) The following info needs to be provided"
host = raw_input("what is the Hostname? ")
host = host.strip()
dbname = raw_input("what is the DatabaseName? ")
dbname = dbname.strip()
username = raw_input("what is the username? ")
username = username.strip()
password= raw_input("what is the password? ")
password= password.strip()
return (host, dbname, username, password)
print("test this thing out")
host, dbname, uname, passw = showhowtogetinfo()
print "the value entered for host; ", host
test = users(dbname, uname, passw, host)
test.connectToDB()
test.closeDB() |
# In Python, there are not built in Arrays,
# The default data type is Lists. Check more
# On that. However, we can also use arrays
# Good old boi
# Tho, not exactly, the are different that in Java
# ARRAYS
# All data must be of the same kind
# You can only sotre simple types of data
# Has an index
# Storage order guaranteed
from array import array
scores = array("d") # What does "d" means???. It means Diggits
scores.append(97) # Add new item
scores.append(109)
print(scores)
print(scores[1])
# Common methods
print(len(scores))# How to get the LENGTH
scores.insert(0, 10) # Inssert before Index (pos, val)
print(scores)
# TUPPLES
# Es una lista inmutable
tupple = (1,2,3,4)
print(tupple[0])
#Tupple unpacking
n1,n2,n3,n4 = tupple
print(n1)
print(n2)
print(n3)
print(n4)
# May raise "not enough values to unpack"
# zip (List1, list2)
# Is a Function that takes two lists and converts them into tupples |
# DICCIONARIES
# Its similar to JSON
# It stores values as
# pairs by key/value
# The items order is not guaratee*
dic = {"primero": "Christopher"}
# To add:
dic["last"] = "Harrison"
#To delete:
#del dic['last']
print(dic)
print(dic["primero"])
# Returns a list of all keys in a dict
print(dic.keys())
# Returns a list of all stored values in a dict
print(dic.values())
# Returns a set of all keys and values
print(dic.items()) |
from Mascota import *
from Vete import *
listaDeDueños = []
listaDeMascotas = []
pepe = Dueño()
pepe.Nombre = "pepe"
jose = Dueño()
jose.Nombre="jose"
listaDeDueños.append(pepe)
listaDeDueños.append(jose)
a = Pajarito("pepe", jose)
listaDeMascotas.append(a)
while True:
print("1)Agregar Mascota")
print("2)Borrar Mascota")
print("3)Modificar Mascota")
print("4)Agregar Dueño")
print("5)Alimentar Mascota")
print("6)Saludar mascota")
a = input()
if a == "1":
print("Seleccione Mascota")
print(" 1)Perro")
print(" 2)Gato")
print(" 3)Pajarito")
print(" 4)Pez")
b = input()
if b == "1":
Nombre = input()
Dueño = input()
tu_vieja = []
mi_vieja_ = []
for dueño in listaDeDueños:
tu_vieja.append(dueño.Nombre)
if Dueño in tu_vieja:
Dueño = dueño
nombres = []
for item in listaDeMascotas:
nombres.append(item.Nombre)
print(item.Nombre)
if not Nombre in nombres:
c = Perro(Nombre, Dueño)
listaDeMascotas.append(c)
print("dd")
print(c.Saludo)
else:
print("Ya existe una mascota con ese nombre")
else:
print("No existe dueño")
elif b == "2":
Nombre = input()
Dueño = input()
tu_vieja = []
mi_vieja_ = []
for dueño in listaDeDueños:
tu_vieja.append(dueño.Nombre)
if Dueño in tu_vieja:
Dueño = dueño
nombres = []
for item in listaDeMascotas:
nombres.append(item.Nombre)
print(item.Nombre)
if not Nombre in nombres:
c = Gato(Nombre, Dueño)
listaDeMascotas.append(c)
print("dd")
print(c.Saludo)
else:
print("Ya existe una mascota con ese nombre")
else:
print("No existe dueño")
elif b == "3":
Nombre = input()
Dueño = input()
Saludo = input()
tu_vieja = []
mi_vieja_ = []
for dueño in listaDeDueños:
tu_vieja.append(dueño.Nombre)
if Dueño in tu_vieja:
Dueño = dueño
nombres = []
for item in listaDeMascotas:
nombres.append(item.Nombre)
print(item.Nombre)
if not Nombre in nombres:
if Saludo != "":
c = Pajarito(Nombre, Dueño, Saludo)
listaDeMascotas.append(c)
print("dd")
else:
c = Pajarito(Nombre, Dueño)
listaDeMascotas.append(c)
print("aa")
else:
print("Ya existe una mascota con ese nombre")
else:
print("No existe dueño")
elif b == "4":
Nombre = input()
Dueño = input()
Saludo = ""
tu_vieja=[]
mi_vieja_= []
for dueño in listaDeDueños:
tu_vieja.append(dueño.Nombre)
if Dueño in tu_vieja:
Dueño = dueño
nombres = []
for item in listaDeMascotas:
nombres.append(item.Nombre)
print(item.Nombre)
if not Nombre in nombres:
c = Pez(Nombre, Dueño)
listaDeMascotas.append(c)
print("dd")
else:
print("Ya existe una mascota con ese nombre")
else:
print("No existe dueño")
elif a ==
|
import cv2 as cv
import numpy as np
def find_faces_haar(img, face_cascade):
""" Find all the regions in the image that have faces.
Parameters
----------
img : The input image.
face_cascade : A pre-trained face detector API.
Returns
-------
The final image, and the list of faces detected.
"""
# Convert the image to grayscale (black and white) for detection.
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# Find all the faces. Calls the OpenCV detection API.
faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.08,
minNeighbors=5,
minSize=(120, 120),
maxSize=(300, 300),
flags=cv.CASCADE_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 3)
return img, faces
def anonymize_random_colors(img, faces):
""" Anonymize faces by covering face region using randon colors
Parameters
----------
img : The input image.
faces : A list of faces. Each face is a rectangle with (x, w, w, h)
Example: [(3,6,9,10), (a,b,c,d)....]
Returns
-------
The final image.
"""
if len(faces) < 1:
return img
for f in faces:
print(f)
f_x, f_y, f_w, f_h = f[0], f[1], f[2], f[3]
img[f_y:f_y+f_w, f_x:f_x+f_h, 0] = np.random.randint(255)
img[f_y:f_y+f_w, f_x:f_x+f_h, 1] = np.random.randint(255)
img[f_y:f_y+f_w, f_x:f_x+f_h, 2] = np.random.randint(255)
return img
def _draw_vertial_lines(img, face):
# TODO - write documentation
f_x, f_y, f_w, f_h = face[0], face[1], face[2], face[3]
for step in range(0, f_h, 20):
img[f_y:f_y+f_w, f_x+step:f_x+step+3, 0] = np.random.randint(255)
img[f_y:f_y+f_w, f_x+step:f_x+step+3, 1] = np.random.randint(255)
img[f_y:f_y+f_w, f_x+step:f_x+step+3, 2] = np.random.randint(255)
return img
def _draw_horizonal_lines(img, face):
# TODO - write documentation
f_x, f_y, f_w, f_h = face[0], face[1], face[2], face[3]
for step in range(0, f_w, 20):
img[f_y+step:f_y+step+3, f_x:f_x+f_h, 0] = np.random.randint(255)
img[f_y+step:f_y+step+3, f_x:f_x+f_h, 1] = np.random.randint(255)
img[f_y+step:f_y+step+3, f_x:f_x+f_h, 2] = np.random.randint(255)
return img
def anonymize_lines(img, faces, direction='vertical'):
""" Anonymize faces by drawing lines (vertical, horizontal, both)
Parameters
----------
img : The input image.
faces : A list of faces. Each face is a rectangle with (x, w, w, h)
Returns
-------
The final image.
"""
if len(faces) < 1:
return img
for f in faces:
if direction == 'vertical':
img = _draw_vertial_lines(img, f)
elif direction == 'horizontal':
img = _draw_horizonal_lines(img, f)
elif direction == 'both':
img = _draw_vertial_lines(img, f)
img = _draw_horizonal_lines(img, f)
else:
print('Invalid choice of direction.')
return img
def _make_smaller_rectangles(f, dx=10, dy=10):
f_x, f_y, f_w, f_h = f[0], f[1], f[2], f[3]
rectangles = []
for step_h in range(f_x, f_x+f_h, dx):
for step_w in range(f_y, f_y+f_w, dy):
rectangles.append((step_h, step_w, dx, dy))
return rectangles
def pixelate_faces(img, faces):
""" Pixelate the face regions
Parameters
----------
img : The input image.
faces : A list of faces. Each face is a rectangle with (x, w, w, h)
Returns
-------
The final image with all faces pixelated.
"""
if len(faces) < 1:
return img
for f in faces:
rects = _make_smaller_rectangles(f, 20, 20)
for r in rects:
f_x, f_y, f_w, f_h = r[0], r[1], r[2], r[3]
img[f_y:f_y+f_w, f_x:f_x+f_h, 0] = np.average(img[f_y:f_y+f_w, f_x:f_x+f_h, 0])
img[f_y:f_y+f_w, f_x:f_x+f_h, 1] = np.average(img[f_y:f_y+f_w, f_x:f_x+f_h, 1])
img[f_y:f_y+f_w, f_x:f_x+f_h, 2] = np.average(img[f_y:f_y+f_w, f_x:f_x+f_h, 2])
return img
if __name__ == '__main__':
face_cascade = cv.CascadeClassifier('haar_model_frontface.xml')
cap = cv.VideoCapture(1)
while True:
ret, img = cap.read()
# Detect the faces
img, faces = find_faces_haar(img, face_cascade)
# TODO - write this function.
img = pixelate_faces(img, faces)
# img = anonymize_random_colors(img, faces)
# img = anonymize_lines(img, faces, 'both')
# show the result.
cv.imshow('capture', img)
# Wait for ESC key, then quit.
ch = cv.waitKey(1)
if ch == 27:
break
cv.destroyAllWindows()
|
# 冒泡排序可以记住交换次数,这样一旦有一轮全程没有进行交换,那就表示已经排好序了,可以结束了。
# 所以最好的时间复杂度就是数列直接就是有序的,时间复杂度为O(n).
# 因为存在两层for循环,所以时间复杂度平均和最坏都为O(n^2).
# 未使用多余空间,空间复杂度为O(1)。
class Sorting:
def bubbleSort(self, s): # 正确
for i in range(0,len(s)): # 这里的i并不是控制从前往后的,而是控制后面每次该减几个
for j in range(0,len(s)-i-1): # 每一轮的最后面一个元素下一轮就不再比较了
if s[j] > s[j+1]:
temp = s[j+1]
s[j+1] = s[j]
s[j] = temp
return s
# 疑惑,这里的i和a为什么会出现这么奇怪的现象
def bubbleSortError(self, s): # 有疑问
a = 0
for i in range(0,len(s)-a):
print(len(s)-a)
print(i)
for j in range(0,len(s)-i-1):
if s[j] > s[j+1]:
temp = s[j+1]
s[j+1] = s[j]
s[j] = temp
a += 1
return s
s = [5,4,5,3,2,1,7,8,9]
S = Sorting()
result = S.bubbleSort(s)
print(result) |
import math as mt
r=input("Radio: ")
r=float(r)
theta=input("Ángulo [Rad]: ")
theta=float(theta)
x=r*mt.cos(theta)
y=r*mt.sin(theta)
print("x es: ",x)
print("y es: ",y)
|
from itertools import combinations
def main():
data = []
with open("data/data_1.txt", "r") as f:
for line in f:
data.append(int(line))
for x, y, z in combinations(data, 3):
if x + y + z == 2020:
return x * y * z
if __name__ == "__main__":
print(main())
|
import random
def jogar_adivinhacao():
print("----------------------------------\n")
print("Bem vindo ao jogo de adivinhação!\n")
print("----------------------------------\n")
secret_number = int(random.randrange(1,101))
print(secret_number)
cont = 1
while cont == 1:
print("Niveis: (1)Fácil - (2)Médio - (3)Difícil ")
nivel = int(input("Escolha o nivel do jogo: "))
if nivel == 1:
full_attempt = 15
cont += 1
elif nivel == 2:
full_attempt = 10
cont += 1
elif nivel == 3:
full_attempt = 5
cont += 1
else:
print("\nNivel inválido!\n")
for rounds in range(1, full_attempt+1):
print(f"\nTentativa {rounds} de {full_attempt} tentativa!")
attempt = int(input("Digite seu número entre 1 e 100: "))
print(f"\nVocê digitou: {attempt}\n")
if attempt < 1 or attempt > 100:
print("Você deve digitar um numero entre 1 e 100!\n ")
continue
if attempt == secret_number:
print("VOCÊ ACERTOUUUUUUU!")
break
else:
if attempt > secret_number:
print("O numero secreto é MENOR !\n")
continue
elif attempt < secret_number:
print("O numero secreto é MAIOR !\n")
continue
print("----------------------------------")
print(f"Número secreto: {secret_number}")
print("----------------------------------")
print("Fim do jogo!")
print("----------------------------------")
if(__name__ == "__main__"):
jogar_adivinhacao() |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
get_ipython().run_line_magic('mathplotlib', 'inline')
import mathplotlib.pyplot as plt
import np as numpy
# In[ ]:
def function_to_integrate(x):
# e^(-2x)*cos(10x)
return math.e**(-2*x)*math.cos(10*x)
# In[ ]:
def trapazoid core(f,x,h)
return math.e**(-2*x)*math.cos(10*x)
# In[1]:
def trapezoid method(f,a,b,N)
#f == function to integration
#a == lower limit of integration
#b == upper limit of integration
#N == number of function evaluation to use
#define x value to perform trapezoid use
x = np.linspace(a,b,n)
h = x[1] - x[0]
#define the value of the interval
Fint = 0.0
#perform the integral using the trapezoid method
for i in range (0,pi)
Fint x= trapezoid_core(f,x_i,h)
#return the answer
return Fint
# In[ ]:
|
#!/usr/bin/python3
import random
numbers=[i+1 for i in range(45)]
for i in range(5):
random.shuffle(numbers)
print(sorted(numbers[:6]))
input()
|
# Filename: classes.py
# Name: Chua Yu Peng
# Description: Implements suitable class relationship for Staff, between Teaching and Support Staff.
class Staff():
''' superclass for staff '''
def __init__(self, StaffID, Name, EmployeeType):
''' define variables '''
self.__StaffID = StaffID
self.__Name = Name
self.__EmployeeType = EmployeeType
''' getty '''
def getStaffID(self):
return self.__StaffID
def getName(self):
return self.__Name
def getEmployeeType(self):
return self.__EmployeeType
''' setty '''
def setName(self, newName):
self.__Name = newName
def setEmployeeType(self, newEmployeeType):
self.__EmployeeType = newEmployeeType
''' show all '''
def display(self):
return ("{0:5s}{1:35s}{2:1s}".format(self.__StaffID,self.__Name, self.__EmployeeType))
class Teaching(Staff):
''' subclass for staff '''
def __init__(self, StaffID, Name, EmployeeType, CourseCode1, CourseCode2, CourseCode3):
''' define variables '''
super().__init__(StaffID, Name, EmployeeType)
self.__CourseCode1 = CourseCode1
self.__CourseCode2 = CourseCode2
self.__CourseCode3 = CourseCode3
''' getty '''
def getCourseCode1(self):
return self.__CourseCode1
def getCourseCode2(self):
return self.__CourseCode2
def getCourseCode3(self):
return self.__CourseCode3
''' setty '''
def setCourseCode1(self, newCourseCode1):
self.__CourseCode1 = newCourseCode1
def setCourseCode2(self, newCourseCode2):
self.__CourseCode2 = newCourseCode2
def setCourseCode3(self, newCourseCode3):
self.__CourseCode3 = newCourseCode3
''' show all '''
def display(self):
return ("{0:41s}{1:4s}{2:4s}{3:4s}{4:3s}{5:3s}".format(super().display(),self.__CourseCode1,self.__CourseCode2,self.__CourseCode3, "NIL", "NIL"))
class Support(Staff):
''' subclass for staff '''
def __init__(self, StaffID, Name, EmployeeType, SubjectArea1, SubjectArea2):
''' define variables '''
super().__init__(StaffID, Name, EmployeeType)
self.__SubjectArea1 = SubjectArea1
self.__SubjectArea2 = SubjectArea2
''' getty '''
def getSubjectArea1(self):
return self.__SubjectArea1
def getSubjectArea2(self):
return self.__SubjectArea2
''' setty '''
def setSubjectArea1(self, newSubjectArea1):
self.__SubjectArea1 = newSubjectArea1
def setSubjectArea2(self, newSubjectArea2):
self.__SubjectArea2 = newSubjectArea2
''' show all '''
def display(self):
return ("{0:41s}{1:4s}{2:4s}{3:4s}{4:3s}{5:3s}".format(super().display(),"NIL", "NIL", "NIL",self.__SubjectArea1,self.__SubjectArea2))
|
# def operasiBilangan():
# a = 7
# b = 8
# yield a + b
# x = 19
# y = 90
# yield x - y
# z = 80
# w = 90
# yield z * w
# c = 999
# k = 10
# yield c / k
# oprGen = operasiBilangan()
# for i in oprGen:
# print(i)
def operasiBilangan():
yield "Hello World"
yield "Selamat Pagi"
yield "Selamat Siang"
yield "Selamat Sore"
oprGen = operasiBilangan()
for i in oprGen:
print(i) |
import Helper
nama = ""
umur = 0
tinggi = 0.0
tryAgain = True
print("software perkenalan : ")
print("==============================")
while tryAgain:
#input case
nama = str(input("masukkan nama : "))
umur = Helper.inputInteger("masukkan umur : ",0,100)
tinggi = Helper.inputFloat("masukkan tinggi badan : ",0,300)
print("Nama saya {}, umur saya {} tahun dan tinggi saya {} cm.".format(nama,umur,tinggi))
#input try Again
value = Helper.inputYesNo("mau coba lagi ")
tryAgain = Helper.checkYN(value)
Helper.printClosing()
|
#!/usr/bin/env python
# coding: utf-8
# ## 目標:在一list中的連續整數,有一個數字重複、且因此該數字的下一個數字沒有成功加入list中。此題需要找出重複之數, 未出現之數,並以陣列方式返回出來
# #### Leetcode題目位置:https://leetcode.com/problems/set-mismatch/
# In[1]:
class Solution:
def findErrorNums(self, nums):
n = len(nums)
# 全部總和
nums_sum = sum(nums)
# 不重複總和
unique_sum = sum(list(set(nums)))
# 正確情況下總和
correct_sum = n * (n + 1) / 2
duplicated_num = nums_sum - unique_sum
missing_num = correct_sum - unique_sum
missing_num = int(missing_num)
duplicated_num = int(duplicated_num)
return [duplicated_num, missing_num]
# In[2]:
nums = [1, 2, 3, 3, 5, 6]
a = Solution()
a.findErrorNums(nums)
# #### Submissions_結果
# 
|
#!/usr/bin/env python
# coding: utf-8
# # 法一:偷吃步
# ###直接應用python的既有函式,如append、pop等
# In[50]:
class MyLinkedList1(object):
def __init__(self):
self.linkedlist = list()
def get(self, index):
if index < 0 or index >= len(self.linkedlist):
return -1
else:
return self.linkedlist[index]
def addAtHead(self, val):
self.linkedlist.insert(0, val)
def addAtTail(self, val):
self.linkedlist.append(val)
def addAtIndex(self, index, val):
if 0 <= index and index <= len(self.linkedlist):
self.linkedlist.insert(index, val)
def deleteAtIndex(self, index):
if 0 <= index and index < len(self.linkedlist):
self.linkedlist.pop(index)
# 因為我想 print出 list中所有元素,因此參考下方網址的程式碼,才得以將所有list中的元素直接在結果中呈現
# https://github.com/dokelung/Python-QA/blob/master/questions/dunder/自己寫的數據類型使用print無法輸出每個元素.md
def __str__(self):
return str(self.linkedlist)
def __repr__(self):
return str(self)
# In[60]:
listtest = MyLinkedList1()
param_1 = obj.get(5)
listtest.addAtHead(11)
listtest.addAtTail(99)
listtest.addAtIndex(1, 55)
listtest.addAtIndex(2, 77)
# In[61]:
listtest
# 結果是 [11, 55, 77, 99]
# In[63]:
listtest.deleteAtIndex(3)
listtest
# 結果是 [11, 55, 77]
# # 法二:按照題目規定的來
# ### 但是難度對我來說有點高,第一次寫class在不少地方卡住
# In[ ]:
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
class MyLinkedList2(object):
def __init__(self):
self.head = None
self.size = 0
def get(self, index):
if index < 0 or index >= self # or self.head == None: 這是參考別人程式碼後發現是我沒注意到的
return -1
else:
def addAtHead(self, val: int) -> None:
def addAtTail(self, val: int) -> None:
def addAtIndex(self, index: int, val: int) -> None:
def deleteAtIndex(self, index: int) -> None:
|
import sys
import time
class parking:
S_count = 0
L_count = 0
M_count = 0
slot_id = 0
id = "0"
t = "V"
slot_id = 0
slot = []
slot[0:9] = ['S'] * 10
slot[10:16] = ['M'] * 7
slot[17:19] = ['L'] * 3
def vehicle_details(self):
parking.id = str(input("Please Enter Vehicle ID"))
parking.t = str(input("Vehicle Type eg: S- Motor Bike M- Car L- Bus"))
parking.slot_id += 1
if parking.t == 'S':
parking.S_count += 1
elif parking.t == 'M' or (parking.S_count>10 and parking.t == 'S'):
parking.M_count += 1
elif parking.t == 'L' or (parking.S_count>10 and parking.t == 'S') or (parking.M_count>10 and parking.t == 'M'):
parking.L_count += 1
def capacity(self):
if parking.slot_id > 19:
print("oops!!!! PARKING SLOT NOT AVAILABLE")
time.sleep(2)
def fill_slot(self,slot_id,vehicleid,vtype):
parking.slot.pop((slot_id))
parking.slot.insert((slot_id), {slot_id: [vehicleid, vtype]})
print(parking.slot)
self.show()
def show(self):
print("\n\n##################")
print("Vehicle ID:{0}\nVehicle Type: {1}\nSlot ID: {2}".format(parking.id,parking.t,parking.slot_id))
print("##################\n\n")
time.sleep(3)
def end_parking(self,v_id,v_type,s_id):
#print(parking.slot,len(parking.slot))
if s_id < 10:
n = 'S'
elif s_id >= 10 or s_id < 17:
n = 'M'
else:
n = 'L'
d = parking.slot.pop(s_id-1)
print(d)
print(parking.slot)
parking.slot.insert(s_id-1,n)
#print(parking.slot, len(parking.slot))
v = list(d.values())
k = list(d.keys())
print("\n\n###########################")
print("End parking: SUCCESS\n\nVehicle ID: {0}\nVehicle Type: {1}\nSlot ID: {2}\n\n\n".format(v[0][0],v[0][1],k[0]))
print("###########################\n\n")
time.sleep(2)
count = 0
while(1):
option = int(input("Enter option \n1. Check Availability \n2. End Parking \n3. Exit\n"))
p = parking()
if option == 1:
t = str(input("Enter Vehicle Type (S-Motor Cycle,M-Car,L-Bus)"))
p.vehicle_details()
if t == 'S':
if 'S' in parking.slot or 'M' in parking.slot or 'L' in parking.slot:
print("Slot Available\n")
print("Entered details id {0} type {1}".format(p.id,p.t))
if 'S' in parking.slot:
s = parking.slot.index(t)
p.fill_slot(s,p.id,t)
else:
if 'M' in parking.slot:
s = parking.slot.index('M')
p.fill_slot(s,p.id,t)
else:
s = parking.slot.index('L')
p.fill_slot(s, p.id,t)
else:
p.capacity()
elif t == 'M':
if 'M' in parking.slot:
s = p.slot.index('M')
p.fill_slot(s,p.id,t)
elif 'L' in parking.slot:
s = p.slot.index('L')
p.fill_slot(s,p.id,t)
else:
print("oops!!!! PARKING SLOT NOT AVAILABLE")
time.sleep(2)
elif t == 'L':
if 'L' in parking.slot:
s = p.slot.index('L')
p.fill_slot(s,p.id,t)
else:
print("oops!!!! PARKING SLOT NOT AVAILABLE")
time.sleep(2)
else:
print("Please Enter a valid vehicle Type")
time.sleep(2)
elif option == 2:
id = input("Please Enter vehicle id")
t = str(input("Please enter vehicle type"))
s_id = int(input("Please Enter parking slot id"))
p.end_parking(id,t,s_id)
elif option == 3:
sys.exit()
else:
print("Please Enter a valid option")
time.sleep(2) |
def has_negatives(a):
"""
YOUR CODE HERE
"""
# Your code here
result = []
a_dict = dict.fromkeys(a, 'I exist')
for num in a:
if num < 0:
pos_num = 0 - num
if a_dict.get(pos_num) is not None:
result.append(pos_num)
return result
if __name__ == "__main__":
print(has_negatives([-1, -2, 1, 2, 3, 4, -4]))
'''
U
Input
list of integers
positive and negative
Output
list of integers
positive only
Task
return list of positive integers with corresponding negative values in input
P
Create a dict
every integer in input
Iterate over given list
check if dict[negative version of integer] exists
dict.get(integer) - returns None if not there
if exists
add to result list
Return result
''' |
class Cat: # A Cat class.
def __init__(
self, name, preferred_food, meal_time
): # Every Cat has attributes name, preferred_food, and meal_time.
self.name = name
self.preferred_food = preferred_food
self.meal_time = meal_time
def __str__(self):
return f'''The cat {self.name} likes {self.preferred_food} at {self.meal_time}:00.'''
def eats_at(
self
): # Converts 24-hour time to a 12-hour time. ie: 13 becomes 1pm.
if self.meal_time == 0: # 0:00 is 12am.
return str(self.meal_time + 12) + " am"
elif self.meal_time == 12: # 12:00 is 12pm.
return str(self.meal_time) + " pm"
elif self.meal_time < 12: # Any other time less than 12 is in the AM.
return str(self.meal_time) + " am"
elif self.meal_time <= 23: # Any other time less than 23 is in the PM.
return str(self.meal_time - 12) + " pm"
else:
return "12 pm" # If number is too high, sets default to 24.
def meow(self): # Returns an plain-English string.
return f"My name is {self.name} and I eat {self.preferred_food} at {self.eats_at()}."
felix = Cat("Felix", "oreos", 17)
print(felix)
# print(felix.eats_at())
print(felix.meow())
print()
garfield = Cat("Garfield", "lasagna", 23)
print(garfield)
# print(garfield.eats_at())
print(garfield.meow())
print()
hobbes = Cat("Hobbes", "tuna casserole", 0)
print(hobbes)
# print(hobbes.eats_at())
print(hobbes.meow())
|
from urllib import request as req
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
# get profile id and privacy settings
print("https://steamcommunity.com/id/[THIS PART IS WHAT YOU ENTER]")
print('Check for spelling / case mistakes!')
print('Avatar will be downloaded to folder directory containing steamavatardownloader.py')
repeat = True
def dict(repeat):
return {
"y": True,
"Y": True,
"n": False,
"N": False,
}.get(repeat, False)
while repeat == True:
profileID = input("Enter steam profile id: ")
# variable holding desired URL
myUrl = "https://steamcommunity.com/id/" + profileID
# Open Connection + Grab page
uClient = uReq(myUrl)
# Variable stores raw html
pageHtml = uClient.read()
# Close Connection
uClient.close()
# Parse html
pageSoup = soup(pageHtml, "html.parser")
# locate profile avatar url
if pageSoup.find('div', {"class":"playerAvatarAutoSizeInner"}):
avatarUrl = pageSoup.find('div', {"class":"playerAvatarAutoSizeInner"}).find('img', recursive = False)['src']
# create substring containing avatar file name
print(avatarUrl)
file = avatarUrl.split("/avatars/")
avatar = file[1][3:]
# download profile avatar
req.urlretrieve(avatarUrl, avatar)
else: # messages if profile/avatar cant be located
print("Could not find steam profile/avatar or you mistyped Y/N response")
print("Check your spelling and run the script again")
# Prompt another profile search
repeat = input("Search for another profile? (Y/N):" )
repeat = dict(repeat)
|
def listToTuple(list):
odd_sum = 0
product = 1
for item in list:
if item % 2 == 0:
product *= item
else:
odd_sum += item
return (odd_sum, product)
# print(listToTuple([4,2,5,7,3,6,9]))
def kebabToScreamingSnake(str):
str = str.upper().replace('-', '_')
return str
# print(kebabToScreamingSnake("electricity-is-really-just-organized-lightning"))
def productCounterIterative(dict):
product_count = {}
for item in dict.keys():
itemParts = dict[item]
for part in itemParts:
if part in product_count.keys():
product_count[part] += 1
else:
product_count[part] = 1
return product_count
test_dict = {
'A': ['B', 'B', 'C'],
'B': [],
'C': ['D','E','F'],
'D': [],
'E': ['B','D'],
'F': []
}
# print(productCounterIterative(test_dict))
def productCounterRecursive(dict, key):
product_count = {}
if key is None:
product_count = productCounterRecursive(dict, next(iter(dict.keys())))
else:
for part in dict[key]:
if part in product_count.keys():
product_count[part] += 1
else:
product_count[part] = 1
product_count = productCounterRecursive(dict, part)
return product_count
print(productCounterRecursive(test_dict, None))
|
n = 5
longest = 0
nlong = 0
while n < 1000000:
terms = 1
m = n
while m > 1:
if m % 2:
m = 3 * m + 1
else:
m = m / 2
terms += 1
if terms > longest:
longest = terms
nlong = n
print nlong, "took", longest, "steps"
n += 1
print nlong, longest
|
import turtle
t = turtle.Turtle()
t.reset()
t.color("red")
for angle in range(0, 360, 15):
t.seth(angle)
t.circle(100)
|
#!/usr/bin/python3
# guess what this program doess????
import random
r=random.randint(67,89) # gives random num
print(r)
if r<50:
print(r)
print(":is less than 50")
elif r==45:
|
import pygame.font
class Help:
"""Class used to render how to play text as an image."""
def __init__(self, ai_game):
self.screen = ai_game.screen
self.screen_rect = self.screen.get_rect()
self.settings = ai_game.settings
self.finder = ai_game.finder
# Font settings for scoring information.
self.small_font = pygame.font.Font(self.finder.find_data_file(
'silkscreen.ttf', 'fonts'), 18)
self.large_font = pygame.font.Font(self.finder.find_data_file(
'silkscreen.ttf', 'fonts'), 36)
# Prepare help text.
self._prep_help_title()
self._prep_help_text()
self._prep_how_to_title()
self._prep_how_to_text()
def _prep_help_title(self):
"""Turn the help title into a rendered image."""
help_title_str = 'Help'
self.help_title_image = self.large_font.render(help_title_str, True,
self.settings.text_colour, self.settings.bg_colour)
# Display the title in the middle top of the screen.
self.help_title_rect = self.help_title_image.get_rect()
self.help_title_rect.centerx = self.screen_rect.centerx
self.help_title_rect.top = 50
def _prep_help_text(self):
"""Turn the help into a rendered image."""
help_text = [
'- Press "q" at any time to quit the game.',
'- Press "p" during the game to pause the game.']
self.help_text_images = []
self.help_text_rects = []
for line in help_text:
self.help_text_images.append(self.small_font.render(line, True,
self.settings.text_colour, self.settings.bg_colour))
for index in range(len(self.help_text_images)):
# Display the help text in the middle of the screen under the title.
self.help_text_rects.append(self.help_text_images[index].get_rect())
self.help_text_rects[index].centerx = self.help_title_rect.centerx
self.help_text_rects[index].top = (self.help_title_rect.bottom + 50
+ ((self.help_text_rects[index].height + 20) * index))
def _prep_how_to_title(self):
"""Turn the title into a rendered image."""
how_to_title_str = 'How To Play'
self.how_to_title_image = self.large_font.render(how_to_title_str,
True, self.settings.text_colour, self.settings.bg_colour)
# Display the title in the middle top of the screen.
self.how_to_title_rect = self.how_to_title_image.get_rect()
self.how_to_title_rect.centerx = self.screen_rect.centerx
self.how_to_title_rect.top = self.help_text_rects[-1].bottom + 50
def _prep_how_to_text(self):
"""Turn the help into a rendered image."""
how_to_text = [
'1. Use the left and right arrow keys to move the spaceship.',
'2. Press the space key to fire a bullet.',
'3. Only 3 bullets can be active at a time.',
'4. If a bullet hits an alien, the alien is destroyed.',
'5. When an entire wave is destroyed, a more advanced wave '
'appears.',
'6. If an alien reaches the spaceship the spaceship is destroyed.',
'7. If an alien reaches the bottom of the screen the spaceship is '
'destroyed',
'8. After 3 spaceships have been destroyed the game is over.',
'9. Destroy as many aliens as you possibly can. Good Luck!']
self.how_to_text_images = []
self.how_to_text_rects = []
for line in how_to_text:
self.how_to_text_images.append(self.small_font.render(line, True,
self.settings.text_colour, self.settings.bg_colour))
for index in range(len(self.how_to_text_images)):
# Display the help text in the middle of the screen under the title.
self.how_to_text_rects.append(
self.how_to_text_images[index].get_rect())
self.how_to_text_rects[index].centerx = (
self.how_to_title_rect.centerx)
self.how_to_text_rects[index].top = (self.how_to_title_rect.bottom
+ 50 + ((self.how_to_text_rects[index].height + 20) * index))
def show_help(self):
"""Draw the help text including the title onto the screen."""
self.screen.blit(self.help_title_image, self.help_title_rect)
for index in range(len(self.help_text_images)):
self.screen.blit(self.help_text_images[index],
self.help_text_rects[index])
self.screen.blit(self.how_to_title_image, self.how_to_title_rect)
for index in range(len(self.how_to_text_images)):
self.screen.blit(self.how_to_text_images[index],
self.how_to_text_rects[index])
|
import unittest
from classes import Customer, Amazon, Book, CoffeeMachine
class TestCustomer(unittest.TestCase):
def setUp(self):
pass
def test_deposit(self):
cust = Customer("Sarah")
self.assertEqual(cust.balance, 0)
cust.deposit(1000) # This is where we call the method to test
self.assertEqual(cust.balance, 1000)
def test_withdraw_success(self):
cust = Customer("Sarah")
cust.balance = 1000
cust.withdraw(523)
self.assertEqual(cust.balance, 477)
def test_withdraw_error(self):
cust = Customer("Sarah")
cust.balance = 500
self.assertRaises(ValueError, cust.withdraw, 501)
class TestAmazon(unittest.TestCase):
# Assume customer exists in dictionary for all tests!!!
def setUp(self):
self.amazon = Amazon()
self.daniel_id = self.amazon.create_account("Daniel")
self.daniel_cust = self.amazon.customers[self.daniel_id]
self.book = Book()
self.coffee_machine = CoffeeMachine()
def test_create_account(self):
if self.daniel_id not in self.amazon.customers:
self.fail(f"{self.daniel_id} not in customers dict")
def test_delete_account(self):
self.amazon.delete_account(self.daniel_id)
if self.daniel_id in self.amazon.customers:
self.fail(f"{self.daniel_id} should have been deleted")
def test_add_to_cart(self):
self.amazon.add_to_cart(self.daniel_id, self.book)
if self.book not in self.daniel_cust.cart:
self.fail(f"{self.book} should be in {self.daniel_cust.cart}")
def test_remove_from_cart(self):
self.daniel_cust.cart.append(self.book)
returned_book = self.amazon.remove_from_cart(self.daniel_id, self.book)
if self.book in self.daniel_cust.cart:
self.fail(f"{self.book} should not be in {self.daniel_cust.cart}")
self.assertEqual(self.book, returned_book)
def test_remove_from_cart_None(self):
returned_book = self.amazon.remove_from_cart(self.daniel_id, self.book)
self.assertEqual(returned_book, None)
def test_buy_item_error_cart(self):
self.assertRaises(ValueError, self.amazon.buy_item, self.daniel_id, self.coffee_machine)
def test_buy_item_error_price(self):
self.daniel_cust.balance = 99
self.assertRaises(ValueError, self.amazon.buy_item, self.daniel_id, self.coffee_machine)
def test_buy_item_success(self):
self.daniel_cust.cart.append(self.coffee_machine)
self.daniel_cust.balance = 101
self.daniel_cust.money_spent = 0
self.amazon.buy_item(self.daniel_id, self.coffee_machine)
self.assertEqual(self.daniel_cust.balance, 1)
self.assertEqual(self.daniel_cust.money_spent, 100)
if self.coffee_machine in self.daniel_cust.cart:
self.fail(f"{self.coffee_machine} should not be in {self.daniel_cust.cart}") |
class Shape():
def what_am_i(self):
print("I am a Shape.")
class Square(Shape):
def __init__(self, s1):
self.s1 = s1
def calculate_perimetre(self):
print(self.s1*4)
class Rectangle(Shape):
def __init__(self,w,l):
self.w = w
self.l = l
def calculate_perimeter(self):
print(2*(self.w+self.l))
square = Square(5)
square.what_am_i()
square.calculate_perimetre()
rectangle = Rectangle(5,10)
rectangle.what_am_i()
rectangle.calculate_perimeter()
|
o_list = [3,2,7,5,6]
n_list = [c for c in o_list if c % 7 == 0]
print(n_list)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.