text stringlengths 37 1.41M |
|---|
class Neighborhood:
def __init__(self,name,blocks):
self.name = name
self.blocks = blocks
class Block:
def __init__(self,number,available_apartments=0,price_per_apt=None):
self.number = number
self.available_apartments = available_apartments
self.price_per_apt = price_per_apt
if __name__ == "__main__":
neighborhood_input = input().split(' -> ')
neighborhood_list = []
while not neighborhood_input[0] == 'collectApartments':
new_neighborhood = Neighborhood(name=neighborhood_input[0],blocks = [])
for block in sorted(list(map(int,neighborhood_input[1].split(",")))):
new_block = Block(number=block)
if new_block.number not in [existing_block.number for existing_block in new_neighborhood.blocks]:
new_neighborhood.blocks.append(new_block)
if not new_neighborhood.name in [existing_neighborhood.name for existing_neighborhood in neighborhood_list]:
neighborhood_list.append(new_neighborhood)
else:
for existing_neighborhood in neighborhood_list:
if existing_neighborhood.name == new_neighborhood.name:
for existing_block in existing_neighborhood.blocks:
for new_block in new_neighborhood.blocks:
if existing_block.number == new_block.number:
new_neighborhood.blocks.remove(new_block)
existing_neighborhood.blocks += new_neighborhood.blocks
neighborhood_input = input().split(' -> ')
apartments_data = input().split(' -> ')
while not apartments_data[0] == 'report':
for neighborhood in neighborhood_list:
if neighborhood.name == apartments_data[0].split('&')[0]:
for block in neighborhood.blocks:
if block.number == int(apartments_data[0].split('&')[1]):
block.available_apartments = apartments_data[1].split('|')[0]
block.price_per_apt = apartments_data[1].split('|')[1]
apartments_data = input().split(' -> ')
neighborhood_list_sorted = sorted(neighborhood_list,key=lambda x: x.name)
for neighborhood in neighborhood_list_sorted:
print(f'Neighborhood: {neighborhood.name}')
for block in neighborhood.blocks:
print(f'* Block number: {block.number} -> {block.available_apartments} apartments for sale. Price for one: {block.price_per_apt}') |
def max_element_index(array):
even_odd_index = {'even': 0, 'odd': 0}
try:
max_element_even = max([el for el in array if el % 2 == 0])
even_odd_index['even'] = max(
[idx for idx, el in enumerate(array) if el == max_element_even])
except:
even_odd_index['even'] = 'q'
try:
max_element_odd = max([el for el in array if el % 2 == 1])
even_odd_index['odd'] = max(
[idx for idx, el in enumerate(array) if el == max_element_odd])
except:
even_odd_index['odd'] = 'q'
return even_odd_index
def min_element_index(array):
even_odd_index = {'even': 0, 'odd': 0}
try:
min_element_even = min([el for el in array if el % 2 == 0])
even_odd_index['even'] = max(
[idx for idx, el in enumerate(array) if el == min_element_even])
except:
even_odd_index['even'] = 'q'
try:
min_element_odd = min([el for el in array if el % 2 == 1])
even_odd_index['odd'] = max(
[idx for idx, el in enumerate(array) if el == min_element_odd])
except:
even_odd_index['odd'] = 'q'
return even_odd_index
if __name__ == "__main__":
input_array = list(map(int, input().split()))
input_cmd = input().split()
while not input_cmd[0] == 'end':
if input_cmd[0] == 'exchange':
index = int(input_cmd[1])
if index > len(input_array) - 1 or index < 0:
print('Invalid index')
else:
part_one = input_array[:index+1]
part_two = input_array[index+1:]
input_array = part_two + part_one
if input_cmd[0] == 'max':
if input_cmd[1] == 'odd':
odd_list = [el for el in input_array if el % 2 == 1]
if len(odd_list) == 0:
print('No matches')
else:
print(max_element_index(input_array)['odd'])
else:
even_list = [el for el in input_array if el % 2 == 0]
if len(even_list) == 0:
print('No matches')
else:
print(max_element_index(input_array)['even'])
if input_cmd[0] == 'min':
if input_cmd[1] == 'odd':
odd_list = [el for el in input_array if el % 2 == 1]
if len(odd_list) == 0:
print('No matches')
else:
print(min_element_index(input_array)['odd'])
else:
even_list = [el for el in input_array if el % 2 == 0]
if len(even_list) == 0:
print('No matches')
else:
print(min_element_index(input_array)['even'])
if input_cmd[0] == 'first':
count = int(input_cmd[1])
if count > len(input_array):
print('Invalid count')
else:
if input_cmd[2] == 'odd':
odd_list = [el for el in input_array if el % 2 == 1]
print(odd_list[0:count])
else:
even_list = [el for el in input_array if el % 2 == 0]
print(even_list[0:count])
if input_cmd[0] == 'last':
count = int(input_cmd[1])
if count > len(input_array):
print('Invalid count')
else:
if input_cmd[2] == 'odd':
odd_list = [el for el in input_array if el % 2 == 1]
print(odd_list[-count:])
else:
even_list = [el for el in input_array if el % 2 == 0]
print(even_list[-count:])
input_cmd = input().split()
print(input_array)
|
class RealNumber:
def __init__(self, value, count):
self.value = value
self.count = count
if __name__ == "__main__":
list_of_nums = input().split()
list_of_RealNumber = []
for num in list_of_nums:
Real_Num = RealNumber(value=num, count=0)
if num not in [x.value for x in list_of_RealNumber]:
list_of_RealNumber.append(Real_Num)
for real_num in list_of_RealNumber:
for num in list_of_nums:
if real_num.value == num:
real_num.count += 1
new_list = sorted(list_of_RealNumber,key=lambda x: float(x.value))
for real_num in new_list:
print(f'{float(real_num.value)} -> {real_num.count} times')
|
if __name__ == '__main__':
user_dict = {}
command = input().split(' -> ')
while not command[0] == 'end':
key = command[0]
values = command[1]
if values[0].isdigit():
if key in user_dict.keys():
user_dict[key] += ', ' + values
else:
user_dict[key] = values
else:
if values in user_dict.keys():
user_dict[key] = user_dict[values]
command = input().split(' -> ')
for k,v in user_dict.items():
print(f'{k} === {v}') |
class Topic:
def __init__(self,name,tags=[]):
self.name = name
self.tags = tags
def remove_duplicate_topics(arr):
return sorted(set(arr), key=lambda x: arr.index(x))
if __name__ == '__main__':
input_list = input().split(" -> ")
topics = []
while not input_list[0] == 'filter':
new_topic = Topic(name=input_list[0],tags=input_list[1].split(', '))
if new_topic.name not in [old_topic.name for old_topic in topics]:
topics.append(new_topic)
else:
for old_topic in topics:
if old_topic.name == new_topic.name:
old_topic.tags.extend(new_topic.tags)
input_list = input().split(" -> ")
for topic in topics:
topic.tags = remove_duplicate_topics(topic.tags)
cmd_list = input().split(', ')
for topic in topics:
if all(item in topic.tags for item in cmd_list):
new_topics = ['#' + i for i in topic.tags]
print(f'{topic.name} | {", ".join(new_topics)}') |
if __name__ == '__main__':
n = int(input())
sum = 0
for x in range (0,n):
sum += int(input())
print(sum) |
#Creating The List
my_list = list()
my_list.append(2)
my_list.append(4)
my_list.append(1)
my_list.append(5)
my_list.append(3)
# Remove the last element from the list
my_list.pop()
#Remove the specific element
my_list.remove(2)
#Max num from the list
maximum = max(my_list)
print(f"Maximum number from the list is {maximum}")
#Min num from the list
minimum = min(my_list)
print(f"Minimum number from the list is {minimum}")
print(my_list)
#create tuple
my_tuple = ('s','y','r','a','c','a','r','d')
print(my_tuple[::-1])
#converting tuple into list
my_list1 = list(my_tuple)
print(my_list1)
|
from Movie_Extractor import FileExtractor
from Watchlist_Information import display_watchlist
def movie_selection():
catalogue = FileExtractor.extract_movie_dict("movies_length.txt")
watchlist = {}
print("==================")
print("Movie Catalogue")
print("==================")
for film in catalogue:
print(film)
print("==================")
print("")
decision = "Y"
while decision.upper() == "Y":
selection = input("Please select a film you would like to add to your watchlist: ")
if selection in catalogue:
watchlist[selection] = catalogue[selection]
print(selection, "has been added to your watchlist!")
else:
print("Sorry we don't have that movie in our catalogue")
decision = input("Would you like to add any other movie to your watchlist?(Y/N): ")
if decision == "N":
print(watchlist)
display_watchlist(watchlist)
movie_selection()
|
from euler_utils import collatz
"""
Problem 14 Statement:
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms.
Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
"""
def doProb14():
longest = 0
num = 1000000
for n in range(1000000,0,-1):
l = len(collatz(n))
if (longest < l):
longest = l
num = n
print "Longest Collatz sequence under 1 million is",longest,"from",num |
import math
import pygame
from Data import Data
# Euclidean distance between two points
def distance_between(pos1, pos2):
"""Calculates the Euclidean distance between two positions
:arg pos1: The first position
:arg pos2: The second position
:return: The distance between the two positions
:rtype: float
"""
# Gets x and y distance between points
dx = pos2[0] - pos1[0]
dy = pos2[1] - pos1[1]
# Returns distance via good ol Pythagoras
return math.sqrt(dx ** 2 + dy ** 2)
def find_points_on_circumference(NUM_POINTS, radius):
"""Find all the points on the circumference of a given circle
:arg NUM_POINTS: A constant multiple which determines how many points should be found
:arg radius: The radius of the given circle, whose positions on the circumference
:return: A list of the points on the circumference of the circle, specified by the radius, which have been found
:rtype: List
"""
points_found = []
for j in range(NUM_POINTS):
# X and Y values of the points
x = radius * math.sin((2 * math.pi / NUM_POINTS) * j) + Data.CENTER[0]
y = radius * math.cos((2 * math.pi / NUM_POINTS) * j) + Data.CENTER[1]
# Round points to nearest int and add as a tuple of new points on the circumference
points_found.append(tuple(map(int, (x, y))))
return points_found
class Circle:
"""This class represents circles. Need I say more?"""
def __init__(self, window, col, rad, thickness):
"""Creates a new circle object
:arg window: The window onto which the circle will be drawn on
:arg col: The colour of the circle
:arg rad: The radius of the circle
:arg thickness: The thickness of the circle's circumference
"""
self.window = window
self.colour = col
self.rad = rad
self.thickness = thickness
# The points on the circle's circumference
self.points_on_circumference = find_points_on_circumference(int(2 * math.pi * rad), rad)
def draw(self):
"""Draws the circle itself to the window
"""
pygame.draw.circle(self.window, self.colour, Data.CENTER, self.rad, self.thickness)
def draw_tangent_line(self, pos):
"""Draws the tangent line to the circle at a given position
:arg pos: A position on the circle's circumference
"""
# Get the x and y values, relative to the center of the circle, of the position
x = pos[0] - Data.CENTER[0]
y = pos[1] - Data.CENTER[1]
# Check for undefined slope, draw a vertical line in this case
if y == 0:
pygame.draw.line(self.window, self.colour, (pos[0], pos[1] - 100), (pos[0], pos[1] + 100))
else:
# Gets the slope (derived using derivative calculus :DD)
slope = -x / y
# The positions of the points to the left and right of the position, which will be used to form the line
left_pos = (pos[0] - 100, pos[1] - 100 * slope)
right_pos = (pos[0] + 100, pos[1] + 100 * slope)
# Draws the line by connecting said points
pygame.draw.line(self.window, self.colour, left_pos, right_pos)
# Finds closest point to a position on the circumference of this circle
def closest_point_on_circumference(self, position):
"""Finds the closest point on the circumference of the circle, given a position
:arg position: The position, which doesn't necessarily have to be on the circle's circumference
:return: The location of the closest point on the circle's circumference
:rtype: tuple
"""
# Default closest point to first point on circumference
closest = self.points_on_circumference[0]
shortest_distance = distance_between(Data.CENTER, closest)
# Checks each dot on the circumference
for dot in self.points_on_circumference:
# Find distance between point and the position
distance = distance_between(position, dot)
# Sets new closest point and distance if a closer point is found
if distance < shortest_distance:
closest = dot
shortest_distance = distance
# Once all points have been checked, return the closest point on circumference
return closest
|
'''Passing function as a parameter'''
def f(x):
return x * x
def modify(L,fn):
for idx,v in enumerate(L):
L[idx] = fn(v)
L = [2,4,6]
modify(L,f)
print(L)
|
#smallest_number
def smallest_no(arr):
smallest_no = arr[0]
for num in arr[1:]:
if smallest_no > num:
smallest_no = num
return smallest_no
print smallest_no([100, 200, 500, 300, 55 ])
|
"""
A module that fleshes out the strategy class which can control when
a trading algorithm decides to buy/sell assets.
This file also specifies certain parameters for trading, such as the fee percentage per
transaction.
"""
fee_pc = 0.0000
class Strategy(object):
"""
Determines when to buy/sell assets. Base class all actual strategy classes should
inherit from.
"""
def buy(self, **data):
"""
Decides whether to buy assst based on provided data.
Returns:
The number of assets to buy, or 0 for no buys.
"""
raise NotImplementedError()
def sell(self, **data):
"""
Decides whether to sell asset based on provided data.
Returns:
The number of assets to buy, or 0 for no sells.
"""
raise NotImplementedError()
class Portfolio(object):
"""
Tracks the details of a portfolio, such as cash and positions. Each portfolio
only has one strategy object.
Portfolio object should be passed a strategy object when created.
"""
def __init__(self, strategy, start_cash, logfile):
self.strat = strategy
self.cash = start_cash
self.logfile = logfile
self.position = 0
self.t = 0
self.active = True # not used right now
self.fees = 0
self.last_sp = 0
self.title = "t, spot_price, cash, pos, fees"
with open(logfile, 'w+') as f:
f.write(self.title)
f.close()
def __str__(self):
return f'{self.t}, {self.last_sp}, {self.cash}, {self.position}, {self.fees}'
def trade(self, sp, order_num):
"""
Execute trade based off of order. Negative order_num means sell
Args:
order_num: float of coins to be exchanged in transaction
"""
# flip sign to reflect cash flow movement based on buying versus selling
# fee is paid separately from order
subtotal = sp * order_num
fee = abs(subtotal) * fee_pc
self.cash -= subtotal
self.cash -= fee
# adjust position to reflect transaction
self.position += order_num
# keep tracks of fees paid
self.fees += fee
def timestep(self, data):
"""
Execute strategy for one time step.
Args:
data: dictionary of current market conditions
"""
self.t += 1
data["cash"] = self.cash
data["position"] = self.position
buy_num = self.strat.buy(**data)
sell_num = self.strat.sell(**data)
sp = data["spot_price"] = float(data["spot_price"])
self.last_sp = sp
self.trade(sp, buy_num - sell_num)
self._log(**data)
def toggle_trading(self):
"""
Switches portfolio between active and non-active for trading.
"""
raise NotImplementedError()
def _log(self, **data):
if not self.logfile:
raise FileNotFoundError()
with open(self.logfile, 'w+') as f:
f.write(self.__str__())
f.close()
class Bot(object):
"""
Manages several portfolios and presents information about them.
"""
def __init__(self, logfile='test.csv'):
self.portfolios = []
self.logfile = logfile
self.t = 0
def summary(self):
"""
Prints information about each portfolio in the bot.
"""
for i, p in enumerate(self.portfolios):
print(f'\t\t\t {p.title}')
print(f'Portfolio {i}: {p}')
def timestep(self):
data = self._data_pull()
# only considered a timestep if data is received
if not data:
return None
self.t += 1
for p in self.portfolios:
p.timestep(data)
self._log()
print('*'*50 + '\n')
self.summary()
def add_port(self, strat, start_cash, logfile=None):
if not logfile:
logfile = f'portfolio_{len(self.portfolios)+1}.csv'
self.portfolios.append(Portfolio(strat, start_cash, logfile))
def _log(self, **data):
pass
def _data_pull(self):
"""
Pulls data from the exchange API.
Returns:
Dictionary of price/currency data from exchange.
"""
raise NotImplementedError("Bot data pull function") |
use_kont = False
while not use_kont:
use_nam = input("create a user name composed of 3-18 characters: ")
if use_nam.isalpha():
use_kont=True
else:
print("WARNING!!! a user name cannot include a number.")
pas_kont = False
while not pas_kont:
pas_nam = input("create a password composed of 6-12 characters: ")
if 6<=len(pas_nam)<=12:
pas_kont=True
else:
print("WARNING!!! the number of characters in the password is less than 6 or more than 12.")
print("\n***********************\n"
f"Your user name; {use_nam}\n"
f"Your password; {pas_nam}")
# The End
|
"""
Exercício 21
Nome: Números repetidos
Objetivo: Criar uma lista com alguns números e detectar números repetidos dentro da lista.
Dificuldade: Avançado
1 - Crie uma lista com 20 números quaisquer (certifique-se de que alguns números são repetidos). Ordene a lista em ordem numérica com o método 'sort()' e exiba-a na tela.
2 - Exiba a quantidade de elementos que a lista possui.
3 - Varra todos os números da lista utilizando o for e exiba na tela apenas os números repetidos. Certifique-se de que cada número repetido apareça apenas uma vez.
4 - Declare uma nova lista e insira 20 números (de 1 a 30) de forma aleatória utilizando a biblioteca random, com o método random.randint(inicio, limite). Ordene a lista em ordem numérica com o método 'sort()' e exiba-a na tela. Consulte a documentação da biblioteca em caso de dúvidas.
5 - Pegue o código de varredura da lista com o for declarado no item 3 e coloque-o em uma função chamada 'detectar_numeros_repetidos(lista)' que recebe um argumento referente a lista de números e retorna apenas os números repetidos. Execute a função para a lista de números criada no item 1 e exiba-a na tela.
6 - Execute a função declarada no item 5 para a lista de números criada no item 4.
7 - Crie uma função que receba uma lista de números e exiba na tela a quantidade de vezes que o número aparece repetido. Exiba a mensagem apenas para números repetidos e uma só vez por número. Dica: utilize o método 'lista.count(elemento)'.
8 - Crie uma função que receba uma lista de números e retorne um dicionário para cada número, onde a chave do dicionário é o número em questão e o valor do dicionário é a quantidade de vezes que o número se repete. Utilize o método 'lista.count(elemento)'. Se o item não se repetir, exiba a mensagem "O número X não se repete.", caso contrário, exiba a mensagem "O número X se repete Y vezes.".
9 - Faça a mesma coisa que no item 9, porém, em vez de utilizar o método 'count()', faça a checagem para saber se o item em questão está no dicionário utilizando a checagem do método 'dicionário.get(chave)'. Caso a checagem seja negativa (o dicionário ainda não possui o numero) adicione-o no dicionário utilizando 'dicionario[numero] = 1'. Caso a checagem seja positiva, atribua um valor adicional à posição do dicionário utilizando: 'dicionario[numero] = dicionario[numero] + 1'.
10 - Crie uma função que insere 20 números aleatórios (de 1 a 30) em uma lista certificando de que NENHUM número é repetido. Ordene a lista em ordem numérica com o método 'sort()' e exiba-a na tela.
"""
# Resolução
# Item 1
print("Item 1")
print("1 - Crie uma lista com 20 números quaisquer (certifique-se de que alguns números são repetidos). Ordene a lista em ordem numérica com o método 'sort()' e exiba-a na tela.")
lista = [9, 1, 2, 2, 3, 3, 4, 5, 7, 7, 9, 11, 13, 9, 4, 3, 7, 1, 6, 8]
lista.sort()
# Item 2
print("\nItem 2")
print("2 - Exiba a quantidade de elementos que a lista possui.")
print("A lista {} possui {} elementos.".format(lista, len(lista)))
# Item 3
print("\nItem 3")
print("3 - Varra todos os números da lista utilizando o for e exiba na tela apenas os números repetidos. Certifique-se de que cada número repetido apareça apenas uma vez.")
nova_lista = []
for numero in lista:
if lista.count(numero) > 1 and nova_lista.count(numero) == 0:
print("O número {} está repetido.".format(numero))
nova_lista.append(numero)
# Item 4
print("\nItem 4")
print("4 - Declare uma nova lista e insira 20 números (de 1 a 30) de forma aleatória utilizando a biblioteca random, com o método random.randint(inicio, limite). Ordene a lista em ordem numérica com o método 'sort()' e exiba-a na tela. Consulte a documentação da biblioteca em caso de dúvidas.")
from random import randint
lista_aleatoria = []
for numero in range(20):
lista_aleatoria.append(randint(1, 30))
lista_aleatoria.sort()
print("Lista com números aleatórios: {}.".format(lista_aleatoria))
# Item 5
print("\nItem 5")
print("5 - Pegue o código de varredura da lista com o for declarado no item 2 e coloque-o em uma função chamada 'detectar_numeros_repetidos(lista)' que recebe um argumento referente a lista de números e retorna apenas os números repetidos. Exiba a lista na tela.")
def detectar_numeros_repetidos(lista_recebida):
nova_lista = []
for numero in lista_recebida:
if lista_recebida.count(numero) > 1 and nova_lista.count(numero) == 0:
nova_lista.append(numero)
return nova_lista
print("A lista {} criada no item 1 possui os seguintes números repetidos: {}".format(lista, detectar_numeros_repetidos(lista)))
# Item 6
print("\nItem 6")
print("6 - Execute a função declarada no item 5 para a lista de números criada no item 4.")
print("A lista {} criada no item 4 possui os seguintes números repetidos: {}".format(lista_aleatoria, detectar_numeros_repetidos(lista_aleatoria)))
# Item 7
print("\nItem 7")
print("7 - Crie uma função que receba uma lista de números e exiba na tela a quantidade de vezes que o número aparece repetido. Exiba a mensagem apenas para números repetidos e uma só vez por número. Dica: utilize o método 'lista.count(elemento)'.")
def exibir_quantidade_repeticao(lista_recebida):
print("Exibir Quantidade de Repetição da lista {}.".format(lista_recebida))
numeros_exibidos = []
for numero in lista_recebida:
if numeros_exibidos.count(numero) == 0:
quantidade_repeticao = lista_recebida.count(numero)
numeros_exibidos.append(numero)
if quantidade_repeticao > 1:
print("O número {} aparece {} vezes na lista.".format(numero, quantidade_repeticao))
exibir_quantidade_repeticao(lista)
# Item 8
print("\nItem 8")
print("8 - Crie uma função que receba uma lista de números e retorne um dicionário para cada número, onde a chave do dicionário é o número em questão e o valor do dicionário é a quantidade de vezes que o número se repete. Utilize o método 'lista.count(elemento)'. Se o item não se repetir, exiba a mensagem \"O número X não se repete.\", caso contrário, exiba a mensagem \"O número X se repete Y vezes.\".")
def detectar_quantidade_repeticao(lista_recebida):
dicionario = {}
for numero in lista_recebida:
if not dicionario.get(numero):
dicionario[numero] = lista_recebida.count(numero)
return dicionario
lista_numeros_quantidade_repeticao = detectar_quantidade_repeticao(lista_aleatoria)
for numero in lista_numeros_quantidade_repeticao:
quantidade_repeticao = lista_numeros_quantidade_repeticao[numero]
if quantidade_repeticao == 1:
print("O número {} não está repetido.".format(numero))
else:
print("O número {} está repetido {} vezes.".format(numero, quantidade_repeticao))
# Item 9
print("\nItem 9")
print("9 - Faça a mesma coisa que no item 9, porém, em vez de utilizar o método 'count()', faça a checagem para saber se o item em questão está no dicionário utilizando a checagem do método 'dicionário.get(chave)'. Caso a checagem seja negativa (o dicionário ainda não possui o numero) adicione-o no dicionário utilizando 'dicionario[numero] = 1'. Caso a checagem seja positiva, atribua um valor adicional à posição do dicionário utilizando: 'dicionario[numero] = dicionario[numero] + 1'.")
def detectar_quantidade_repeticao(lista_recebida):
dicionario = {}
for numero in lista_recebida:
if not dicionario.get(numero):
dicionario[numero] = 1
else:
dicionario[numero] = dicionario[numero] + 1
return dicionario
lista_numeros_quantidade_repeticao = detectar_quantidade_repeticao(lista_aleatoria)
for numero in lista_numeros_quantidade_repeticao:
quantidade_repeticao = lista_numeros_quantidade_repeticao[numero]
if quantidade_repeticao == 1:
print("O número {} não está repetido.".format(numero))
else:
print("O número {} está repetido {} vezes.".format(numero, quantidade_repeticao))
# Item 10
print("\nItem 10")
print("10 - Crie uma função que insere 20 números aleatórios (de 1 a 30) em uma lista certificando de que NENHUM número é repetido. Ordene a lista em ordem numérica com o método 'sort()' e exiba-a na tela.")
def criar_lista_aleatoria_sem_repetir():
lista = []
while len(lista) < 20:
numero_aleatorio = randint(1, 30)
if lista.count(numero_aleatorio) == 0:
lista.append(numero_aleatorio)
return lista
lista_aleatoria_item11 = criar_lista_aleatoria_sem_repetir()
lista_aleatoria_item11.sort()
print("A lista gerada com números aleatórios entre 1 e 30, sem repetir nenhum número é: {}.".format(lista_aleatoria_item11))
|
"""
Exercício 6
Nome: Catapulta
Objetivo: Receber o número de baterias e duração da bateria e calcular a quantidade de pedras que a catapulta irá soltar.
Dificuldade: Principiante
1 - Uma catapulta lançou 300 pedras em 5 baterias de 15 minutos, cada.
2 - Quantas pedras ela lançaria em 8 baterias de 7 minutos, cada?
3 - Crie um programa que receba os valores base para que a aplicação funcione de forma que, se alterarmos o número de bateriais e a duração de cada bateria, o programa funcione sem precisar de mais modificações.
"""
# Resolução
pedras_minuto = 300 / (5 * 15)
baterias = int(input("Informe quantas baterias: "))
duracao_bateria = int(input("Informe a duração de cada bateria: "))
pedras = pedras_minuto * baterias * duracao_bateria
print("A catapulta lançou {:.0f} pedras em {} baterias de {} minutos, cada.".format(pedras, baterias, duracao_bateria))
|
"""
Exercício 13
Nome: Convertendo Celsius/Farenheit
Objetivo: Escrever duas funções de conversão, uma de graus celsius em farenheit e a outra que faça o contrário.
Dificuldade: Principiante
1 - Crie um aplicativo de conversão entre as temperaturas Celsius e Farenheit.
2 - Primeiro o usuário deve escolher se vai entrar com a temperatura em Célsius ou Farenheit, depois a conversão escolhida é realizada.
3 - Se C é a temperatura em Celsius e F em farenheit, as fórmulas de conversão são:
F = (9 * C / 5) + 32
C = 5 * (F - 32) / 9
"""
|
"""
Exercício 12
Nome: Praticando Funções
Objetivo: Escrever diversas funções para reaproveitar trechos de código
Dificuldade: Intermediário
Escreva um código de modo que exiba o valor do x digitado pelo usuário e que seja
substituído nas funções.
1 - Sendo f(x) = 3x - 2 determine o valor de f(5) + f(0).
2 - Na produção de peças, uma fábrica tem um custo fixo de R$ 30,00 mais um custo variável
de R$ 2,00 por unidade produzida. Sendo x o número de peças unitárias produzidas, determine
o custo de produção de 100 peças.
3 - Crie uma função que receba 2 números e retorne o maior valor.
4 - Crie uma função que receba 3 números e retorne o maior valor, use a função da questão 3.
5 - Dadas as funções f(x) = x – 5 e g(x) = 3x + 1, crie um código que retorne o valor da
soma de f(9) + g(2). Depois crie um código que retorne o valor da soma das duas funções
com números digitados pelo usuário.
6 - Considere as seguintes funções: f(x) = x - 4 e g(x) = 5x + 1.
Qual é o valor da função composta g(f(3))? Depois crie um código que retorne o valor da
soma das duas funções com números digitados pelo usuário.
7 - Crie uma função chamada dado() que retorna, através de sorteio, um número de 1 até 6.
Exiba 10 números sorteados utilizando a mesma função criada.
Números aleatórios: random.randint(inicio, fim)
"""
|
import pandas as pd
import sys
def parse_data(filename, colnames=['hour','stock_id','stock_price']):
""" parse the data file. assumes file as 3 inputs per row.
filename : path to file to parse.
colnames : default column names to use
Returns a pandas dataframe
"""
df = pd.read_csv( filename,
sep = '|',
header = None,
names = colnames,
float_precision='high')
df.sort_values(by=['hour','stock_id'], inplace=True)
"""create a column of unique keys combining
hour and stock_id to use as index.
This will be useful in merding data frames"""
unique_keys = [str(hour)+stock_id for hour,stock_id in
zip(list(df['hour']), list(df['stock_id']))]
df.index = unique_keys
return df
def merge_frames(df1, df2, keys = ['hour','stock_id']):
""" merge two dataframes (inner join) on 'hour' and 'stock_id'
Returns a dataframe where keys match in both df1 and df2.
"""
return pd.merge(df1, df2, on=keys)
def compute_rolling_errors(df1, df2, roll_on, target, window_size):
"""Computes the rolling mean error between two columns
df1,df2 : dataframes
roll_on : column to roll on (should be sorted)
target : target column for which error required
window : rolling window size
Returns a dataframe with 3 columns named
'start_hour', 'end_hour', 'error'
"""
#First check that the columns actually exist in the dataframe
if ( (roll_on not in df1.columns) | (target not in df1.columns) or
(target not in df2.columns) ) :
printf("Input Error in compute_rolling_errors: A specified column not in data frame\n")
return
#Get the minimum and maximun time
min_time = min(df1[roll_on])
max_time = max(df1[roll_on])
results = {}
while min_time <= max_time-window_size+1:
stop_time = min_time + window_size - 1
window_mask = ( (df1[roll_on] >= min_time) & (df1[roll_on] <= stop_time) )
actual = df1[window_mask]
#see https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html
selection = actual.index
predicted = df2.reindex(selection)
#compute the error for the current window
error = abs(actual[target] - predicted[target]).mean()
results[min_time] = [min_time, stop_time, error]
min_time +=1
#take the transpose to have correct columns
results = pd.DataFrame(results).T
results.columns = ['start_hour', 'end_hour', 'error']
return results
def write_dfto_file(df, file_out):
""" Write data frame to a file
df : DataFrame
file_out : string specifying the output file
"""
#convert hours to string to avoid float_format from to_csv
df['start_hour'] = df['start_hour'].map(lambda x: '%d'%(x))
df['end_hour'] = df['end_hour'].map(lambda x: '%d'%(x))
pd.DataFrame(df).to_csv(file_out,
sep='|',
index=False,
header=False,
na_rep='NA',
float_format='%.2f')
if __name__=="__main__":
#get input file paths from command line
file_window = sys.argv[1]
file_actual = sys.argv[2]
file_predicted = sys.argv[3]
file_out = sys.argv[4]
#parse the files
actual_df = parse_data(file_actual)
predicted_df = parse_data( file_predicted)
window = int(open(file_window,'r').readlines()[0])
results = compute_rolling_errors(actual_df, predicted_df,
roll_on = 'hour',
target = 'stock_price',
window_size = window)
#write result to file
write_dfto_file(results, file_out)
|
class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __str__(self):
return "TreeNode({}, {}, {})".format(str(self.value), self.left, self.right)
def in_order_str(tree):
if tree is None:
return ""
return str(in_order_str(tree.left)) + str(tree.value) + str(in_order_str(tree.right))
def num_tree_nodes(tree):
if tree is None:
return 0
return num_tree_nodes(tree.left) + 1 + num_tree_nodes(tree.right)
def create_n_spaces(n):
return "".join([" " for _ in range(n - 1)])
def pretty_print_tree(tree):
"""
Given a tree node, this function prints the tree in a pretty manner.
For example:
w
/ \
a v
/ \ / \
b c o u
/ \ / \ / \ / \
d z e f x 1 q t
\ \ / \ \ \ / \
g h i j m p r s
/ /
k l
:param tree: the given tree to print out
"""
def calculate_element_location(tree_node, current_spaces, depth=0):
def calculate_directional_element_location(root, last_index, direction_symbol):
if root is not None:
next_index = in_order_tree.index(root.value)
if depth + 1 not in rows_to_elements:
rows_to_elements[depth + 1] = []
rows_to_elements[depth + 1] += [(direction_symbol, current_spaces + (next_index - last_index))]
calculate_element_location(root, current_spaces + (next_index - last_index) * 2, depth + 2)
if tree_node is not None:
if depth not in rows_to_elements:
rows_to_elements[depth] = []
rows_to_elements[depth] += [(tree_node.value, current_spaces)]
cur_in_order_index = in_order_tree.index(tree_node.value)
calculate_directional_element_location(tree_node.left, cur_in_order_index, left_slash)
calculate_directional_element_location(tree_node.right, cur_in_order_index, right_slash)
left_slash = "/"
right_slash = "\\"
in_order_tree = in_order_str(tree)
rows_to_elements = {}
calculate_element_location(tree, num_tree_nodes(tree))
for idx, elements_in_row in rows_to_elements.items():
row = ""
current_element_space = 0
for element, element_index in elements_in_row:
spaces_to_fill = element_index - current_element_space
row += create_n_spaces(spaces_to_fill)
row += element
current_element_space = element_index
print(row)
def serialize_tree(tree):
"""
Given a tree's root, serializes it into a string.
For example:
tree = TreeNode("a", TreeNode("b", TreeNode("c")), TreeNode("d"))
serialize_tree(tree) ====>>> abc***d** (using pre-order traversal)
"""
if tree is None:
return "*"
return str(tree.value) + serialize_tree(tree.left) + serialize_tree(tree.right)
def deserialize_tree(tree_str):
"""
Given a string, turns the string into a TreeNode
For example:
tree_str = abc***d**
deserialize_tree(tree_str) ====>>> TreeNode("a", TreeNode("b", TreeNode("c")), TreeNode("d"))
"""
def inner_helper(idx_dict):
idx_dict["idx"] += 1
str_idx = idx_dict["idx"]
if str_idx == len(tree_str) or tree_str[str_idx] == "*":
return None
return TreeNode(tree_str[str_idx], inner_helper(idx_dict), inner_helper(idx_dict))
return inner_helper({"idx": -1})
def num_unival_trees(root):
"""
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
0
/ \
1 0
/ \
1 0
/ \
1 1
"""
def unival_helper(tree_node):
"""
returns the number of unival trees and the value of the nodes. If -1 is the value, not all nodes are equal.
"""
if tree_node.left is None and tree_node.right is None:
return 1, tree_node.value
if tree_node.left is None:
right_tree = unival_helper(tree_node.right)
if right_tree[1] == tree_node.value:
return right_tree[0] + 1, right_tree[1]
else:
return right_tree[0], -1
if tree_node.right is None:
left_tree = unival_helper(tree_node.left)
if left_tree[1] == tree_node.value:
return left_tree[0] + 1
else:
return left_tree[0], -1
left_tree = unival_helper(tree_node.left)
right_tree = unival_helper(tree_node.right)
if right_tree[1] == tree_node.value and right_tree[1] == left_tree[1]:
return left_tree[0] + right_tree[0] + 1, tree_node.value
else:
return left_tree[0] + right_tree[0], -1
if root is None:
return 0
return unival_helper(root)[0]
if __name__ == '__main__':
k = TreeNode("k")
g = TreeNode("g", k)
d = TreeNode("d", right=g)
z = TreeNode("z")
b = TreeNode("b", d, z)
h = TreeNode("h")
e = TreeNode("e", right=h)
i = TreeNode("i")
j = TreeNode("j")
f = TreeNode("f", i, j)
c = TreeNode("c", e, f)
tree_node1 = TreeNode("a", b, c)
l1 = TreeNode("l")
m = TreeNode("m", l1)
x = TreeNode("x", right=m)
z1 = TreeNode("1")
o = TreeNode("o", x, z1)
p = TreeNode("p")
q = TreeNode("q", right=p)
r = TreeNode("r")
s = TreeNode("s")
t = TreeNode("t", r, s)
u = TreeNode("u", q, t)
tree_node2 = TreeNode("v", o, u)
tree_node3 = TreeNode("w", tree_node1, tree_node2)
pretty_print_tree(tree_node3)
print(deserialize_tree(serialize_tree(TreeNode("a", TreeNode("b", TreeNode("c")), TreeNode("d")))))
print(num_unival_trees(TreeNode("0", TreeNode("1"), TreeNode("0", TreeNode("1", TreeNode("1"), TreeNode("1")),
TreeNode("0"))))) # 5
|
"""
Week 2 Problem Set - Problem 3
You'll notice that in Problem 2, your monthly payment had to be a multiple of $10. Why did we make it that way? You can try running your code locally so that the payment can be any dollar and cent amount (in other words, the monthly payment is a multiple of $0.01). Does your code still work? It should, but you may notice that your code runs more slowly, especially in cases with very large balances and interest rates. (Note: when your code is running on our servers, there are limits on the amount of computing time each submission is allowed, so your observations from running this experiment on the grading system might be limited to an error message complaining about too much time taken.)
Well then, how can we calculate a more accurate fixed monthly payment than we did in Problem 2 without running into the problem of slow code? We can make this program run faster using a technique introduced in lecture - bisection search!
"""
_balance = balance
monthlyInterestRate = annualInterestRate/12.0
monthlyPaymentLower = balance/12.0
monthlyPaymentUpper = (balance * (1 + monthlyInterestRate)**12)/12.0
while _balance != 0:
_balance = balance
month = 0
monthlyPaymentMid = (monthlyPaymentLower + monthlyPaymentUpper)/2
while month < 12:
month = month + 1
unpaidBalance = _balance - monthlyPaymentMid
updatedBalance = unpaidBalance + monthlyInterestRate * unpaidBalance
_balance = updatedBalance
if _balance <-0.01:
_balance = balance
monthlyPaymentUpper = monthlyPaymentMid
monthlyPaymentMid = (monthlyPaymentLower + monthlyPaymentUpper)/2
elif _balance > 0.01:
_balance = balance
monthlyPaymentLower = monthlyPaymentMid
monthlyPaymentMid = (monthlyPaymentLower + monthlyPaymentUpper)/2
else:
break
print("Lowest Payment: " + str(round(monthlyPaymentMid,2)))
|
def vogal(a):
if a.upper() == 'A':
return ('True')
elif a.upper() == 'E':
return ('True')
elif a.upper() == 'I':
return ('True')
elif a.upper() == 'O':
return ('True')
elif a.upper() == 'U':
return ('True')
else:
return ('False')
def main():
letra = input()
resultado = vogal(letra)
print(f'{resultado}')
if __name__ == "__main__":
main()
|
"""
Ejemplo 4: Uso de función lambda
@davisalex22
"""
# Cada elemento de datos, tiene (edad y estatura)
datos = ((30 , 1.79) , (25, 1.60) , (35, 1.68))
dato = lambda x: x[2]
edad = lambda x: x[1] * 100
print(edad(dato(datos)))
|
"""
Purpose: Determine how to split income.
Inputs:
Outputs:
Author: t0w3l4
Date: August 4, 2021
"""
# Function that will determine the income split
# Takes in gross and net income as parameters
def income_split(gross_income, net_income):
# Assign passed in variables to local variables
gr_inc = gross_income
nt_inc = net_income
|
print('see powerpoint file')
print('the cost of strokes can be incorportated into the model by counting the number of strokes '
'a patient has, and multiplying it by $5,000 then adding it to the costs of treatment.'
'This would be possible counting with for and if statements. ')
|
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(n-i-1):
if arr[j+1] < arr[j]:
arr[j], arr[j+1] = arr[j+1], arr[j]
print(arr)
if __name__ == '__main__':
arr = [5,4,3,2,1]
bubble_sort(arr) |
#! /usr/bin/python3
import sys
#Vegenere Cipher: Encryption + Decryption
def errorm():
print('Usage: vegenere [key] [plaintext/ciphertext]')
def errorm2():
print('please put in "e"(encryption) or "d"(decryption) to operate!')
def get_key(val):
for key, value in rot_list.items():
if val == value:
return key
return "symbol doesn't exist"
key = sys.argv[1]
message = sys.argv[2]
print('Do you want to encrypt or decrypt a message? (e/d):')
answer = input()
#Dictionary for shifting
rot_list = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,
'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26,
'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,'G':7,'H':8,'I':9,'J':10,'K':11,
'L':12,'M':13,'N':14,'O':15,'P':16,'Q':17,'R':18,'S':19,'T':20,'U':21,'V':22,'W':23,'X':24,'Y':25,'Z':26}
marks = [' ',',','.','?','!']
keylen = len(key)
messlen = len(message)
#remove marks
s = 1
for y in range(0, messlen):
if message[y] in marks:
message = message[:y] + message[y+1:]
message = message + "e"
s = s + 1
message = message + "e"
message = message[:-s]
messlen = len(message)
#Convert letters to digits
keylist = []
for a in range(0, keylen):
keylist.append(rot_list[key[a]])
messlist = []
for b in range(0, messlen):
messlist.append(rot_list[message[b]])
#How often will the key be used
fest = keylist
if (messlen/keylen) >= 1:
iteration = int(messlen/keylen)
else:
iteration = int(keylen/messlen)
for c in range(0, iteration):
keylist = keylist + fest
#Encryption
if answer == 'e':
#key > text
result = []
if (messlen/keylen) >= 1:
for d in range(0,messlen):
result.append(messlist[d] + keylist[d])
#key < text
elif (messlen/keylen) <= 1:
for e in range(0,messlen):
result.append(messlist[e] + keylist[e])#Bug
#key == text
else:
for f in range(0,keylen):
result.append(messlist[f] + keylist[f])
#Limit the digits to 26
for g in range(0,len(result)):
if (result[g]/26) > 1:
result[g] = result[g]%26
#Convert digits to letters
Cryptmess = []
result_list = list(result)
for h in range(0,len(result)):
Cryptmess.append(get_key(result[h]))
res_string=""
for i in Cryptmess:
res_string=res_string+i
print(res_string)
#Decryption
elif answer == 'd':
#key > text
result = []
if (messlen/keylen) >= 1:
for d in range(0,messlen):
result.append(messlist[d] - keylist[d])
if result[d] <= 0:
result[d] = result[d] + 26
#key < text
elif (messlen/keylen) <= 1:
for e in range(0,messlen):
result.append(messlist[e] - keylist[e])
if result[e] <= 0:
result[e] = result[e] + 26
#key == text
else:
for f in range(0,keylen):
result.append(messlist[f] - keylist[f])
if result[f] <= 0:
result[f] = result[f] + 26
#Limit the digits to 26
for g in range(0,len(result)):
if (result[g]/26) > 1:
result[g] = result[g]%26
#Convert digits to letters
Cryptmess = []
result_list = list(result)
for h in range(0,len(result)):
Cryptmess.append(get_key(result[h]))
res_string=""
for i in Cryptmess:
res_string=res_string+i
print(res_string)
else:
errorm2() |
#! /usr/local/bin/python3
class InsertionSort:
def sort(self, original_list):
if original_list is None:
return []
arr = original_list.copy()
if len(arr) <= 1:
return arr
sorted = [arr.pop()]
while len(arr) > 0:
item = arr.pop()
for i, val in enumerate(sorted):
if val >= item:
sorted = sorted[0:i] + [item] + sorted[i:len(sorted)]
break
else:
sorted.append(item)
return sorted
def test(self):
import time
start = time.process_time()
result = self.sort([23, 2, 6, 3, 77, 4, 98, 8, 5, 5, 8])
end = time.process_time()
print(result, (end - start) * 1000)
if __name__ == '__main__':
InsertionSort().test()
|
# class MyList():
# myindex = 0
# def get_my_index(self):
# return self[self.myindex]
# new_list = MyList([1, 2, 3])
# print(new_list.get_my_index())
# new_list.myindex = 1
# print(new_list.get_my_index())
# class Tweet(str):
# def get_mentions(self):
# words = self.split()
# mentions = []
# for word in words:
# if word.startswith("@"):
# mentions.append(word)
# return mentions
# tweet = Tweet("This is my tweet @someone, @someonelse")
# print(tweet.get_mentions())
class Animal():
def __init__(self, name):
self.name = name
def walking(self):
print("{} is Walking".format(self.name))
class Dog(Animal):
def bark(self):
print("{} is barking".format(self.name))
class Cat(Animal):
def meowing(self):
print("{} is meowing".format(self.name))
dog = Dog("Lassie")
cat = Cat("Garfield")
dog.walking()
cat.walking()
cat.meowing()
dog.bark()
|
# Create new Dictionary
person = {
"first_name": "Nick Lyga",
"age": 21
}
print(person)
# Update key/Values
person["first_name"] ="Nick"
person["last_name"] = "Lyga"
print(person)
# Loop over dictionary (items())
for key,value in person.items():
print("{}: {}".format(key, value))
# Methods, get(), values(), keys()
print(person.keys())
person.update({
"first_name": "bob",
"age": 5
})
print(person)
# delete del
del person["first_name"]
print(person)
# List of Dictionaires
people = []
person = {
"name": "Nick",
"age": 21
}
people.append(person)
print(people)
person2 = {
"name": "billy",
"age": 10
}
people.append(person2)
print(people)
print(people[1]["name"])
|
age = input("Please enter your age")
new_age = age + 1
print(new_age) |
"""
SEE https://matplotlib.org/users/pyplot_tutorial.html
"""
import requests
import matplotlib.pyplot as plt
from datetime import datetime
# simple plot
response = requests.get("https://api.iextrading.com/1.0/stock/aapl/batch?types=quote,news,chart&range=1m&last=10")
jsondata = response.json()
dates = []
close_values = []
for data in jsondata["chart"]:
# Need to cover to datetime object see strptime docs
dates.append(datetime.strptime(data["date"], "%Y-%m-%d"))
close_values.append(data["close"])
# Plot x vs y
plt.plot(dates, close_values)
plt.ylabel('Close Price')
plt.xlabel('Date')
plt.title("Apple Stock")
plt.show() |
import numpy as np
import pandas as pd
# Importing the datasets
dataset = pd.read_csv("E:\machine learning project\customer_churn_prediction\dataset\Churn_Modelling.csv")
# Since RowNumber,CustomerId And Surname doesn't provide much information on predicting the customer churning behaviour in a bank
# So, we remove those columns in our dataset
X = dataset.iloc[:,3:13]
y = dataset.iloc[:,13]
# By observing the feature values ,we know that country and gender are categorical values in the dataset and
# while building our machine learning models the categorical varaibale and values are not allowed. So we need to encode those categorical data
# Encoding Categorical Data
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
label_X_1 = LabelEncoder()
X['Geography'] = label_X_1.fit_transform(X['Geography'])
label_X_2 = LabelEncoder()
X['Gender'] = label_X_2.fit_transform(X['Gender'])
# 0 stans for France , 2 stands for Spain and 1 stands for germany
# 0 stands for Female and 1 stands for Male
# Since we are encoding three different countries France , Spain and germany as 0 , 2 and 1 . However there are not any relationship between these countries
# but encoding them like this shows that Spain is greater than germany and France mathematically. So for this purpose we need to perform one hot encoding.
onehotencoder = OneHotEncoder()
ohe = onehotencoder.fit_transform(X.Geography.values.reshape(-1,1)).toarray()
# 0 stans for France , 2 stands for Spain and 1 stands for germany
# 0 stands for Female and 1 stands for Male
encoded_df = pd.DataFrame(ohe,columns=['France','Germany','Spain'])
X = pd.concat([encoded_df,X],axis=1)
# Removing one dummy feature / variable / columns.
# Dropping Geography columns and one dummy variable columns i.e. France
#
preprocessed_dataframe = X.drop(['France','Geography'],axis=1)
trainable_data = preprocessed_dataframe.iloc[:,:].values
trainable_labels = dataset.iloc[:,13].values
# Splitting the dataset into Training set and Test set
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(trainable_data,trainable_labels,test_size=0.2,random_state=0)
#Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.fit_transform(X_test)
# Now Data preprocessing step is finished now we must focus on building the architecture of ANN
#Importing the Keras Libraries and Packages
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Activation
import tensorflow as tf
rms_model = Sequential()
rms_model.add(Dense(units=16,kernel_initializer='uniform',activation='relu',input_dim=11))
rms_model.add(Dense(units = 16,kernel_initializer='uniform',activation='relu'))
rms_model.add(Dense(units=1,kernel_initializer='uniform',activation='sigmoid'))
rms_model.compile(optimizer='rmsprop',loss='binary_crossentropy',metrics=['accuracy'])
rms_model.fit(x=X_train,y=y_train,batch_size=25,epochs=200,validation_data=(X_test,y_test))
# From all the computations we can say that rms prop optimizer perform better than adam optimizer. So we the final model has 16 hidden layers with batch
# size of 25 and optimizer equals adam and the epochs is equal to 200 and the average validation and testing accuracy is 86%
# Saving our model and it's architecture
# Since rms prop is performing well so we serailize rms_prop model to use it further for deployment.
import json
# serialize model to JSON
model_json = rms_model.to_json()
with open("customer_churn_prediction_model.json", "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
rms_model.save_weights("customer_churn_prediction_model.h5")
print("Saved model to disk")
|
# coding: utf-8
# In[12]:
#Chunking is use to extract a section or part of a sentence as per our own defined set of grammar.
#So as to make some sense out of the sentence
import re
import nltk
from nltk.tokenize import word_tokenize,sent_tokenize
sample='People who own pets recommend the same to everyone. Pets are one of sweetest creation of nature.'
sentences=sent_tokenize(sample)
data=[]
for sentence in sentences:
data=data+nltk.pos_tag(word_tokenize(sentence))
# I defined my grammar here on the basis of which i want to create the chunks
grammar="Chunk:{<NN.?><WP><VB.?>}"
#Then i passed it to the RegularExpressionParser to apply this parsing criteria
parser=nltk.RegexpParser(grammar)
# Finally parsed my list naming data which contains POS tags for each word
tree=parser.parse(data)
# To get a GUI view i used draw method to plot it in form of tree
tree.draw()
|
# Determine whether given string is palindrome or not
# O(n^2) time | O(n) space (Becoz of string memory allocation(static allocation))
def isPalindrome(string):
reverse = ""
for i in reversed(range(len(string))):
reverse += string[i]
return string == reverse
# O(n) time | O(n) space (Becoz of list memory allocation(dynamic allocation))
def isPalindrome2(string):
reverseChars = []
for i in reversed(range(len(string))):
reverseChars.append(string[i])
return string == "".join(reverseChars)
# O(n) time | O(n) space
def isPalindromeRecursive(string, i=0):
j = len(string)-1-i
return True if i >= j else string[i] == string[j] and isPalindromeRecursive(string, i+1)
# O(n) time | O(n) space
def isPalindromeRecursive2(string, i=0):
j = len(string)-1-i
if i >= j:
return True
elif string[i] != string[j]:
return False
else:
return isPalindromeRecursive2(string, i+1)
# O(n) time | O(1) space
def isPalindromeOptim(string):
leftIdx = 0
rightIdx = len(string)-1
while leftIdx < rightIdx:
if string[leftIdx] != string[rightIdx]:
return False
leftIdx += 1
rightIdx -= 1
return True
print(isPalindromeOptim("abcdcba"))
|
import cv2
#read image
img_grey = cv2.imread('numbers\\two.jpg', cv2.IMREAD_GRAYSCALE)
# define a threshold, 128 is the middle of black and white in grey scale
thresh = 128
# threshold the image
img_binary = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY)[1]
print(img_binary)
#save image
|
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("text", help="Inputing text",type=str)
args = parser.parse_args()
print("The given string is:", args.text)
print("All lowercase: ", args.text.lower())
print("All uppercase: ", args.text.upper())
|
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("text", help="Text 7 or more characters long and has an odd number of characters", type=str)
args = parser.parse_args()
mid_pos = int((len(args.text)-1)/2)
mid_chars = args.text[mid_pos-1:mid_pos+2]
new_string = args.text[0:mid_pos-1] + mid_chars.upper() + args.text[mid_pos+2:]
print("The old string: ", args.text)
print("Middle 3 characters: ", mid_chars)
print("The new string: ", new_string)
|
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("val", type=int)
args = parser.parse_args()
value = args.val
set3 = {1, 2, 3, 4, 5, 6, 7}
if (value > min(set3)) and (value < max(set3)):
print("Yes it is between %d and %d" % (min(set3), max(set3)))
else:
print("Unfortunately it is not between %d and %d" % (min(set3), max(set3)))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import randint
from random import randrange
import math
import sys
sys.setrecursionlimit(1000000)
def fact_tail(n, a):
if (n == 0):
return a
return fact_tail(n - 1, n * a)
def tail_factorial(n):
return fact_tail(n, 1)
def big_int(size=None):
"""
Generador de números aleatorios de un tamaño fijo recibido como parámetro, si el parámetro es
menor que 100 o None, entonces la función no le hace caso y genera uno de tamaño arbitrario,
máximo es de 150 dígitos.
:return: Un número del tamaño descrito.
"""
aux = ""
if not size or size < 100:
size = randint(100,150)
for i in range(size):
aux += str(randint(0,9))
return int(aux)
def check(a,s,d,n):
x = pow(a,d,n)
if x == 1:
return True
for i in range(s - 1):
if x == 1:
return True
for i in range(s - 1):
if x == (n - 1):
return True
x = pow(x,2,n)
return x == (n - 1)
def miller_rabin(n):
"""
Implementación del test de primalidad de Miller-Rabin.
:param n: El número a determinar su primalidad.
:return: True si n es primo, False en otro caso.
"""
k = 512
r = n - 1
s = 0
a = 0
while (r % 2 == 0):
r = r >> 1
s += 1
for i in range(k):
if (n - 2) > 2:
a = randint(2,n - 2)
else:
a = randint(n - 2, 2)
y = pow(a,r,n)
if y != 1 and y != (n - 1):
j = 1
while j <= (s - 1) and y != (n - 1):
y = pow(y,2,n)
if y == 1:
return False
j += 1
if y != (n - 1):
return False
return True
def wilson(n):
"""
Implementaión del test de primalidad de Wilson, basado en el teorema de Wilson,
(p-1)! ≡ -1 mod p
:param n: El número a determinar su primalidad.
:return: True si n es primo, False en otro caso.
"""
r = tail_factorial(n - 1) + 1
v = r % n
if (v == 0):
return True
else:
return False
def generate_prime(size=None):
"""
Genera un primo de al menos $size dígitos, si no se especifica,
este tiene que asegurar que al menos tiene 100 dígitos.
:param size: El tamaño del primo a generar.
:return: Un número que se asegura que es primo.
"""
if not size:
candidato = big_int(100)
else:
candidato = big_int(size)
while not miller_rabin(candidato):
if not size:
candidato = big_int(100)
else:
candidato = big_int(size)
return candidato
if __name__ == "__main__":
print(generate_prime())
|
import operator
from collections import Counter
#------------------------------------------------------------------
#
# Bayes Optimal Classifier
#
# In this quiz we will compute the optimal label for a second missing word in a row
# based on the possible words that could be in the first blank
#
# Finish the procedurce, LaterWords(), below
#
# You may want to import your code from the previous programming exercise!
#
sample_memo = '''
Milt, we're gonna need to go ahead and move you downstairs into storage B. We have some new people coming in, and we need all the space we can get. So if you could just go ahead and pack up your stuff and move it down there, that would be terrific, OK?
Oh, and remember: next Friday... is Hawaiian shirt day. So, you know, if you want to, go ahead and wear a Hawaiian shirt and jeans.
Oh, oh, and I almost forgot. Ahh, I'm also gonna need you to go ahead and come in on Sunday, too...
Hello Peter, whats happening? Ummm, I'm gonna need you to go ahead and come in tomorrow. So if you could be here around 9 that would be great, mmmk... oh oh! and I almost forgot ahh, I'm also gonna need you to go ahead and come in on Sunday too, kay. We ahh lost some people this week and ah, we sorta need to play catch up.
'''
corrupted_memo = '''
Yeah, I'm gonna --- you to go ahead --- --- complain about this. Oh, and if you could --- --- and sit at the kids' table, that'd be ---
'''
data_list = sample_memo.strip().split()
words_to_guess = ["ahead","could"]
def NextWordProbability(sampletext,word):
words = sample_memo.split() # tokenize
word_freq = [words[i+1] for i in range(len(words)) if words[i] == word and i < len(words)]
result = Counter(word_freq)
return result
def LaterWords(sample, word, distance):
'''@param sample: a sample of text to draw from
@param word: a word occuring before a corrupted sequence
@param distance: how many words later to estimate (i.e. 1 for the next word, 2 for the word after that)
@returns: a single word which is the most likely possibility
'''
# TODO: Given a word, collect the relative probabilities of possible following words
# from @sample. You may want to import your code from the maximum likelihood exercise.
word_count = len(data_list)
word_frequency = NextWordProbability(sample, word)
probabilities = [value / float(word_count) for value in word_frequency.values()]
p_w1_w = dict(zip(word_frequency.keys(), probabilities))
sorted_p = sorted(p_w1_w.items(), key=operator.itemgetter(1), reverse=True)
d1_wd = zip(*sorted_p)[0][0]
p_d1_wd = p_w1_w[d1_wd]
# TODO: Repeat the above process--for each distance beyond 1, evaluate the words that
# might come after each word, and combine them weighting by relative probability
# into an estimate of what might appear next.
for i in xrange(1, distance):
word_frequency2 = NextWordProbability(sample, d1_wd)
probabilities2 = [v / float(word_count) for v in word_frequency2.values()]
p_w2_w1 = dict(zip(word_frequency2.keys(), probabilities2))
p_w2_w1andw = dict(zip(p_w2_w1.keys(), [p_d1_wd * p_w2_w1[w] for w in p_w2_w1.keys()]))
sorted_p2 = sorted(p_w2_w1andw.items(), key=operator.itemgetter(1), reverse=True)
d1_wd = zip(*sorted_p2)[0][0]
print(d1_wd)
p_d1_wd = p_w2_w1andw[d1_wd]
return d1_wd
if __name__ == '__main__':
print LaterWords(sample_memo,'gonna', 3)
|
def cross3vecs( v1, v2 ):
'''
Given two vectors, v1, v2, stored in lists,
return the normalized cross-product or die if 0.
'''
from math import sqrt
###############################################
# HOMEWORK: Finish the code for C1 and C2
###############################################
c0 = v1[1]*v2[2] - v2[1]*v1[2]
c1 = v1[2]*v2[0] - v1[0]*v2[2]
c2 = v1[0]*v2[1] - v1[1]*v2[0]
csq = c0**2 + c1**2 + c2**2
if not csq > 0:
print "ERROR: cross product is Null vector."
exit(1)
zz = 1.0 / sqrt( csq )
c = []
c.append( zz*c0 )
c.append( zz*c1 )
c.append( zz*c2 )
return c
def bondvec( a1, a2 ):
b = []
b.append( a2[0] - a1[0] )
b.append( a2[1] - a1[1] )
b.append( a2[2] - a1[2] )
return b
# not used in this program...
def distance3( x, y ):
from math import sqrt
d2 = ( y[0] - x[0] )**2 + ( y[1] - x[1] )**2 + ( y[2] - x[2] )**2
if d2 > 0:
d = sqrt(d2)
else:
d = False
return d
#ATOM 32 CB VAL A 6 54.977 -70.796 -8.926 1.00 17.11 C
#ATOM 33 CG1 VAL A 6 55.702 -71.127 -10.195 1.00 16.13 C
#01234567890123456789012345678901234567890123456789012345678901234567890123456789
# 1 2 3 4 5 6 7
# atnam13:16 x30:38 y38:46 z46:54
def get_coords_from_PDB_line( line ):
x = float( line[30:38] )
y = float( line[38:46] )
z = float( line[46:54] )
return (x, y, z)
#
# read in file and determine normal vector to peptide plane
#
fh = open("tetrapeptide.pdb","r")
lines = fh.readlines()
fh.close()
N = []; CA = []; C = []; O = []
for l in lines:
if l[0:6] == 'ATOM ':
print l[13:16], "**", l
if l[13:16].strip() == "N" :
N.append( get_coords_from_PDB_line( l ) )
elif l[13:16].strip() == "CA" :
CA.append( get_coords_from_PDB_line( l ) )
elif l[13:16].strip() == "C" :
C.append( get_coords_from_PDB_line( l ) )
elif l[13:16].strip() == "O" :
O.append( get_coords_from_PDB_line( l ) )
atmnolast = int( l[6:11] )
debug = True
if debug:
print "N ", N
print "CA", CA
print "C ", C
print "O ", O
print "atmnolast:", atmnolast
# We will now calculate the normals and write out a new file
# including all of the original file with the extra fake atoms defining
# the peptide normal vectors appended...
debug = False
if debug:
for i in range(0,3):
print i, C[i], O[i], N[i+1], CA[i+1]
atmno = atmnolast + 1
resnum = 9000
newpdb = open("tetrapepnew.pdb","w")
# re-write all of the previous lines into a new PDB file...
for l in lines:
print >> newpdb, l.strip()
#
# Add fake HETATMS to new pdb representing midpoint of CN bond and
# endpoint of normal vector filere-write all of the previous lines
# into a new PDB file...
#
# Also, save the atom pairs for drawing normal vectors for second Pymol
# rendering demo...
#
normal_pts = []
for i in range(0,3):
# Calculate two approximate normals for each peptide bond...
# n1_i = C_i--O_i cross C_i--N_i+i (will be up )
# n2_i = C_i--N_i+i cross N_i+i--CA_i+1 (will be down)
n1 = cross3vecs( bondvec( C[i], O[i] ), bondvec( C[i], N[i+1] ) )
n2 = cross3vecs( bondvec( N[i+1], CA[i+1]), bondvec( C[i], N[i+1] ) )
#print "n1:", n1
#print "n2:", n2
# for drawing normal, chose midpoint of peptide bond as basepoint...
origx = ( C[i][0] + N[i+1][0] ) / 2.
origy = ( C[i][1] + N[i+1][1] ) / 2.
origz = ( C[i][2] + N[i+1][2] ) / 2.
s = "HETATM%5d X1 UNK %4d %8.3f%8.3f%8.3f 1.00 50.00 X" %(atmno,resnum,origx,origy,origz)
print >> newpdb, s
atmno += 1
scale = 2.0
x = scale*(n1[0] + n2[0]) / 2. + origx
y = scale*(n1[1] + n2[1]) / 2. + origy
z = scale*(n1[2] + n2[2]) / 2. + origz
s = "HETATM%5d X2 UNK %4d %8.3f%8.3f%8.3f 1.00 50.00 X" %(atmno,resnum,x,y,z)
print >> newpdb, s
atmno += 1
resnum += 1
normal_pts.append( ( origx, origy, origz, x,y,z ) )
newpdb.close()
#
# Write out a small Python program to be run within a PyMol .pml file to
# render the normal vectors as cylinders.
#
fhpy = open("pymol_cylinders.py", "w" )
part1 = '''
# (Based on a program found at: http://www.rubor.de/bioinf/tips_python.html)
from pymol.cgo import *
from pymol import cmd
#
# CYLINDER, 0., 0., 0., 10., 0., 0., 0.2, 1.0, 1.0, 1.0, 1.0, 0.0, 0.,
# -------- ---------- ---- ------------- -----------
# xyz 1 xyz 2 rad rgb 1 rgb2
obj = [
'''
print >>fhpy, part1,
color1 = ( 1.0, 0.5, 0.25 )
color2 = ( 1.0, 0.5, 0.25 )
cylrad = 0.1 # Angstroms
first = True
for pairs in normal_pts:
if not first:
print >>fhpy, ','
else:
first = False
coords_string = " CYLINDER, %8.3f, %8.3f, %8.3f, %8.3f, %8.3f, %8.3f," %pairs
print coords_string
cylrad_string = " %5.2f," %cylrad
colors_string = " %5.3f, %5.3f, %5.3f, " %color1 + " %5.3f, %5.3f, %5.3f" %color2
print >>fhpy, coords_string + cylrad_string + colors_string,
part2 = '''
]
# load it into PyMOL
cmd.load_cgo(obj,'axes')
'''
print >>fhpy, part2
fhpy.close()
|
from copy import deepcopy
STEP_X = [0, 0, 1, 1, 1, -1, -1, -1]
STEP_Y = [-1, 1, 0, -1, 1, 0, -1, 1]
STEPS = list(zip(STEP_X, STEP_Y))
FLOOR = '.'
EMPTY = 'L'
OCCUPIED = '#'
NUM_ROWS = 0
NUM_COLS = 0
def count_occupied(seats):
count = 0
for row in seats:
for seat in row:
if seat == OCCUPIED:
count += 1
return count
def print_seats(seats):
for row in seats:
print("".join(row))
print()
input()
def _advance(current_state, threshold, see_far=False):
next_state = [[None] * NUM_COLS for _ in range(NUM_ROWS)]
move = 0
for i in range(NUM_ROWS):
for j in range(NUM_COLS):
if current_state[i][j] == FLOOR:
next_state[i][j] = FLOOR
continue
num_neighbors = 0
visible = 0
for dx, dy in STEPS:
x, y = i + dx, j + dy
if (0 <= x < NUM_ROWS) and (0 <= y < NUM_COLS) and current_state[x][y] == OCCUPIED:
num_neighbors += 1
while see_far and (0 <= x < NUM_ROWS) and (0 <= y < NUM_COLS):
if current_state[x][y] == OCCUPIED:
visible += 1
break
elif current_state[x][y] == EMPTY:
break
x, y = x + dx, y + dy
if current_state[i][j] == EMPTY and visible == 0:
next_state[i][j] = OCCUPIED
move += 1
elif current_state[i][j] == OCCUPIED and visible >= threshold:
next_state[i][j] = EMPTY
move += 1
else:
next_state[i][j] = current_state[i][j]
return next_state, move
def solve(init_state, threshold, see_far=False):
current_state = deepcopy(init_state)
while True:
next_state, move = _advance(current_state, threshold, see_far)
if move == 0:
break
current_state = next_state
return current_state
if __name__ == '__main__':
fin = open("input.txt")
init_state = []
for line in fin:
init_state.append([ch for ch in line.strip()])
fin.close()
NUM_ROWS = len(init_state)
NUM_COLS = len(init_state[0])
print(count_occupied(solve(init_state, 4)))
print(count_occupied(solve(init_state, 5, True))) |
#!/usr/bin/python2
import sys
import argparse
def main(args):
#
print "\n--- main() ---\n"
print "args: : ", args
print "args.foo : ", args.foo
print "args.foo1 : ", args.foo1
print "args.foo2 : ", args.foo2
print "args.name : ", args.name
print "args.ints : ", args.ints
print "args.input : ", args.input
#
if args.input == None:
sys.exit(0)
#
#--------------------------------------------
# read from a file line by line (incl. '\n')
#--------------------------------------------
line = args.input.readline()
while line:
print line.strip()
line = args.input.readline()
#
# args.input.close
#
print "read done..."
args.input.seek(0)
#
#--------------------------------------------
# read from a file everything (incl. '\n')
#--------------------------------------------
lines = args.input.readlines()
args.input.close()
#
for line in lines:
print line,
print "read done..."
#-----------------------------------------------------
# MAIN Procedure
#-----------------------------------------------------
if __name__ == "__main__":
#
#
parser = \
argparse.ArgumentParser(
description = '= Process some integers =', # help: header
epilog = '(end of help)', # help: footer
add_help = True # help: option -h,--help
)
#
#
parser.add_argument(
'name', # Positional argument 1
metavar = 'S', # for help message
nargs = '+',
help = 'an integer for the accumulator'
)
#
parser.add_argument(
'ints', # Positional argument 2
metavar = 'N', # for help message
type = float, # default: string
nargs = 1,
help = 'an integer for the accumulator'
)
#
parser.add_argument(
'--sum', '-sum', # Optional argument 1
dest = 'accumulate',
action = 'store_const',
default = max,
const = sum,
help = 'sum the integers (default: find the max)'
)
#
parser.add_argument(
'--foo', '-foo', # Optional (flag)
action = 'store_true',
help = 'just testing foo'
)
#
parser.add_argument(
'--foo1', '-foo1', # Optional (1 arg)
action = 'store_const',
default = 0, # 0: if no -foo
const = 1, # 1: if -foo there
help = 'just testing foo1'
)
#
parser.add_argument(
'--foo2', '-foo2', # Optional (two args)
metavar = 'val',
nargs = 2,
default = [0, 0],
help = 'just testing foo2'
)
#
parser.add_argument(
'--input', '-input',
metavar = 'filename',
# type = argparse.FileType('wb', 0)
type = argparse.FileType('r', 0)
)
#
args = parser.parse_args()
print args.accumulate(args.ints)
main(args)
print "\nEND OF SCRIPT\n"
#-----------------------------------------------------
# edit ~/.vimrc , add "set modeline"
# then, do not remove:
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# ###: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#-----------------------------------------------------
|
import unittest
from main import pig_latin_converter
class Test(unittest.TestCase):
def test_input_as_string(self):
with self.assertRaises(TypeError) as context:
pig_latin_converter(1)
pig_latin_converter(False)
self.assertEqual(
'Argument should be a string',
context.exception.message,
'String inputs allowed only'
)
def test_correct_output_if_vowel_at_first_pos(self):
result1 = pig_latin_converter('andela')
result2 = pig_latin_converter('ipsum')
self.assertEqual(result1, 'andelaway')
self.assertEqual(result2, 'ipsumway')
def test_correct_output_if_first_pos_not_vowel(self):
result1 = pig_latin_converter('dryer')
result2 = pig_latin_converter('chemistry')
result3 = pig_latin_converter('verge')
self.assertEqual(result1, 'erdryay')
self.assertEqual(result2, 'emistrychay')
self.assertEqual(result3, 'ergevay')
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
The Porter's Algorithm
is the most common English stemmer
This code is a simple implementaion of the algorithm.
The main idea is to remove the affixes:
cats -> cat
walking -> walk
relational -> relate
*activate -> activ
*Some words are stemmed to be similar the original word such as ponies -> poni,
the letter changes are ignored, but the stems are still understandable
3 main steps:
Step 1a:
-sses -> -ss
-ies -> -i
-ss -> -ss
-s -> -
Step 1b:
(*v*)ing -> (*v*)
(*v*)ed -> (*v*)
Step 2: (for long stems)
-ational -> -ate
-izer -> -ize
-ator -> -ate
Step 3: (for long stems)
-al -> -
-able -> -
-ate -> -
*v* means verb stem and the stem must contain at least one vowel or 'y'
This steps are based on Standford NLP Course:
https://www.youtube.com/watch?v=oWsMIW-5xUc&list=PLLssT5z_DsK8HbD2sPcUIDfQ7zmBarMYv
'''
def contains_vowel(word):
vowels='aeiouy'
for v in vowels:
if v in word:
return True
return False
def porter_stemmer(word, is_verb=False):
noun_suffixes = [['sses', 'ss'], ['ies', 'i'], ['ss', 'ss'], ['s', ''], #STEP 1
['ational', 'ate'], ['izer', 'ize'], ['ator', 'ate'], #STEP 2
['al', ''], ['able', ''], ['ate', '']] #STEP 3
verb_suffixes = [['ing', ''], ['ed', '']]
if is_verb:
for suffix, transform in verb_suffixes:
length = len(suffix)
if word[-length:] == suffix and contains_vowel(word[:-length]):
return word[:-length] + transform
return word
for suffix, transform in noun_suffixes:
length = len(suffix)
if word[-length:] == suffix and contains_vowel(word[-length:]):
return word[:-length] + transform
return word
|
#!/usr/bin/env python3
class Contact(object):
def __init__(self, name):
self.name = name
self.phone_num = ""
def __str__(self):
citation = "name: {} \nphone number: {}"
return citation.format(self.name, self.phone_num)
# def __str__(self):
# return "{}, {}".format(self.name, self.phone_num)
def append_to_name(self, string_to_append):
self.name = self.name + string_to_append
c1 = Contact("Emil")
c2 = Contact("Benno")
c3 = Contact("Kalle")
c1.phone_num = "0701-111111"
c2.phone_num = "0702-222222"
c3.phone_num = "0700-123456"
c1.append_to_name(" Säll")
c2.append_to_name(" Nossbring")
c3.append_to_name(" Ytterberg")
contact_list = [c1, c2, c3]
for element in contact_list:
print(element)
|
#!/usr/bin/env python3
import random
import math
import sys
def lunchvärmare(eaters):
heaters = []
antal_matlådor = len(eaters)
times = math.ceil(antal_matlådor/2)
while len(heaters) < times:
person = random.choice(eaters)
if person in heaters:
pass
else:
heaters.append(person)
for person in heaters:
print("Dagens värmare är: {}".format(person))
lunchvärmare(sys.argv[1:])
|
#函数
#'def'为定义函数的关键字
def add(x,y):
return x + y
print(add(1,2))
#多返回函数
def division(x,y):
return x/y ,x%y
w,v = division(5,2) #函数的返回值是以'tuple'的形式返回的,在赋值时会分别将值赋值给变量
print(w,v)
u = division(7,2) #当把多返回函数的返回值赋值给一个容器时,该容器为'tuple'
print(u)
#可变参数函数
def adds(*nNum): #可变参数只需要填写一个参数,但需要在参数前添加'*'以表示可变参数
print(nNum) #可变参数以'tuple'的格式传递,为不可变参数
nSum = 0
for x in nNum:
nSum = nSum + x
return nSum
print(adds(1,2,3))
print(adds(*(1,3))) #当直接传递'list','tuple'为多参数时,需要在容器前添加'*'以表示可变参数
#关键字参数
def info(**role): #关键字参数需要添加'**'以表示当前参数为关键字参数
print(role)
info(**{'name':'锤子','age':23,'isLive':True}) #关键字参数在以'dist'作为参数直接传递的时候需要添加'**'以表示关键字参数
#命名关键字参数
def all_info(name,age,*,islive,address):
print(name,age,islive,address)
all_info('锤子',23,islive=True,address='Beijing')
def all_info_dou(name,age,*birthday,islive,address):
print(name,age,birthday,islive,address)
all_info_dou('锤子',23,1994,8,25,islive = True,address = 'Beijing') |
#'dist' 字典
myDist = {'name':'锤子','age':23,'sex':'man'} #'dist'采用键值对的表现形式'key - value'
print(myDist['name'])
print(myDist['age'])
print(myDist['sex'])
#'dist'相比'list'会占用较多内存,但速度会很快
#'dist'的查询方式类似字典,会先通过'key'计算出'value'的内存地址
#'dist'中的'key'为不可变值,所以不能使用'list'这种可变列表作为'key'
myDist['age'] = 25 #'dist'的值可以通过'key'赋值改变
print(myDist['age'])
#myDist['class'] #'list'中不能使用不存在的'key'
if 'class' in myDist: #使用'in'可以检测出'dist'中是否存在此'key'
print('存在')
else:
print('不存在')
print(myDist.get('class',-1)) #'get'检测'dist'中是否存在此元素,('key',err),'err'可忽略
myDist.pop('age') #删除指定'key'的元素
print(myDist)
#'dist'为非顺序容器 |
import datetime
from decimal import Decimal, InvalidOperation
def format_date(date_str):
'''
format date
:param date_str: date in the format ddmmyyyy
:return: datetime
'''
if not isinstance(date_str, str):
raise ValueError
try:
result = datetime.datetime.strptime(date_str, '%d%m%Y')
except ValueError:
raise ValueError
return result
def format_currency(value_str):
'''
format currency value
:param value: value in format 0000000000 to two decimal places
:return: Decimal
'''
if not isinstance(value_str, str):
raise ValueError
tmp_value = value_str.lstrip('0')
new_value = tmp_value[0:-2] + '.' + tmp_value[-2:]
try:
result = Decimal(new_value)
except InvalidOperation:
raise InvalidOperation
return result
|
import unittest
from pl_classes import ParkingLot, Vehicle
class TestParkingLotMethods(unittest.TestCase):
'''Test ParkingLot and Vehicle classes'''
def test_create_parking_lot_with_expected_number_of_slots(self):
'''Ensure parking_lot_size dict is created with proper keys when ParkingLot obejct created'''
parking_lot_size = 6
parking_lot = ParkingLot(parking_lot_size)
self.assertEqual(len(parking_lot.parking_lot_spaces), parking_lot_size)
self.assertIsNone(parking_lot.parking_lot_spaces[1])
self.assertIsNone(parking_lot.parking_lot_spaces[parking_lot_size])
self.assertRaises(KeyError, lambda: parking_lot.parking_lot_spaces[0])
self.assertRaises(KeyError, lambda: parking_lot.parking_lot_spaces[parking_lot_size+1])
def test_park_returns_slot_key_if_slot_is_empty_and_none_if_all_slots_taken(self):
'''Ensure park function fills slots in proper order and None is slots are full'''
parking_lot_size = 2
parking_lot = ParkingLot(parking_lot_size)
park_return_variable = parking_lot.park("ka-01-hh-1234" , "white")
self.assertEqual(park_return_variable, 1)
park_return_variable = parking_lot.park("ka-01-hh-1234" , "white")
self.assertEqual(park_return_variable, 2)
park_return_variable = parking_lot.park("ka-01-hh-1234" , "white")
self.assertIsNone(park_return_variable)
def test_park_creates_vehicle_with_correct_variable_formatting(self):
'''Ensures registration numbers are always uppercase and colors are always capialized'''
parking_lot_size = 1
parking_lot = ParkingLot(parking_lot_size)
parking_lot.park("ka-01-hh-1234", "white")
self.assertEqual(parking_lot.parking_lot_spaces[1].registration_number, "KA-01-HH-1234")
self.assertEqual(parking_lot.parking_lot_spaces[1].color, "White")
def test_leave_returns_true_if_slot_exists_and_false_otherwise(self):
'''Ensures 'leave' only works if called on an actual parking slot'''
parking_lot_size = 2
parking_lot = ParkingLot(parking_lot_size)
self.assertTrue(parking_lot.leave(1))
self.assertTrue(parking_lot.leave(2))
self.assertFalse(parking_lot.leave(0))
self.assertFalse(parking_lot.leave(3))
def test_leave_converts_strings_to_integer(self):
'''Ensures 'leave' will convert properly formatted string to an integer'''
parking_lot_size = 2
parking_lot = ParkingLot(parking_lot_size)
self.assertTrue(parking_lot.leave("1"))
def test_find_matches_returns_list_of_correct_vehicle_attributes_or_parking_slots(self):
'''Ensures vehicle attribute searches return the correct information'''
parking_lot_size = 6
parking_lot = ParkingLot(parking_lot_size)
for x in range(6):
parking_lot.park("AK-01-HH-1234", "White")
self.assertEqual(parking_lot.find_matches("AK-01-HH-1234","registration_number","slot"),[1,2,3,4,5,6])
self.assertEqual(parking_lot.find_matches("White","color","slot"),[1,2,3,4,5,6])
self.assertEqual(parking_lot.find_matches("whit","color","slot"),[])
self.assertEqual(parking_lot.find_matches("White","color","registration_number"),["AK-01-HH-1234"]*6)
if __name__ == '__main__':
unittest.main() |
from sys import stdin
def main():
input = stdin.readline
N = int(input())
ST_list = []
for _ in range(N):
S, T = input().split()
T = int(T)
ST_list.append([T, S])
ST_list.sort(reverse = True)
print(ST_list[1][1])
if __name__ == "__main__":
main() |
def main():
S = input()
for i in range(len(S)):
if i % 2 == 0 and not S[i].islower():
print("No")
exit()
elif i % 2 != 0 and S[i].islower():
print("No")
exit()
print("Yes")
if __name__ == "__main__":
main() |
import math
import sys
import re
class ParseError(Exception): pass #To indicate a parsing error
class EmptyError(Exception): pass #To indicate empty data passed to the parser
class NoResultError(Exception): pass #To indicate that a method did not feel like producing a result, used in parse_psic()
def parse_sequence(d_in, d_fasta):
"""
pp returns two sequence files: query.in and query.fasta. No idea why.
Here we check that both are the same and return the sequence.
"""
seq_in = ''
seq_fasta = ''
for line in d_in.split('\n')[1:]:
if not line: continue
seq_in += line
for line in d_fasta.split('\n')[1:]:
if not line: continue
seq_fasta += ''.join(line.split()) #Get rid of those strange whitespaces within the sequence!
if seq_in != seq_fasta:
sys.exit("Error!!!ProNA2019 can not be done for protein %s.\nProtein sequence of *in and * fasta are not identical.\npp seems to work with different sequences.\n" % d_fasta.split('\n')[0][1:])
return {'seq':seq_in},d_fasta.split('\n')[0][1:]
def parse_sequence(d_in, d_fasta):
"""
pp returns two sequence files: query.in and query.fasta. No idea why.
Here we check that both are the same and return the sequence.
"""
seq_in = ''
seq_fasta = ''
for line in d_in.split('\n')[1:]:
if not line: continue
seq_in += line
for line in d_fasta.split('\n')[1:]:
if not line: continue
seq_fasta += ''.join(line.split()) #Get rid of those strange whitespaces within the sequence!
if seq_in != seq_fasta:
raise ParseError('pp seems to work with different sequences.')
return {'seq':seq_in},d_fasta.split('\n')[0][1:]
def parse_blast_reorder(d_blast):
ori_order='ARNDCQEGHILKMFPSTWYV'
#ress
new_order='RKDEQNHSTYCWAILMFVPG'
#res
# new_order='AVLIPFWMGSTCYNQDEKRH'
if d_blast == '':
raise EmptyError('Empty pssm file!')
pssm_mat = []
perc_mat = []
inf_per_pos = []
rel_weight = []
pssm_seq = ''
#First turn pssm into a matrix we can handle
for line in d_blast.split('\n'):
tokens = line.split()
if len(tokens) == 40 and line.strip() != 'A R N D C Q E G H I L K M F P S T W Y V A R N D C Q E G H I L K M F P S T W Y V':
raise ParseError("It seems that we have an issue now. Blast produces columns with altering meanings!")
if len(tokens) != 44: continue
pssm_seq += tokens[1]
inf_per_pos.append( float(tokens[42]) ) #The second last column in the blast output
rel_weight.append( float(tokens[43]) ) #The very last column
#The first matrix i.e. pssm
pssm_mat_row = []
tmp={}
for ind in range(len(ori_order)):
tmp[ori_order[ind]]=tokens[2:22][ind]
for r in new_order:
pssm_mat_row.append(int(tmp[r]))
#The second one, i.e. the percentages
perc_mat_row = []
tmp={}
for ind in range(len(ori_order)):
tmp[ori_order[ind]]=tokens[22:42][ind]
for r in new_order:
perc_mat_row.append(int(tmp[r]))
#Check if we are really dealing with 20 values here!
if len(pssm_mat_row) != 20 or len(perc_mat_row) != 20:
raise ParseError("It seems that we have a situation now. The expected amount of columns is 20, found: %s!" % len(pssm_mat_row))
pssm_mat.append(pssm_mat_row)
perc_mat.append(perc_mat_row)
#Further consistency check...
if len(pssm_mat) != len(pssm_seq) != len(perc_mat) != len(inf_per_pos) != len(rel_weight):
raise ParseError("It seems that we have an issue now. Something went wrong during parsing the pssm matrix!")
return {'seq':pssm_seq, 'pssm':pssm_mat, 'perc':perc_mat, 'inf_per_pos':inf_per_pos, 'rel_weight':rel_weight}
def parse_consurf(consurf):
if consurf == '':
raise EmptyError('Empty consurf file!')
out1 = []
out2 = []
for line in consurf.split('\n'):
tokens = line.split('\t')
if len(tokens) < 6 or 'COLOR' in line: continue
out1.append( float(tokens[2]) )
out2.append( float(tokens[4].lstrip()[0]) )
#Consistency check
if len(out1) != len(out2):
raise ParseError("Something happened! consurf returns different column lengths!")
return {'consurf_score':out1, 'consurf_color':out2}
def parse_blast(d_blast):
"""
Note that we do not parse out the weighted observed percentages part.
Meaning of pssm columns:
A R N D C Q E G H I L K M F P S T W Y V
Returns a dictionary with keys as follows:
'seq': The sequence as blast sees it
'pssm': pssm matrix as a list of lists. Each sublist represents a row in the PSSM matrix.
'perc': perc matrix
'inf_per_pos': The second last column in the blast output
'rel_weight': The last column
"""
if d_blast == '':
raise EmptyError('Empty pssm file!')
pssm_mat = []
perc_mat = []
inf_per_pos = []
rel_weight = []
pssm_seq = ''
#First turn pssm into a matrix we can handle
for line in d_blast.split('\n'):
tokens = line.split()
if len(tokens) == 40 and line.strip() != 'A R N D C Q E G H I L K M F P S T W Y V A R N D C Q E G H I L K M F P S T W Y V':
raise ParseError("It seems that we have an issue now. Blast produces columns with altering meanings!")
if len(tokens) != 44: continue
pssm_seq += tokens[1]
inf_per_pos.append( float(tokens[42]) ) #The second last column in the blast output
rel_weight.append( float(tokens[43]) ) #The very last column
#The first matrix i.e. pssm
pssm_mat_row = []
for t in tokens[2:22]:
pssm_mat_row.append(int(t))
#The second one, i.e. the percentages
perc_mat_row = []
for t in tokens[22:42]:
perc_mat_row.append(int(t))
#Check if we are really dealing with 20 values here!
if len(pssm_mat_row) != 20 or len(perc_mat_row) != 20:
raise ParseError("It seems that we have a situation now. The expected amount of columns is 20, found: %s!" % len(pssm_mat_row))
pssm_mat.append(pssm_mat_row)
perc_mat.append(perc_mat_row)
#Further consistency check...
if len(pssm_mat) != len(pssm_seq) != len(perc_mat) != len(inf_per_pos) != len(rel_weight):
raise ParseError("It seems that we have an issue now. Something went wrong during parsing the pssm matrix!")
return {'seq':pssm_seq, 'pssm':pssm_mat, 'perc':perc_mat, 'inf_per_pos':inf_per_pos, 'rel_weight':rel_weight}
def parse_psic(d_psic):
"""
Unfortunately, psic returns no sequence.
Meaning of psic's columns:
A R N D C Q E G H I L K M F P S T W Y V NumSeq
This is exactly what could be found in the sublist of each residue.
Returns a dictionary with keys as follows:
'psic': psic matrix as a list of lists. Each sublist represents a row in the psic matrix.
'NumSeq': the very last column, denoting NumSeq i.e. number of aligned sequences at that pos
"""
if d_psic == '':
raise EmptyError('Empty psic file!')
elif d_psic.startswith('sequence too short'):
raise NoResultError('Sequence seems to be too short for psic. No psic output found.')
psic_mat = []
numseq = []
for line in d_psic.split('\n'):
if line.startswith('Pos') or line == '': continue
tokens = line.split()
if len(tokens) != 22:
raise ParseError('"It seems that we have a situation now. The expected amount of columns is 22, found: %s!" % len(tokens)')
psic_mat_row = [ float(t) for t in tokens[1:21] ]
numseq.append( int(tokens[21]) ) #The last column is an integer denoting the amount of aligned seqs at that pos.
psic_mat.append(psic_mat_row) #Now glue the current column to the matrix
#Check!
if len(psic_mat) != len(numseq):
raise ParseError("It seems that we have an issue now. Something went wrong during parsing the psic matrix!")
return {'psic':psic_mat, 'NumSeq':numseq}
def parse_disis(d_disis):
"""
Returns a dictionary with keys as follows:
'seq': The sequence as disis sees it
'prd_bin': binary prdct
'prd_raw': raw prdct
"""
if d_disis == '':
raise EmptyError('Empty disis file!')
disis_seq_binprd = [] #Sequence parsed out of the binary prediction part
disis_seq_rawprd = [] #...parsed out of the raw (numeric) predictions
disis_prd_bin = [] #Binary predictions
disis_prd_raw = [] #Raw numeric predictions
cnt = 0
for line in d_disis.split('\n'):
if line == '': continue
tokens = line.split()
if len(tokens) == 1: #We are in the upper part of disis' output, i.e. the binary predictions
if cnt % 2 == 0:
disis_seq_binprd.extend( list(line) )
else:
disis_prd_bin.extend( list(line.replace('P','+')) )
elif len(tokens) == 2: #Now we are in the lower part, i.e. the numeric outputs of disis
disis_seq_rawprd.append( tokens[0] )
disis_prd_raw.append( int(tokens[1]) )
cnt += 1
#Now do some consistency checks
if disis_seq_binprd != disis_seq_rawprd:
raise ParseError("It seems that we have an issue now. Disis returns different sequences in the upper and lower part!")
if len(disis_seq_binprd) != len(disis_prd_bin) != len(disis_prd_raw):
raise ParseError("It seems that we have an issue now. Parsed datastructures have different lengths!")
return {'seq':''.join(disis_seq_binprd), 'prd_bin':disis_prd_bin, 'prd_raw':disis_prd_raw}
def parse_isis(d_isis):
"""
Returns a dictionary with keys as follows:
'seq': The sequence as isis sees it
'prd_bin': binary prdct
'prd_raw': raw prdct
"""
if d_isis == '':
raise EmptyError('Empty isis file!')
isis_seq_binprd = [] #Sequence parsed out of the binary prediction part
isis_seq_rawprd = [] #...parsed out of the raw (numeric) predictions
isis_prd_bin = [] #Binary predictions
isis_prd_raw = [] #Raw numeric predictions
cnt = 0
for line in d_isis.split('\n'):
if line == '' or line.startswith('>'): continue
tokens = line.split()
if len(tokens) == 1: #We are in the upper part of disis' output, i.e. the binary predictions
if cnt % 2 == 0:
isis_seq_binprd.extend( list(line) )
else:
isis_prd_bin.extend( list(line.replace('P','+')) )
elif len(tokens) == 3: #Now we are in the lower part, i.e. the numeric outputs of disis
isis_seq_rawprd.append( tokens[1] )
isis_prd_raw.append( int(tokens[2]) )
cnt += 1
#Now do some consistency checks
if isis_seq_binprd != isis_seq_rawprd:
raise ParseError("It seems that we have an issue now. Isis returns different sequences in the upper and lower part!")
if len(isis_seq_binprd) != len(isis_prd_bin) != len(isis_prd_raw):
raise ParseError("It seems that we have an issue now. Parsed datastructures have different lengths!")
return {'seq':''.join(isis_seq_binprd), 'prd_bin':isis_prd_bin, 'prd_raw':isis_prd_raw}
def parse_md(d_md):
"""
Returns a dictionary with keys as follows:
'seq': sequence as MD sees it
'norsnet_raw': raw norsnet prdct
'norsnet_bin': binary norsnet prdct
'bval_raw': raw bval prdct
'bval_bin': binary bval prdct
'ucon_raw': raw ucon prdct
'ucon_bin': binary ucon prdct
'prd_raw': MD's raw prdct
'prd_ri': MD's reliability index
'prd_bin': MD's binary prdct
"""
if d_md == '':
raise EmptyError('Empty md file!')
md_seq = []
md_norsnet_raw = []
md_norsnet_bin = []
md_bval_raw = []
md_bval_bin = []
md_ucon_raw = []
md_ucon_bin = []
md_raw = []
md_ri = []
md_bin = []
for line in d_md.split('\n'):
if line.startswith('Number'): continue #The header
if line == '': break #We reached the end of the output block
tokens = line.split()
if len(tokens) != 11:
raise ParseError("It seems that we have an issue now. MD returned an unexpected number of columns!")
md_seq.append( tokens[1] )
md_norsnet_raw.append( float(tokens[2]) )
md_norsnet_bin.append( tokens[3].replace('D','+') )
md_bval_raw.append( float(tokens[4]) )
md_bval_bin.append( tokens[5].replace('D','+') )
md_ucon_raw.append( float(tokens[6]) )
md_ucon_bin.append( tokens[7].replace('D','+') )
md_raw.append( float(tokens[8]) )
md_ri.append( int(tokens[9]) )
md_bin.append( tokens[10].replace('D','+') )
#Check it!
if len(md_seq) != len(md_norsnet_raw) != len(md_norsnet_bin) != len(md_bval_raw) != len(md_bval_bin) != len(md_ucon_raw) != len(md_ucon_bin) != len(md_raw) != len(md_ri) != len(md_bin):
raise ParseError("It seems that we have an issue now. MD returned unequal column lengths!")
return {'seq':''.join(md_seq), 'norsnet_raw':md_norsnet_raw, 'norsnet_bin':md_norsnet_bin, 'bval_raw':md_bval_raw, 'bval_bin':md_bval_bin, 'ucon_raw':md_ucon_raw, 'ucon_bin':md_ucon_bin, 'prd_raw':md_raw, 'prd_ri':md_ri, 'prd_bin':md_bin}
def parse_profsecacc(d_prof):
"""
Returns a dictionary where keys have the same designation as the column names in prof's tabular output.
Values hold lists of per-residue predictions.
AA
OHEL
PHEL
RI_S
OACC
PACC
OREL
PREL
RI_A
pH
pE
pL
Obe
Pbe
Obie
Pbie
OtH
OtE
OtL
Ot0
Ot1
Ot2
Ot3
Ot4
Ot5
Ot6
Ot7
Ot8
Ot9
Their meaning (taken from prof's output):
# NOTATION BODY : PROFsec
# NOTATION OHEL : observed secondary structure: H=helix, E=extended (sheet), blank=other (loop)
# NOTATION PHEL : PROF predicted secondary structure: H=helix, E=extended (sheet), blank=other (loop) PROF = PROF: Profile network prediction HeiDelberg
# NOTATION RI_S : reliability index for PROFsec prediction (0=lo 9=high) Note: for the brief presentation strong predictions marked by '*'
# NOTATION pH : 'probability' for assigning helix (1=high, 0=low)
# NOTATION pE : 'probability' for assigning strand (1=high, 0=low)
# NOTATION pL : 'probability' for assigning neither helix, nor strand (1=high, 0=low)
# NOTATION OtH : actual neural network output from PROFsec for helix unit
# NOTATION OtE : actual neural network output from PROFsec for strand unit
# NOTATION OtL : actual neural network output from PROFsec for 'no-regular' unit
#
# ------------------------------------------------------------------------
# NOTATION BODY : PROFacc
# NOTATION OACC : observed solvent accessibility (acc) in square Angstroem (taken from DSSP: W Kabsch and C Sander, Biopolymers, 22, 2577-2637, 1983)
# NOTATION PACC : PROF predicted solvent accessibility (acc) in square Angstroem
# NOTATION OREL : observed relative solvent accessibility (acc) in 10 states: a value of n (=0-9) corresponds to a relative acc. of between n*n % and (n+1)*(n+1) % (e.g. for n=5: 16-25%).
# NOTATION PREL : PROF predicted relative solvent accessibility (acc) in 10 states: a value of n (=0-9) corresponds to a relative acc. of between n*n % and (n+1)*(n+1) % (e.g. for n=5: 16-25%).
# NOTATION RI_A : reliability index for PROFacc prediction (0=low to 9=high) Note: for the brief presentation strong predictions marked by '*'
# NOTATION Obe : observerd relative solvent accessibility (acc) in 2 states: b = 0-16%, e = 16-100%.
# NOTATION Pbe : PROF predicted relative solvent accessibility (acc) in 2 states: b = 0-16%, e = 16-100%.
# NOTATION Obie : observerd relative solvent accessibility (acc) in 3 states: b = 0-9%, i = 9-36%, e = 36-100%.
# NOTATION Pbie : PROF predicted relative solvent accessibility (acc) in 3 states: b = 0-9%, i = 9-36%, e = 36-100%.
# NOTATION Ot4 : actual neural network output from PROFsec for unit 0 coding for a relative solvent accessibility of 4*4 - 5*5 percent (16-25%). Note: OtN, with N=0-9 give the same information for the other output units!
#
"""
if d_prof == '':
raise EmptyError('Empty prof file!')
ret = {}
for line in d_prof.split('\n'):
if not line.startswith('#') and line != '':
#First parse the column header
if line.startswith('No'):
column_names = re.split('\s+', line)
#Now the predicted values per line
else:
value_tokens = re.split('\s+', line)
for i in range(len(value_tokens)):
#Get its specific column name
col = column_names[i]
#Try to convert the current value into an integer.
#If that fails we are dealing with a string
try:
val = int(value_tokens[i])
except ValueError:
val = value_tokens[i]
#Now append it
try:
ret[col].append(val)
except KeyError:
ret[col] = [val]
#Do some final consistency checks: Has everything the same length?
l = len(list(ret.values())[0])
for listt in ret.values():
if len(listt) != l:
raise ParseError("Something happened! profsecacc returns different column lengths!")
#Add an additional entry containing the concatenated aa sequence
seq = ''.join(ret['AA'])
ret['seq'] = seq
return ret
def parse_profbval(d_bval):
"""
Returns a dictionary with keys and values as follows:
'prd_raw1': list of integers corresponding to first output node
'prd_raw2': list of integers corresponding to second output node
Unfortunately, there is neither sequence information nor a binary prediction to be found in the output.
"""
if d_bval == '':
raise EmptyError('Empty bval file!')
out1 = []
out2 = []
region_of_interest = False
for line in d_bval.split('\n'):
if region_of_interest:
tokens = line.split()
if len(tokens) == 0: continue
out1.append( int(tokens[1]) )
out2.append( int(tokens[2]) )
if line.startswith('* out vec:'):
region_of_interest = True
#Consistency check
if len(out1) != len(out2):
raise ParseError("Something happened! profbval returns different column lengths!")
return {'prd_raw1':out1, 'prd_raw2':out2}
def parse_pfam_annotations(d_hmmer):
"""
This method performs residue-wise domain annotations according to aligned pfam domains. Search against the PfamA database should be performed
by means of the new hmmer3 suite, so using the old hmmer2 is strongly discouraged, due to its different output style!
The parsing depends on hmmer-3.0rc1 output (as of February 2010), so check that before running a newer hmmer3!!!
Each sequence position of the query seq is annotated in a dictionary in the following way:
{ ...
i: {mdl#:[(query_i,domain_i-eval,consensus_i,match_i,pp_i),(...)], mdl#:[(...),(...),...] } ,
i+j: {mdl#:[(...),(...),...], ...},
...
},
where
i: the i-th position in the query seq (starting at 0!!),
mdl#: the number of the model
query_i: the residue of the query sequence, intended for checking purposes for the function caller
domain_i-eval: the domain's i-evalue
consensus_i: the aligned residue in the consensus pfam domain
match_i: the information of the conservation grade ,
pp_i: the posterior probability of that specific aligned residue (new to hmmer3)
Note, the hierarchy of hmmer output:
A query sequence could match to different Pfam models, each consisting of several domains. Furthermore, a residue could be aligned to
more than one domain _within_ a model, hence the assigned list to each model number in the nested dictionary:
Each entry essentially refers to one domain where that specific residue i is aligned to.
A sample hmmer output against PfamA could look like this:
-------------------------------------------------------------------------------------------------------------------------------------
Query: query [L=386]
Scores for complete sequence (score includes all domains):
--- full sequence --- --- best 1 domain --- -#dom-
E-value score bias E-value score bias exp N Model Description
------- ------ ----- ------- ------ ----- ---- -- -------- -----------
3.1e-94 315.1 5.1 1e-78 264.1 0.4 2.7 2 PF00224.14 Pyruvate kinase, barrel domain
5.2e-26 90.1 6.7 6e-26 89.9 3.7 1.8 1 PF02887.9 Pyruvate kinase, alpha/beta domain
Domain annotation for each model (and alignments):
>> PF00224.14 Pyruvate kinase, barrel domain
# score bias c-Evalue i-Evalue hmmfrom hmm to alifrom ali to envfrom env to acc
--- ------ ----- --------- --------- ------- ------- ------- ------- ------- ------- ----
1 ! 53.2 0.0 2.2e-18 1.3e-14 2 72 .. 24 89 .. 23 90 .. 0.93
2 ! 264.1 0.4 1.7e-82 1e-78 173 344 .. 89 259 .. 88 263 .. 0.96
Alignments for each domain:
== domain 1 score: 53.2 bits; conditional E-value: 2.2e-18
--SEEEEEE--TTTSHHHHHHHHH----EEEEETT---HHHHHHHHHHHHHHHHCTTTS-EEEEE------ CS
PF00224.14 2 rrtkivctlGPasesvekleklieaGlnvvRlnfshGsheehkeridnvreaeeklgkkvaillDtkGpei 72
++t+ivctlGPa +sve+l kli+aG+++ R+n she+hke +nv +a+ +l +++llDtkGp i
query 24 KKTHIVCTLGPACKSVETLVKLIDAGMDICRFN----SHEDHKEMFNNVLKAQ-ELRCLLGMLLDTKGPPI 89
89******************************9....789*********9986.56788**********76 PP
== domain 2 score: 264.1 bits; conditional E-value: 1.7e-82
SS-HHHHHHHH---TT.-SEEEETTE-SHHHHHHHHHHHHHTTTTSEEEEEE-S----TTHHHHHHH----EEE-------S-GGGHHHHHHHHHHHCCC-----EEESSTTGGGGTSSS--HHHHHHHHHHHH----EEEE---------HHHHHHHHHHHHHHHHCTS-H CS
PF00224.14 173 alsekDkadlkfgvkqgvdliaasfvRkaedvkevRevleekgkeikiiakienqegvenldeileasdgimvaRGDlGieipaekvvlaqkllikkcnlagkpvitatqmlesmiknPrptRaevsDvanavldGaDavmLsgetakGkyPveavkamaevaleaekalke 344
+sekDk+d+ + ++iaasf+ +a+dv+ +R++l+++g++ikii kien eg+ ++d+il +sdgim+aRGDlG+ei ekv+laqkl+i+kcnl gkp+itatqmlesm+knPrptRaev+DvanavldG+D+vmLsgeta Gk+Pveav++m++++leae+ +++
query 89 IISEKDKNDILNFAIPMCNFIAASFIQSADDVRLIRNLLGPRGRHIKIIPKIENIEGIIHFDKILAESDGIMIARGDLGMEISPEKVFLAQKLMISKCNLQGKPIITATQMLESMTKNPRPTRAEVTDVANAVLDGTDCVMLSGETA-GKFPVEAVTIMSKICLEAEACIDY 259
69******9765555579********************************************************************************************************************************8.*******************99986 PP
>> PF02887.9 Pyruvate kinase, alpha/beta domain
# score bias c-Evalue i-Evalue hmmfrom hmm to alifrom ali to envfrom env to acc
--- ------ ----- --------- --------- ------- ------- ------- ------- ------- ------- ----
1 ! 89.9 3.7 1e-29 6e-26 2 116 .. 278 383 .. 277 384 .. 0.94
Alignments for each domain:
== domain 1 score: 89.9 bits; conditional E-value: 1e-29
HHHHHHHHHHHHH----EEEEE-----HHHHHHCC---..EEEEE----HHH---EEE---TT---HHHHCHHHHHHHHHCCHHH-----SSS-EEEE--....-------EEEE CS
PF02887.9 2 eaiaeaaveaAkelgakaIvvltesGstarlvskyrpgvpIlavtpseetarqlalvwGvhplvgkeraistdeviaealraalkkglikkgdevvvtaglpfgtaggtntikvv 116
ea+a++ave+A++++a+ I++lte+G+tarl++ky+p++ Ila++ s++t + l++++Gv+++ + + td vi++a+++a++++++k gd v++++g +tn++kvv
query 278 EAVARSAVETAESIQASLIIALTETGYTARLIAKYKPSCTILALSASDSTVKCLNVHRGVTCIKVGSF---TDIVIRNAIEIAKQRNMAKVGDSVIAIHG------IKTNLMKVV 383
99************************************************************544444...59***************************......589999998 PP
-------------------------------------------------------------------------------------------------------------------------------------
Each model is introduced by an '>>', each model could have several domains, introduced by an '=='.
Mind e.g. query residue i=88 in the first model (89 in the output above): It is annotated in both domains. Hence its annotation in the return dictionary would
look like:
88:{0:[('I','1.3e-14', 'i', 'i', '6'), ('I','1e-78', 'a', ' ', '6')]}
If it would align in a domain of the second model, that annotation would accur as another entry in the sub-dictionary, introduced by a 1.
Here, you can also see what is actually used as annotation: first the i-evalue of the domain (1.3e-14 or 1e-78) followed by the subject (consensus) residue, the
conservation letter (line between query and subject) and the posterior probability (beneath the query line).
There could be other information to be extracted (like bit score, start stop positions...). Perhaps in the future.
"""
if 'No hits detected that satisfy reporting thresholds' in d_hmmer:
#raise NoResultError('No significant hit found')
raise NoResultError('hmmer3 did not detect any hits.')
#First we split up into models
#Look for the '>>' at the beginning of the line.
rgx = re.compile('^>>', re.M)
models_tmp = rgx.split(d_hmmer)
models = []
for model in models_tmp[1:-1]: #The first one is the hmmscan header and general information, we aren't interested in that one; the last one
models.append(model) #needs to be purged off the footer
#Get rid of the last model's footer and append it to models
rgx = re.compile('^Internal pipeline statistics summary', re.M)
models.append(rgx.split(models_tmp[-1])[0])
#Now handle each single domain within the models and save models and their domains into model_list
rgx = re.compile('^ ==', re.M) #Each domain starts with this string
mdl_cnt = 0 #How many models are we dealing with? Remember, each model is made up of at least one domain
#model_list = {} #Here we store each model along with their domains
residues = {}
for model in models:
if 'No individual domains that satisfy reporting thresholds' in model:
continue
domains = rgx.split(model)
domains_header = domains[0]
domains_aligns = domains[1:]
#Parse the header first for domain-specific information
# # score bias c-Evalue i-Evalue hmmfrom hmm to alifrom ali to envfrom env to acc
dom = []
for line in domains_header.split('\n'):
if re.match('\s+\d+\s+', line):
tokens = line.strip().split()
assert tokens[1] == '!' #If this fails, we didn't fully understand what's going on during parsing!
score = tokens[2] #See the docu about the significance of both evalues. i-eval (independent) is the one
c_eval = tokens[4] #we're probably interested in later, as well as the bitscore.
i_eval = tokens[5] #Yes we are, since pfam website only reports i_eval as _the_ evalue
hmm_endpoints = tokens[8] #Is either '..', '.]', '[.' or '[]', indicating if alignment ended internally a domain ('.') or end exactly with domain boundaries ([/])
start_model = tokens[6]
end_model = tokens[7]
start_query = tokens[9]
end_query = tokens[10]
#Not all of this is currently needed.
info = {'score':score, 'i_eval':i_eval, 'start_model':start_model, 'end_model':end_model, 'start_query':start_query, 'end_query':end_query, 'hmm_endpoints':hmm_endpoints}
dom.append(info)
#Now handle the alignments in each domain
i = 0
feature_string = ''
for algn in domains_aligns:
lines = algn.strip().split('\n')
#There could be up to two additional annotation lines present above the actual alignment (s. hmmer docu p.18). Get rid of those!
if len(lines) == 5:
lines = lines[1:]
elif len(lines) == 6:
lines = lines[2:]
elif len(lines) == 7:
lines = lines[3:]
else:
raise ParseError('Well, that is indeed interesting. Something went terribly wrong during assuming the amount of possible lines per alignment! I think I will be dying now!')
line_model = lines[0] #The line containing the consensus of the domain sequence
line_match = lines[1]
line_target = lines[2] #Our target sequence for which we just found a homologous domain
line_pp = lines[3]
name_model = line_model.split()[0]
start_query = int(dom[i]['start_query'])
end_query = int(dom[i]['end_query'])
seq_model = line_model.split()[2] #The domain consensus sequence
seq_query = line_target.split()[2] #The query sequence
#We need the start index of the match sequence which is the same as from all the others, e.g. seq_model
m_start = line_model.index(seq_model)
seq_match = line_match[m_start:] #The match sequence between both
seq_pp = line_pp.lstrip().split()[0] #The posterior probability sequence
#Some semantics checks: each string length has to be the same. Otherwise, something went wrong during parsing!
assert len(seq_model) == len(seq_match) == len(seq_query) == len(seq_pp)
#Now do the mapping
actual_pos = 0
for pos in range(len(seq_query)):
if seq_query[pos] == '-':
continue
try:
residues[actual_pos+start_query-1][mdl_cnt].append( (seq_query[pos],dom[i]['i_eval'],seq_model[pos], seq_match[pos], seq_pp[pos]) )
except KeyError:
try:
residues[actual_pos+start_query-1][mdl_cnt] = [ (seq_query[pos],dom[i]['i_eval'],seq_model[pos], seq_match[pos], seq_pp[pos]) ]
except KeyError:
residues[actual_pos+start_query-1] = {mdl_cnt: [ (seq_query[pos],dom[i]['i_eval'],seq_model[pos], seq_match[pos], seq_pp[pos]) ] }
actual_pos += 1
#A further consistency check!
assert end_query == actual_pos+start_query-1
#Proceed with the next residue within the alignment
i += 1
#Proceed with the next model
mdl_cnt += 1
return residues
def parse_prosite(d_prosite):
"""
"""
if d_prosite == '':
raise EmptyError('Empty prosite file!')
stretches = [] #Here we store the prosite matches: A list of 3-lists, i.e. one per prosite match: start,stop,stretch
within = False
for line in d_prosite.split('\n'):
if line.startswith('Pattern:'):
within = True
continue
if line.startswith('Pattern-ID:') or line.strip() == '':
within = False
continue
if within:
tokens = line.strip().split()
start = int(tokens[0]) #Prosite starts counting at 1!
stretch = tokens[1]
stop = start + len(stretch) - 1
#We return sequence positions 0-based!
stretches.append( [start-1,stop-1,stretch] )
return stretches
if __name__ == '__main__':
import os
from lib_parser import *
import sys
pp_path = '/mnt/home/schaefer/SNAPv2/pp/'
chains = os.listdir(pp_path)
i = 0
N = len(chains)
mn = 0
mx = 0
for chain in chains:
#print chain
i += 1
#print chain, i, N
try:
#d_blast = open(pp_path+chain+"/query.blastPsiMat").read()
#d_disis = open(pp_path+chain+"/query.disis").read()
#d_isis = open(pp_path+chain+"/query.isis").read()
#d_md = open(pp_path+chain+"/query.mdisorder").read()
#d_prof = open(pp_path+chain+"/query.profRdb").read()
#d_bval = open(pp_path+chain+"/query.profbval").read()
#d_psic = open(pp_path+chain+"/query.psic").read()
d_in = open(pp_path+chain+"/query.in").read()
d_fasta = open(pp_path+chain+"/query.fasta").read()
#d_hmmer = open(pp_path+chain+"/query.hmm3pfam").read()
d_prosite = open(pp_path+chain+"/query.prosite").read()
except NoResultError:
#print 'too short for psic'
continue
except IOError:
print('file not found')
continue
#print d_hmmer
seq = parse_sequence(d_in, d_fasta)['seq']
for stretch in parse_prosite(d_prosite):
print (stretch[2])
print (seq[stretch[0]:stretch[1]+1])
assert stretch[2] == seq[stretch[0]:stretch[1]+1]
|
import random
class Game:
def __init__(self):
self.player_total = 0
self.computer_total = 0
def another_round(self):
play_again = input("Would you like to play again? ")
if play_again == "y" or play_again == "yes":
self.play()
if play_again == "n" or play_again == "no":
print("Thanks for playing! Until next time. The final score was Computer Score: " + str(self.computer_total) + " and Player score: " + str(self.player_total))
elif play_again != "n" and play_again != "no" and play_again != "yes" and play_again != "y":
print("That isn't a yes or a no. Please try again")
self.another_round()
def current_score(self):
print("The current Computer score is: " + str(self.computer_total) + " and the current Player score is: " + str(self.player_total))
self.another_round()
def play(self):
rock = "rock"
paper = "paper"
scissors = "scissors"
random_response = [rock, paper, scissors]
user_input = input("Let's play a game of Rock, Paper, Scissors. Throw out your guess: ").lower()
computer = random.choice(random_response)
if user_input != scissors and user_input != paper and user_input != rock:
print("That isn't a proper input. Please try again")
self.play()
if user_input == scissors and computer == rock:
print("Player loses! Rock beats Scissors!")
self.computer_total = self.computer_total + 1
self.current_score()
elif user_input == scissors and computer == paper:
print("Player wins! Scissors beats paper!")
self.player_total = self.player_total + 1
self.current_score()
if user_input == paper and computer == rock:
print("Player wins! Paper beats Rock!")
self.player_total = self.player_total + 1
self.current_score()
elif user_input == paper and computer == scissors:
print("Player loses! Scissors beats Paper!")
self.computer_total = self.computer_total + 1
self.current_score()
if user_input == rock and computer == scissors:
print("Player wins! Rock beats Scissors!")
self.player_total = self.player_total + 1
self.current_score()
elif user_input == rock and computer == paper:
print("Player loses! Paper beats Rock!")
self.computer_total = self.computer_total + 1
self.current_score()
if user_input == computer:
print("The result is a tie!")
self.current_score()
game = Game()
game.play()
|
# Python program performing
# operation using def()
def fun(x, y, z):
return x*y+z
a = 1
b = 2
c = 3
# logical jump
d = fun(a, b, c)
print(d)
# Pythonn performing
# operation using lambda
d = (lambda x, y, z: x*y+z)(1, 2, 3)
print(d)
|
while True:
print ('Menu')
print ('Kalkulator')
print ('Nilai Mahasiswa')
a=input('Masukan Menu: ')
if a == '1':
import kalkulator
elif a == '2':
import mahasiswa
else:
break
|
import unittest
def fizzbuzz(i):
if i % 15 == 0:
return "FizzBuzz"
elif i % 3 == 0:
return "Fizz"
elif i % 5 == 0:
return "Buzz"
else:
return i
def main():
for i in range(1, 101):
print(fizzbuzz(i))
if __name__ == '__main__':
main()
class TestFizzBuzz(unittest.TestCase):
def test_fizz(self):
for i in [3, 6, 9, 18]:
print('testing', i)
assert fizzbuzz(i) == 'Fizz'
def test_buzz(self):
for i in [5, 10, 50]:
print('testing', i)
assert fizzbuzz(i) == 'Buzz'
def test_fizzbuzz(self):
for i in [15, 30, 75]:
print('testing', i)
assert fizzbuzz(i) == 'FizzBuzz' |
def divide(num1, num2):
result = ""
try:
result = num1/num2
except ZeroDivisionError:
result = "Error!"
finally:
return result
print(divide(6, 3))
print(divide(6, 0)) |
import cProfile
def fib_recursivo(n):
if n > 1:
return fib_recursivo(n-1) + fib_recursivo(n-2)
else:
return 1
def fib_loop(n):
if n > 1:
fibs = {0:1,1:1}
for i in range(2,n+1):
fibs[i] = fibs[i-1]+fibs[i-2]
return fibs[n]
else:
return 1
print("fib_recursivo")
cProfile.run("[fib_recursivo(x) for x in range(1,31)]")
print("fib_loop")
cProfile.run("[fib_loop(x) for x in range(1,31)]") |
import sqlite3
conn = sqlite3.connect("peoples")
cursor = conn.cursor()
sql = "CREATE TABLE people (id INTEGER PRIMARY KEY, name VARCHAR(20))"
cursor.execute(sql)
sql = "INSERT into people VALUES (1, 'André')"
cursor.execute(sql)
sql = "INSERT into people VALUES (2, 'João')"
cursor.execute(sql)
sql = "INSERT into people VALUES (3, 'Lucas')"
cursor.execute(sql)
conn.commit()
sql = "SELECT * FROM people"
cursor.execute(sql)
result = cursor.fetchall()
print(result) |
#1.Fazer uma calculadora que execute operacoes de adicao, subtracao, multiplicacao, divisao, quadrado, cubo, raiz quadrada,
# seno, cosseno, tangente.
print("----Inicio exercicio 1----")
import math
def calculadora(funcao,arg1,arg2):
return funcao(arg1,arg2)
def somar(arg1,arg2):
return arg1+arg2
def subtrair(arg1,arg2):
return arg1-arg2
def multiplicar(arg1,arg2):
return arg1*arg2
def dividir(arg1,arg2):
return arg1/arg2
def quadrado(arg1,arg2):
return arg1**2
def raizquadrada(arg1,arg2):
return math.sqrt(arg1)
def seno(arg1,arg2):
return math.sin(arg1)
def cosseno(arg1,arg2):
return math.cos(arg1)
def tangente(arg1,arg2):
return math.tan(arg1)
print(calculadora(somar,1,2))
print(calculadora(subtrair,1,2))
print(calculadora(multiplicar,5,2))
print(calculadora(dividir,6,2))
print(calculadora(quadrado,6,0))
print(calculadora(raizquadrada,6,0))
print(calculadora(seno,6,0))
print(calculadora(cosseno,6,0))
print(calculadora(tangente,6,0))
#2.Faca um programa que ao receber um valor de raio, retorne a area e perımetro do cırculo
print("----Inicio exercicio 2----")
raio = float(input("Informe o valor do raio: "))
area = math.pi * raio**2
perimetro = math.pi * raio * 2
print("A area tem o valor de: %.2f"%(area))
print("O perimetro tem o valor de: %.2f"%(perimetro)) |
nums = [1,2,3,4,5,6,7,8,9,10,11,12]
mymap = map(lambda num:num/3,nums)
print(list(mymap)) |
tuplas=("andre","python","udemy")
print(tuplas[0])
print(tuplas[0:3])
print(tuplas[1:3])
print(len(tuplas))
print(tuplas+tuplas)
print("andre" in tuplas)
print('udemy' in tuplas)
lista = [1,2,4,"andre"]
print(lista)
tupla2 = tuple(lista)
print(tupla2)
|
import random
import string
for num in range(10):
print(random.randint(1, 10))
for num in range(10):
print(random.random())
for num in range(10):
print(random.uniform(1,10))
print(random.choice(string.ascii_lowercase)) |
import time
interval = 10000
def factorial(num):
f = 1
while num > 1:
f *= num
num -= 1
return f
def factorial_recursive(num):
if num == 0 or num == 1:
return 1
else:
return num * factorial_recursive(num-1)
time1_begin = time.time()
for index in range(interval):
factorial(index)
#print("Factorial of %s is: %s" % (index, factorial(index)))
time1_end = time.time()
diff_1 = time1_end - time1_begin
"""
time2_begin = time.time()
for index in range(interval):
factorial_recursive(index)
#print("Factorial of %s is: %s" % (index, factorial_recursive(index)))
time2_end = time.time()
diff_2 = time2_end - time2_begin
"""
print("Time to non-recursive: ",diff_1)
#print("Time to recursive: ",diff_2)
|
#!/usr/bin/env python2
#CODE IS FROM: https://www.geeksforgeeks.org/python-frequency-of-each-character-in-string/
# Python3 code to demonstrate
# each occurrence frequency using
# naive method
import sys
message = open(sys.argv[1], 'rb')
# change from string to input of file
test_str = message
# using naive method to get count
# of each element in string
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
# printing result
#print ("Count of all characters in GeeksforGeeks is :\n "
# + str(all_freq))
for entry in all_freq.items():
print(entry)
|
#!/usr/local/bin/python3
import re
import sys
if len(sys.argv) < 2:
print('syntax: ' + sys.argv[0] + ' <filename>')
sys.exit()
filename = sys.argv[1]
inFile = open(filename, 'r')
print('reading ' + filename)
lineList = inFile.readlines()
inFile.close()
lineCount = len(lineList)
groupCount = 0
answerCount = 0
answerSet = {''}
answerSet.clear()
for i in range(lineCount):
if len(lineList[i]) == 1:
#
# handle blank line / end group / start new group
#
answerCount = answerCount + len(answerSet)
groupCount = groupCount + 1
print('group ' + str(groupCount))
print(answerSet)
answerSet.clear()
else:
lineList[i] = lineList[i].strip()
print(lineList[i])
for j in range(len(lineList[i])):
answer = lineList[i][j]
if (answer >= 'a') and (answer <= 'z'):
answerSet.add(answer)
if len(answerSet) > 0:
answerCount = answerCount + len(answerSet)
groupCount = groupCount + 1
print('group ' + str(groupCount))
print(answerSet)
answerSet.clear()
print('number of groups: ' + str(groupCount))
print('sum of answer counts: ' + str(answerCount))
|
def main():
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
newList = []
print("a =", a)
number = int(input("Enter number: "))
for i in a:
if i >= number:
break
newList.append(i)
print("The new list is", newList)
main()
|
"""
联系
在控制台中获取一个月份
打印季节(春1-3 夏4-6,秋7-9,冬10-12)
"""
month = int(input("请输入月份:"))
#
# if 1 <= month <= 3:
# print("春天")
# elif 4 <= month <= 6:
# print("夏天")
# elif 7 <= month <= 9:
# print("秋天")
# elif 10 <= month <= 12:
# print("冬天")
# else:
# print("您输入的月份有问题")
# 代码优化
if month < 1 or month > 12:
print("您输入的月份有问题")
elif month <= 3:
print("这是春天")
elif month <= 6:
print("这是夏天")
elif month <= 9:
print("这是秋天")
else:
print("这是冬天")
|
"""
练习01
在控制台中获取小时/分钟/秒,计算总秒数
"""
hour = int(input("请输入小时"))
minute = int(input("请输入分钟"))
second = int(input("请输入秒数"))
result = hour * 3600 + minute * 60 + second
print("你的总秒数为:" + str(result))
"""
在控制台中获取一个总秒数
计算几个调式零几分钟零几秒
"""
int_second = int(input("请输入一个总秒数:"))
int_hour = int_second // 3600
int_minute = int_second % 3600 // 60
int_second = int_second % 3600 % 60
print(str(int_hour) + "时" + str(int_minute) + "分" + str(int_second) + "秒")
|
class Registry:
"""Store classes in one place.
Usage examples:
>>> import torch.optim as optim
>>> my_registry = Registry()
>>> my_registry.add(optim.SGD)
>>> my_registry["SGD"](*args, *kwargs)
Add items using decorator:
>>> my_registry = Registry()
>>> @my_registry
>>> class MyClass:
>>> pass
"""
def __init__(self):
self.registered_items = {}
def add(self, item):
"""Add element to a registry.
Args:
item (type): class type to add to a registry
"""
name = item.__name__
self.registered_items[name] = item
def __call__(self, item):
"""Add element to a registry.
Usage examples:
>>> class MyClass:
>>> pass
>>> r = Registry()
>>> r.add(MyClass)
Or using as decorator:
>>> r = Registry()
>>> @r
>>> class MyClass:
>>> pass
Args:
item (type): class type to add to a registry
Returns:
same item
"""
self.add(item)
return item
def __len__(self):
return len(self.registered_items)
def __getitem__(self, key):
if key not in self.registered_items:
raise KeyError(f"Unknown or not registered key - '{key}'!")
return self.registered_items[key]
def __repr__(self) -> str:
return "Registry(content={})".format(",".join(k for k in self.registered_items.keys()))
|
import _thread
import time
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count +=1
print("%s:%s"%(threadName,time.ctime(time.time())))
try:
_thread.start_new_thread(print_time,("Thread-1",2,))
_thread.start_new_thread(print_time,("Thread-2",4,))
except:
print("Error: unable to start thread")
while 1:
pass
import threading
import time
exitFlag = 0
class myThread(threading.Thread):
def __init__(self,threadId,threadName,counter):
threading.Thread.__init__(self)
self.threadId = threadId
self.threadName = threadName
self.counter = counter
def run(self):
print("开始线程:"+self.threadName)
print_time(self.threadName,self.counter,5)
print("退出线程:"+self.threadName)
def print_time(threadName,delay,counter):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print(threadName+time.asctime(time.localtime()))
counter -=1
thread1 = myThread(1,"Thread-1",1)
thread2 = myThread(2,"Thread-2",1.5)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("退出主线程")
|
#unidays coding challenge
import math
AddAnother=True
allItems=(["ItemA", 8.00],["ItemB", 12.00],["ItemC", 4.00],["ItemD", 7.00],["ItemE", 5.00]) #another list containing items to choose from
class UnidaysDiscountChallenge(object):
def __init__(self):
self.items = list() #constructor for new list aka basket
def __len__(self): #allows me to check the length of a class list
return len(self.items)
def AddToBasket(self, name, price, amount): #method to add item to class
if name not in self.items: #checking if the item is already in list
self.items.extend([name, price, amount]) #if not then it will add as a whole new item to basket
else:
changingIndex = self.items.index(name) + 2 #if it is then the index corresponding to that items quantity/amount is retrieved
amountToUpdate = self.items[changingIndex]
self.items.pop(changingIndex) #the quantity is updated by removing the previous quantity/amount value then adding the new calculated one.
self.items.insert(changingIndex, amountToUpdate + amount)
def PricingRules(self,indexI, mult, usualPrice, total):
numberOfItems = self.items[self.items.index(indexI) + 2] #1) For numberOfItems/priceOfItems value accessed through adding 2 or 1 to current index...
priceOfItem = self.items[self.items.index(indexI) + 1] #2) ...this is because price and quantity values are always a certain number of elements away from name.
discountMultiple = math.floor(numberOfItems / mult)
if numberOfItems / mult>= 1 and indexI != "ItemA":
if indexI == "ItemB" or indexI == "ItemC":
numberOfItems -= (discountMultiple * mult)
total+= ((usualPrice * discountMultiple) + (priceOfItem * numberOfItems))
return(total)
elif indexI == "itemD" or indexI == "ItemE":
total+= ((numberOfItems * priceOfItem) - (priceOfItem * discountMultiple))
return(total)
else:
total+= numberOfItems * priceOfItem
return(total) #adds to total here under else statement below if no discount applicable
def CalculateTotalPrice(self):
total = 0
for i in self.items:
if i=="ItemA": #ItemA
total = self.PricingRules(i, 1, 0, total)
elif i == "ItemB": #ItemB, 2 for £20
total = self.PricingRules(i, 2, 20, total)
elif i == "ItemC": #ItemC, 3 for £10
total = self.PricingRules(i, 3, 10, total)
elif i == "ItemD": #ItemD, 2 for 1"
total=self.PricingRules(i, 2, 0, total)
elif i == "ItemE": #ItemE, 3 for 2"
total = self.PricingRules(i, 3, 0, total)
if total<50: #delivery charge is calculated if total less than 50 pounds then 7 pound charge is added...
total+=7
print("£7 Delivery charge applied.")
return(total)
else:
print("Total over £50. No Delivery charge applied.")
return(total) #if over or equal to 50 pounds then delivery is free of charge!
def PrintBasket(self):
print(self.items)
basket = UnidaysDiscountChallenge() #initialised basket list that will contain customer items
def AmountValidation(n): #validation to check if the number of items they add in one go is within a reasonable range, lets say upper limit 20.
if n >=1 and n <= 20:
valid=True
return (valid)
else:
valid=False
return (valid)
def Main(basket, position):
try:
howMany=int(input("How many would you like to add?: "))
valid = AmountValidation(howMany) #checking if input is valid for use by calling function.
if valid==True:
basket.AddToBasket(allItems[position][0], allItems[position][1], howMany) #uses method to add specific items to basket depending on the item value selected.
basket.PrintBasket()
return(basket)
else:
print("Invalid amount of items : Please try again.")
except ValueError:
print("Input error, make sure input is an integer (whole number).")
while AddAnother!= False or len(basket) == 0: #while the customer keeps wanting to add another item and/or the basket is empty the nested code will loop
KeepAdding=input("Would you like to add to your basket? Type 'y' or 'yes' to add. Or anything else to exit.").lower() #user asked if they want to add an item
if KeepAdding == "yes" or KeepAdding == "y":
AddAnother=True
itemValue=input("Which item would you like to add (Enter A, B, C, D or E)?").lower()
if itemValue == "a": #adding itemA
Main(basket, 0)
elif itemValue == "b": #adding itemB
Main(basket, 1)
elif itemValue == "c": #adding itemC
Main(basket, 2)
elif itemValue == "d": #adding itemD
Main(basket, 3)
elif itemValue == "e": #adding itemE
Main(basket, 4)
else:
print("Input Error : Please try again.")
else:
AddAnother = False #user no longer wants to add items
FinalPrice = basket.CalculateTotalPrice() #final price with delivery and discounts applied
print("Total: £", FinalPrice)
|
empty_dictionary = {}
empty_dictionary['apple'] = 'company'
empty_dictionary['stive jobs'] = 'founder of this company'
for k, v in empty_dictionary.items():
print(f'{k.title()} is a {v.title()} ')
|
from typing import List
def solve(numbers: List[int]) -> int:
"""Returns the lowest positive integer that does not exist in the array.
Args:
numbers: a list of positive or negative integers.
Returns:
The lowest positive integer that does not exist in the array.
"""
numbers.sort()
previous = 0
for n in (n for n in numbers if n > 0):
want = previous + 1
if n in {previous, want}:
previous = n
else:
return previous + 1
return previous + 1
|
import pygame
import random
# blit(arg1, arg2) - used to put one surface on another surface
# arg1: the surface we want to put on screen surface
# arg2: the location- coordinates (xcor,ycor)
# convert() - convert the image into a type of file => easy to work with pygame
# allow our game to run at a faster pace
# rotozoom() - used to scale and rotate the surface
# Functions
def draw_base():
screen.blit(base_surface, (base_x_position, 900))
screen.blit(base_surface, (base_x_position + 576, 900))
def create_pipe():
random_pipe_position = random.choice(pipe_height)
bottom_pipe = pipe_surface.get_rect(midtop=(700, random_pipe_position))
top_pipe = pipe_surface.get_rect(midbottom=(700, random_pipe_position - 300))
return bottom_pipe, top_pipe
def move_pipe(pipes):
for pipe in pipes:
pipe.centerx -= 5 # Move the pipe leftwards a bit
visible_pipes = [pipe for pipe in pipes if pipe.right > - 50] # Show pipes surely on the screen
return visible_pipes
def draw_pipes(pipes):
for pipe in pipes:
if pipe.bottom >= 1024: # this is used for the bottom pipe
screen.blit(pipe_surface, pipe)
else:
flip_pipe = pygame.transform.flip(pipe_surface, False, True)
# The first Booleans arg indicates whether we want to flip in the x direction
# The second Booleans arg indicates whether we want to flip in the y direction
screen.blit(flip_pipe, pipe)
def check_collision(pipes):
global can_score
for pipe in pipes:
if bird_rect.colliderect(pipe):
flap_sound_death.play()
can_score = True
return False
if bird_rect.top <= -100 or bird_rect.bottom >= 900:
can_score = True
return False
return True
def rotate_bird(bird):
new_bird = pygame.transform.rotozoom(bird, -bird_movement, 1)
return new_bird
def bird_animation():
new_bird = bird_frames[bird_index]
new_bird_rect = new_bird.get_rect(center=(100, bird_rect.centery))
return new_bird, new_bird_rect
def update_score(score, current_high_score):
if score > current_high_score:
global high_score
high_score = score
def score_display(game_state):
if game_state == 'main_game':
score_surface = game_font.render(str(int(score)), True, (255, 255, 255))
score_rect = score_surface.get_rect(center=(288, 100))
screen.blit(score_surface, score_rect)
if game_state == 'game_over':
score_surface = game_font.render(f'Score: {int(score)}', True, (255, 255, 255))
score_rect = score_surface.get_rect(center=(288, 100))
screen.blit(score_surface, score_rect)
score_surface = game_font.render(f'Press Space to restart', True, (255, 255, 255))
score_rect = score_surface.get_rect(center=(288, 600))
screen.blit(score_surface, score_rect)
high_score_surface = game_font.render(f'High score: {int(high_score)}', True, (255, 255, 255))
high_score_rect = high_score_surface.get_rect(center=(288, 850))
screen.blit(high_score_surface, high_score_rect)
def pipe_score_check():
global score, can_score
if pipe_list:
for pipe in pipe_list:
if 95 < pipe.centerx < 105 and can_score: # Check if the position of the pipe equals to the bird's
score += 1
flap_sound_score.play()
can_score = False
elif pipe.centerx < 0:
can_score = True # Which means the pipe moves to the left further of the screen = the bird has passed
# the pipe
# Initialize the screen
pygame.init()
screen = pygame.display.set_mode((576, 1024))
clock = pygame.time.Clock() # Limit the frame-rate
running = True
game_font = pygame.font.Font('font/04B_19__.TTF', 40)
# Game Variables
gravity = 0.375 # Add gravity to every frame of bird_movement
bird_movement = 0
game_active = True
score = 0
high_score = 0
can_score = True
# Background
bg_surface = pygame.image.load('flappy_bird/background-day.png').convert()
bg_surface = pygame.transform.scale2x(bg_surface) # Double the surface's size
# return a new surface
# Base
base_surface = pygame.image.load('flappy_bird/base.png').convert()
base_surface = pygame.transform.scale2x(base_surface)
base_x_position = 0
# Bird
bird_down_flap = pygame.transform.scale2x(pygame.image.load('flappy_bird/bluebird-downflap.png')).convert_alpha()
bird_mid_flap = pygame.transform.scale2x(pygame.image.load('flappy_bird/bluebird-midflap.png')).convert_alpha()
bird_up_flap = pygame.transform.scale2x(pygame.image.load('flappy_bird/bluebird-upflap.png')).convert_alpha()
bird_frames = [bird_down_flap, bird_mid_flap, bird_up_flap]
bird_index = 0
bird_surface = bird_frames[bird_index]
bird_rect = bird_surface.get_rect(center=(100, 512))
BIRD_FLAP = pygame.USEREVENT + 1
pygame.time.set_timer(BIRD_FLAP, 200)
# Pipes
pipe_surface = pygame.image.load('flappy_bird/pipe-green.png')
pipe_surface = pygame.transform.scale2x(pipe_surface)
pipe_list = [] # Contains lots of rectangles which continuously move leftwards
spawn_pipe = pygame.USEREVENT # cannot be triggered by the mouse-click or button but by the timer
pygame.time.set_timer(spawn_pipe, 1200) # the second argument is millisecond => 1200 ms= 1.2s
pipe_height = [400, 600, 800] # Positions of the pipes - randomly picked
# Death message
death_surface = pygame.image.load('flappy_bird/gameover.png')
death_surface = pygame.transform.scale2x(death_surface)
death_rect = death_surface.get_rect(center=(288, 512))
# Game-over message
game_over_surface = pygame.image.load('flappy_bird/message.png').convert_alpha()
game_over_surface = pygame.transform.scale2x(game_over_surface)
game_over_rect = game_over_surface.get_rect(center=(288, 512))
# Sound effects
flap_sound_wing = pygame.mixer.Sound('flappy_bird/sfx_wing.wav')
flap_sound_death = pygame.mixer.Sound('flappy_bird/sfx_hit.wav')
flap_sound_score = pygame.mixer.Sound('flappy_bird/sfx_point.wav')
flap_sound_score_countdown = 100
# Logic of the game
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN: # Check if any key of keyboard happens pressed down
if event.key == pygame.K_SPACE and game_active:
bird_movement = 0
bird_movement -= 12 # bird moves upwards
flap_sound_wing.play()
elif event.key == pygame.K_SPACE and game_active == False:
game_active = True
pipe_list.clear()
bird_rect.center = (100, 512)
bird_movement = 0
score = 0
elif event.type == spawn_pipe:
pipe_list.extend(create_pipe())
elif event.type == BIRD_FLAP:
if bird_index < 2:
bird_index += 1
else:
bird_index = 0
bird_surface, bird_rect = bird_animation()
pygame.display.flip()
screen.blit(bg_surface, (0, 0))
if game_active:
# Bird
bird_movement += gravity
rotated_bird = rotate_bird(bird_surface)
bird_rect.centery += bird_movement
screen.blit(rotated_bird, bird_rect)
game_active = check_collision(pipe_list)
# Pipes
pipe_list = move_pipe(pipe_list)
draw_pipes(pipe_list)
# Scoring
pipe_score_check()
score_display('main_game')
else:
screen.blit(death_surface, death_rect)
update_score(score, high_score)
score_display('game_over')
base_x_position -= 1
draw_base()
if base_x_position <= -576:
base_x_position = 0
pygame.display.update()
clock.tick(120) # Frame-rate's limitation is 120 fps(frame per second)
pygame.quit()
|
# The sum of the squares of the first ten natural numbers is,
# 12 + 22 + ... + 102 = 385
# The square of the sum of the first ten natural numbers is,
# (1 + 2 + ... + 10)2 = 552 = 3025
# Hence the difference between the sum of the squares of the first ten natural numbers
# and the square of the sum is 3025 ? 385 = 2640.
# Find the difference between the sum of the squares of the first one hundred
# natural numbers and the square of the sum.
squares = [x**2 for x in range(1, 101)]
nats = [x for x in range(1, 101)]
total = sum(squares) - sum(nats)
print(total)
|
import itertools
import sys
def spilting(sentence):
words = sentence.split()
ns = range(1, len(words)) # n = 1..(n-1)
for n in ns: # split into 2, 3, 4, ..., n parts.
for idxs in itertools.combinations(ns, n):
yield [' '.join(words[i:j]) for i, j in zip((0,) + idxs, idxs + (None,))]
def logic(size,array,k):
maximum=0
#if we can count all the words in the phrase, return the length of the phrase itself
if(sum(array)<=k):
return len(array)
else:
#Convert the number array into a string as we want all combinations of the phrase
sentence=str(array[0])
for i in range(1,size):
sentence=sentence+" "+str(array[i])
#Spliting function makes all combinations of phrases possible with an array
for word in spilting(sentence):
print("word",word)
lists=[x for x in range(len(word))] #Contains the index range of the words (0...n)
#Calculate the length of each subdivided word in the phrase
for item in word:
str1=item.split()
int_str1=[int(i) for i in str1]
if(len(int_str1)>maximum and sum(int_str1)<=k):#We need to find the maximum number of words in the entire phrase
maximum=len(int_str1)
return maximum
def main():
phrase=input("enter the phrase: ")
wordCountList=[len(x) for x in phrase.split()]
print("List of word length: ",wordCountList)
k=int(input("Enter value of k: "))
size=len(wordCountList)
result=logic(size,wordCountList,k)
print(result)
main()
|
import xlrd
wb = xlrd.open_workbook('eLife_query_tool_508.xls')
sh = wb.sheet_by_index(0)
row_with_colnames = 3
col_names = sh.row_values(row_with_colnames)
# traspose into a list, so I can slice the list.
rows = []
for rownum in range(sh.nrows):
rows.append(sh.row_values(rownum))
print ""
data = rows[4:]
for data_row in data:
for index, col in enumerate(col_names):
print col, " : " ,data_row[index]
print ""
# for rownum in range(sh.nrows):
# print sh.row_values(rownum)
# print "" |
def addMultiDict(ddict,val1,val2):
if val1 not in ddict:
ddict[val1] = ({ val2 : 1})
else:
if val2 not in ddict[val1]:
ddict[val1].update({ val2 : 1})
else:
ddict[val1][val2] += 1
#ddict[val1].update({val2 : ddict[val1][val2] + 1})
return ddict
def extendMultiDict(dict1,key1,dict2,key2):
if key1 not in dict1:
dict1.update({key1 : dict1[key2]})
else:
#dict1 for hero
for heroid in dict1[key2]:
if heroid not in dict1[key1]:
print("---------------------------")
print(key1)
print(key2)
print(heroid)
print(dict1)
dict1[key1].update({heroid : dict1[key2][heroid]})
print(dict1)
print("---------------------------")
else:
#dict1[key1][heroid] += dict1[key2][heroid]
dict1[key1].update({heroid : dict1[key2][heroid] + 1})
return dict1
|
# Start Dict
my_dict={}
print(my_dict)
my_dict=dict()
print(my_dict,type(my_dict))
my_dict={'one':1,'two':2,'three':3}
print(my_dict)
my_dict1={1:'one',1:'two'}
print(my_dict1[1])
#Key Dict True or False
print('one' in my_dict.keys(), 'Fokka' in my_dict )
print(1 in my_dict.values(), 3 in my_dict ) #Value not get without .value (but slow wordS)
print(my_dict.keys())
print(my_dict.values())
# Start problem solve of dict
# 1. Write a Python script to sort (ascending and descending) a dictionary by value.
dict={-1:'nage',10:1,9:"bbb",2:'ctc'}
p=sorted(dict.items())
m=sorted(dict.items(),reverse=True)
print('Ascending',p)
print("descending",m)
# 2. Write a Python script to add a key to a dictionary.
dict = {0: 10, 1: 20}
dict[2] = 30
print(dict)
dict.update({3:'last'})
print(dict)
#3. Write a Python script to concatenate following dictionaries to create a new one.
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,1:60}
dic2.update(dic3)
dic1.update(dic2)
print(dic1)
#4. Write a Python script to check whether a given key already exists in a dictionary.
dict={1: 60, 2: 20, 3: 30, 4: 40, 5: 50}
key=dict.keys()
i=int(input('type num: '))
if i == key:
print(i,"key already exists" )
else:
print(i,"key not exists" )
# 5. Write a Python program to iterate over dictionaries using for loops
dict= {1: 60, 2: 20, 3: 30, 4: 40, 5: 50}
for x in dict.items():
print(x)
# end problem solve |
import unittest
from trivia_refactored import Game
BOB = 0
MIKE = 1
class TriviaTest(unittest.TestCase):
def testGameWithOnePlayerIsNotPlayable(self):
game = Game().with_players(["Bob"])
self.assertFalse(game.is_playable())
def testGameWithTwoPlayersIsPlayable(self):
game = Game().with_players(["Bob", "Mike"])
self.assertTrue(game.is_playable())
def testGameCanCountPlayers(self):
game = Game().with_players(["Bob", "Mike"])
self.assertEqual(2, game.how_many_players)
def testPlayersStartGameOnPlaceZero(self):
game = Game().with_players(["Bob", "Mike"])
self.assertEqual(0, game.places[BOB])
self.assertEqual(0, game.places[MIKE])
def testPlayersStartGameWithNoGoldCoins(self):
game = Game().with_players(["Bob", "Mike"])
self.assertEqual(0, game.purses[BOB])
self.assertEqual(0, game.purses[MIKE])
def testPlayersStartGameNotInPenaltyBox(self):
game = Game().with_players(["Bob", "Mike"])
self.assertFalse(game.in_penalty_box[BOB])
self.assertFalse(game.in_penalty_box[MIKE])
def testAnsweringQuestionWrongPutsPlayerInPenaltyBox(self):
game = Game().with_players(["Bob"])
game.wrong_answer()
self.assertTrue(game.in_penalty_box[BOB])
def testRollingOddNumberWhenInPenaltyBoxRemovesPlayerFromPenaltyBox(self):
game = Game().with_players(["Bob"])
game.in_penalty_box[BOB] = True
game.roll(1)
self.assertFalse(game.in_penalty_box[BOB])
def testRollingEvenNumberWhenInPenaltyBoxDoesNotRemovePlayerFromPenaltyBox(self):
game = Game().with_players(["Bob"])
game.in_penalty_box[BOB] = True
game.roll(2)
self.assertTrue(game.in_penalty_box[BOB])
def testGameBeginsWithFirstPlayerAdded(self):
game = Game().with_players(["Bob", "Mike"])
self.assertEqual(BOB, game.current_player)
def testRollingWhenNotInPenaltyBoxAdvancesPlayerByRoll(self):
game = Game().with_players(["Bob"])
game.in_penalty_box[BOB] = False
game.roll(6)
self.assertEqual(6, game.places[BOB])
def testRollingOddNumberWhenInPenaltyBoxAdvancesPlayerPlacesByRoll(self):
game = Game().with_players(["Bob"])
game.in_penalty_box[BOB] = True
game.roll(3)
self.assertEqual(3, game.places[BOB])
def testRollingEvenNumberWhenInPenaltyBoxDoesNotAdvancePlayer(self):
game = Game().with_players(["Bob"])
game.in_penalty_box[BOB] = True
game.roll(4)
self.assertEqual(0, game.places[BOB])
def testPlayerPlaceCannotExceedEleven(self):
game = Game().with_players(["Bob"])
game.places[BOB] = 8
game.roll(5)
self.assertEqual(1, game.places[BOB])
def testAnsweringQuestionCorrectlyWhenInPenaltyBoxDoesNotEarnGoldCoin(self):
game = Game().with_players(["Bob"])
game.in_penalty_box[BOB] = True
game.correct_answer()
self.assertEqual(0, game.purses[BOB])
def testAnsweringQuestionCorrectlyWhenNotInPenaltyBoxEarnsGoldCoin(self):
game = Game().with_players(["Bob"])
game.in_penalty_box[BOB] = False
game.correct_answer()
self.assertEqual(1, game.purses[BOB])
def testAnsweringQuestionWronglyDoesNotEarnGoldCoin(self):
game = Game().with_players(["Bob"])
game.in_penalty_box[BOB] = False
game.wrong_answer()
self.assertEqual(0, game.purses[BOB])
def testPlayerDoesNotWinTheGameByEarningFiveCoins(self):
game = Game().with_players(["Bob"])
game.in_penalty_box[BOB] = False
game.purses[BOB] = 4
is_game_won = game.correct_answer()
self.assertFalse(is_game_won)
def testPlayerWinsTheGameByEarningSixCoins(self):
game = Game().with_players(["Bob"])
game.in_penalty_box[BOB] = False
game.purses[BOB] = 5
is_game_won = game.correct_answer()
self.assertTrue(is_game_won)
if __name__ == '__main__':
unittest.main()
|
The_little_mermaid = 3
Brother_Bear = 5
Hercules = 1
cost = 3
total_days = The_little_mermaid + Brother_Bear + Hercules
total_cost = total_days * cost
print("The total cost for the movies is", total_cost, "dollars")
# Suppose you are working as a contractor for 3 companies: Google, Amazon, Facebook,
# they pay you a different rate per hour. Google pays 400/hr, Amazon 380/hr, and FB 350.
# How much will you recive in pmt this week? 10 hrs FB, 6 hrs GGL, 4 hrs Amazon.
google_hr = 400
google_hrs_worked = 6
google_pay = google_hr * google_hrs_worked
amazon_hr = 380
amazon_hrs_worked = 4
amazon_pay = amazon_hr * amazon_hrs_worked
fb_hr = 350
fb_hrs_worked = 10
fb_pay = fb_hr * fb_hrs_worked
total_pay = google_pay + amazon_pay + fb_pay
print("This week you will recieve", total_pay, "dollars.")
# A student can be enrolled to a class only if the class is not full and the
#class schedule does not conflict with her current schedule.
class_full = False
schedule_conflict = False
enrollable = not (class_full or schedule_conflict)
enrollable
# A product offer can be applied only if people buys more than 2 items,
# and the offer has not expired. Premium members do not need to buy a specific amt.
Offer_expired = False
More_than_2_items = True
Premium_members = True
offer_applied = Premium_members or (More_than_2_items and not Offer_expired)
print (offer_applied)
#Use the following code to follow the instructions below:
username = 'codeup'
password = 'notastrongpassword'
len(password) >= 5
len(username) <= 20
password != username
#bonus
|
#!/usr/bin/python3
class Factor:
def __init__(self, number):
self._factors = []
self._number = number
## recursive method seems beyond python default recursive depth 1000
# def _calculate(self, factor, number):
# if factor >= number:
# return
# if (number % factor == 0):
# self._factors.append(factor)
# number = number / factor
# else:
# factor += 1
# self._calculate(factor, number)
def _calculate(self):
factor = 2
number = self._number
while factor < number:
if (number % factor == 0):
number = number / factor
self._factors.append(factor)
else:
factor += 1
self._factors.append(int(number))
def factors(self):
# this is used recursive method
#self._calculate(2, self._number)
self._calculate()
results = set(self._factors)
return results
class Prime:
def __init__(self):
pass
@staticmethod
def isPrime(number):
f = Factor(number)
if len(f.factors()) == 1:
return True
return False
if __name__ == "__main__":
#number = 13195
number = 600851475143
fac = Factor(number)
results = fac.factors()
print("Factors of number {} is {}".format(number, results))
primes = []
for num in results:
if ( Prime.isPrime(num) ):
primes.append(num)
print("In which primes are {}, max prime is {}".format(primes, max(primes)))
|
# c=0
# while c<10:
# print(c)
# c+=1
# i=0
# while i<6:
# i+=1
# if i==3:
# continue
# print(i)
i=0
while i<10:
print(i)
if i==3:
break
i+=1
|
# set1={"a","b","c","d"}
# print(set1)
# for i in set1:
# print(i)
# print("b" in set1)
# set1.add("e")
# print(set1)
# set1.update(["f","g","h"])
# print(set1)
# print(len(set1))
# set1.remove("d")
# print(set1)
# set1.discard("d")
# print(set1)
# set1.pop()
# print(set1)
# set1.clear()
# print(set1)
# del set1
# set1=set(("a","b","c"))
# print(set1)
# set1={'a','b','c',1,2}
# set2={1,2,3,4}
# set3=set1.union(set2)
# print(set3)
# set3=set1|set2
# print(set3)
# set1.update(set2)
# print(set1)
# set3=set1-set2
# print(set3)
# set3=set2-set1
# print(set3)
# list=(1,2,3,4,5,5,3,3,5,74,3,2)
# print(set(list))
# print(set(sorted(list)))
list={1,2,3,4,5,5,3,3,5,74,3,2}
t=(sorted(list))
print(t)
t=(sorted(list))
print(t[::-1])
|
# MIT 6.034 Lab 7: Support Vector Machines
# Written by 6.034 staff
from svm_data import *
from functools import reduce
#### Part 1: Vector Math #######################################################
def dot_product(u, v):
"""Computes the dot product of two vectors u and v, each represented
as a tuple or list of coordinates. Assume the two vectors are the
same length."""
ans=0
for i in range(len(u)):
ans+=u[i]*v[i]
return ans
def norm(v):
"""Computes the norm (length) of a vector v, represented
as a tuple or list of coords."""
s=0
for i in range(len(v)):
s+=v[i]**2
return s**0.5
#### Part 2: Using the SVM Boundary Equations ##################################
def positiveness(svm, point):
"""Computes the expression (w dot x + b) for the given Point x."""
return dot_product(svm.w,point.coords)+svm.b
def classify(svm, point):
"""Uses the given SVM to classify a Point. Assume that the point's true
classification is unknown.
Returns +1 or -1, or 0 if point is on boundary."""
if positiveness(svm, point)==0:
return 0
if positiveness(svm, point)>0:
return 1
return -1
def margin_width(svm):
"""Calculate margin width based on the current boundary."""
return 2/norm(svm.w)
def check_gutter_constraint(svm):
"""Returns the set of training points that violate one or both conditions:
* gutter constraint (positiveness == classification, for support vectors)
* training points must not be between the gutters
Assumes that the SVM has support vectors assigned."""
bad=set()
for point in svm.support_vectors:
if positiveness(svm,point)!=point.classification:
bad.add(point)
for point in svm.training_points:
if abs(positiveness(svm,point))<1:
bad.add(point)
return bad
#### Part 3: Supportiveness ####################################################
def check_alpha_signs(svm):
"""Returns the set of training points that violate either condition:
* all non-support-vector training points have alpha = 0
* all support vectors have alpha > 0
Assumes that the SVM has support vectors assigned, and that all training
points have alpha values assigned."""
bad=set()
for point in svm.training_points:
if point.alpha<0:
bad.add(point)
if point not in svm.support_vectors:
if point.alpha!=0:
bad.add(point)
for point in svm.support_vectors:
if point.alpha<=0:
bad.add(point)
return bad
def check_alpha_equations(svm):
"""Returns True if both Lagrange-multiplier equations are satisfied,
otherwise False. Assumes that the SVM has support vectors assigned, and
that all training points have alpha values assigned."""
cond4 = False
cond5 = False
s=0
for point in svm.training_points:
s+=point.classification*point.alpha
if s==0:
cond4 = True
v=[]
for i in range(len(svm.w)):
s=0
for point in svm.training_points:
s+=point.classification*point.alpha*point.coords[i]
v.append(s)
if v==svm.w:
cond5 = True
return cond4 and cond5
#### Part 4: Evaluating Accuracy ###############################################
def misclassified_training_points(svm):
"""Returns the set of training points that are classified incorrectly
using the current decision boundary."""
bad = set()
for point in svm.training_points:
if classify(svm,point)!=point.classification:
bad.add(point)
return bad
#### Part 5: Training an SVM ###################################################
def update_svm_from_alphas(svm):
"""Given an SVM with training data and alpha values, use alpha values to
update the SVM's support vectors, w, and b. Return the updated SVM."""
v=[]
for point in svm.training_points:
if point.alpha>0:
v.append(point)
svm.support_vectors=v
v=[]
for i in range(2):
s=0
for point in svm.training_points:
s+=point.classification*point.alpha*point.coords[i]
v.append(s)
svm.w = v
posb=[]
negb=[]
for point in svm.support_vectors:
if point.classification==1:
posb.append(1-dot_product(svm.w,point.coords))
if point.classification==-1:
negb.append(-1-dot_product(svm.w,point.coords))
svm.b=(max(posb)+min(negb))/2
return svm
#### Part 6: Multiple Choice ###################################################
ANSWER_1 = 11
ANSWER_2 = 6
ANSWER_3 = 3
ANSWER_4 = 2
ANSWER_5 = ['A','D']
ANSWER_6 = ['A','B','D']
ANSWER_7 = ['A','B','D']
ANSWER_8 = []
ANSWER_9 = ['A','B','D']
ANSWER_10 = ['A','B','D']
ANSWER_11 = False
ANSWER_12 = True
ANSWER_13 = False
ANSWER_14 = False
ANSWER_15 = False
ANSWER_16 = True
ANSWER_17 = [1,3,6,8]
ANSWER_18 = [1,2,4,5,6,7,8]
ANSWER_19 = [1,2,4,5,6,7,8]
ANSWER_20 = 6
#### SURVEY ####################################################################
NAME = "Aaryan Garg"
COLLABORATORS = ""
HOW_MANY_HOURS_THIS_LAB_TOOK = 3
WHAT_I_FOUND_INTERESTING = "everything"
WHAT_I_FOUND_BORING = "nothing"
SUGGESTIONS = None
|
"""
Code to test scope.
RESULT: this demonstrates the unexpected behavior that
when a function changes a dict entry it is changed
outside the scope of the function, even if we do not
return the dict!
The reason, apparently, is that:
"the dictionary insertion is not an assigment, but a
method call. In fact, inserting a key-value pair into
a dictionary is equivalent to calling the __setitem__ method
on the dictionary object."
Interesting!
Even more interesting, or disturbing, is that the function
call h() below also modifies the dict, despite the fact that
I did not pass it anything. h() only does this if we specifically
modify dict "d" and not some other name. So why does the function
know about the dict object??
Apparently "You don't assign to dictionaryVar, you assign to
dictionaryVar['A']. So it's never being assigned to, so it's
IMPLICITLY GLOBAL (emphasis mine). If you were to actyually assign
to dictionaryVar, you'd get the behavior you were 'expecting'."
"""
import numpy as np
def f(a):
a = 2*a
return a
def g(d):
for k in d.keys():
d[k] = d[k]*2
def h():
for k in d.keys():
d[k] = d[k]+10
a = 1
b = np.arange(3)
d = {'x':1}
print('before')
print(a)
print(b)
print(d)
f(a)
f(b)
g(d)
print('\nafter without return from f()')
print(a)
print(b)
print(d)
a = f(a)
b = f(b)
g(d)
print('\nafter with return from f()')
print(a)
print(b)
print(d)
h()
print('\nafter call to h()')
print(d)
|
"""
Code to get names of pandas line colors
"""
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# make some lines to plot
x = np.linspace(0,10,300)
a = pd.DataFrame(index=x)
plt.close('all')
fig = plt.figure(figsize=(16,8))
ax = fig.add_subplot(111)
for ii in np.linspace(.1, 1,6):
y = np.sin(x**ii)
a.loc[:,ii] = y
a.plot(ax=ax)
for line in ax.get_lines():
print(line.get_color())
plt.show()
|
from attractions.attraction import Attraction
class PettingZoo(Attraction):
def __init__(self,attraction_name,description):
super().__init__(attraction_name, description)
def add_animal(self, animal):
try:
if animal.walk_speed > -1:
self.animals.append(animal)
print(f"{animal} now lives in {self.attraction_name}")
except AttributeError as ex:
print(f"{animal} doesn't like to be petted, so please do not put it in the {self.attraction_name} attraction")
|
#grid布局案例
import tkinter
base = tkinter.Tk()
lb1 = tkinter.Label(base,text='账号:').grid(row=0,sticky=tkinter.W)
entry1 = tkinter.Entry(base)
entry1.grid(row=0,column=1,sticky=tkinter.E)
lb2 = tkinter.Label(base,text='密码:')
lb2.grid(row=1,sticky=tkinter.W)
tkinter.Entry(base).grid(row=1,column=1,sticky=tkinter.E)
btn = tkinter.Button(base,text='登录').grid(row=2,column=1,sticky=tkinter.W)
base.mainloop() |
from abc import ABC, abstractmethod
class Person:
@abstractmethod
def name(self, name):
pass
def age(self, age):
if age > 18:
print(age)
def surname(self):
pass
class Animal(ABC):
@abstractmethod
def feed(self, feed_type, lion_type):
raise NotImplementedError
@abstractmethod
def eat(self):
pass
class Lion(Animal):
def feed(self, feed_type, lion_type):
print(f'Feeding: {feed_type}, {lion_type}')
def eat(self):
print('Lion eats')
class Panda(Animal):
def feed(self, feed_type, panda_type):
print(f'Feeding: {feed_type}, {panda_type}')
def eat(self):
print('Panda eats')
class Snake(Animal):
pass
lion = Lion()
panda = Panda()
# snake = Snake()
animals = (lion, panda)
for animal in animals:
animal.eat()
# animal = Animal()
# try:
# animal = Animal()
# except TypeError as e:
# print(e)
# lion = Lion()
#
# lion.eat()
# lion.feed('meat', 'angry')
|
# 1. Define the id of next variables:
int_a = 55
str_b = 'cursor'
set_c = {1, 2, 3}
lst_d = [1, 2, 3]
dict_e = {'a': 1, 'b': 2, 'c': 3}
print("int_a id =", id(int_a))
print("str_b id =", id(str_b))
print("set_c id =", id(set_c))
print("lst_d id =", id(lst_d))
print("dict_e id =", id(dict_e))
# 2. Append 4 and 5 to the lst_d and define the id one more time.
print("lst_d id =", id(lst_d))
lst_d.append(4)
lst_d.append(5)
print("lst_d id =", id(lst_d))
# 3. Define the type of each object from step 1.
print("int_a type =", type(int_a))
print("str_b type =", type(str_b))
print("set_c type =", type(set_c))
print("lst_d type =", type(lst_d))
print("dict_e type =", type(dict_e))
# 4*. Check the type of the objects by using isinstance.
print("int_a type = int is ", isinstance(int_a, int))
print("str_b type = str is", isinstance(str_b, str))
print("set_c type = set is", isinstance(set_c, set))
print("lst_d type = list is", isinstance(lst_d, list))
print("dict_e type = dict is", isinstance(dict_e, dict))
#
# String formatting:
# Replace the placeholders with a value:
# print(f"Anna has __ apples and __ peaches.")
#
# 5. With .format and curly braces {}
print("Anna has {} apples and {} peaches.".format(55, 3))
# 6. By passing index numbers into the curly braces.
print("Anna has {0} apples and {1} peaches.".format(55, 3))
# 7. By using keyword arguments into the curly braces.
print("Anna has {ff} apples and {three} peaches.".format(ff=55, three=3))
# 8*. With indicators of field size (5 chars for the first and 3 for the second)
print("Anna has {0:5} apples and {1:3} peaches.".format("red", "yellow"))
# 9. With f-strings and variables
print(f"Anna has {int_a} apples and {lst_d[2]} peaches.")
# 10. With % operator
print("Anna has %d apples and %s peaches." % (int_a, "yellow"))
# 11*. With variable substitutions by name (hint: by using dict)
print('Anna has {key1} apples and {key2} peaches.'.format(**{'key1': 'red', 'key2': 'yellow'}))
print('Anna has %(key1)s apples and %(key2)s peaches.' % {'key1': 'red', 'key2': 'yellow'})
# Comprehensions:
# (1)
# lst = []
# for num in range(10):
# if num % 2 == 1:
# lst.append(num ** 2)
# else:
# lst.append(num ** 4)
# print(lst)
#
# # (2)
# list_comprehension = [num // 2 if num % 2 == 0 else num * 10 for num in range(10)]
# print(list_comprehension)
# 12. Convert (1) to list comprehension
list_comprehension = [num**2 if num % 2 == 1 else num ** 4 for num in range(10)]
print(list_comprehension)
# 13. Convert (2) to regular for with if-else
lst = []
for num in range(10):
if num % 2 == 0:
lst.append(num // 2)
else:
lst.append(num * 10)
print(lst)
#
# (3)
# d = {}
# for num in range(1, 11):
# if num % 2 == 1:
# d[num] = num ** 2
# print(d)
# (4)
# d = {}
# for num in range(1, 11):
# if num % 2 == 1:
# d[num] = num ** 2
# else:
# d[num] = num // 0.5
# print(d)
# (5)
# dict_comprehension = {x: x**3 for x in range(10) if x**3 % 4 == 0}
# print(dict_comprehension)
# (6)
# dict_comprehension = {x: x**3 if x**3 % 4 == 0 else x for x in range(10)}
# print(dict_comprehension)
# 14. Convert (3) to dict comprehension.
dict_comprehension = {num: num ** 2 for num in range(1, 11) if num % 2 == 1}
print(dict_comprehension)
# 15*. Convert (4) to dict comprehension.
dict_comprehension = {num: num ** 2 if num % 2 == 1 else num // 0.5 for num in range(1, 11)}
print(dict_comprehension)
# 16. Convert (5) to regular for with if.
d = {}
for x in range(10):
if x ** 3 % 4 == 0:
d[x] = x ** 3
print(d)
# 17*. Convert (6) to regular for with if-else.
d = {}
for x in range(10):
if x ** 3 % 4 == 0:
d[x] = x ** 3
else:
d[x] = x
print(d)
#
# Lambda:
#
# (7)
# def foo(x, y):
# if x < y:
# return x
# else:
# return y
# #
# # (8)
# foo = lambda x, y, z: z if y < x and x > z else y
# print(foo(3, 2, 1))
# print(foo(3, 4, 3))
# print(foo(3, 4, 5))
# 18. Convert (7) to lambda function
foo = lambda x, y: x if x < y else y
print(foo(7, 5))
# # 19*. Convert (8) to regular function
def foo(x, y, z):
if y < x and x > z:
return z
else:
return y
print(foo(3, 2, 1))
print(foo(3, 4, 5))
lst_to_sort = [5, 18, 1, 24, 33, 15, 13, 55]
#
# 20. Sort lst_to_sort from min to max
lst_to_sort.sort()
print(lst_to_sort)
# 21. Sort lst_to_sort from max to min
lst_to_sort.sort(reverse=True)
print(lst_to_sort)
# 22. Use map and lambda to update the lst_to_sort by multiply each element by 2
lst_to_sort = list(map(lambda x: x * 2, lst_to_sort))
print(lst_to_sort)
# 23*. Raise each list number to the corresponding number on another list:
list_A = [2, 3, 4]
list_B = [5, 6, 7]
list_C = list(map(lambda x, y: x ** y, list_A, list_B))
print(list_C)
# 24. Use reduce and lambda to compute the numbers of a lst_to_sort.
import functools
lst_to_sort = [5, 18, 1, 24, 33, 15, 13, 55]
print(functools.reduce(lambda a, b: a+b, lst_to_sort))
# 25. Use filter and lambda to filter the number of a lst_to_sort with elem % 2 == 1.
new_list = list(filter(lambda x: (x % 2 == 1), lst_to_sort))
print(new_list)
# 26. Considering the range of values: b = range(-10, 10), use the function filter to return only negative numbers.
b = range(-10, 10)
new_list = list(filter(lambda x: (x < 0), b))
print(new_list)
# 27*. Using the filter function, find the values that are common to the two lists:
list_1 = [1, 10, 6, 5, 10, 9]
list_2 = [2, 10, 5, 6, 7, 8]
new_list = list(filter(lambda x: x in list_1, list_2))
print(new_list)
|
class Book:
def __init__(self):
page1 = Page('This is content for page 1')
page2 = Page('This is content for page 2')
self.pages = [page1, page2]
class Page:
def __init__(self, content):
self.content = content
book = Book() # If I destroy this Book instance,
# the Page instances are also destroyed
|
class MyOpen:
def __init__(self, path, access_attr="r"):
self.file = open(path, access_attr)
def __enter__(self):
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
print(exc_type, exc_val, exc_tb)
if exc_type is None:
self.file.close()
elif exc_type is Exception:
print("EXCEPTION")
return True
with open("test_1.txt", "r") as file:
print(file.read())
with MyOpen("test_1.txt", "r") as file:
print(file.read())
float("f")
|
assert sum([1, 2, 3]) == 6, "test error"
def func(a):
if a is True:
return "Hello"
else:
return 'by'
assert func(True) == "Hello"
assert func(False) == "by"
def hyp(a, b):
hyp = (a ** 2 + b ** 2) ** 0.5
return hyp
try:
assert hyp(3, 4) == 5
except AssertionError:
logger.warning("test failed")
|
import matplotlib.pyplot as plt
from randomwalk import RandomWalk
# 只要程序处于活动状态,就不断地模拟随机散步
while True:
# 创建一个RandomWalk实例,并将其包含的点都绘制出来
rw = RandomWalk(50000)
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues,
edgecolors='none', s=1)
plt.show()
keep_running = input("Make another walk?(y/n)")
if keep_running == 'n':
break |
import tensorflow as tf
from collections import namedtuple
def cnn_text(sentence_length, filter_sizes, num_filters,
embedded_chars_expanded):
# TODO : add some arguments to specify the embedding_size and the CNN layer's input.
"""
build a cnn text preprocessor for a domain.
Some of the code are from http://www.wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/.
The dimensions of every variable in the network is:
1. input_x, [the_number_of_user_in_each_batch, sentence_length]
2. embedded_chars_expanded, [the_number_of_user_in_each_batch, sentence_length, embedding_size, 1]
3. conv2:
* W, [filter_size, embedding_size, 1, num_filters]
* b, [num_filters]
the output of conv2 is [the_number_of_user_in_each_batch, sentence_length - filter_size + 1, embedding_size - embedding_size + 1, num_filters]
4. max_pool, [1, sentence_length - filter_size + 1, 1, 1]
the output of max_pool is [the_number_of_user_in_each_batch, 1, 1,num_filters]
5. tf.reshape, [the_number_of_user_in_each_batch, num_filters_total],
which means that every user in each batch is represented as a vector of a num_filters_total size.
Parameters
----------
sentence_length : int
specify the second dimention of input_x which represents the max length of a sentence.
vocab_size : int
the vocabulary size in text.
filter_sizes : iterable
the list which contains the filter size of every convolution kernel.
num_filters : int
the number of convolution kernels.
embedded_chars_expanded : Tensor
the input of the CNNTextProcessor.
Returns
-------
input_x
the should be use in feed_dict, {input_x: train_x}
h_drop
the output of the cnn text processor, should be used as the input of fm, or combined with user feature to form the input of fm.
drop_keep_prob
the prob of dropout layer, should be used in feed dict, {drop_keep_prob : 0.5}
"""
dropout_keep_prob = tf.placeholder(dtype=tf.float32, name="drop_keep_prob")
pooled_outputs = []
for i, filter_size in enumerate(filter_sizes):
with tf.name_scope("conv_maxpool_%s_%d" % (i, filter_size)):
filter_shape = [
filter_size, embedded_chars_expanded.shape[-2].value, 1,
num_filters
]
W = tf.Variable(
tf.truncated_normal(filter_shape, stddev=0.1), name="W")
b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b")
conv = tf.nn.conv2d(
embedded_chars_expanded,
W,
strides=[1, 1, 1, 1],
padding="VALID",
name="conv")
h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
pooled = tf.nn.max_pool(
h,
ksize=[1, conv.shape[1], 1, 1],
strides=[1, 1, 1, 1],
padding="VALID",
name="pool")
pooled_outputs.append(pooled)
num_filters_total = num_filters * len(filter_sizes)
h_pool = tf.concat(pooled_outputs, 3)
h_pool_flat = tf.reshape(h_pool, [-1, num_filters_total])
h_drop = tf.nn.dropout(h_pool_flat, dropout_keep_prob)
return h_drop, dropout_keep_prob
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.