text stringlengths 37 1.41M |
|---|
'''
Выполнить логические побитовые операции «И», «ИЛИ» и др. над числами 5 и 6.
Выполнить над числом 5 побитовый сдвиг вправо и влево на два знака. Объяснить полученный результат
Начало
5 & 6
5 | 5
5 ^ 5
5 << 2
5 >> 2
Вывод результатов операций
Конец
https://drive.google.com/file/d/1TgzDLuF-cYaGGbTcJxnhDKWibujMQ7dj/view?usp=sharing
'''
a = 5 & 6
b = 5 | 5
c = 5 ^ 5
d = 5 << 2
e = 5 >> 2
print(f'Побитовое И над числами 5 и 6 равно {a}.')
print(f'Побитовое ИЛИ над числами 5 и 6 равно {b}.')
print(f'Побитовое исключающее ИЛИ над числами 5 и 6 равно {c}.')
print(f'Побитовый сдвиг влево на два знака над числом 5 равен {d}. Мы 5 умножаем на 2 в степень равную количеству шагов сдвига, т.е. 5 * 4 = 20.')
print(f'Побитовый сдвиг вправо на два знака над числом 5 равен {e}. Мы 5 целочисленно делим на 2 в степени количества шагов, т.е. 5 // 4 = 1.')
|
'''
Creating a multiplication table with all the elements in the array. So
if your array is [2, 3, 7, 8, 10], you first multiply every element by 2,
then multiply every element by 3, then by 7, and so on.
'''
# To generate sample input arrays
import random
def mulArr(array):
if len(array) < 2:
return array
else:
arr1 = []
for i in range(0, len(array)):
pivot = array[i]
arr1 = [(pivot * item) for item in (array[0:i] + array[i+1:])]
arr1.insert(i, pivot * pivot)
print(pivot, arr1)
def RecMulArr(array, n): # Recursive Function
if n == len(array):
return "\nDone multiplying!"
else:
# Why is list(array) is used? Whenever you try to copy one array's contents into another's, only the REFERENCE OF THE ARRAY is copied. Not the contents.
arr1 = list(array)
pivot = arr1.pop(n)
if pivot >= 0: # Just for beautification of the Output
print(
f'Multiplying with +{pivot} : {[(pivot * item) for item in (array[:])]}')
else:
print(
f'Multiplying with {pivot} : {[(pivot * item) for item in (array[:])]}')
return RecMulArr(array, n+1)
array = []
for i in range(6): # number of numbers
array.append(random.randint(-9, 9)) # start and end limits
# array = [2, 4, 1, -3, -7, 0]
print(f'\nOriginal Array : {array}')
print("\n", end="")
print(RecMulArr(array, 0))
print("\n", end="")
# print(mulArr(array))
# def MulArr(array): # Non-recursive, only FIRST element is used to multiply
# if len(array) < 2:
# return array
# else:
# arr1 = list(array)
# # print(arr1)
# pivot = arr1.pop(0)
# # print(pivot, arr1)
# return [(pivot * item) for item in (array[:])]
# TESTS
# array = [30, 592, -9, 22, -13, 142]
# pivot = array[2] * array[2]
# array = [(array[2] * item) for item in (array[0:2] + array[2+1:])]
# array.insert(2, pivot)
# print(array)
|
'''
Excerpts from the book "Grokking Algorithms" by Aditya Bhargava:
D&C algorithms are RECURSIVE algorithms.
To solve a problem using D&C, there are two steps:
1. Figure out the base case. This should be the simplest possible case.
2. Divide or decrease your problem until it becomes the base case.
Euclid’s algorithm:
“If you find the biggest box that will work for this size, that will be the
biggest box that will work for the entire farm.”
Explanation of the algorithm:
https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm
'''
# Sample input : 3 5 9 13 14 22
def dividePlot(length, breadth, count=1):
if breadth == 0:
return length
else:
print(
f"Length: {breadth}, Breadth: {length % breadth}, Count: {count}")
return dividePlot(breadth, (length % breadth), count+1)
def binSearchDnC(low, high, array, item):
mid = int((low + high) / 2)
guess = array[mid]
if high >= low:
if guess == item:
return mid
elif guess < item:
return binSearchDnC(mid + 1, high, array, item)
elif guess > item:
return binSearchDnC(low, mid - 1, array, item)
else:
return None
def quickSort(array):
if len(array) < 2: # Empty array or array with only one element
return array
else:
pivot = array[0]
lesser = [i for i in array[1:] if i <= pivot]
greater = [i for i in array[1:] if i > pivot]
return quickSort(lesser) + [pivot] + quickSort(greater)
if __name__ == "__main__":
divi = "dividePlotexe"
bins = "binSearchDnCexe"
inp = input(
"Enter:\n'divi' if you want to divide a plot\n'bins' if you want to search for an item in an array:\n")
print("\n")
def dividePlotexe(l, b):
sideOfSquare = dividePlot(l, b)
print(
f'The plot of {l} x {b} can be divided into {(l * b) / (sideOfSquare * sideOfSquare)} square(s) with side = {sideOfSquare}')
def binSearchDnCexe(low, high, array, item):
if binSearchDnC(low, high, array, item) == None:
print(f"{item} not found in array {array}!")
else:
print(
f'{item} is located at index {binSearchDnC(low, high, array, item)} in {array}.')
fname = globals()[inp] # Convert string to function call1
func = globals()[fname] # Convert string to function call2
if inp == 'divi':
l = int(input('Enter length (> breadth) of plot: '))
b = int(input('Enter breadth (< length) of plot: '))
print("\n")
func(l, b)
if inp == 'bins':
array = list(map(int, input("Enter array: ").split()))
if array == []:
print("Empty array! Aborting.")
else:
array = quickSort(array)
print(f"Array has been modified to: {array}")
item = int(input("Enter number you want to search for: "))
func(0, len(array) - 1, array, item)
|
import sys
def show_sizeof(x,level=0):
print "\t"*level,x.__class__, sys.getsizeof(x), x
if hasattr(x,'__iter__'):
if hasattr(x,'items'):
print "iterating items..."
for xx in x.items():
show_sizeof(xx,level+1)
else:
print "iterating a list ..."
for xx in x:
show_sizeof(xx,level+1)
#show_sizeof(None)
#show_sizeof(3)
#show_sizeof(2**63)
#show_sizeof(102947298469128649161972364837164)
#show_sizeof(918659326943756134897561304875610348756384756193485761304875613948576297485698417)
#show_sizeof(3.14159265358979323846264338327950288)
show_sizeof([4,"toaster",230.1,"sdsdsss", "sdddddxxxxxxxx", "yyyyzzzzzzpppppp", "llllkkkkkk"])
|
def print_board(board):
#impressão dos índices das colunas:
print(" ",end='')
for coluna in range(len(board)):
if coluna!=0:
print(" | %4d " %(coluna), end='')
print(" | %4d |" %(coluna+1))
print(" ",end='')
for coluna in range(len(board)+1):
print("+---------", end='-')
print("+")
#impressão das linhas:
for linha in range(len(board[0])+1):
if linha!=0:
print(" | %4d " %(linha), end='')
for j in range(len(board)-1):
print(" | %4s " %(board[linha-1][j]), end='')
j=len(board[0])-1
print(" | %4s |" %(board[linha-1][j]))
print(" ",end='')
for j in range(len(board)+1):
print("+---------", end='-')
print("+")
#---------------------------------------------------------------------------------#
def colocar_ship(tipo,tamanho,ships_board):
from random import randint
ok=True
flag=True
possivel=True
while flag:
ship_x=randint(0,9)
ship_y=randint(0,9)
ship_x_a=ship_x
ship_y_a=ship_y
if ships_board[ship_x][ship_y]=="O":
flag=False
ships_board[ship_x][ship_y]=tipo
primeiro_x=ship_x
primeiro_y=ship_y
if tamanho>1:
while ok:
if ship_x!=0 and ship_x!=9 and ship_y!=0 and ship_y!=9:
number=randint(1,4)
if number==1:
ship_x+=1
elif number==2:
ship_x-=1
elif number==3:
ship_y+=1
elif number==4:
ship_y-=1
elif ship_x==0:
if ship_y==0:
number=randint(1,2)
if number==1:
ship_x+=1
elif number==2:
ship_y+=1
elif ship_y==9:
number=randint(1,2)
if number==1:
ship_x+=1
elif number==3:
ship_y-=1
else:
number=randint(1,3)
if number==1:
ship_x+=1
elif number==2:
ship_y+=1
elif number==3:
ship_y-=1
elif ship_x==9:
if ship_y==0:
number=randint(1,2)
if number==1:
ship_x-=1
elif number==2:
ship_y+=1
elif ship_y==9:
number=randint(1,2)
if number==1:
ship_x-=1
elif number==3:
ship_y-=1
else:
number=randint(1,3)
if number==1:
ship_x-=1
elif number==2:
ship_y+=1
elif number==3:
ship_y-=1
elif ship_y==0:
number=randint(1,3)
if number==1:
ship_x-=1
elif number==2:
ship_y+=1
elif number==3:
ship_x-=1
else:
number=randint(1,3)
if number==1:
ship_x-=1
elif number==2:
ship_x+=1
elif number==3:
ship_y-=1
if ships_board[ship_x][ship_y]=="O":
ok=False
if ok:
ship_x=primeiro_x
ship_y=primeiro_y
ships_board[ship_x][ship_y]=tipo
segundo_x=ship_x
segundo_y=ship_y
passo=2 #quanto somar na coordenada
vertical=False
horizontal=False
while tamanho>2:
if ship_x!=ship_x_a:
if ship_x==0:
ship_x+=passo
ship_x_a=ship_x-1
elif ship_x==9:
ship_x-=passo
ship_x_a=ship_x+1
else:
if ship_x-ship_x_a==1:
ship_x+=1
ship_x_a=ship_x-1
elif ship_x-ship_x_a==-1:
ship_x-=1
ship_x_a=ship_x+1
else:
if ship_y==0:
ship_y+=passo
ship_y_a=ship_y-1
elif ship_y==9:
ship_y-=passo
ship_y_a=ship_y+1
else:
if ship_y-ship_y_a==1:
ship_y+=1
ship_y_a=ship_y-1
elif ship_y-ship_y_a==-1:
ship_y-=1
ship_y_a=ship_y+1
tamanho-=1
passo+=1
ships_board[ship_x][ship_y]=tipo
#--------------------------------------------------#
board=[]
for i in range (0,10):
board.append(["O"]*10)
ships_board=[]
for i in range (0,10):
ships_board.append(["O"]*10)
#Montar o tabuleiro:
#Aircraft Carrier(x1)
colocar_ship("PA",5,ships_board)
#Battleship(x1)
colocar_ship("CO",4,ships_board)
#Cruiser(x1)
colocar_ship("CR",3,ships_board)
#Patrol Boat(x2)
colocar_ship("TD",2,ships_board)
colocar_ship("TD",2,ships_board)
#Submarine(x2)
colocar_ship("SM",1,ships_board)
colocar_ship("SM",1,ships_board)
#jogo
print("BATALHA NAVAL!")
print("O jogo é composto por 6 barcos:")
print("-1 Porta-aviões (5 casas)")
print("-1 Couraçado (4 casas)")
print("-1 Cruzeiro (3 casas)")
print("-2 Torpedeiro (2 casas)")
print("-2 Submarinos (1 casa)")
jogo_nao_acabou=True
print_board(board)
escolha_jogador=input("Escolha uma casa (Ex: linha,coluna) ")
while jogo_nao_acabou:
jogada=escolha_jogador.split(",")
jogada[0]=int(jogada[0])
jogada[1]=int(jogada[1])
if ships_board[jogada[0]-1][jogada[1]-1]=="O":
print("ÁGUAA!")
board[jogada[0]-1][jogada[1]-1]="X"
elif ships_board[jogada[0]-1][jogada[1]-1]=="PA":
if pa<5:
print("Parabéns, você acertou o Porta-aviões!")
elif pa==5:
print("Você destruiu o Porta-aviões!")
board[jogada[0]-1][jogada[1]-1]="PA"
elif ships_board[jogada[0]-1][jogada[1]-1]=="CO":
if co<4:
print("Parabéns, você acertou o Couraçado!")
elif co==4:
print("Você destruiu o Couraçado!")
board[jogada[0]-1][jogada[1]-1]="CO"
elif ships_board[jogada[0]-1][jogada[1]-1]=="CR":
if cr<3:
print("Parabéns, você acertou o Cruzeiro!")
elif cr==3:
print("Você destruiu o Cruzeiro!")
board[jogada[0]-1][jogada[1]-1]="CR"
elif ships_board[jogada[0]-1][jogada[1]-1]=="TD":
print("Parabéns, você acertou o Torpedeiro!")
board[jogada[0]-1][jogada[1]-1]="TD"
elif ships_board[jogada[0]-1][jogada[1]-1]=="SM":
print("Você destruiu um Submarino!")
board[jogada[0]-1][jogada[1]-1]="SM"
print_board(board)
pa=0
co=0
cr=0
td=0
sm=0
for row in board:
for i in row:
if i=="PA":
pa+=1
elif i=="CO":
co+=1
elif i=="CR":
cr+=1
elif i=="TD":
td+=1
elif i=="SM":
sm+=1
if pa==5 and co==4 and cr==3 and td==4 and sm==2:
jogo_nao_acabou=False
if jogo_nao_acabou==False:
print("Parabéns, você venceu!!")
else:
print("Para desistir e ver onde estavam os barcos digite (d)")
print("Para saber quais os barcos do jogo, digite (s)")
saber_o_que_falta=input("Para continuar APERTE ENTER ")
if saber_o_que_falta=="s":
print("1 Porta-aviões (5 casas), 1 Couraçado (4 casas), 1 Cruzeiro (3 casas), 2 Torpedeiros (2 casas), 2 Submarinos (1 casa)")
elif saber_o_que_falta=="d":
print("Ok, até a próxima!")
print_board(ships_board)
jogo_nao_acabou=False
if jogo_nao_acabou:
escolha_jogador=input("Escolha outra casa: ")
|
def seperator():
for i in range(100):
print("*", end = '')
print()
def count_instances(string, letter):
step = len(letter)
choice = input("Enter \'y\' if cases are to be considered: ")
if choice == 'y':
pass
else:
string = string.lower()
letter = letter.lower()
curr = 0
count = 0
while curr + step <= len(string):
op_string = string[curr: curr + step]
curr += step
if op_string == letter:
count += 1
return count
def letter_counter():
string = input("Please enter the string that is to be operated on=>\n")
letter = input("Please enter letter whose total instances are to be found: ")
if letter in string:
count = count_instances(string, letter)
print(f"There are {count} instances of \'{letter}\' in given string")
else:
print(f"Sorry \'{letter}\' is not in the given string")
seperator()
def greet():
name = input('What is your name:')
print(f'Hello {name.title()}')
seperator()
print("This is a letter counter; here we will tell you how many instances of a certain charachter there is in a string")
print()
if __name__ == '__main__':
greet()
letter_counter() |
print ("This will be a number comparison.")
print ("first number.")
userinput1 = input ()
print ("Second number.")
userinput2 = input ()
if userinput1 > userinput2:
print ("first number is bigger.")
elif userinput1 < userinput2:
print ("first number is smaller.")
else:
print ("Both are equal") |
print ("How many bars should be charged")
chargebars = int(input())
charged = 0
print()
while (charged < chargebars ):
charged = charged + 1
print ("Charging", "█" * charged)
print ("done charging")
|
def observed():
observations = []
for count in range(7):
print("Please enter an observation:")
observations.append(input())
return observations
def run():
print("Counting observations...")
observations = observed()
# populate set
observations_set = set()
for observation in observations:
data = (observation, observations.count(observation))
observations_set.add(data)
# display set
for data in observations_set:
print(f"{data[0]} observed {data[1]} times.")
run()
|
print ("How Far are we from the cave")
steps = int (input ())
# Display count down
print ()
for count in range(steps, 0, -1):
print(count, "steps remaining")
print("We have reached the cave!")
|
print("Towards which direction should I paint (up, down, left or right)?")
direction = input ()
if (direction == "up"):
print ("you are painting up")
elif (direction == "down"):
print ("you are painting down")
elif (direction == "left"):
print ("you are painting left")
elif (direction == "right"):
print ("you are painting right")
else:
print ("You have a incorrect input")
print ("Finished")
|
'''
a decorator function accepts a function as an argument and returns a modified function
without syntactic sugar, we pass our function to the decorator and get an
enhanced function returned back; we can then run this new function
with syntactic sugar, we run in one line
'''
# ==============================================================================
# simple decorator function
def my_decorator(fn):
def wrapper():
print("Before function is called")
fn()
print("After function is called")
return wrapper
def my_decorator_with_args(*args):
return my_decorator
# without sugar
def just_some_function1():
print("Wheee!")
# with sugar
@my_decorator
def just_some_function2():
print("Whooo!")
# with args
@my_decorator_with_args(1, 2)
def just_some_function3():
print("Whaaa!")
# ==============================================================================
# chained decorator
def makebold(fn):
def wrapper():
return "<b>" + fn() + "</b>"
return wrapper
def makeitalic(fn):
def wrapper():
return "<i>" + fn() + "</i>"
return wrapper
@makebold
@makeitalic
def hello():
return "hello world"
# ==============================================================================
# decorator with arguments
# need an extra nested function because first job is to return
# function without args
def decorator_with_args(arg1, arg2, arg3):
def wrap(fn):
print("Inside wrap()") # executes when function is constructed
def wrapper(*args): # a1, a2, a3, a4
print("Inside wrapped_f()")
print("decorator_with_args arguments:", arg1, arg2, arg3)
fn(*args)
print("After f(*args)")
return wrapper
return wrap
@decorator_with_args("hello", "world", 42)
def say_hello(a1, a2, a3, a4):
print('say_hello arguments:', a1, a2, a3, a4)
# ==============================================================================
import pdb; pdb.set_trace()
print('===== simple decorator function =====')
# without sugar
f1 = my_decorator(just_some_function1)
f1()
# with sugar
just_some_function2()
# with args
just_some_function3()
print('===== chained decorator =====')
print(hello())
print('===== decorator with arguments =====')
say_hello("say", "hello", "argument", "list")
pass
|
import unittest
from decorators import accepts
@accepts(str, int)
def acceptTestFunc(string, integer):
return f'{string} {integer}'
class TestDecorators(unittest.TestCase):
def test_accept_raises_exception_when_args_types_do_not_match_the_decorator_args(self):
with self.subTest('Second arg type does not match the decorator arg'):
with self.assertRaises(TypeError) as e:
acceptTestFunc('str', 'str')
self.assertEqual(
str(e.exception),
'Argument 1 of acceptTestFunc is not int'
)
with self.subTest('Both arg types do not match the decorator args'):
with self.assertRaises(TypeError) as e:
acceptTestFunc([], [])
self.assertEqual(
str(e.exception),
'Argument 0 of acceptTestFunc is not str'
)
def test_accept_decorator_doesnt_change_the_func_output(self):
with self.subTest('Func args types match the decorators args'):
self.assertEqual(
acceptTestFunc('Anton', 20),
'Anton 20'
)
if __name__ == '__main__':
unittest.main()
|
import re
import os
from money_tracker import MoneyTracker
class MoneyTrackerMenu:
def __init__(self):
os.system('clear')
self._user_name = input('Enter user name:')
self.initialize_file_and_money_tracker()
self.initialize_options()
self.date_message = '(Format of the date is DD,MM,YYYY)\nEnter date:'
def initialize_file_and_money_tracker(self):
information_entered = False
while information_entered is False:
try:
self._file_with_data = input('Enter file to load:')
self._money_tracker = MoneyTracker(self._file_with_data)
information_entered = True
os.system('clear')
except Exception:
print('The file name is incorect or its content is invalid!')
def initialize_options(self):
self.options = ['1', '2', '3', '4', '5', '6', '7']
self.options_functions = [self.option_one, self.option_two,
self.option_three, self.option_four,
self.option_five, self.option_six,
self.option_seven]
def start(self):
self.working = True
option_chosen = ''
while self.working is True:
self.print_menu_options()
option_chosen = input()
if option_chosen not in self.options:
print('Invalid option, try again!')
else:
self.options_functions[int(option_chosen) - 1]()
if self.working is True:
input('Press enter to continue:')
os.system('clear')
def print_menu_options(self):
print(f'Hello, {self._user_name}!\n'
'Choose one of the following options to continue:\n'
'1 - show all data\n'
'2 - show data for specific date\n'
'3 - show expenses, ordered by categories\n'
'4 - add new income\n'
'5 - add new expense\n'
'6 - exit without saving\n'
'7 - exit and save\n')
def option_one(self):
print(self._money_tracker.list_user_data())
def option_two(self):
try:
day, month, year = self.date_parser(input(self.date_message))
print(self._money_tracker.show_user_data_per_date(day,
month, year))
except ValueError as ex:
print(f'\nError!\n{ex}\n')
def option_three(self):
print(self._money_tracker.list_user_exepences_ordered_by_categories())
def option_four(self):
try:
day, month, year = self.date_parser(input(self.date_message))
category = input('Category of income:')
amount = self.amount_parser(input('Amount of income:'))
self._money_tracker.add_income(day, month, year, category, amount)
except ValueError as ex:
print(f'\nError!\n{ex}\n')
def option_five(self):
try:
day, month, year = self.date_parser(input(self.date_message))
category = input('Category of expence:')
amount = self.amount_parser(input('Amount of expense:'))
self._money_tracker.add_expence(day, month, year, category, amount)
except ValueError as ex:
print(f'\nError!\n{ex}\n')
def option_six(self):
self.working = False
def option_seven(self):
self.working = False
self.save_data_in_a_file()
def save_data_in_a_file(self):
with open(self._file_with_data, 'w') as f:
f.write(self._money_tracker.list_user_data())
@staticmethod
def date_parser(date):
if re.match(r'\d{1,2},\d{1,2},\d{4}', date) is None:
raise ValueError('The date is invalid!')
parts = date.split(',')
return int(parts[0]), int(parts[1]), int(parts[2])
@staticmethod
def amount_parser(amount):
try:
checked_amount = float(amount)
return checked_amount
except Exception:
raise ValueError('The amount should be a number!')
|
class Bill:
def __init__(self, amount):
if isinstance(amount, int) is False:
raise TypeError("Amount must be integer!")
if amount < 0:
raise ValueError("Amount must be positive!")
self.amount = amount
def __str__(self):
return str(self.amount)
def __int__(self):
return self.amount
def __eq__(self, other):
return self.amount == other.amount
def __repr__(self):
return str(self.amount)
def __hash__(self):
return hash(self.amount)
|
import sys
sys.path.insert(0, '/home/anton/HackBulgaria/week01')
from firstDay import to_digits
from secondDay import group
def is_number_balanced(number):
digits = to_digits(number)
if (len(digits) % 2 == 0):
return (sum(digits[0: len(digits) // 2]) ==
sum(digits[len(digits) // 2:]))
return (sum(digits[0: len(digits) // 2]) ==
sum(digits[len(digits) // 2 + 1:]))
# print(is_number_balanced(1238033))
# print(is_number_balanced(4518))
# print(is_number_balanced(9))
# print(is_number_balanced(28471))
# print(is_number_balanced(1238033))
def increasing_or_decreasing(seq):
is_up = True
is_down = True
for i in range(0, len(seq) - 1):
if seq[i] >= seq[i + 1]:
is_up = False
if seq[i] <= seq[i + 1]:
is_down = False
if is_up:
return "Up!"
if is_down:
return "Down!"
return False
# print(increasing_or_decreasing([1, 2, 3, 4, 5]))
# print(increasing_or_decreasing([5, 6, -10]))
# print(increasing_or_decreasing([1, 1, 1, 1]))
# print(increasing_or_decreasing([9, 8, 7, 6]))
def get_largest_palindrome(n):
for i in reversed(range(0, n)):
if str(i) == str(i)[::-1]:
return i
return 0
# print(get_largest_palindrome(99))
# print(get_largest_palindrome(252))
# print(get_largest_palindrome(994687))
# print(get_largest_palindrome(754649))
def sum_of_numbers(input_string):
result = 0
curr_number = ""
for x in input_string:
if x.isdigit():
curr_number += x
else:
if curr_number != "":
result += int(curr_number)
curr_number = ""
if curr_number != "":
result += int(curr_number)
return result
# print(sum_of_numbers("ab125cd3"))
# print(sum_of_numbers("ab12"))
# print(sum_of_numbers("ab"))
# print(sum_of_numbers("1101"))
# print(sum_of_numbers("1111O"))
# print(sum_of_numbers("1abc33xyz22"))
# print(sum_of_numbers("0hfabnek"))
def birthday_ranges(birthdays, ranges):
return [(sum([i >= x[0] and i <= x[1] for i in birthdays]))
for x in ranges]
# print(birthday_ranges([1, 2, 3, 4, 5],
# [(1, 2), (1, 3), (1, 4), (1, 5), (4, 6)]))
# print(birthday_ranges([5, 10, 6, 7, 3, 4, 5, 11, 21, 300, 15],
# [(4, 9), (6, 7), (200, 225), (300, 365)]))
digit_to_letters = {
2: "abc",
3: "def",
4: "ghi",
5: "jkl",
6: "mno",
7: "pqrs",
8: "tuv",
9: "wxyz"
}
CAPITALIZE = 1
SPACE = 0
END_SEQUENCE = -1
def numbers_to_message(pressed_sequence):
message = ""
grouped_sequence = group(pressed_sequence)
to_capital = False
for x in grouped_sequence:
if x == [1]:
to_capital = True
elif x == [0]:
message += " "
elif x == [-1]:
continue
else:
letter = digit_to_letters[x[0]][(len(x) - 1) %
len(digit_to_letters[x[0]])]
if to_capital:
message += letter.upper()
else:
message += letter
to_capital = False
return message
# print(numbers_to_message([2, -1, 2, 2, -1, 2, 2, 2]))
# print(numbers_to_message([2, 2, 2, 2]))
# print(numbers_to_message([1, 4, 4, 4, 8, 8, 8, 6, 6, 6, 0, 3,
# 3, 0, 1, 7, 7, 7, 7, 7, 2, 6, 6, 3, 2]))
def letter_to_numbers(letter):
for button, letters in digit_to_letters.items():
if letter in letters:
return [button] * (letters.index(letter) + 1)
def message_to_numbers(message):
numbers = []
prev = -1
for x in message:
if x == " ":
numbers.append(0)
else:
numbers_list = letter_to_numbers(x.lower())
if x.isupper():
numbers.append(1)
elif prev == numbers_list[0]:
numbers.append(-1)
numbers.extend(numbers_list)
prev = numbers_list[0]
return numbers
# print(message_to_numbers("abc"))
# print(message_to_numbers("a"))
# print(message_to_numbers("Ivo e Panda"))
# print(message_to_numbers("aabbcc"))
def elevator_trips(people_weight, people_floors, elevator_floors,
max_people, max_weight):
trips_count = 0
people_in_elevator, weight_in_elevator = 0, 0
floors_visited = set()
for person in people_weight[:len(people_floors)]:
if (person + weight_in_elevator > max_weight or
people_in_elevator + 1 > max_people):
trips_count += len(floors_visited) + 1
people_in_elevator, weight_in_elevator = 0, 0
floors_visited = set()
floors_visited.add(people_floors[people_weight.index(person)])
people_in_elevator += 1
weight_in_elevator += person
if len(floors_visited) != 0:
trips_count += len(floors_visited) + 1
return trips_count
# print(elevator_trips([], [], 5, 2, 200))
# print(elevator_trips([40, 50], [], 5, 2, 200))
# print(elevator_trips([40, 40, 100, 80, 60], [2, 3, 3, 2, 3], 3, 5, 200))
# print(elevator_trips([80, 60, 40], [2, 3, 5], 5, 2, 200))
def char_histogram(string):
dictionary = {}
for x in string:
if x in dictionary:
dictionary[x] += 1
else:
dictionary[x] = 1
return dictionary
def anagrams():
words = input().split(' ')
first_word = char_histogram(words[0].lower())
second_word = char_histogram(words[1].lower())
if first_word == second_word:
return "ANAGRAMS"
return "NOT ANAGRAMS"
# print(anagrams())
def helper(idx, digit):
if idx % 2 == 1:
if (2 * int(digit) > 10):
return 2 * int(digit) - 9
return 2 * int(digit)
return int(digit)
def is_credit_card_valid(number):
return sum([helper(idx, digit)
for idx, digit in enumerate(str(number)[::-1])]) % 10 == 0
print(is_credit_card_valid(79927398713))
print(is_credit_card_valid(79927398715))
def is_prime(n):
return n > 1 and all([n % i for i in range(2, n)])
def goldbach(n):
return [(x, n - x) for x in range(2, n // 2 + 1)
if is_prime(x) and is_prime(n - x)]
print(goldbach(4))
print(goldbach(6))
print(goldbach(8))
print(goldbach(10))
print(goldbach(100))
def bombed_position(m, x, y, curr_x, curr_y):
if (x >= 0 and y >= 0 and x < len(m) and y < len(m[x])):
m[x][y] = max(m[x][y] - m[curr_x][curr_y], 0)
def bomb_position_and_sum(matrix, x, y):
directions = [(1, 0), (-1, 0), (0, 1), (0, -1),
(1, 1), (-1, -1), (1, -1), (-1, 1)]
m = [list(row) for row in matrix]
for x1, y1 in directions:
bombed_position(m, x + x1, y + y1, x, y)
return sum(map(sum, m))
def matrix_bombing_plan(m):
dict_matrix = {}
for row in range(len(m)):
for col in range(len(m[row])):
dict_matrix[(row, col)] = bomb_position_and_sum(m, row, col)
return dict_matrix
# print(matrix_bombing_plan([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
STAY_IN_THE_SAME = '.'
GO_BACK = '..'
UNNECESSERY = ''
def reduce_file_path(path):
directs = path.split("/")
reduced_path = []
for direc in directs:
if direc == UNNECESSERY or direc == STAY_IN_THE_SAME:
continue
elif direc == GO_BACK:
if reduced_path != []:
reduced_path.pop()
else:
reduced_path += ['/' + direc]
if reduced_path == []:
return "/"
return "".join(reduced_path)
# print(reduce_file_path("/"))
# print(reduce_file_path("/srv/../"))
# print(reduce_file_path("/srv/www/htdocs/wtf/"))
# print(reduce_file_path("/srv/www/htdocs/wtf"))
# print(reduce_file_path("/srv/./././././"))
# print(reduce_file_path("/etc//wtf/"))
# print(reduce_file_path("/etc/../etc/../etc/../"))
# print(reduce_file_path("//////////////"))
# print(reduce_file_path("/../"))
|
import unittest
from client import Client
from exceptions import InvalidPassword
class ClientTests(unittest.TestCase):
def setUp(self):
self.test_client = Client(1, "Ivo", 200000.00,
'Bitcoin mining makes me rich', "ivo@abv.bg")
def test_client_id(self):
self.assertEqual(self.test_client.get_id(), 1)
def test_client_name(self):
self.assertEqual(self.test_client.get_username(), "Ivo")
def test_client_balance(self):
self.assertEqual(self.test_client.get_balance(), 200000.00)
def test_client_message(self):
self.assertEqual(self.test_client.get_message(), "Bitcoin mining makes me rich")
def test_validate_password_returns_False(self):
with self.subTest('username is substring of the password!'):
with self.assertRaisesRegex(InvalidPassword,
'The password should\'t contain the username!'):
Client.validate_password('#Antonski1', 'tons')
with self.subTest('password is shorter than 8 symbols'):
with self.assertRaisesRegex(InvalidPassword,
'The password should be longer then 8 symbols!'):
Client.validate_password('#Aa1arg', 'Z')
with self.subTest('passwort does\'t contain any digits'):
with self.assertRaisesRegex(InvalidPassword,
'The password must contain a digit!'):
Client.validate_password('#Aaargqwe', 'Z')
with self.subTest('passwort does\'t contain any capital letters'):
with self.assertRaisesRegex(InvalidPassword,
'The password must contain a capital letter!'):
Client.validate_password('#aargqwe1', 'Z')
with self.subTest('passwort does\'t contain any special symbol'):
with self.assertRaisesRegex(InvalidPassword,
'The password must contain a special symbol!'):
Client.validate_password('Aaargqwe1', 'Z')
def test_validate_password_returns_True(self):
try:
Client.validate_password('#anton1Naumov', 'Toni')
except InvalidPassword as e:
self.fail(e)
if __name__ == '__main__':
unittest.main()
|
def count_substrings(haystack, needle):
counter = 0
x = 0
while x <= len(haystack) - len(needle):
if haystack[x: x + len(needle)] == needle:
counter += 1
x += len(needle)
else:
x += 1
return counter
# print("count_substrings tests:")
# print(count_substrings("This is a test string", "is"))
# print(count_substrings("babababa", "baba"))
# print(count_substrings("Python is an awesome language to program in!", "o"))
# print(count_substrings("We have nothing in common!", "really?"))
# print(count_substrings("This is this and that is this", "this"))
def sum_matrix(m):
# return sum(map(sum, m))
return sum([sum(line) for line in m])
# print("sum_matrix tests:")
# print(sum_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
# print(sum_matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]]))
# print(sum_matrix([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]))
def nan_expand(times):
if (times == 0):
return ""
return "".join(["Not a " for x in range(0, times)]) + "NaN"
# print("nan_expand tests:")
# print(nan_expand(0))
# print(nan_expand(1))
# print(nan_expand(2))
# print(nan_expand(3))
def is_prime(n):
return sum([(n % i == 0) for i in range(2, n)]) == 0
def prime_factorization(n):
resultList = []
for x in range(2, n + 1):
if is_prime(x):
bestPower = 0
for y in range(1, n):
if (n % (x ** y) == 0):
bestPower = y
if bestPower != 0:
resultList.append((x, bestPower))
n //= (x ** bestPower)
if (n == 1):
return resultList
# print("prime_factorization tests:")
# print(prime_factorization(10))
# print(prime_factorization(14))
# print(prime_factorization(356))
# print(prime_factorization(89))
# print(prime_factorization(1000))
def my_group(l):
resultList = []
currIdx = 0
while (currIdx < len(l)):
nextList = [l[currIdx]]
currIdx += 1
while currIdx < len(l) and l[currIdx] == nextList[0]:
nextList.append(l[currIdx])
currIdx += 1
resultList.append(nextList)
return resultList
def group(arr):
result = []
current_group = [arr[0]]
for item in arr[1:]:
if item == current_group[0]:
current_group.append(item)
else:
result.append(current_group)
current_group = [item]
result.append(current_group)
return result
# print("group tests:")
# print(group([1, 1, 1, 2, 3, 1, 1]))
# print(group([1, 2, 1, 2, 3, 3]))
def max_consecutive(items):
return max([len(subS) for subS in group(items)])
# print("max_consecutive tests:")
# print(max_consecutive([1, 2, 3, 3, 3, 3, 4, 3, 3]))
# print(max_consecutive([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 5]))
def check_dir(matrix, x, y, dirX, dirY, currWord, word):
if (x < 0 or y < 0 or x >= len(matrix) or y >= len(matrix[0])):
return False
currWord += matrix[x][y]
if (currWord == word):
return True
return check_dir(matrix, x + dirX, y + dirY, dirX, dirY, currWord, word)
def count_words(matrix, word):
directions = [(1, 0), (-1, 0), (0, 1), (0, -1),
(1, 1), (-1, -1), (1, -1), (-1, 1)]
counter = 0
for x in range(0, len(matrix)):
for y in range(0, len(matrix[x])):
for x1, y1 in directions:
counter += check_dir(matrix, x, y, x1, y1, "", word)
if (word == word[::-1]):
return counter // 2
return counter
def take_matrix_input():
word = input()
sizeOfMatrix = input().split(" ")
rows = int(sizeOfMatrix[0])
matrix = []
for x in range(0, rows):
matrix.append(input().split(" "))
print(count_words(matrix, word))
# take_matrix_input()
def gas_stations(distance, tank_size, stations):
stations_visited = []
fuel = tank_size - stations[0]
stations.append(distance)
for x in range(0, len(stations) - 1, 1):
distance_to_next_station = stations[x + 1] - stations[x]
# if distance_to_next_station > tank_size:
# print("It is not possible to travel the distance!")
# return
if distance_to_next_station > fuel:
stations_visited.append(stations[x])
fuel = tank_size
fuel -= distance_to_next_station
return stations_visited
# print("gas_stations tests:")
# print(gas_stations(320, 90, [50, 80, 140, 180, 220, 290]))
# print(gas_stations(390, 80, [70, 90, 140, 210, 240, 280, 350]))
# print("Printing test %.5d on day %.2f." % (1, 2))
|
import camelCase # Name of file
from unittest import TestCase
class TestCamelCase(TestCase):
def test_camelcase_sentance(self):
self.assertEqual('helloWorld', camelCase.camelcase('Hello World'))
self.assertEqual('minnesotaVikings', camelCase.camelcase(' MInnesota vIKINGS '))
self.assertEqual('', camelCase.camelcase(''))
self.assertEqual('mVP', camelCase.camelcase(' M v p'))
self.assertEqual('!@#$%', camelCase.camelcase(' ! @ # $ % '))
# Test program with -> python -m unittest test_camelCase.py
|
import random
class zipf():
"""
This class implement some methods for zipf distribution.
"""
def __init__(self, d=10):
"""
The constructor for zipf class.
Attributes:
category (int): How many category that want to be generated.
"""
self.d = d
self.indices = [i for i in range(d)]
self.weights = [1 / w for w in range(1, d + 1)]
def gen_data(self, amount):
"""
The function to generate data which distribution follow zipf's law.
Parameters:
amount (int): Total amount that want to be generated.
Returns:
Data which distribution follow zipf's law.
"""
return random.choices(self.indices, weights=self.weights, k=amount)
def getValue(self):
"""
The function to get an index following zipf's law.
Returns:
Index(range from 0 to self.d - 1).
"""
return random.choices(self.indices, weights=self.weights, k=1)[0]
# if __name__ == "__main__":
# d = 10
# amount = 10000
# total = [0] * d
# z = zipf(category)
# data = z.gen_data(amount)
# for d in data:
# total[d] += 1
# print(total)
|
# Link to tthe problem
# https://www.hackerrank.com/challenges/angry-professor/problem
def angryProfessor(k, a):
count = 0
for time in a:
if time <= 0:
count += 1
if count >= k:
return "NO"
return "YES"
total = 3
times = [-1,-3,4,2]
print(angryProfessor(total, times)) |
from flask import Flask
from flask_restful import Api, Resource, reqparse
app = Flask(__name__)
api = Api(app)
# Not a real way to store data for an actual project.
# Using a global dicitonary just for an example.
users = {
"Nick": {"name": "Nick", "age": 42, "job": "programmer"},
"Elvin": {"name": "Elvin", "age": 30, "job": "doctor"},
"Jim": {"name": "Jim", "age": 22, "job": "salesperson"}
}
class User(Resource):
def get(self, name):
if name in users:
return users[name], 200
return "User not found", 404
def post(self, name):
parser = reqparse.RequestParser()
parser.add_argument("age")
parser.add_argument("job")
args = parser.parse_args()
if name in users:
return f"User with name {name} already exists", 400
user = {"name": name, "age": args["age"], "job": args["job"]}
users[name] = user
return user, 201
def put(self, name):
parser = reqparse.RequestParser()
parser.add_argument("age")
parser.add_argument("job")
args = parser.parse_args()
if name in users:
users[name]["age"] = args["age"]
users[name]["job"] = args["job"]
return users[name], 200
user = {"name": name, "age": args["age"], "job": args["job"]}
users[name] =user
return user, 201
def delete(self, name):
global users
if name in users:
del users[name]
return f"{name} is deleted.", 200
class Display(Resource):
def get(self):
return users, 200
api.add_resource(Display, "/display/")
api.add_resource(User, "/user/<string:name>")
app.run(debug=True)
|
#!/usr/local/bin/python3
# Can use 'in' to check if value is in a list.
# Use 'not in' to see if value is missing from list.
def check_for_ringo(band):
if "Ringo" in band:
print("I'm a real drummer!")
elif "ringo" in band:
print("I guess I can call .capitalize() on myself.")
else:
print("Ringo is sad :(")
band_members = ["John", "Paul", "George"]
check_for_ringo(band_members)
if "Ringo" not in band_members and "ringo" not in band_members:
band_members.append("ringo")
check_for_ringo(band_members)
# Can check if a list is empty by providing the
# list in a conditional.
if band_members:
print("There are band members!")
while band_members:
print(f"{band_members.pop()} was in the band!")
if not band_members:
print("No more band members.")
|
def continue_example():
try:
for i in range(10):
continue
finally:
print("This prints for continue")
def break_example():
try:
for i in range(10):
break
finally:
print("This prints for break")
def return_example():
try:
for i in range(10):
if i == 5:
print("Going to return")
return
finally:
print("This prints for return")
continue_example()
break_example()
return_example()
|
from stack import Stack
class UniqueStack(Stack):
"""
UniqueStack has the same methods and functionality as Stack, but will only store one
copy of a particular item at a time.
If push is called with an item that is already in the UniqueStack, a ValueError should be raised
with an appropriate error message.
If push is called where item equals None, a TypeError should be raised like in the base class.
Define and implement the relevant methods from the base Stack class to enable the behavior
described above. New versions of __init__(), push(), and pop() should be sufficient.
Hint: One option to implement this is to maintain an internal set() alongside the internal list.
"""
# Add mehods here. Remove this comment and the next line before doing so.
pass
class LimitedStack(Stack):
"""
A LimitedStack has the same methods and functionality as Stack, but will only hold up to a certain
number of items.
The __init__ method for LimitedStack should take a single, positive integer as an argument. This will
be the maximum number of items that the LimitedStack can hold. If push is called with an item and that
item would go beyond the LimitedStack's capacity, the item is not added to the LimitedStack and a
LimitedStack.LimitedStackOverflowError should be raised.
If push is called where item equals None, a TypeError should be raised like in the base class.
If __init__ is called with a non-integer argument, a TypeError should be raised.
If __init__ is called with an int <= 0, a ValueError should be raised.
Define and implement the relevant methods from the base Stack class to enable the behavior
described above. New versions of __init__() and push() should be sufficient.
"""
class LimitedStackOverflowError(Exception):
pass
# Add mehods here. Remove this comment and the next line before doing so.
pass
class RotatingStack(LimitedStack):
"""
A RotatingStack has the same methods and functionality as LimitedStack, but will not raise an
exception when an item is added that would go beyond the maximum capacity. Instead, the item
will be added to the stack and then the oldest item from the RotatingStack will be dropped.
The __init__ method for RotatingStack should take a single, positive integer as an argument. This will
be the maximum number of items that the RotatingStack can hold. If push is called with an item and that
item would go beyond the Rotating's capacity, the item will be added to the stack, but only after
discarding the oldest item in the stack.
If push is called where item equals None, a TypeError should be raised like in the base class.
If __init__ is called with a non-integer argument, a TypeError should be raised.
If __init__ is called with an int <= 0, a ValueError should be raised.
Define and implement the relevant methods from the base Stack class to enable the behavior
described above. As long as LimitedStack has properly handled the __init__ method functionality,
only a new version of push() should be needed.
"""
# Add mehods here. Remove this comment and the next line before doing so.
pass |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv("numbers.csv")
# Can select individual columns
print("col x:", data['x'], sep='\n')
print("col y:", data['y'], sep='\n')
# Can get basic stats for columns with describe
print("data stats:", data.describe(), sep='\n')
# Can also target certain values (for entire dataframe or a single column)
print(data['x'].min())
# It's possible to combine data from multiple dataframes. This example
# creates a new dataframe by doubling each value in the original dataframe
data_2 = data * 2
print("doubled-data:", data_2.describe(), sep='\n')
# Can also concatenate data in multiple dataframes
data_3 = pd.concat([data, data_2])
print("concat data:", data_3.describe(), sep='\n')
# Dataframes are capable of generating different types of plots.
# Scatter plot example:
plt.figure()
data_3.plot.scatter('x', 'y')
# Pandas can bin data
data_3['x-bin'] = pd.cut(data_3['x'], bins=range(-10, 10, 1))
print("bins for x column:", data_3['x-bin'].value_counts(), sep='\n')
# Can also bin datas into buckets evenly
data_3['y-bin'] = pd.qcut(data_3['y'], 10)
print("y-bin:", data_3['y-bin'].head(10), sep='\n')
# Can plot out the bucket counts
plt.figure()
bar_data = data_3[['x-bin', 'x']].groupby('x-bin').count().plot()
plt.figure()
bar_data = data_3[['y-bin', 'y']].groupby('y-bin').count().plot(kind='bar')
# It's possible to select a subset of data.
# Let's find all rows with positive x and y values.
# Note that the conditional syntax is slightly different than what you would
# expect to see with plain old Python conditionals.
positive_vals = data_3[(data_3['x'] > 0) & (data_3['y'] > 0)]
print("positive stats:", positive_vals.describe(), sep='\n')
negative_vals = data_3[(data_3['x'] < 0) & (data_3['y'] < 0)]
print("negative stats:", negative_vals.describe(), sep='\n')
# Can capture the output of a plot call to get the axis object
# for the plot. Can set the ax argument to future plot calls
# in order to display other dataframes on the same plot
plt.figure()
plot_axis = positive_vals.plot.scatter(x='x', y='y', c='red')
negative_vals.plot.scatter(x='x', y='y', c='blue', ax=plot_axis) |
#!/usr/local/bin/python3
# Can return single values.
def add(a, b):
return a + b
# Can return multiple values.
# They are returned as a tuple.
def get_coordinates(a, b, c):
x = add(a, b)
y = add(b, c)
return x, y # Or, return (x, y)
# A function can return multiple different types.
# Probably not the most readable/usable code though...
# Just because you *can* do it does not mean it is
# a good idea.
def different_return_types(i):
if i < 10:
return i
else:
return str(i)
print(add(10, 20))
# Multiple return values are contained in a tuple.
# Can assign the result to multiple variables to
# extract the tuple's values.
x, y = get_coordinates(5, 6, 10)
print(x, y, sep=', ')
# Or get the tuple itself
coordinates = get_coordinates(4, 7, 10)
print(coordinates)
print(type(different_return_types(5)))
print(type(different_return_types(20)))
|
def ChemSplit(a):
#To let my string ends with a capital letter:
a=a+'A'
s=0
blist=[]
for ii in range(1,len(a)):
if str(a[ii]).isupper():
blist.append(a[s:ii])
s=ii
#print(blist,'\n')
clist=[]
dlist=[]
for ii in range(len(blist)):
strtemp = blist[ii]
#Case 1: only 1 element
if len(strtemp) == 1:
clist.append(strtemp)
dlist.append(1)
else:
#Case 2: the second character is "number":
if (ord(strtemp[1])) >= 48:
if (ord(strtemp[1])) <= 57:
clist.append(strtemp[0])
dlist.append(float(strtemp[1:]))
#Case 3: the second character is "little letter":
if(ord(strtemp[1])) >= 97:
if(ord(strtemp[1])) <= 122:
clist.append(strtemp[0:2])
if len(strtemp) == 2:
dlist.append(1)
else:
dlist.append(float(strtemp[2:]))
return clist, dlist
################################################################
#Main Program:
#a='F1.33333333Sn1Pb1.33333333'
#print(a,'\n')
#clist, dlist = ChemSplit(a)
#print(clist)
#print(dlist)
|
print("enter a value")
x = int(input())
print("enter another value")
y = int(input())
print("enter the operation: ex: +,-,*,/")
o = input()
if (o == '+'):
print("your answer is:", x+y)
elif(o == '-'):
print("your answer is:", x-y)
elif(o == '*'):
print("your answer is:", x*y)
elif(o == '/'):
if (y == 0):
print("We cannot divide by zero")
exit (1)
print("your answer is:", x/y)
else:
print("It seems that you have not used the following symbols:+,-,*,/, please try again with these symbols.")
|
# Here is a new proposed method of compressing strings :
# "Anywhere in the string if a character c occurs k number of times consecutively, it can be written as c"
# Using this algorithm, your task is to compress the string such that its final length is minimum.
# Note that it is not compulsory for you to compress every single character.
# You may choose to compress whatever characters you want. Only the length of the final string must be minimum.
# INPUT
# The input is one string that needs to be compressed.
# OUTPUT
# Print the final compressed string of minimum length
# CONSTRAINTS
# Length of input string will not be more than 1000.
# Input string will consist of lowercase english alphabets only.
# Sample Input 0
# bbaannaannaa
# Sample Output 0
# banana
# Explanation 0
# string "bbaannaannaa" can be compressed to "banana" by compressing every pair of adjacent equal characters.
s = input()
news = ""
for ch in range(len(s) - 1):
if s[ch] == s[ch + 1]:
pass
else:
news += s[ch]
news += s[-1]
print(news)
|
# Exclusive OR
# Find the XOR of two numbers and print it.
# Hint : Input the numbers as strings.
# Input Format
# First line contains first number X and second line contains second number Y.
# The numbers will be given to you in binary form.
# Constraints
# 0 <= X <= 2^1000
# 0 <= Y <= 2^1000
# Output Format
# Output one number in binary format, the XOR of two numbers.
# Sample Input 0
# 11011
# 10101
# Sample Output 0
# 01110
# Enter your code here. Read input from STDIN. Print output to STDOUT
a = input()
b = input()
ab = int(a,2)
bc = int(b,2)
x = len(a)
y = len(b)
if x>y:
m=x
else:
m=y
ans = ab^bc
print("{0:b}".format(ans).zfill(m)) |
# Given an array, Mister Arr the owner of the array wants to move each element k places
# to its left. I.E. the array a[0],a[1],a[2],...a[n] becomes a[1],a[2]...a[n],a[0]
# after moving one place to the left.
# Note that the first element becomes the last element after each rotation.
# Input Format
# The first line contains two space-separated integers denoting the respective values of n
# (the number of integers) and k (the number of left rotations you must perform).
# The second line contains n space-separated integers describing the respective elements of the array's initial state.
# Sample Input
# 5 4
# 1 2 3 4 5
# Sample Output
# 5 1 2 3 4
a, b = map(int, input().split())
li = list(map(int, input().split()))
newl = []
for i in range(a):
pos = (i + b)
if pos >= a:
pos = pos % a
newl.append(li[pos])
for i in newl:
print(i, end=' ')
|
# Count the number of pairs in an array having the given sum
# Given an array of integers, and a number ‘sum’, chef wants to find the number of pairs of integers in the array whose sum is equal to ‘sum’.
# Examples:
# Input : arr[] = {1, 5, 7, -1},
# sum = 6
# Output : 2
# Pairs with sum 6 are (1, 5) and (7, -1)
# Input : arr[] = {1, 5, 7, -1, 5},
# sum = 6
# Output : 3
# Pairs with sum 6 are (1, 5), (7, -1) &
# (1, 5)
# Input : arr[] = {1, 1, 1, 1},
# sum = 2
# Output : 6
# There are 3! pairs with sum 2.
# Input : arr[] = {10, 12, 10, 15, -1, 7, 6,
# 5, 4, 2, 1, 1, 1},
# sum = 11
# Output : 9
# cook your dish here
# Brute Force Method [O(n^2)]
n = int(input())
arr = list(map(int,input().split()))
sum = int(input())
count = 0
for i in range(0, n):
for j in range(i+1, n):
if arr[i]+arr[j]==sum:
count+=1
print(count)
# Map Approach [O(n)] :
# Idea is to create a hashmap to store freq of the elements, and lookup those elements while traversing the array to check if their sum is equal to the given sum or not
# GeeksforGeeks Explanation: https://youtu.be/bvKMZXc0jQU
def getPairsCount(arr, n, sum):
m = [0] * 1000
# Store counts of all elements in map m
for i in range(0, n):
m[arr[i]] # Stores the frequency of the number in the array
m[arr[i]] += 1
twice_count = 0
# Iterate through each element and increment the count (Every pair is counted twice)
for i in range(0, n):
twice_count += m[sum - arr[i]]
# if (arr[i], arr[i]) pair satisfies the condition, then we need to ensure that the count is decreased by one such that the (arr[i], arr[i]) pair is not considered
if (sum - arr[i] == arr[i]):
twice_count -= 1
# return the half of twice_count
return int(twice_count / 2)
n = int(input())
arr = list(map(int,input().split()))
sum = int(input())
print(getPairsCount(arr, n, sum)) |
# Pyramid by Numericals
# Identify the logic behind the series
# 6 28 66 120 190 276....
# The numbers in the series should be used to create a Pyramid. The base of the Pyramid will be the widest and will start converging towards the top where there will only be one element. Each successive layer will have one number less than that on the layer below it. The width of the Pyramid is specified by an input parameter N. In other words there will be N numbers on the bottom layer of the pyramid.
# The Pyramid construction rules are as follows
# 1. First number in the series should be at the top of the Pyramid
# 2. Last N number of the series should be on the bottom-most layer of the Pyramid, with Nth number being the right-most number of this layer.
# 3. Numbers less than 5-digits must be padded with zeroes to maintain the sanctity of a Pyramid when printed. Have a look at the examples below to get a pictorial understanding of what this rule actually means.
# Example
# If input is 2, output will be
# 00006
# 00028 00066
# If input is 3, output will be
# 00006
# 00028 00066
# 00120 00190 00276
# Input Format
# First line of input will contain number N that corresponds to the width of the bottom-most layer of the Pyramid
# Constraints
# 0 < N <= 14
# Output Format
# The Pyramid constructed out of numbers in the series as per stated construction rules
# Sample Input 0
# 2
# Sample Output 0
# 00006
# 00028 00066
# Sample Input 1
# 3
# Sample Output 1
# 00006
# 00028 00066
# 00120 00190 00276
# Enter your code here. Read input from STDIN. Print output to STDOUT
n=int(input())
sum=0
for i in range(n+1):
sum+=i
l=[]
l.append(6)
for i in range(1,sum):
a=6+l[i-1]+16*(i)
l.append(a)
# print(l)
# print("{:05d}".format(x))
t=0
for i in range(n+1):
for j in range(n,i+1,-1):
print(" ",end='')
for k in range(i+1):
print("{:05d}".format(l[t]),end=' ')
t+=1
print() |
# Contacts Application
# Your task is to design a contacts application that supports two features :
# add name where name is a string that denotes the name of the contact. This operation must store a new contact by the name name.
# find partial where partial is a string denoting a part of the name to search for in the directory. It must count the number of contacts that start with partial and print the count.
# You are given n sequential operations of either type 1 or type 2. You are expected to perform them in the order given.
# Input Format
# The first line contains a single integer, n , denoting the number of operations to perform. Each line i of the n subsequent lines contains an operation in one of the two forms defined above.
# Constraints
# 1 <= n <= 105
# 1 <= |name|, |partial| <= 21
# It is guaranteed that name and partial contain lowercase english letters only.
# Output Format
# For each find partial operation, print the number of contact names starting with partial on a new line.
# Sample Input 0
# 4
# add hack
# add hackerrank
# find hac
# find hak
# Sample Output 0
# 2
# 0
# Enter your code here. Read input from STDIN. Print output to STDOUT
def check(string, sub_str):
if (string.find(sub_str) == -1):
return("NO")
else:
return("YES")
n = int(input())
l=[]
for i in range(n):
act = input()
l.append(act)
names=[]
search=[]
for x in l:
cmd,name = x.split()
if(cmd=='add'):
names.append(name)
if(cmd=='find'):
search.append(name)
# print(names)
# print(search)
ct=0
for i in search:
ct=0
for j in names:
if(check(i,j)=="YES"):
ct+=1
print(ct) |
MAX_WRONG = len(HANGMAN)
WORDS = ("powershell","python","animal","didacticum")
wrong = 0
word = random.choice(WORDS)
#word ="pow"
your_guess = len(word) * "_"
print(your_guess)
guess = input("Raad een letter: ")
#Write code that will continue to ask you to guess a letter
#If a letter is in the word the program should tell you this
#The program should terminate when the maximum tries has been reached.
#Don't worry about displaying the HANGMAN drawings or even the letters guessed, just show that the
#letter is found and don't go beyond the max elements in the HANGMAN Tuple
while wrong <= MAX_WRONG and guess != word :
for i in range(len(word)):
if guess in word[i]:
print("The letter ", guess, " is in the word!")
else :
print("too bad, the letter ", guess, " is not in the word. Try again!")
wrong+=1
guess = input("Raad een letter: ") |
names = ["bla","flap","flop"]
print (range(len(names)))
guess = input()
for i in range(len(names)):
if guess == names[i]:
print("gevind")
word = "hangman"
guess = input()
for i in range(len(word)):
if guess == word[i]:
print("found something") |
number = int(input("Enter a number:"))
primeFlag = True
for i in range(2, number):
if number % i == 0:
primeFlag = False
break
if primeFlag == True:
print(number, " is prime.")
else:
print(number, " is not prime.") |
class PasswordException(Exception):
def __init__(self, msg):
self.msg = msg
try:
ps = input("Enter your Password")
if (len(ps)) < 8:
raise PasswordException("Enter Password more than eight digit")
except PasswordException as obj:
print(obj)
else:
print("Password set") |
import game_logic as game
from random import randint
class AI:
name = "Default"
team = -1
def __init__(self,team):
self.name="Default"
self.team=team
def make_move(self,board):
return 0
class InputPlayer(AI):
name = "Player"
def __init__(self, team):
super().__init__(team)
self.name="Player"
def make_move(self,board):
return int(input("Make Move (0-6):\n"))
class RandomPlayer(AI):
name = "Random"
def __init__(self,team):
super().__init__(team)
self.name="Random"
def make_move(self,board):
valid_moves = []
for i in range(0,game.BOARD_SIZE[0]):
if game.get_y_of(board,i)!=-1:
valid_moves.append(i)
return valid_moves[randint(0,len(valid_moves)-1)]
game.ai_classes.append(RandomPlayer)
class Minimax(AI):
# Loss function is how many the opponent has in a row.
name = "Minimax"
def __init__(self,team,depth=2):
super().__init__(team)
self.depth = depth
self.other_team = game.RED if self.team == game.BLACK else game.BLACK
def value_of(self, board):
if isinstance(board,int) or isinstance(board,float):
return board
win = game.check_game_end(board)
if win == self.team:
loss = -1000 + game.pieces_on_board(board)
elif win == self.other_team:
loss = 1000 - game.pieces_on_board(board)
else:
loss = game.in_row(board, self.other_team) - 0.2*game.in_row(board,self.team)
return loss
def choose_val(self,values,evaluator=max):
max_indices = []
max_val = evaluator(values)
for i in range(0,len(values)):
if values[i] == max_val:
max_indices.append(i)
return max_indices[randint(0,len(max_indices)-1)], max_val
def get_boards(self, board,team):
boards = []
if isinstance(board,int) or isinstance(board,float):
return [board]
if game.check_game_end(board) != -1:
return [self.value_of(board)]
for i in range(0, 7):
new_board, valid = game.make_move(board, i, team)
if not valid:
boards.append(1000000 if team == self.team else -1000000)
else:
boards.append(new_board)
return boards
def make_move(self,board):
boards = self.get_boards(board,self.team)
return self.choose_move(boards)[0]
def choose_move(self,boards,layer=1):
playing = self.team if layer % 2 == 0 else self.other_team
if layer==self.depth:
values = []
for board in boards:
value = self.value_of(board)
values.append(value)
val = self.choose_val(values,max if playing==self.team else min)
return val
else:
values = []
for i in range(0,len(boards)):
new_boards = self.get_boards(boards[i],playing)
val = self.choose_move(new_boards,layer+1)
values.append(val[1])
val = self.choose_val(values,max if playing==self.team else min)
return val
game.ai_classes.append(Minimax)
class MinimaxD4(Minimax):
# Loss function is how many the opponent has in a row.
name = "MinimaxD4"
def __init__(self,team,depth=4):
super().__init__(team)
self.depth = depth
self.other_team = game.RED if self.team == game.BLACK else game.BLACK
game.ai_classes.append(MinimaxD4)
class Sweeper(AI):
name = "Sweeper"
def __init__(self,team):
super().__init__(team)
self.location = randint(-1,5)
self.direction = 1
def make_move(self,board):
# This is where your logic will go. This default AI will always go in the leftmost column.
if self.location == 0:
self.direction=1
elif self.location==6:
self.direction=-1
self.location+=self.direction
if game.check_game_end(board) != -1:
return 0
while game.get_y_of(board,self.location) == -1:
self.location+=self.direction
return self.location
game.ai_classes.append(Sweeper)
class Hierarchy(AI):
# Change "Template" to your AI's name
name = "Hierarchy"
def __init__(self,team):
super().__init__(team)
self.hierarchy = [self.win,self.block_win,self.make_trap,self.block_trap,self.threaten_win,self.stop_threaten,self.increase_row,self.stop_increase_row]
self.other_team = 2 if self.team==1 else 1
def win(self,board,team=-1):
if team==-1:
team=self.team
wcons = game.win_conditions(board,team)
if len(wcons)==0:
return -1
return wcons[randint(0,len(wcons)-1)]
def block_win(self,board):
return self.win(board,self.other_team)
def make_trap(self,board,team=-1):
if team==-1:
team=self.team
boards = game.next_boards(board,team)
for i in range(0,len(boards)):
if len(game.win_conditions(boards[i],team))>=2:
return i
return -1
def block_trap(self,board):
return self.make_trap(board,team=self.other_team)
def threaten_win(self,board,team=-1):
if team==-1:
team=self.team
other_team = 1 if team==2 else 2
boards = game.next_boards(board,team)
moves = []
for i in range(0,len(boards)):
if len(game.win_conditions(boards[i],other_team))>0:
continue
conditions = len(game.win_conditions(boards[i],team))
if conditions>0:
moves.append(i)
if len(moves)==0:
return -1
return moves[randint(0,len(moves)-1)]
def stop_threaten(self,board):
return self.threaten_win(board,self.other_team)
def increase_row(self,board,team=-1):
if team==-1:
team=self.team
boards = game.next_boards(board,team)
current_score = game.in_row(board,team)
moves=[]
for i in range(0,len(boards)):
if game.in_row(boards[i],team)>current_score:
moves.append(i)
if len(moves)==0:
return -1
return moves[randint(0,len(moves)-1)]
def stop_increase_row(self,board):
return self.increase_row(board,self.other_team)
def make_move(self,board):
for move in self.hierarchy:
do_move = move(board)
if do_move != -1 and game.is_valid_move(board,do_move):
return do_move
# Choose random valid move if no choices apply
valid_moves = []
for i in range(0, game.BOARD_SIZE[0]):
if game.get_y_of(board, i) != -1:
valid_moves.append(i)
return valid_moves[randint(0, len(valid_moves) - 1)]
# Change "Template" to your AI's name
game.ai_classes.append(Hierarchy)
# Here's what you edit
class Template(AI):
# Change "Template" to your AI's name
name = "Default"
def __init__(self,team):
super().__init__(team)
def make_move(self,board):
# This is where your logic will go. This default AI will always go in the leftmost column.
return 0
# Change "Template" to your AI's name
game.ai_classes.append(Template)
|
#Grading Students
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'gradingStudents' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY grades as parameter.
#
def transformGrade(grade):
remainder = grade%5
quotient = grade//5
nextVal = (quotient +1) * 5
if abs(nextVal - grade ) <3 :
return nextVal
return grade
def gradingStudents(grades):
result = []
for grade in grades:
if grade >= 38 :
grade = transformGrade(grade)
result.append(grade)
return result
|
#import modules
from datetime import datetime
from time import sleep
from pytz import timezone
#set CONSTANTS
TIME_ZONE = timezone('US/Central')
START_TIME = datetime.strptime('1555','%H%M').time() #enter the time of day to begin the cycle
RUN_TIME = 1 #enter the length of time to run each zone in minutes
TOTAL_ZONES = 4 #enter the number of zones you have, zones will$
DAYS = [0, 1, 2, 3, 4, 5, 6] #select days of week to run as list, 0 for sund$
TEST_MODE = True #set true to print pinouts and duration instead of activating GPIO
PIN_LIST = [3, 5, 7, 8]
#set initialVariables
rtSeconds = RUN_TIME*60
day = datetime.now(TIME_ZONE)
currentDay = day.weekday()
currentTime = day.time().replace(second=0, microsecond=0)
#setup GPIO
#Functions
def activatePin(pin, duration):
if TEST_MODE == True:
print(pin, )
print(duration, )
print(currentDay, )
print(datetime.now(TIME_ZONE).time())
sleep(duration)
else:
sleep(duration)
def convertTime(time): #convert times back to datetime so it can be compared (because python can be stupid sometimes)
conTime = datetime.now().replace(hour=time.hour, minute=time.minute)
return conTime
def offTimeDebug():
print('Next Scheduled watering: ',' ')
if currentTime < START_TIME:
waitTime = convertTime(START_TIME) - convertTime(currentTime)
print(datetime.strftime(waitTime))
if waitTime.total_seconds() > 330:
sleep(300)
else:
sleep(30)
else:
print('Tomorrow')
sleep(3600)
#Main Program
while True:
day = datetime.now(TIME_ZONE)
currentDay = day.weekday()
currentTime = day.time().replace(second=0, microsecond=0)
if currentDay in DAYS: #check to make sure it's the right day to water
if currentTime == START_TIME:
for zone in range(TOTAL_ZONES):
activatePin(PIN_LIST[zone],rtSeconds)
else:
offTimeDebug()
#print(currentTime, )
#print('Not the right time')
#sleep(1)
|
m=input()
if m==str(m)[::-1]:
print("yes")
else:
print("no")
|
import random
# game levels
level_one = random.randint(1, 10)
level_two = random.randint(1, 20)
level_three = random.randint(1, 50)
guess_count = 0 # used to keep track of guess attempts
print('''
Hi, Welcome to the number guessing game.
Here are the available levels:
E --- Easy
M --- Medium
H --- Hard
''')
difficulty = input("Please, pick a level [E; M; or H]: ").upper()
# setting conditions for each level
if difficulty == "E":
guess_limit = 6
secret_number = level_one
print("Okay, I have set a number between 1 and 10")
elif difficulty == "M":
guess_limit = 4
secret_number = level_two
print("Okay, I have set a number between 1 and 20")
else:
if difficulty == "H":
guess_limit = 3
secret_number = level_three
print("Okay, I have set a number between 1 and 50")
# running the game until user exhaust their life lines
while guess_count < guess_limit:
try: # using the try/ecxept ErrorValue to ensure user inputs a number
guess = int(input('Take a guess: '))
guess_count += 1
if guess < secret_number or guess > secret_number:
print(f'''That was wrong! You have {guess_limit - guess_count} guesses left!
*****************************************
''')
else:
if guess == secret_number:
break
except ValueError:
print('Please, enter a number.')
continue
if guess == secret_number: # this happens if user guess is right
guess_count = str(guess_count)
print('YOU GOT IT RIGHT! It took you ' + guess_count + ' guesses!')
else:
if guess != secret_number: # if user wrong/exhausted life line
secret_number = str(secret_number)
print('GAME OVER! The correct guess is ' + secret_number)
|
#!/usr/bin/python
# AUTHOR: JASON CHEN (cheson@stanford.edu)
# DATE: July 31, 2017
# The find_votesmart_id function takes a list of targets with each target
# structured as the format "firstname_lastname".
# If you call this function, you will get in return a map from the target
# name to the votesmart id associated with that target. If the target is
# not found, a message is outputted. You can also choose to have the function
# return a tuple that contains the list of unfound targets.
import csv
def find_votesmart_ids(target_list = None):
### CREATE MAP OF VOTESMART PEOPLE TO THEIR DATABASE IDS ###
id_matrix = 'inputs/votesmart_id_matrix.csv'
id_map_all = {}
if target_list == None:
return []
with open(id_matrix, 'rb') as csvfile:
reader = csv.reader(csvfile)
next(csvfile)
for row in reader:
entry = row[0]
columns = entry.split(";")
# print columns
if len(columns) == 12:
politician_id = columns[0]
first_name = columns[5].lower().replace("\"", "")
last_name = columns[8].lower().replace("\"", "")
full_name = first_name + "_" + last_name
id_map_all[full_name] = int(politician_id)
csvfile.close()
# print id_map_all
### FIND IDS OF TARGETS ###
all_names = id_map_all.keys()
targets_found = {}
targets_not_found = []
for target in target_list:
if target in all_names:
targets_found[target] = id_map_all[target]
else:
print target + " not in votesmart database [please double check manually]"
targets_not_found.append(target)
# print targets_found
# print len(targets_found)
print len(targets_found), "found |", len(targets_not_found), "not found"
return targets_found
#return (targets_found, targets_not_found)
|
a = int(input()) - 1
b = 1
while a > -1:
print(' '*a + "@"*b)
b+=2
a-=1
|
# Question:
#------------------------------------------------------------------------------
# tags:
'''
We have a list of points on the plane. Find the K closest points to the origin (0, 0).
(Here, the distance between two points on a plane is the Euclidean distance.)
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)
Example 1:
Input: points = [[1,3],[-2,2]], K = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].
Example 2:
Input: points = [[3,3],[5,-1],[-2,4]], K = 2
Output: [[3,3],[-2,4]]
(The answer [[-2,4],[3,3]] would also be accepted.)
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
import random
class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
dist = lambda i: points[i][0]**2 + points[i][1]**2
def sort(i, j, K):
k = random.randint(i, j)
points[j], points[k] = points[k], points[j]
mid = partition(i, j)
if K < mid - i - 1:
sort(i, mid - 1, K)
elif K > mid - i + 1:
sort(mid + 1, j, K - (mid - i + 1))
def partition(start, end):
pIndex = start
pivot = dist(end)
i = start
while i < end:
if dist(i) <= pivot:
points[i], points[pIndex] = points[pIndex], points[i]
pIndex += 1
i += 1
points[pIndex], points[end] = points[end], points[pIndex]
return pIndex
sort(0, len(points) - 1, K)
return points[:K]
#------------------------------------------------------------------------------
'''
Time:
Space:
'''
def f():
pass
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_simple(self):
s = Solution()
points = [[3,3],[5,-1],[-2,4]]
k = 2
ans = s.kClosest(points, k)
self.assertEqual(set(ans), set([[[3,3],[-2,4]]]) )
unittest.main(verbosity=2)
|
#------------------------------------------------------------------------------
# Question: 0096_unique_binary_search_trees.py
#------------------------------------------------------------------------------
# tags: #trees #medium
'''
Given n, how many structurally unique BST's (binary search trees) that store
values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
4
/ \
2 5
/ \ \
1 3 6
\
7
1234 5 67890
r
L = numTrees(i-1)
R = numTrees(n-i)
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
from test_utils.debug import debug
class SolutionDFS:
'''
Time: O(n^2)
Space: O(1)
'''
# @debug
def numTrees(self, n: int) -> int:
if n <= 1:
return 1
res = 0
for i in range(1, n + 1):
left = self.numTrees(i - 1)
right = self.numTrees(n - i)
res += left*right
return res
class SolutionDP:
'''
Time:O(n^2)
Space:O(n)
'''
def numTrees(self, n: int) -> int:
if n <= 1:
return 1
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for n in range(2, n + 1):
for i in range(1, n +1):
left = dp[i - 1]
right = dp[n - i]
dp[n] += left * right
return dp[-1]
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_simple(self):
s = SolutionDFS()
self.assertEqual(s.numTrees(3), 5)
s = SolutionDP()
self.assertEqual(s.numTrees(3), 5)
def test_one(self):
s = SolutionDFS()
self.assertEqual(s.numTrees(1), 1)
s = SolutionDP()
self.assertEqual(s.numTrees(1), 1)
unittest.main(verbosity=2)
|
#------------------------------------------------------------------------------
# Question: 043_Multiply_Strings.py
#------------------------------------------------------------------------------
# tags:
'''
Given two non-negative integers num1 and num2 represented as strings, return
the product of num1 and num2.
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer
directly.
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
class Solution:
def multiply(self, num1: str, num2: str) -> str:
'''
[0,0,0,0,0,0]
456
123
p
6*123 + 5*123*10 + 4*123*100
321
654
[0 0 0 0 0 12]
p
S
'''
result = [0] * (len(num1) * len(num2))
start = len(result) - 1
for n1 in num1[::-1]:
for i, n2 in enumerate(num2[::-1]):
pos = start - i
prod = int(n1) * int(n2)
result[pos] += prod
result[pos - 1] += result[pos] // 10
result[pos] %= 10
start -= 1
for i, v in enumerate(result):
if v != 0:
x = i
break
else:
return "0"
return "".join([str(x) for x in result[x:]])
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_simple(self):
s = Solution()
num1 = "123"
num2 = "456"
ans = s.multiply(num1, num2)
self.assertEqual(ans, '56088')
def test_simple2(self):
s = Solution()
num1 = "0"
num2 = "0"
ans = s.multiply(num1, num2)
self.assertEqual(ans, '0')
unittest.main(verbosity=2)
|
#------------------------------------------------------------------------------
# Question:
#------------------------------------------------------------------------------
# tags: #tree
'''
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if root is None:
return
s = [root]
cur = None
while s:
n = s.pop()
if n:
s.append(n.right)
s.append(n.left)
if not cur:
cur = n
else:
cur.right = n
cur.left = None
cur = cur.right
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_simple(self):
s = Solution()
self.assertEqual(True, True)
unittest.main(verbosity=2)
|
#------------------------------------------------------------------------------
# Questions: 0103_binary_tree_zigzag_level_order_traversal.py
#------------------------------------------------------------------------------
# tags: Binary, Traversal
'''
Given a binary tree, return the zigzag level order traversal of its nodes' values.
(ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
# Time = O(N)
# Space = O(N)
class Solution(object):
# Two Stacks
def zigzagLevelOrder(self, root):
if not root:
return []
s_1 = [] #prints left to right
s_2 = [] #prints right to left
n = len(root)
result = []
cur = 0
s_1.append((0, root[0]))
while len(s_1) > 0 or len(s_2) > 0:
temp = []
while len(s_1) > 0:
node = s_1.pop()
temp.append(node[1])
right_child = 2 * node[0] + 2
left_child = 2 * node[0] + 1
if left_child <= n-1 and root[left_child]:
s_2.append((left_child, root[left_child]))
if right_child <= n-1 and root[right_child]:
s_2.append((right_child, root[right_child]))
if len(temp) > 0:
result.append(temp)
temp = []
while len(s_2) > 0:
node = s_2.pop()
temp.append(node[1])
right_child = 2 * node[0] + 2
left_child = 2 * node[0] + 1
if right_child <= n-1 and root[right_child]:
s_1.append((right_child, root[right_child]))
if left_child <= n-1 and root[left_child]:
s_1.append((left_child, root[left_child]))
if len(temp) > 0:
result.append(temp)
return result
import queue
class Solution2(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root: return []
res = []
temp = []
n = len(root)
q = queue.Queue()
q.put((0, root[0]))
flag = -1
while not q.empty():
for i in range(q.qsize()):
node = q.get()
temp+=[node[1]]
right_child = 2 * node[0] + 2
left_child = 2 * node[0] + 1
if right_child <= n-1 and root[right_child]:
q.put((right_child, root[right_child]))
if left_child <= n-1 and root[left_child]:
q.put((left_child, root[left_child]))
res+=[temp[::flag]]
temp=[]
flag*=-1
return res
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution1(unittest.TestCase):
def test_simple(self):
root = [3,9,20,None,None,15,7]
s = Solution()
self.assertEqual(s.zigzagLevelOrder(root), [[3], [20,9], [15,7]])
s2 = Solution2()
self.assertEqual(s2.zigzagLevelOrder(root), [[3], [20,9], [15,7]])
def test_none_root(self):
root = None
s = Solution()
self.assertEqual(s.zigzagLevelOrder(None), [])
s2 = Solution2()
self.assertEqual(s2.zigzagLevelOrder(None), [])
if __name__ == "__main__":
unittest.main()
|
# **************************************************************************** #
# #
# ::: :::::::: #
# 106_construct_binary_tree_from_inorder_an :+: :+: :+: #
# +:+ +:+ +:+ #
# By: kcheung <kcheung@42.fr> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2018/01/30 23:44:26 by kcheung #+# #+# #
# Updated: 2018/01/31 16:08:02 by kcheung ### ########.fr #
# #
# **************************************************************************** #
'''
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
'''
import unittest
from typing import *
# tags:
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Time = O(N)
# Space = O()
class Solution(object):
def buildTreeRecur2(self, inorder, postorder, lookup, inorder_start, inorder_end):
if inorder_start > inorder_end:
return None
val = postorder[self.pIndex]
node = TreeNode(val)
if inorder_start == inorder_end:
return node
inorderIndex = lookup[val] #find index of this val in Inorder lookup
self.pIndex -= 1
node.right = self.buildTreeRecur2(inorder, postorder, lookup, inorderIndex+1, inorder_end)
node.left = self.buildTreeRecur2(inorder, postorder, lookup, inorder_start, inorderIndex-1)
return node
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
n = len(inorder)
self.pIndex = n - 1
lookup = {}
for i,val in enumerate(inorder):
lookup[val] = i
return(self.buildTreeRecur2(inorder, postorder ,lookup, 0, n - 1))
class Solution2(object):
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
def helper(in_left, in_right):
# if there is no elements to construct subtrees
if in_left > in_right:
return None
# pick up the last element as a root
# val = postorder.pop() #this modifies original post order
val = postorder[self.pIndex]
root = TreeNode(val)
self.pIndex -= 1
# root splits inorder list
# into left and right subtrees
index = idx_map[val]
# build right subtree
root.right = helper(index + 1, in_right)
# build left subtree
root.left = helper(in_left, index - 1)
return root
# build a hashmap value -> its index
self.pIndex = len(postorder) - 1
idx_map = {val:idx for idx, val in enumerate(inorder)}
return helper(0, len(inorder) - 1)
class TestSolution1(unittest.TestCase):
def test_simple(self):
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
def get_inorder(root, res):
if root is None:
return
get_inorder(root.left, res)
res.append(root.val)
get_inorder(root.right, res)
def get_postorder(root, res):
if root is None:
return
get_postorder(root.left, res)
get_postorder(root.right, res)
res.append(root.val)
s = Solution2()
myinorder = []
mypostorder = []
tree = s.buildTree(inorder, postorder)
get_inorder(tree, myinorder)
get_postorder(tree, mypostorder)
self.assertEqual(myinorder, inorder)
self.assertEqual(mypostorder, postorder)
if __name__ == "__main__":
unittest.main()
|
# **************************************************************************** #
# #
# ::: :::::::: #
# 198_House_Robber.py :+: :+: :+: #
# +:+ +:+ +:+ #
# By: kcheung <kcheung@42.fr> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2018/01/15 21:51:27 by kcheung #+# #+# #
# Updated: 2018/01/16 11:35:44 by kcheung ### ########.fr #
# #
# **************************************************************************** #
'''
You are a professional robber planning to rob houses along a street. Each house
has a certain amount of money stashed, the only constraint stopping you from
robbing each of them is that adjacent houses have security system connected and
it will automatically contact the police if two adjacent houses were broken into
on the same night.
Given a list of non-negative integers representing the amount of money of each
house, determine the maximum amount of money you can rob tonight without
alerting the police.
'''
class Solution(object):
def rob(self, num):
last, now = 0, 0
for i in num:
print('val:{} last:{} now:{}'.format(i,last,now))
last, now = now, max(last + i, now)
return now
s = Solution()
print(s.rob([8,100,8,100,500,6,5,4,4,10]))
|
# **************************************************************************** #
# #
# ::: :::::::: #
# 070_Climbing_Stairs.py :+: :+: :+: #
# +:+ +:+ +:+ #
# By: kcheung <kcheung@42.fr> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2018/01/15 19:56:09 by kcheung #+# #+# #
# Updated: 2018/01/16 13:54:08 by kcheung ### ########.fr #
# #
# **************************************************************************** #
'''
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you
climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
def climbStairs(self, n):
:type n: int
:rtype: int
'''
class Solution1(object): # Time:O(2^n) Space:O(n)
def climbStairsHelper(self, i, n ):
if i > n:
return 0
if i == n:
return 1
return (self.climbStairsHelper(i + 1, n) + self.climbStairsHelper(i + 2, n))
def climbStairs(self, n):
return(self.climbStairsHelper(0, n))
'''
f(i+1, n) + f(i+2, n)
L
....f(10,10) = > 1
/
f(3,10)
/
f(2,10) => ?
\
f(5,10)
/
f(1,10) => ?
\
f(3,10)
/
f(0,10)
\
f(3, 10)
/
f(2,10) => memo[2]
\
f(5, 10)
R
'''
class Solution2(object): # Time:O(n) Space:O(n)
def climbStairsHelper(self, i, n, memo):
if i > n:
return 0
if i == n:
return 1
if memo[i] > 0:
return memo[i]
memo[i] = self.climbStairsHelper(i + 1, n, memo) + self.climbStairsHelper(i + 2, n, memo)
return memo[i]
def climbStairs(self, n):
memo = [0] * (n + 1)
return(self.climbStairsHelper(0, n, memo))
class Solution3(object): # Time:O(n) Space:O(1)
def climbStairs(self, n):
if n == 1:
return 1
first = 1
second = 2
for i in range(3, n+1):
third = first + second
first, second = second, third
return second
s = Solution3()
print(s.climbStairs(5))
|
# **************************************************************************** #
# #
# ::: :::::::: #
# 518_CoinChange_2-Combinations.py :+: :+: :+: #
# +:+ +:+ +:+ #
# By: kcheung <kcheung@42.fr> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2018/01/11 12:15:39 by kcheung #+# #+# #
# Updated: 2018/02/16 15:15:24 by kcheung ### ########.fr #
# #
# **************************************************************************** #
'''
You are given coins of different denominations and a total amount of money.
Write a function to compute the number of combinations that make up that amount.
You may assume that you have infinite number of each kind of coin.
Note: You can assume that
0 <= amount <= 5000
1 <= coin <= 5000
the number of coins is less than 500
the answer is guaranteed to fit into signed 32-bit integer
'''
class Solution: #recursion + memoization
def coinChangeHelper(self, target, coins, index, hashMap):
if (target == 0):
return (1)
if(index >= len(coins)):
return(0)
#memo
key = str(target) + '-' + str(index)
if key in hashMap:
return hashMap[key]
#memo
coinsValue = 0
ways = 0
while(coinsValue <= target):
remaining = target - coinsValue
ways += self.coinChangeHelper(remaining, coins, index+1, hashMap)
coinsValue += coins[index]
hashMap[key] = ways
return ways
def change(self, amount, coins):
map = {}
result = self.coinChangeHelper(amount, coins, 0, map)
print(map)
return(result)
class Solution2: #Tabulation
def change(self, amount, coins):
dp = [0] * (amount + 1)
dp[0] = 1
for i in range(len(coins)):
for j in range(1,amount + 1):
if j >= coins[i]:
dp[j] += dp[j - coins[i]]
return dp[-1]
#Test Code
s = Solution2()
s = Solution()
coins = [1,2,5]
target = 5
print(s.change(target, coins))
|
#------------------------------------------------------------------------------
# Question:
#------------------------------------------------------------------------------
# tags:
'''
Given a non-empty array of integers, every element appears twice except for
one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement
it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
import functools
class Solution:
'''
Time: O(n)
Space: O(n)
'''
def singleNumber(self, nums: List[int]) -> int:
h = {}
for n in nums:
h[n] = False if n not in h else not(h[n])
single = [n for n in h if h[n] is False]
return(single[0])
class Solution2:
'''
Time: O(n)
Space: O(n)
'''
def singleNumber(self, nums: List[int]) -> int:
bit = 0
for n in nums:
bit ^= n
return bit
# return functools.reduce(lambda x,y: x^y, nums)
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_simple(self):
nums = [2,2,1]
s = Solution()
self.assertEqual(s.singleNumber(nums), 1)
s = Solution2()
self.assertEqual(s.singleNumber(nums), 1)
def test_simple2(self):
nums = [4,1,2,1,2]
s = Solution()
self.assertEqual(s.singleNumber(nums), 4)
s = Solution2()
self.assertEqual(s.singleNumber(nums), 4)
unittest.main(verbosity=2)
|
# ------------------------------------------------------------------------------
# Question:
# ------------------------------------------------------------------------------
# tags: #binarytree
'''
'''
# ------------------------------------------------------------------------------
# Solutions
# ------------------------------------------------------------------------------
import unittest
from test_utils.BinaryTree import BinaryTree
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
'''
Time:
Space:
'''
def distributeCoins(self, root: TreeNode) -> int:
ans = 0
def dfs(root):
nonlocal ans
if not root:
return 0
L = dfs(root.left)
R = dfs(root.right)
ans += (abs(L) + abs(R))
excess = root.val + L + R - 1
return excess
dfs(root)
return ans
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
class TestSolution(unittest.TestCase):
def test_simple(self):
s = Solution()
root = [3, 0, 0]
root = BinaryTree(root).root
ans = s.distributeCoins(root)
self.assertEqual(ans, 2)
unittest.main(verbosity=2)
|
#------------------------------------------------------------------------------
# Question:
#------------------------------------------------------------------------------
# tags:
'''
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
'''
SORT BY START
[[1, 3], [2,6], [8, 10], [15, 18]]
s e
[1,3] [2,6] - need merge
[1,3] [3,6] - need merge
[1,3] [4,6] - does not need to merge
result [[1, 6], [8, 10], [15, 20]]
2 var
s -> start of interval ->init intervals[0][0]
e -> end of interval ->.init intervals[0][1]
loop through intervals:
if i[start] <= e, then I need to merge
merge: set e to interval[end]
else add [s,e] to result and move s to next interval start and e to next interval end
add [s, e] to result
'''
result = []
n = len(intervals)
if n == 0:
return result
intervals = sorted(intervals, key=lambda x: x[0])
start = 0
end = 1
s = intervals[0][start] # 1
e = intervals[0][end] # 3
for i in range(1, n): #[8, 10]
if intervals[i][start] <= e: #8 <= 6
#merge
e = max(e, intervals[i][end]) #
else:
result.append([s, e])
s = intervals[i][start]
e = intervals[i][end]
'''
result = [[1,6]]
'''
result.append([s, e])
return result
class SolutionSort:
'''
Medium if sorting first
[1, 4], [5, 10]
result = [[1,4]]
'''
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=lambda x: x[0])
result = []
start = 0
end = 1
for interval in intervals:
if not result or result[-1][end] < interval[start]:
result.append(interval)
else:
#need to merge
result[-1][end] = max(result[-1][end], interval[end])
return result
import collections
class SolutionGraph:
'''
Complexity Analysis
Time complexity : O(n^2)
Building the graph costs O(V + E) = O(V) + O(E) = O(n) + O(n^2)
time, as in the worst case all intervals are mutually overlapping. Traversing
the graph has the same cost (although it might appear higher at first) because
our visited set guarantees that each node will be visited exactly once.
Finally, because each node is part of exactly one component, the merge step
costs O(V)=O(n) time. This all adds up as follows:
O(n^2) + O(n^2) + O(n) = O(n^2)
Space complexity : O(n^2)
As previously mentioned, in the worst case, all intervals are mutually
overlapping, so there will be an edge for every pair of intervals.
Therefore, the memory footprint is quadratic in the input size.
'''
'''
Graph:
{
(1, 3): [[2, 6], [0, 4]],
(2, 6): [[1, 3], [0, 4]],
(0, 4): [[1, 3], [2, 6]],
(8, 15): [[15, 18]],
(15, 18): [[8, 15]]}
'''
def build_graph(self, intervals):
'''
generate graph where there is an undirected edge between intervals u
and v iff u and v overlap.
'''
graph = collections.defaultdict(list)
def overlap(a, b):
# (1, 3) (2, 4)
start = 0
end = 1
return a[start] <= b[end] and a[end] >= b[start]
for i, interval_i in enumerate(intervals):
# for j in range(i + 1, len(intervals)):
for j, interval_j in enumerate(intervals[i+1:], i+1):
if overlap(interval_i, intervals[j]):
graph[tuple(interval_i)].append(interval_j)
graph[tuple(interval_j)].append(interval_i)
return graph
# merges all of the nodes in this connected component into one interval.
def merge_nodes(self, nodes):
min_start = min(node[0] for node in nodes)
max_end = max(node[1] for node in nodes)
return [min_start, max_end]
'''
{
comp-number : [(interval1), (interval2)]
0: [(1, 3), (0, 4), (2, 6)],
1: [(8, 15), (15, 18)],
2: [(19, 20)]
}
'''
def get_components(self, graph, intervals):
'''
gets the connected components of the interval overlap graph.
'''
visited = set()
comp_number = 0
nodes_in_comp = collections.defaultdict(list)
#iterative
def mark_component_dfs(start):
stack = [start]
while stack:
node = tuple(stack.pop())
if node not in visited:
visited.add(node)
nodes_in_comp[comp_number].append(node)
stack.extend(graph[node])
# Recursive
# def mark_component_dfs(start):
# node = tuple(start)
# visited.add(node)
# nodes_in_comp[comp_number].append(node)
# for children in graph[tuple(start)]:
# n = tuple(children)
# if n not in visited:
# visited.add(n)
# nodes_in_comp[comp_number].append(n)
# mark_component_dfs(n)
# mark all nodes in the same connected component with the same integer.
for interval in intervals:
if tuple(interval) not in visited:
mark_component_dfs(interval)
comp_number += 1
print(nodes_in_comp)
return nodes_in_comp, comp_number
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
graph = self.build_graph(intervals)
print(graph)
nodes_in_comp, number_of_comps = self.get_components(graph, intervals)
# all intervals in each connected component must be merged.
result = [
self.merge_nodes(nodes_in_comp[comp])
for comp in range(number_of_comps)]
return result
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_simple(self):
s = SolutionGraph()
intervals = [[1, 3], [2, 6], [8, 15], [15, 18], [0, 4], [19, 20]]
self.assertEqual(s.merge(intervals), [[0, 6], [8, 18], [19, 20]])
unittest.main(verbosity=2)
|
#------------------------------------------------------------------------------
# Question: 027_course_schedule.py
#------------------------------------------------------------------------------
# tags: medium
'''
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to
first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it
possible for you to finish all courses?
Example 1:
Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take. To take course 1 you should
have finished course 0. So it is possible.
Example 2:
Input: 2, [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take. To take course 1 you should
have finished course 0, and to take course 0 you should also have finished course
1. So it is impossible.
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
from test_utils.debug import debug
import collections
class Solution:
'''
Time:
'''
# def canFinish(self, numCourses, prerequisites):
# # @debug
# def dfs(course):
# visited[course] = True
# for nei in graph[course]:
# if visited[nei] == False:
# dfs(nei)
# stack.append(course)
# visited = [False] * numCourses
# graph = collections.defaultdict(set)
# stack = []
# for course, pre in prerequisites:
# graph[course].add(pre)
# print(graph)
# # check for cycles
# for i in range(numCourses):
# if visited[i] == False:
# dfs(i)
# print(stack)
# return(len(stack) == numCourses)
class SolutionLeet:
'''
Time:
Space:
Intuition: Topological Sort
'''
def canFinish(self, numCourses, prerequisites):
courses = collections.defaultdict(set)
prereqs = collections.defaultdict(set)
for course, pre in prerequisites:
courses[course].add(pre)
prereqs[pre].add(course)
#get all nodes that don't have a prerequisite
stack = [n for n in range(numCourses) if not courses[n]]
'''
0 > 1 > 2
^___|
'''
print(f'\n courses: {courses}')
print(f'\n neighbors: {prereqs}')
count = 0
print(f'\n starting stack: {stack}')
while stack:
print(f'\n stack: {stack}')
course = stack.pop()
# print(f'\nnode: {course}')
count += 1
# print(f'\ncount: {count}')
for p in prereqs[course]:
courses[p].remove(course)
# course does not have any pre-reqs to process
if not courses[p]:
stack.append(p)
# print(f'\ncount: {count}')
return count == numCourses
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_simple_true(self):
numsCourses = 2
prereqs = [[0, 1]]
s = SolutionLeet()
self.assertEqual(s.canFinish(numsCourses, prereqs), True)
prereqs = [[1, 0], [0, 1]]
s = SolutionLeet()
self.assertEqual(s.canFinish(numsCourses, prereqs), False)
def test_simple_false2(self):
'''
1 > 0
^___|
'''
numsCourses = 2
prereqs = [[0, 1], [1, 0]]
s = SolutionLeet()
self.assertEqual(s.canFinish(numsCourses, prereqs), False)
def test_simple_false3(self):
'''
0 > 1 > 2
^_______|
'''
numsCourses = 3
prereqs = [[2, 1], [1, 0], [0, 2]]
s = SolutionLeet()
self.assertEqual(s.canFinish(numsCourses, prereqs), False)
def test_simple_false4(self):
'''
0 > 1 > 2
^___|
'''
numsCourses = 3
prereqs = [[2, 1], [1, 0], [1, 2]]
s = SolutionLeet()
self.assertEqual(s.canFinish(numsCourses, prereqs), False)
def test_two_classes_require_one(self):
numsCourses = 3
prereqs = [[0, 1], [0, 2], [1, 2]]
s = SolutionLeet()
self.assertEqual(s.canFinish(numsCourses, prereqs), True)
def test_circular(self):
'''
graph:
0 : []
1 : [0,4]
2 : [1]
3 : [2]
4 : [0]
5 : []
Cycle exists
3
^
0 > 1 > 2
^ | |
4<--* |
^-------*
'''
numsCourses = 6
prereqs = [[1, 0], [2, 1], [3, 2], [4, 1], [0, 4], [2, 4]]
s = SolutionLeet()
self.assertEqual(s.canFinish(numsCourses, prereqs), False)
unittest.main(verbosity=2)
|
#------------------------------------------------------------------------------
# Question: 1048_longest_string_chain.py
#------------------------------------------------------------------------------
# tags:
'''
Given a list of words, each word consists of English lowercase letters.
Let's say word1 is a predecessor of word2 if and only if we can add exactly
one letter anywhere in word1 to make it equal to word2. For example, "abc" is a
predecessor of "abac".
A word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1,
where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on.
Return the longest possible length of a word chain with words chosen from the
given list of words.
Example 1:
h[a] = 1
h[b] = 1
h[ba] = 2
h[bca] = 2 check:for x (_ca, b_a, ...), if in h, h[bca] = max([x1,x2,x3, ...])
Input: ["bdca", "a","b","ba","bca","bda","ca"]
Output: 4
Explanation: one of the longest word chain is "a","ba","bda","bdca".
init dp: -> serve as already visited node and store already calculated len
dp[bdca] = None
dp[a] = None
dp[b] = None
... etc
for word in words if dp[word] == None
start dfs: bdca
dp[bdca]: 4
dp[dca]: return 0 NOT in DP
dp[bca]: 3
dp[ca]: 2
dp[a]: 1
dp[""]: return 0 NOT in DP
dp[c]: return 0 NOT in DP
dp[ba]: 2
dp[b]: 1
dp[""]: return 0 NOT in DP
dp[a]: 1 -> already calcualted, don't dfs, just look up
dp[bda]: 3
dp[da]: return 0 Not in DP
dp[ba]: 2 -> already calculated in dp, end dfs
dp[bd]: return 0 Not in DP
current dp
bdca: 4
bca: 3
ca: 2
a: 1
b: 1
bda: 3
start dfs: a -> already calcualted in dp, skip
start dfs: b -> already calculated in dp, skip
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
from pprint import pprint
class Solution:
def longestStrChain(self, words: List[str]) -> int:
h = {}
for w in sorted(words, key=len):
h[w] = max(h.get(word[:i] + word[i+1:],0) + 1 for i in range(len(w)))
return max(h.values())
class Solution:
def longestStrChain(self, words: List[str]) -> int:
def dfs(word):
if word not in dp:
return 0
if not dp[word]:
dp[word] = max([dfs(word[:i]+word[i+1:]) + 1 for i in range(len(word))])
return dp[word]
#keep track of already visited and calculated lens (seen and memo)
dp = {word: None for word in words}
ans = [dfs(word) for word in dp if not dp[word]]
print('\n')
pprint(dp)
return max(ans)
# class Solution:
# def longestStrChain(self, words: List[str]) -> int:
# h = set(words)
# graph = {}
# for w in words:
# graph[w] = 1
# for i in range(len(w)):
# x = w[:i] +w[i:1:]
# if x in h:
# graph[x] = graph.get(x,0) + graph[w]
# return max(h.values())
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_simple(self):
s = Solution()
words = ["bdca", "a","b","ba","bca","bda","ca"]
self.assertEqual(s.longestStrChain(words), 4)
unittest.main(verbosity=2)
|
#------------------------------------------------------------------------------
# Question:
#------------------------------------------------------------------------------
# tags:
'''
Given an array of unique characters arr and a string str, Implement a function
getShortestUniqueSubstring that finds the smallest substring of str containing
all the characters in arr. Return "" (empty string) if such a substring doesn’t
exist. Come up with an asymptotically optimal solution and analyze the time and
space complexities.
Example:
input: arr = ['x','y','z'], str = "axyyzyzyx"
output: "zyx"
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
class Solution:
'''
Time:
Space:
'''
def smallestSubstring(self, arr, S):
n = len(S)
d = {}
for a in arr:
d[a] = 0
patLen = len(arr)
head = 0
uniqueCount = 0
result = ""
for tail in range(n):
c = S[tail]
if c in d:
if d[c] == 0:
uniqueCount += 1
d[c] += 1
# found substring with all chars
while (uniqueCount == patLen):
tempLen = head - tail + 1
#check if cur len is smaller than result and update if necessary
if tempLen < len(result) or result == "":
result = S[head:tail+1]
# try to shorten the window
headChar = S[head]
if headChar in d:
d[headChar] -= 1
if d[headChar] == 0:
uniqueCount -= 1
head += 1
return result
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_simple(self):
s = Solution()
arr = ['x','y','z']
string = "xyyzyzyx"
self.assertEqual(s.smallestSubstring(arr, string), "zyx")
unittest.main(verbosity=2)
|
#------------------------------------------------------------------------------
# Question:
#------------------------------------------------------------------------------
# tags:
'''
There is a new alien language which uses the latin alphabet. However, the
order among letters are unknown to you. You receive a list of non-empty words
from the dictionary, where words are sorted lexicographically by the rules of
this new language. Derive the order of letters in this language.
Example 1:
Input:
[
wer
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
Output: "wertf"
Example 2:
Input:
[
"z",
"x"
]
Output: "zx"
Example 3:
Input:
[
"z",
"x",
"z"
]
Output: ""
Explanation: The order is invalid, so return "".
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
import collections
class Solution:
'''
Time:
Space:
m = average minimum length of words
n = word in words
'''
def alienOrder(self, words: List[str]) -> str:
# Extract dependencies from input and put into graph
graph = collections.defaultdict(set)
in_degree = collections.Counter({c: 0 for word in words for c in word})
n = len(words)
for w1, w2 in zip(words, words[1:]): #O(n*m)
for c1, c2 in zip(w1, w2): #O
if c1 != c2:
if c1 in graph[c2]: return ""
if c2 not in graph[c1]:
graph[c1].add(c2)
in_degree[c2] += 1
break
else: # check if w2 is a perfix if w1
if len(w2) < len(w1): return ""
print(graph)
print(in_degree)
#check circular Reference
# Don't have to check, instead check if the output len of char
# is the same as the number of chars in the graph
#traverse graph topological order
result = []
q = [c for c in in_degree if in_degree[c] == 0]
print(q)
while q:
node = q.pop()
result.append(node)
#remove incomming edge from nodes that depend on node
for nei in graph[node]:
in_degree[nei] -= 1
if in_degree[nei] == 0:
q.append(nei)
if len(in_degree) != len(result): return ""
return "".join(result)
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
# def test_simple(self):
# s = Solution()
# input = ["wrt", "wrf", "er", "ett", "rftt"]
# self.assertEqual(s.alienOrder(input), "wertf")
# def test_simple2(self):
# s = Solution()
# input = ["bsusz","rhn","gfbrwec","kuw","qvpxbexnhx","gnp","laxutz","qzxccww"]
# self.assertEqual(s.alienOrder(input), "")
def test_simple3(self):
s = Solution()
input = ["wrt","wrf","er","ett","rftt","te"]
self.assertEqual(s.alienOrder(input), "wertf")
unittest.main(verbosity=2)
|
'''
Created on May 15, 2010
@author: Dr. Rainer Hessmer
'''
import math
def GetBaseAndExponent(floatValue, resolution=4):
'''
Converts a float into a tuple holding two integers:
The base, an integer with the number of digits equaling resolution.
The exponent indicating what the base needs to multiplied with to get
back the original float value with the specified resolution.
'''
if (floatValue == 0.0):
return (0, 0)
else:
exponent = int(1.0 + math.log10(abs(floatValue)))
multiplier = math.pow(10, resolution - exponent)
base = int(floatValue * multiplier)
return(base, exponent - resolution)
def TestRoundTrip(floatValue):
pair = GetBaseAndExponent(floatValue)
print(pair)
regenFloat = pair[0] * math.pow(10, pair[1])
print(regenFloat)
if __name__ == '__main__':
TestRoundTrip(3.14)
TestRoundTrip(12.345)
TestRoundTrip(9.999999)
TestRoundTrip(0)
TestRoundTrip(-3.14)
|
from string import ascii_lowercase
for letter in ascii_lowercase:
filename = 'ex_45/'+letter+'.txt'
with open(filename, 'w') as file:
file.write(letter)
|
from math import pi
def sphere_volume(h, r=10):
vol = (4 * pi * (r**3)) / 3
air_vol = (pi * (h**2) * (3 * r - h)) / 3
return vol - air_vol
print(sphere_volume(2)) |
import pandas as pd
df = pd.read_csv('countries-by-area.txt', index_col='rank')
df['density']=df['population_2013']/df['area_sqkm']
df = df.sort_values(by='density', ascending=False)
for index, row in df[:5].iterrows():
print(row['country'])
|
digitsInString = input( "Entrez une liste de chiffres :" )
digitsInTab = []
for i in range( len( digitsInString ) ) :
if (digitsInString[i].isdigit()) :
digitsInTab.append( int(digitsInString[i] ))
atLeastOneDigitLeft = True
while (atLeastOneDigitLeft) :
atLeastOneDigitLeft = False
for i in range (len(digitsInTab)) :
print (str(digitsInTab[i]), end='')
if (digitsInTab[i] == 0 or digitsInTab[i] == " ") :
digitsInTab[i] = " "
else :
atLeastOneDigitLeft = True
digitsInTab[i] -= 1
print()
|
arr=[54,67,13,21,90,32]
def selectionsort(arr):
for i in range(len(arr)):
minidx=i
for j in range(i+1,len(arr)):
if arr[minidx]>arr[j]:
minidx=j
arr[i],arr[minidx]=arr[minidx],arr[i]
for i in range(0,len(arr)):
print(arr[i])
selectionsort(arr)
|
# TIE-02107: Programming 1: Introduction
# MAHABUB HASAN, mahabub.hasan@student.tut.fi, Student No.: 281749
# Solution of Task - 3.6.3
# Parasetamol
def calculate_dose(weight, time, total_doze_24):
amount_applicable = weight*15
if time > 5:
remain_dose = 4000-total_doze_24
if remain_dose > amount_applicable:
amount_can_given = amount_applicable
else:
amount_can_given = remain_dose
else:
amount_can_given = 0
return amount_can_given
def main():
weight=int(input("Patient's weight (kg): "))
time = int(input("How much time has passed from the previous dose (full hours): "))
total_doze_24= int(input("The total dose for the last 24 hours (mg): "))
amount = calculate_dose(weight, time, total_doze_24)
print("The amount of Parasetamol to give to the patient:", amount)
main()
|
def print_dict_order(input_dict):
copy_dict = []
copy_dict.clear()
for key, value in input_dict.items():
copy_dict.append((str(key)).strip()+ " " +(str(value)).strip())
copy_dict.sort()
print("Contestant score:")
count=0
for i in copy_dict:
count+=1
print(i)
#print(i,'and count',count)
def main():
input_dict={}
file_name = input("Enter the name of the score file: ")
infile=open(file_name,'r')
line=infile.readline()
line_count=1
while line:
temp_list=line.split(" ")
key=temp_list[0]
value=temp_list[1]
#print('key', key,'value',value)
if key in input_dict:
#print(temp_list[0],'key and value',temp_list[1])
pre_value=int(input_dict.get(key))
current_value=pre_value+int(value)
#print("pre value",pre_value, "current value",current_value)
input_dict[key]=current_value
else:
input_dict[key]=value
#print('value added')
#print(f"{line_count} {line}",end="")
line = infile.readline()
line_count+=1
infile.close()
print_dict_order(input_dict)
main()
|
# TIE-02107: Programming 1: Introduction
# MAHABUB HASAN, mahabub.hasan@student.tut.fi, Student No.: 281749
# Solution of Task - 5.4.4
def main():
performance1 = float(input('Enter the time for performance 1: '))
performance2 = float(input('Enter the time for performance 2: '))
performance3 = float(input('Enter the time for performance 3: '))
performance4 = float(input('Enter the time for performance 4: '))
performance5 = float(input('Enter the time for performance 5: '))
performance = [performance1, performance2, performance3, performance4, performance5]
best = min(performance)
worst = max(performance)
remove = best+worst
total = get_total(performance)
total = total - remove
average = total/(len(performance)-2)
print("The official competition score is", format(average, ".2f"), "seconds.")
def get_total(performance):
total = 0
for number in performance:
total = total + number
return total
main() |
# TIE-02107: Programming 1: Introduction
# Solution of Task - 6.3
# A program that shows stats from recorded step counts
"""
group members:
prasun biswas(267948)
Mahbub hasan(281749)
"""
"""this returns the count number withing certain limits(low & high)
from a input list"""
def filter_by_steps(input_list, lower_lim, higher_lim):
count_in_limit=0
for i in input_list:
if i>=lower_lim and i<=higher_lim:
count_in_limit+=1
return count_in_limit
""" this returns a list after removing the number which falls
between certain lower and upper limit"""
def filter_list(input_list,lower_lim,higher_lim):
filtered_list = []
for i in input_list:
if i not in range(lower_lim,higher_lim+1):
# print(i)
filtered_list.append(i)
return filtered_list
""" it calculates the minimum number of catagories required to divide all of the
steps counts in a range of 4000 thousand starting from the minimum of 1000 steps
after passing a filtered list as an input which already excludes any measurements
below 1000"""
def divide_categories(filtered_list):
max_step=max(filtered_list)+1
lower_limits_of_category=[]
number_of_category=(max_step-1000)//4000+((max_step-1000)%4000>0)
# print(number_of_category)
for i in range(1,number_of_category+1):
nth_lower_limit=4000*i + (1000-4000)
# print("nth lower",nth_lower_limit)
lower_limits_of_category.append(nth_lower_limit)
# print(lower_limits_of_category)
return lower_limits_of_category
"""this generates graphical representation"""
def counts_in_category(lower_limit_list,alist):
counts_in_category_list=[]
digit = 5
if len(str(max(lower_limit_list)))>5:
digit = len(str(max(lower_limit_list)))
# print("biggest digit", digit)
print("Graphical representation of information:")
for i in lower_limit_list:
count=filter_by_steps(alist,i,i+3999)
counts_in_category_list.append(count)
print(f"{i:{digit}d} {count*'#'}")
# print(f"count is {count} between {i} and {i+3999}")
# print("counts in each category")
# print(counts_in_category_list)
max_counts_in_category=max(counts_in_category_list)
index_max_count_category=counts_in_category_list.index(max_counts_in_category)
lower_limit=lower_limit_list[index_max_count_category]
print()
print(f"Steps taken during most of the days: over {lower_limit} but under {lower_limit+4000} steps")
""" prints miscellaneous information about days over 9000 steps,
longest distance walked in a day and total calories burned"""
def miscellaneous(filtered_list):
c_over_9000=filter_by_steps(filtered_list, 9000, (max(filtered_list) + 1))
longest_dis_a_day=float(max(filtered_list))*1.5/2500
total_steps_to_dis=float(sum(filtered_list))*1.5/2500
total_calory=total_steps_to_dis*50
if c_over_9000>=0:
print(f"Days with over 9000 steps taken: {c_over_9000} days")
if max(filtered_list)>=1000:
print(f"Longest distance walked during a day: {format(longest_dis_a_day,'.2f')} km")
print(f"Total calories consumed by walking: {int(round(total_calory))} kcal")
def main():
print("Enter the amount of steps/day, one day per line.")
print("End by entering an empty row.")
list_of_steps =[]
# user_input = None
user_input = (input())
while user_input !="":
if user_input !='':
int_user_input= int(user_input)
list_of_steps.append(int_user_input)
user_input = (input())
else:
break
total_days=len(list_of_steps)
rejected=filter_by_steps(list_of_steps, 0, 999)
filtered_list=filter_list(list_of_steps,0,999)
if total_days>0:
print(f"Information related to the period of measurement ({total_days} days):")
if rejected > 0:
print(f"Rejected {rejected} results of under 1000 steps/day.")
print()
if len(filtered_list)>0:
lower_limit_list=divide_categories(filtered_list)
counts_in_category(lower_limit_list,filtered_list)
# graphical_representation(filtered_list)
if len(filtered_list)>0:
miscellaneous(filtered_list)
# print(list_of_steps)
# print("steps in range",filter_by_steps(list_of_steps,5,10))
main()
|
'''
Python Program to Display the multiplication Table
'''
#Taking Input From User
num = int(input("Enter The number to display the multiplication table "))
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
|
my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
def dictionaryToTuple(dic):
newList = []
for k, v in dic.iteritems():
newList.append((k, v))
print newList
dictionaryToTuple(my_dict)
|
# Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.
raio = float(input("Digite o raio do círculo:\n"))
pi = 3.1415
area = (raio * raio) * pi
resultado = round(area, 2)
print(f"O valor do raio do círculo é: {resultado}")
|
while True:
print "enter -1 to break and 2 to continue "
x=int(raw_input("enter the choice"))
if x==-1:
break
#print "hello i have breaked it "
if x==2:
continue
#print "hello i am in continue"
print "hello i am in while loop"
print "hello i am outside of the loop "
|
n = raw_input("5")
if n >0:
print ("hello i am an interger number")
else:
print ("i am not an integer") |
#!/usr/bin/python3
"""
Design and implement a data structure for Least Recently Used (LRU) cache. It
should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists
in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present.
When the cache reached its capacity, it should invalidate the least recently
used item before inserting a new item.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
"""
class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.prev, self.next = None, None
class LRUCache:
def __init__(self, capacity: int):
"""
O(1) look up - Map
O(1) update most recent vs. least recent - Linked List
But Single linked list is not enough then Double Linked List
Need dummy head and tail to avoid over complication of null checking
"""
self.head = Node(None, None)
self.tail = Node(None, None)
self.head.next = self.tail
self.tail.prev = self.head
self.cap = capacity
self.map = {}
def get(self, key: int) -> int:
if key in self.map:
node = self.map[key]
self._remove(key)
self._appendleft(node)
return node.val
return -1
def put(self, key: int, value: int) -> None:
if key in self.map:
self._remove(key)
elif len(self.map) >= self.cap:
node = self.tail.prev
self._remove(node.key)
node = Node(key, value)
self._appendleft(node)
def _appendleft(self, node: Node):
self.map[node.key] = node # update/delete map in these two operators
nxt = self.head.next
self.head.next = node
node.prev = self.head
node.next = nxt
nxt.prev = node
def _remove(self, key: int):
node = self.map[key]
prev = node.prev
nxt = node.next
prev.next = nxt
nxt.prev = prev
del self.map[key] # update/delete map in these two operators
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
|
class BookShelf:
def __init__(self, *books):
self.books = books
def __str__(self):
return f"Bookshelf with {len(self.books)} books"
class Book:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Book {self.name}"
book = Book("Harry Potter")
book2 = Book("Hands ON ML")
book3 = Book("Hands ON ML")
book4 = Book("Hands ON ML")
shelf = BookShelf(book, book2, book3, book4)
print(len(shelf.books))
print(shelf)
|
### args collects everything being passed
def multiply(*args):
total = 1
for arg in args:
total = total *arg
return total
print(multiply(1,3,5))
def add(x,y):
return x+y
nums = [4,5]
print(add(*nums))
nums = {"x": 15, "y": 25}
print(add(x=nums["x"], y=nums["y"]))
print(add(**nums))
def add2(x,y,z ):
return x+y+z
nums = {"x": 15, "y": 25, "z": 30}
print(add2(**nums)) |
# Faça um programa que leia nome e peso de várias pessoas, guardando tudo em uma lista,
# depois do dado inserido, pergunte ao usuário se ele quer continuar,
# se ele não quiser pare o programa. No final mostre:
# Quantas pessoas foram cadastradas
# Mostre o maior peso
# Mostre o menor peso
people = list()
grupo = list()
ch = cont = 0
while True:
people.append(int(input('Insira o peso: ')))
people.append(str(input('Insira o nome: ')))
grupo.append(people[:])
people.clear()
ch = str(input('Deseja parar o programa?[Sim/Não] ')).upper().strip()[0]
cont += 1
if ch == 'S':
break
max_peso = min_peso = 0
grupo.sort()
print(grupo)
max_peso = grupo[cont-1][0]
min_peso = grupo[0][0]
print(f'O maior peso é de: {max_peso}')
print(f'O menor peso é de: {min_peso}')
|
pessoas = list()
cont = cont2 = cont3 = 0
while True:
pessoas.append(str(input('Insira o nome: ')))
pessoas.append(int(input('Insira sua idade: ')))
pessoas.append(str(input('Insira seu gênero[Homem/Mulher]: ').strip().upper()[0]))
if pessoas[1] > 18:
cont +=1
if pessoas[2] == 'H':
cont2 +=1
if pessoas[2] == 'M' and pessoas[1] < 20:
cont3 +=1
ch = str(input('Deseja parar o programa?[Sim/Não] ').strip().upper()[0])
if ch == 'S':
break
pessoas.clear()
print(f'Número de maiores de 18 é de: {cont} pessoas')
print(f'Número de homens é de: {cont2} pessoas')
print(f'Número de mulheres menores de 20 é de: {cont3} pessoas')
|
temp = list()
par = list()
impar = list()
lista = par,impar
for i in range(0,7):
temp.append(int(input('Insira um número: ')))
for i in temp:
if i % 2 == 0:
lista[0].append(i)
else:
lista[1].append(i)
par.sort()
impar.sort()
print(f'Resultado: {lista}')
|
def func(NOTA):
if NOTA >=0 and NOTA <=10:
if NOTA >=9:
return 'A'
elif NOTA >=8:
return 'B'
elif NOTA >=7:
return 'C'
elif NOTA >=6:
return 'D'
elif NOTA <=4:
return 'F'
else:
return 'INVÁLIDO!!!'
nota = float(input('Insira sua nota: '))
print(f'Você tirou a nota: {func(nota)}')
|
temp = list()
mta = list()
cont = 0
while cont != 3:
for i in range(0,3):
temp.append(int(input('Insira um número: ')))
mta.append(temp[:])
cont +=1
temp.clear()
print(f'[{mta[0][0]}] [{mta[0][1]}] [{mta[0][2]}]')
print(f'[{mta[1][0]}] [{mta[1][1]}] [{mta[1][2]}]')
print(f'[{mta[2][0]}] [{mta[2][1]}] [{mta[2][2]}]')
|
temp = list()
mta = list()
cont2 = cont3 = cont4 = 0
for cont in range(0,3):
for i in range(0,3):
temp.append(int(input('Insira um número: ')))
for i in temp:
if i % 2 == 0:
cont2 += i
if cont == 2:
for i in temp:
cont3 += i
if cont == 1:
for i in temp:
if cont4 < i:
cont4 = i
mta.append(temp[:])
temp.clear()
for i in mta:
print(f'[ {i[0]} ] [ {i[1]} ] [ {i[2]} ]')
print(f'A soma de todos os pares é igual a: {cont2}')
print(f'A soma da terceira coluna é igual a: {cont3} ')
print(f'O maior valor da coluna 2 é: {cont4}') |
import time
from turtle import Screen, Turtle
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0) # to enable control screen update instead of auto
home_position = [(0, 0), (-20, 0), (-40, 0)]
snake_squares = []
for position in home_position:
new_sq = Turtle("square")
new_sq.color("white")
new_sq.penup()
new_sq.goto(position)
snake_squares.append(new_sq)
game_is_on = True
while game_is_on:
screen.update()
time.sleep(0.1)
for sq_num in range(len(snake_squares) - 1, 0, -1):
new_x = snake_squares[sq_num - 1].xcor()
new_y = snake_squares[sq_num - 1].ycor()
snake_squares[sq_num].goto(new_x, new_y) # last square will go to second last square of snake body
snake_squares[0].forward(20)
screen.exitonclick()
|
#! /bin/python3
with open('input.txt') as f:
sum = 0
cnt = 0
for num in f:
sum += int(num)
cnt += 1
print('The average of the numbers in input.txt is ' + str(sum/cnt))
|
#!/bin/python3
import os
import sys
from functools import reduce
import operator
#
# Complete the connectingTowns function below.
#
def connectingTowns(n, routes):
#
# Write your code here.
# The code here.
if (len(routes)+1 == n):
out = reduce(operator.mul,routes,1)
return (out%1234567)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
routes = list(map(int, input().rstrip().split()))
result = connectingTowns(n, routes)
fptr.write(str(result) + '\n')
fptr.close()
|
import threading
import time
balance = 0
lock_k = threading.Lock()
def change(n):
global balance
with lock_k:
balance = balance + n
time.sleep(2)
balance = balance - n
time.sleep(1)
print("Thread name: {} ---> var n : {} var balance : {}".format(threading.current_thread().name, balance, n))
class ChangeBalanceThread(threading.Thread):
def __init__(self, n, *argsd, **kwargs):
super().__init__()
self.n = n
def run(self):
for i in range(10):
change(self.n)
if __name__ == '__main__':
t1 = ChangeBalanceThread(5)
t2 = ChangeBalanceThread(10)
t1.start()
t2.start()
t1.join()
t2.join() |
import time
import threading
from multiprocessing.dummy import Pool
def thread_run(n):
# 线程执行的任务
time.sleep(2)
print('start thread "{}" duty'.format(threading.current_thread().name))
print("the number n : {}".format(n))
print('stop thread "{}" duty'.format(threading.current_thread().name))
def use_Pool():
t1 = time.time()
pool = Pool(10)
list_var = range(100)
pool.map(thread_run, list_var)
pool.close()
pool.join()
t2 = time.time()
print("完成时间 {}".format(t2 - t1))
if __name__ == '__main__':
use_Pool() |
"""
event.wait(timeout=None):调用该方法的线程会被阻塞,如果设置了timeout参数,超时后,线程会停止阻塞继续执行;
event.set():将event的标志设置为True,调用wait方法的所有线程将被唤醒;
event.clear():将event的标志设置为False,调用wait方法的所有线程将被阻塞;
event.isSet():判断event的标志是否为True。
"""
import threading
from time import sleep
def test_event(n, event):
while not event.isSet():
print("Thread %s is ready" % n)
sleep(1)
while event.isSet():
print("Thread %s is running" % n)
sleep(1)
if __name__ == '__main__':
event = threading.Event()
t = threading.Thread(target=test_event, args=(10, event,))
t.start()
# event未作设置,则线程一致是准备状态
sleep(10)
# event做set,则线程是运行状态
event.set()
sleep(10)
# 清除事件,则线程运行停止
event.clear() |
# coding: utf-8
# # Weeks 13-14
#
# ## Natural Language Processing
# ***
# Read in some packages.
# In[2]:
# Import pandas to read in data
import numpy as np
import pandas as pd
# Import models and evaluation functions
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import BernoulliNB
from sklearn import metrics
from sklearn import cross_validation
# Import vectorizers to turn text into numeric
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
# Import plotting
import matplotlib.pylab as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# ## Basic Feature Engineering
# We have examined two ways of dealing with categorical (i.e. text based) data: binarizing/dummy variables and numerical scaling.
#
# See the following examples for implementation in sklearn to start:
# In[3]:
data = pd.read_csv("data/categorical.csv")
# In[4]:
data
# ### Binarizing
# Get a list of features you want to binarize, go through each feature and create new features for each level.
# In[5]:
features_to_binarize = ["Gender", "Marital"]
# Go through each feature
for feature in features_to_binarize:
# Go through each level in this feature (except the last one!)
for level in data[feature].unique()[0:-1]:
# Create new feature for this level
data[feature + "_" + level] = pd.Series(data[feature] == level, dtype=int)
# Drop original feature
data = data.drop([feature], 1)
# In[6]:
data
# ### Numeric scaling
# We can also replace text levels with some numeric mapping we create
# In[7]:
data['Satisfaction'] = data['Satisfaction'].replace(['Very Low', 'Low', 'Neutral', 'High', 'Very High'],
[-2, -1, 0, 1, 2])
# In[8]:
data
# ## Text classification
# We are going to look at some Amazon reviews and classify them into positive or negative.
# ### Data
# The file `data/books.csv` contains 2,000 Amazon book reviews. The data set contains two features: the first column (contained in quotes) is the review text. The second column is a binary label indicating if the review is positive or negative.
#
# Let's take a quick look at the file.
# In[9]:
get_ipython().system('head -3 data/books.csv')
# Let's read the data into a pandas data frame. You'll notice two new attributed in `pd.read_csv()` that we've never seen before. The first, `quotechar` is tell us what is being used to "encapsulate" the text fields. Since our review text is surrounding by double quotes, we let pandas know. We use a `\` since the quote is also used to surround the quote. This backslash is known as an escape character. We also let pandas now this.
# In[22]:
data = pd.read_csv("data/books.csv", quotechar="\"", escapechar="\\")
# In[23]:
data.head()
# ### Text as a set of features
# Going from text to numeric data is very easy. Let's take a look at how we can do this. We'll start by separating out our X and Y data.
# In[24]:
X_text = data['review_text']
Y = data['positive']
# In[25]:
# look at the first few lines of X_text
X_text.head()
# Do the same for Y
# In[26]:
# your code here
Y.head()
# Next, we will turn `X_text` into just `X` -- a numeric representation that we can use in our algorithms or for queries...
#
# Text preprocessing, tokenizing and filtering of stopwords are all included in CountVectorizer, which builds a dictionary of features and transforms documents to feature vectors.
#
# The result of the following is a matrix with each row a file and each column a word. The matrix is sparse because most words only appear a few times. The values are 1 if a word appears in a document and 1 otherwise.
# In[27]:
# Create a vectorizer that will track text as binary features
binary_vectorizer = CountVectorizer(binary=True)
# Let the vectorizer learn what tokens exist in the text data
binary_vectorizer.fit(X_text)
# Turn these tokens into a numeric matrix
X = binary_vectorizer.transform(X_text)
# In[28]:
# Dimensions of X:
X.shape
# There are 2000 documents (each row) and 22,743 words/tokens.
#
# Can look at some of the words by querying the binary vectorizer:
# In[29]:
# List of the 20 features (words) in column 10,000
features = binary_vectorizer.get_feature_names()
features[10000:10020]
# Spend some time to look at the binary vectoriser.
#
# Examine the structure of X. Look at some the rows and columns values.
# In[30]:
# see the density of 0s and 1s in X
import scipy.sparse as sps
import matplotlib.pyplot as plt
plt.figure(figsize=(20,10))
plt.spy(X.toarray())
plt.show()
# Look at the sparse matrix above. Notice how some columns are quite dark (i.e. the words appear in almost every file).
#
# What are the 5 most common words?
# In[31]:
# your code here
value = X.toarray().sum(axis=0)
re = pd.Series(value)
re.index = features
print re.sort_values(ascending=False)[0:5]
# Your answer here
# Write a function that takes the sparse matrix X, and gets the feature list from the vectoriser, and a document index (1 - 2000) and returns a list of the words in the file that corresponds to the index (the list should be obtained from the sparse matrix / bag of words representation NOT from the original data file).
# In[32]:
# complete the function
# returns vector of words / features
def getWords(bag_of_words, file_index_row, features_list):
Spare_matrix_array = bag_of_words.toarray()
test = Spare_matrix_array[file_index_row,:]
result = []
for i in range (0,len(test)):
if(test[i]==1):
result.append(features_list[i])
return result
getWords(X, 1, features)
# ### Modeling
# We have a 22743 features, let's use them in some different models.
# In[34]:
# Create a model
logistic_regression = LogisticRegression()
# Use this model and our data to get 5-fold cross validation accuracy
acc = cross_validation.cross_val_score(logistic_regression, X, Y, scoring="accuracy", cv=5)
# Print out the average accuracy rounded to three decimal points
print ("Mean accuracy of our classifier is " + str(round(np.mean(acc), 3)) )
# In[ ]:
Use the above classifier to classify a new example (new review below):
# In[38]:
new_review = """"
really bad book!
"""
# your code here ...
temp = new_review.split(' ')
matrix = []
for i in range(0,len(features)):
if features[i] in temp:
matrix.append(1)
else:
matrix.append(0)
logistic_regression = logistic_regression.fit(X.toarray(),Y)
# predit function needs a array with two dimensions.
predict = logistic_regression.predict([matrix])
print predict
# Let's try using full counts instead of a binary representation (i.e. each time a word appears use the raw count value).
# In[40]:
# Create a vectorizer that will track text as binary features
count_vectorizer = CountVectorizer()
# Let the vectorizer learn what tokens exist in the text data
count_vectorizer.fit(X_text)
# Turn these tokens into a numeric matrix
X = count_vectorizer.transform(X_text)
# Create a model
logistic_regression = LogisticRegression()
# Use this model and our data to get 5-fold cross validation accuracy
acc = cross_validation.cross_val_score(logistic_regression, X, Y, scoring="accuracy", cv=5)
# Print out the average AUC rounded to three decimal points
print( "Accuracy for our classifier is " + str(round(np.mean(acc), 3)) )
# Now try using TF-IDF:
# In[41]:
# Create a vectorizer that will track text as binary features
tfidf_vectorizer = TfidfVectorizer()
# Let the vectorizer learn what tokens exist in the text data
tfidf_vectorizer.fit(X_text)
# Turn these tokens into a numeric matrix
X = tfidf_vectorizer.transform(X_text)
# Create a model
logistic_regression = LogisticRegression()
# Use this model and our data to get 5-fold cross validation AUCs
acc = cross_validation.cross_val_score(logistic_regression, X, Y, scoring="accuracy", cv=5)
# Print out the average AUC rounded to three decimal points
print( "Accuracy for our classifier is " + str(round(np.mean(acc), 3)) )
# Use the tfidf classifier to classify some online book reviews from here: https://www.amazon.com/
#
# Hint: You can copy and paste a review from the online site into a multiline string literal with 3 quotes:
# ```
# """
# copied and pasted
# multiline
# string...
# """
# ```
# In[ ]:
# your code here
sample = "I loved Reed and Charlotte Everything that happened with the both of them made them that much more real There were also some laugh out loud moments so watch out for those if you are reading in a public place or else people will look at you like you are crazy"
sample_temp = sample.split(' ')
sample_matrix = []
for i in range(0,len(features)):
if features[i] in sample_temp:
sample_matrix.append(1)
else:
sample_matrix.append(0)
logistic_regression = logistic_regression.fit(X.toarray(),Y)
# predit function needs a array with two dimensions.
sample_predict = logistic_regression.predict([sample_matrix])
print sample_predict
# ### Extending the implementation
# #### Features
# Tfidf is looking pretty good! How about adding n-grams? Stop words? Lowercase transforming?
#
# We saw that the most common words include "the" and others above - start by making these stop words.
#
# N-grams are conjunctions of words (e.g. a 2-gram adds all sequences of 2 words)
#
#
# Look at the docs: `CountVectorizer()` and `TfidfVectorizer()` can be modified to handle all of these things. Work in groups and try a few different combinations of these settings for anything you want: binary counts, numeric counts, tf-idf counts. Here is how you would use these settings:
#
# - "`ngram_range=(1,2)`": would include unigrams and bigrams (ie including combinations of words in sequence)
# - "`stop_words="english"`": would use a standard set of English stop words
# - "`lowercase=False`": would turn off lowercase transformation (it is actually on by default)!
#
# You can use some of these like this:
#
# `tfidf_vectorizer = TfidfVectorizer(ngram_range=(1,2), lowercase=False)`
#
# #### Models
# Next swap out the line creating a logistic regression with one making a naive Bayes or support vector machines (SVM). SVM have been shown to be very effective in text classification. Naive Bayes has been used a lot also.
#
# For example see: http://www.cs.cornell.edu/home/llee/papers/sentiment.pdf
#
# In[ ]:
# Try different features, models, or both!
# What is the highest accuracy you can get?
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
from sklearn.naive_bayes import MultinomialNB
tfidf_vectorizer = TfidfVectorizer(ngram_range=(1,2), lowercase=False)
tfidf_vectorizer.fit(X_text)
numeric_X = tfidf_vectorizer.transform(X_text)
LinearSVC = LinearSVC()
MultinomialNB = MultinomialNB()
acc_SVC = cross_validation.cross_val_score(LinearSVC, numeric_X, Y, scoring="accuracy", cv=5)
acc_NB = cross_validation.cross_val_score(MultinomialNB, numeric_X, Y, scoring="accuracy", cv=5)
print( "Accuracy for our classifier by using SVM is " + str(round(np.mean(acc_SVC), 3)) )
print( "Accuracy for our classifier by using Native Bayes is " + str(round(np.mean(acc_NB), 3)) )
|
from random import randrange
def create_array(size_of_array: int) -> []:
array = [randrange(1, 50) for i in range(size_of_array)]
return array
array = create_array(10)
def quick_sort(array):
size_of_array = len(array) - 1
pivot_index = randrange(0, size_of_array)
pivot = array[pivot_index]
for index, i in enumerate(array):
print(index, i)
quick_sort(array)
|
from datetime import datetime
class Message:
DATE_FORMAT = '%Y.%m.%d'
TIME_FORMAT = '%H:%M:%S'
DATE_SEPARATOR = '.'
TIME_SEPARATOR = ':'
DATETIME_SEPARATOR = ' '
DATE_TIME_FORMAT = DATE_FORMAT + DATETIME_SEPARATOR + TIME_FORMAT
def __init__(self, date, time, sender, text):
self.date = date
self.time = time
self.datetime = date + Message.DATETIME_SEPARATOR + time
self.sender = sender
self.text = text
def getMessageLength(self):
return len(self.text)
def getHour(self):
return self.time.split(Message.TIME_SEPARATOR)[0]
def getWeekDay(self):
return datetime.strptime(self.datetime, Message.DATE_TIME_FORMAT).weekday()
def getMonth(self):
return self.date.split(Message.DATE_SEPARATOR)[1]
def getYear(self):
return self.date.split(Message.DATE_SEPARATOR)[0]
def __str__(self):
return "{} {} {}".format(self.datetime, self.sender, self.text)
|
def checkio(numbers_array):
result_array = []
for i in numbers_array:
if type(i)== int:
result_array.append(i)
else:
while type(i)!=int:
list(i)
result_array.append(i)
result_array = sorted(result_array, key= lambda v : -v if v<0 else v)
print(result_array)
return result_array
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
def check_it(array):
if not isinstance(array, (list, tuple)):
raise TypeError("The result should be a list or tuple.")
return list(array)
assert check_it(checkio((-20, -5, 10, 15))) == [-5, 10, 15, -20], "Example" # or (-5, 10, 15, -20)
assert check_it(checkio((1, 2, 3, 0))) == [0, 1, 2, 3], "Positive numbers"
assert check_it(checkio((-1, -2, -3, 0))) == [0, -1, -2, -3], "Negative numbers"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
|
# Implementation of binary search algorithm
# We will prove that binary search is faster than naive search
# naive search: scan the entire list and ask if it's equal to the target
# if yes, return the index
# if no, then return -1
def naive_search(l, target):
for i in range(len(l)):
if l[i] == target:
return i
return -1
# binary search uses divide and conquer
# we will leverage the fact that our list is sorted
def binary_search(l, target, low=None, high=None):
if low == None:
low = 0
if high == None:
high = len(l) - 1
midpoint = (low + high) // 2
if high < low:
return -1
if l[midpoint] == target:
return midpoint
elif target < l[midpoint]:
return binary_search(l, target, low, midpoint-1)
else:
return binary_search(l, target, midpoint+1, high)
if __name__ == '__main__':
l = [1, 3, 5, 10, 12]
target = 10
print(naive_search(l, target))
print(binary_search(l, target))
|
def gradient_descent(X, Y, learning_rate=0.3, m=0, b=0, iterations=5):
for i in range(iterations):
b_gradient = - (2 / len(X)) * sum([Y[i] - (m * X[i] + b)
for i in range(len(X))])
m_gradient = - (2 / len(X)) * sum([X[i] * (Y[i] - (m * X[i] + b))
for i in range(len(X))])
b = b - (learning_rate * b_gradient)
m = m - (learning_rate * m_gradient)
return b, m
if __name__ == '__main__':
from sklearn.datasets import make_regression
from misc import mean_square_error
import matplotlib.pyplot as plt
import pandas as pd
# Sample Data
data_regression = make_regression(n_samples=300, n_features=1, n_targets=1, noise=30, bias=10)
data = pd.DataFrame.from_records(data_regression[0], columns=['x'])
data['y'] = data_regression[1]
X = data.x.values
Y = data.y.values
b, m = gradient_descent(X, Y)
Y_prediction = [m * X[i] + b for i in range(len(X))]
print("mean_square_error: ", mean_square_error(Y, Y_prediction))
f = plt.figure(figsize=(12, 4), dpi=80)
plt.scatter(X, Y, figure=f)
plt.plot(X, Y_prediction, "--", figure=f)
plt.show()
|
#Whats your name ?
import time
name = input('What is your name? ')
if len(name) < 3:
print("Name must be at least 3 characters long")
elif len(name) > 50:
print("Name must be maximum of 50 characters")
print('Hi ' + name + " \U0001F60A")
time.sleep(.70)
#favourite Color
favourite_color = input('What is your favourite color? ')
time.sleep(.70)
print('What a choice ' + favourite_color + ' is so unique ' )
time.sleep(.70)
#Person Age
person_age = input('What is your Age? ')
time.sleep(.70)
print("What a coincidence i am " + person_age + ' too ' + "\U0001F632")
import random
import time
#!/usr/bin/env python3
import random
guess = 0
number = random.randint(1, 10)
tries = 1
#Guess Game
print("Hey " + name + " wanna play a game" )
question = input("Would you like top play A Game? [Y/N] ")
if question == "n":
print("oh..okay")
if question == "y" or question == "" or question == "" or question == "":
print("I am thinking of a number between 1 and 10")
guess = int(input("Have a guess: "))
if guess > number:
print("Guess lower...")
if guess < number:
print("Guess higher..")
while guess != number:
tries += 1
guess =int(input("Try Again: "))
if guess < number:
print("Guess Higher")
if guess == number:
print("You are right! you won! The number was", number, \
"and it took you ", tries, " tries")
#Facts
time.sleep(1 )
facts = input("Hey Wanna Know some Fun Facts about our World [Y/N] ")
if facts == "n" or facts == "N":
print('No Problem ')
if facts == "y" or facts == "Y":
print("1. North Korea and Cuba are the only places you can't buy Coca-Cola.")
time.sleep(4)
print("2. the longest place name on the planet is 85 letters long")
time.sleep(4)
print("3. If you make ice cubes with tap water, they will be white; if you use boiled water, they will be transparent")
time.sleep(4)
print("4. You spend so little electricity charging your smartphone that even if you calculated the yearly cost of it, it would be less than $1.")
time.sleep(4)
print("5. In order to burn just 1 calorie, you need to click a mouse button 10 million times.")
time.sleep(4)
print("6. When you take a hot bath, you burn as many calories as you would if you went for a 30-minute walk.")
time.sleep(4)
print("7. Bananas have a curved shape because they reach for the sunlight when they grow.")
time.sleep(4)
print("8. The Mona Lisa was in Napoleon Bonaparte's bedroom for a few years.")
time.sleep(4)
print("9. The Pokemon characters Hitmonlee and Hitmonchan were named after Bruce Lee and Jackie Chan.")
time.sleep(4)
print("10. 99% of the microbes that live inside humans are unknown to science.")
|
"""
Dagobert Main file
"""
import pygame
import game_classe
import menu_classe
# -------- Main Program -----------
menu = menu_classe.Menu()
game = game_classe.Game()
done = False
pygame.init()
print('Initialized ! Launching ...')
while not done:
res_m = menu.launch()
print(res_m)
if res_m == 'QUIT':
done = True
elif res_m == 'PLAY':
done = not game.launch(menu.getDifficulty())
print(done)
pygame.quit()
print('QUITTING GAME !!!')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.