text stringlengths 37 1.41M |
|---|
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def compare(a, b):
if a is None and b is None:
return True
if a.val != b.val:
return False
if a is not None and b is not None:
return compare(a.left, b.left) and compare(a.right, b.right)
return False
node1 = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node4 = TreeNode(4)
node5 = TreeNode(5)
node6 = TreeNode(6)
node7 = TreeNode(7)
nodeNone = TreeNode(None)
print(compare(node1, node2))
print(compare(node1, node1))
print(compare(nodeNone, node1))
print(compare(nodeNone, nodeNone))
oneStackRight = TreeNode(1, node1, node2)
oneStackLeft = TreeNode(1, node1, node2)
print(compare(oneStackLeft, oneStackRight))
oneStackRight = TreeNode(1, node1, node3)
oneStackLeft = TreeNode(1, node1, node2)
print(compare(oneStackLeft, oneStackRight))
twoStackRight = TreeNode(1, TreeNode(2, node4, node5), TreeNode(3, node6, node7))
twoStackLeft = TreeNode(1, TreeNode(2, node4, node5), TreeNode(3, node6, node7))
print(compare(twoStackRight, twoStackLeft))
twoStackRight = TreeNode(1, TreeNode(2, node4, node5), TreeNode(3, node6, node5))
twoStackLeft = TreeNode(1, TreeNode(2, node4, node5), TreeNode(3, node6, node7))
print(compare(twoStackRight, twoStackLeft)) |
import pandas as pd
fixed_df = pd.read_table('telrecords.csv', ";")
base_of_numbers = list(fixed_df.loc[:, 'caller'])
base_of_innumbers = list(fixed_df.loc[:, 'caller'])
accepted = []
def inline_calls(number):
for i in base_of_numbers:
right = base_of_numbers[base_of_numbers['caller'] == number]['caller'].count()
print(right)
accepted.append(right)
return accepted
def is_in_base(number):
if number in base_of_numbers:
print(number)
else:
print("Phone number not found")
return False
def perform(number):
if number:
is_in_base(number)
elif number == "":
print("Bye!")
exit()
def statistics(number):
inline_calls(number)
average_time = []
incoming_calls = []
print("{} accepted outgoing calls".format(accepted))
print("average time: " + str(average_time))
print("{} accepted incoming calls".format(incoming_calls))
def choose(choice): # функция выбора пользователя
if choice == "1":
statistics(number)
elif choice == "2":
question()
elif choice == "3":
print("Bye!")
exit()
def question():
print("1) Enter your phone number: ")
number = int(input())
print()
perform(number)
while True:
print("1) Enter your phone number: ")
number = int(input())
print()
perform(number)
print("Select an action:")
print("1 - Call statistics")
print("2 - Call history with other contact")
print("3 - Exit")
print("Your choice: ")
choice = input()
print()
choose(choice) |
## IMPORTS GO HERE
from math import pi
## END OF IMPORTS
#### YOUR CODE FOR get_area GOES HERE ####
def get_area(radius):
r=radius
area=pi*pow(radius,2)
return area
#### End OF MARKER
#### YOUR CODE FOR output_parameter GOES HERE ####
def output_parameter(radius):
r=radius
parameter=2*pi*radius
print 'The parameter of the circle with radius', r ,'is',parameter
#### End OF MARKER
if __name__ == '__main__':
print get_area(2)
output_parameter(1.0)
|
def checkPalindrome(inputString):
return inputString == inputString[::-1]
''' Alternative Solution'''
'''
length = len(inputString)
for i in range((length+1) // 2):
if inputString[i] != inputString[length-1-i]:
return False
return True
'''
|
__author__ = 'BHS-programing'
def findAverage(cost, items):
average = cost/items
print("Average item cost is $ "+ str(average))
def costDisplay(cost):
print("Total cost of items is $" + str(cost))
numItemsPurchased = int(input("How many items? "))
totalCostItems = 0
for numItemsPurchased in range(numItemsPurchased):
itemCost = float(input("Enter the cost of the item: $"))
totalCostItems = totalCostItems + itemCost
costDisplay(totalCostItems)
findAverage(totalCostItems, numItemsPurchased) |
"""
Machine Learning(기계 학습) -> Deep Learning(심층 학습)
training data set(학습 세트) / test data set(검증 세트)
신경망 층을 지나갈 때 사용되는 가중치(weight) 행렬, 편항(bias) 행렬을 찾는 게 목적
오차를 최소화하는 가중치 행렬을 찾아야 한다
손실(loss) 함수 / 비용(cost) 함수의 값을 최소화하는 가중치 행렬 찾기
손실 함수:
- 평균 제곱 오차(MSE: Mean Squared Error)
- 교차 엔트로피(Cross-Entropy)
"""
import numpy as np
from dataset.mnist import load_mnist
if __name__ == '__main__':
(X_train, y_train), (X_test, y_true) = load_mnist()
# 10개 테스트 이미지의 실제 값
print('y_true =', y_true[:10])
# 10개 테스트 이미지의 예측 값
y_pred = np.array([7, 2, 1, 6, 4, 1, 4, 9, 6, 9])
print('y_pred =', y_pred)
# 오차
error = y_pred - y_true[:10]
print('error =', error)
# 오차 제곱(squared error)
sq_err = error ** 2
print('squared error =', sq_err)
# 평균 제곱 오차(mean squared error)
mse = np.mean(sq_err)
print('MSE =', mse)
# RMSE(Root Mean Squared Error)
print('RMSE =', np.sqrt(mse))
|
import numpy as np
import matplotlib.pyplot as plt
def numerical_diff(fn, x):
"""함수 fn과 점 x가 주어졌을 때 x에서의 함수 fn의 미분(도함수) 값"""
h = 1e-4 # 0.0001
return (fn(x + h) - fn(x - h)) / (2 * h)
def f1(x):
return 0.001 * x**2 + 0.01 * x
def f1_prime(x):
"""근사값을 사용하지 않은 함수 f1의 도함수"""
return 0.002 * x + 0.01
def f2(x):
"""x = [x1, x2, ...]"""
if x.ndim == 1:
return np.sum(x**2) # x0**2 + x1**2
else:
return np.sum(x**2, axis=1)
def _numerical_gradient(fn, x):
"""점 x = [x0, x1, ..., xn]에서의
함수 fn = fn(x0, x1, ..., xn)의 각 편미분(partial differential) 값 배열을 리턴
"""
x = x.astype(np.float, copy=False) # 실수 타입
gradient = np.zeros_like(x) # np.zeros(x.shape)
h = 1e-4 # 0.0001
for i in range(x.size):
ith_value = x[i]
x[i] = ith_value + h
fh1 = fn(x)
x[i] = ith_value - h
fh2 = fn(x)
gradient[i] = (fh1 - fh2) / (2 * h)
x[i] = ith_value
return gradient
def numerical_gradient(fn, X):
"""x = [
[x11 x12 x13 ...],
[x21 x22 x23 ...]
...
]"""
if X.ndim == 1:
return _numerical_gradient(fn, X)
else:
grad = np.zeros_like(X)
for idx, x in enumerate(X):
grad[idx] = _numerical_gradient(fn, x)
return grad
def f3(x):
return x[0] + x[1]**2 + x[2]**3
def f4(x):
return x[0]**2 + x[0] * x[1] + x[1]**2
if __name__ == '__main__':
estimate = numerical_diff(f1, 3)
print('근사값:', estimate)
real = f1_prime(3)
print('실제값:', real)
# f2 함수의 점 (3, 4)에서의 편미분 값
estimate_1 = numerical_diff(lambda x: x**2 + 4**2, 3)
print(estimate_1)
estimate_2 = numerical_diff(lambda x: 3**2 + x**2, 4)
print(estimate_2)
gradient = numerical_gradient(f2, np.array([3, 4]))
print(gradient)
# f3 = x0 + x1**2 + x2**3
# 점 (1, 1, 1)에서의 각 편미분 값
# df/dx0 = 1, df/dx1 = 2, df/dx2 = 3
gradient = numerical_gradient(f3, np.array([1, 1, 1]))
print(gradient)
# f4 = x0**2 + x0 * x1 + x1**2
# 점 (1, 2)에서의 df/dx0 = 4, df/dx1 = 5
gradient = numerical_gradient(f4, np.array([1, 2]))
print(gradient)
x0 = np.arange(-2, 2.5, 0.25)
x1 = np.arange(-2, 2.5, 0.25)
X, Y = np.meshgrid(x0, x1)
X = X.flatten()
Y = Y.flatten()
# print(np.array([X, Y]))
grad = numerical_gradient(f2, np.array([X, Y]))
# print(grad)
plt.figure()
plt.quiver(X, Y, -grad[0], -grad[1], angles="xy", color="666666")
plt.xlim([-2, 2])
plt.ylim([-2, 2])
plt.xlabel('x0')
plt.ylabel('x1')
plt.grid()
plt.legend()
plt.draw()
plt.show()
|
x=2
y=3
for i in range(100000):
n=y/x
if int(n)==n:
y=y+1
x=2
elif int(n)!=n:
x=x+1
if x==y:
print(y)
#while x <= y or int(n)==n:
# n=y/x
#
# if int(n)==n:
# print("Ist keine Primenzahl")
# elif int(n)!=n:
# x=x+1
#if x==y:
# print(y)
|
# Task 1 - while loop that repeats forever - comment this task later so you don't run into infinite loop later
number = 1
while True:
print(number)
number += 1
# Task 2 - print only the first 10 integers and calculate the sum of these numbers
number_2 = 1
sum = 0
while number_2 < 11:
print(number_2)
sum += number_2
number_2 += 1
print(sum)
# Task 3 - number of digits in a number
num = 9845198
count = 0
while num != 0:
num //= 10
count+= 1
print("Number of digits: ", count)
# Task 4 - number guessing game
num = 42
guessnum = int(input("How many guesses should we have?\n"))
guess = 0
while guessnum > 0 and guess != num:
guess = int(input("Take a guess:\n"))
if guess > num:
print("I thought of a smaller number.")
elif guess < num:
print("I thought of a bigger number.")
guessnum -= 1
print("You have " + str(guessnum) + " chances left.")
if guess == num:
print("Congratulations, I thought of " + str(guess) + " indeed.")
else:
print("Maybe next time. The number I thought was " + str(num) + ".")
# Task 5 - display the Fibonacci series
counter = 10
num1 = 0
num2 = 1
print("Fibonacci sequence:")
while count > 0:
print(str(num1) + "\n")
temp = num1 + num2
num1 = num2
num2 = temp
count -= 1
# Task 6 - nursery rhyme
i = 0
times = int(input("How many times you want to say it?"))
word = "If you happy and you know it..."
while i < times:
do_something = input("Do something: ") # Clap your hand
print("%s \n%s" %(word, do_something))
i += 1
print("")
# Bonus Task - prime number from 1 to 100
number = 2
counter = 2
isPrime = True
while number < 100:
counter = 2
isPrime = True
while counter < number:
if number % counter == 0:
isPrime = False
counter += 1
if isPrime:
print(number)
number += 1
|
input_date = input("Give me today's date with this format: e.g. 2021-02-24:\n")
date = input("Give me your birth date with the same format:\n")
days = 0
daysOfMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# Spliting the text to list element
for i in date:
born = date.split('-')
for j in input_date:
date_now = input_date.split('-')
# Converting the list element from string to int
for i in range(len(born)):
born[i] = int(born[i])
for i in range(len(date_now)):
date_now[i] = int(date_now[i])
while (not (born[1] == date_now[1] and born[0] == date_now[0] and born[2] == date_now[2])):
if born[1] == 2 and ((born[0] % 4 == 0 and born[0] % 100 != 0) or born[0] % 400 == 0):
if born[2] < daysOfMonths[born[1] - 1] + 1:
born[2] += 1
else:
born[1] += 1
born[2] = 1
else:
if born[2] < daysOfMonths[born[1] - 1]:
born[2] += 1
else:
if born[1] == 12:
born[0] += 1
born[1] = 1
born[2] = 1
else:
born[1] += 1
born[2] = 1
days += 1
print("You are %s days old." % days)
# Task 2 - finding anagrams
word_1 = "Amy"
word_2 = "May"
if len(word_1) == len(word_2):
if sorted(word_1.lower()) == sorted(word_2.lower()):
print("These are anagrams.")
else:
print("These are not anagrams.")
else:
print("These are not anagrams.")
# Task 3 - slow down
speed = [96, 98, 72, 64, 93, 61, 95, 78, 54, 51, 52, 55, 47, 70, 68, 67, 79, 83, 59, 76, 45, 82, 87, 66, 89, 62, 69, 74, 75, 48, 88, 81, 86, 97, 94, 71, 46, 57, 50, 53]
slows = 0
for i in range(len(speed)-1):
minSpeed = speed[i+1]
for j in range(i+1, len(speed)-1):
if speed[j] < minSpeed:
minSpeed = speed[j]
if speed[i] > minSpeed:
slows += 1
print(slows, "cars needs to slow down to avoid accidents.")
# Task 4 - voting for new burger
burgers = ["Spicy Pinata", "Cheesy Dream", "Vegan Fluffy", "Fatty Boom", "Tortuga", "Pork Pie"]
votes = [95061, 93439, 98563, 90478, 90915, 97334]
# number of new burgers
print("We have " + str(len(burgers)) + " different burgers to choose from.")
# votes per burgers
print("The votes on the different burgers are the followings:")
for i in range(len(burgers)-1):
print(f"\t{burgers[i]}: {votes[i]} votes") # using f"string"
# winner of the competition
index = 0
for i in range(len(votes)-1):
if votes[index] < votes[i]:
index = i
print("The winner is %s ." % burgers[index])
# number of votes
number_of_votes = 0
for i in votes:
number_of_votes += i
print(number_of_votes, " people voted in the game.")
|
'''
Dictionaries
Create a function that takes 2 dictionaries and 1 list as inputs.
The output of the function should be a dictionary with one key for each value in the input list
where the corresponding value is a list of key pairs that indicate where the input dictionaries match for that particular value.
See example below for clarification.
# Sample Output:
{
"math":[
["john","michael"],
["john","mary"],
["max","michael"],
["max","mary"]
],
"physics":[
["michael","sam"]
],
"p.e.":[
["mary","john"]
],
"music":[
["sam","max"]
],
"english": None
}
NOTES: A dictionary is not sortable.
'''
import itertools
import pprint
# Sample Input:
best_subject = {
"john":"math",
"michael":"physics",
"mary":"p.e.",
"sam":"music",
"max":"math"
}
worst_subject = {
"john":"p.e.",
"michael":"math",
"mary":"math",
"sam":"physics",
"max":"music"
}
subjects = ["math","physics","p.e.","music","english"]
def students(best_subject, worst_subject, subjects):
#create 1 dict, which will get appended to each loop
stud = {}
for s in subjects:
#needs to be inside loop to restart the lists each loop,
#otherwise if it is outside, it will add too many values to the list
best = []
worst = []
for k,v in best_subject.items():
if v == s:
best.append(k)
for k,v in worst_subject.items():
if v == s:
worst.append(k)
#utilize itertools to make cartesian product of lists
result = list(itertools.product(best,worst))
stud[s] = None if len(result) == 0 else result
return stud
buddies = students(best_subject, worst_subject, subjects)
pprint.pprint(buddies)
|
# Вывести последнюю букву в слове
word = 'Архангельск'
print(word[-1])
# Вывести количество букв "а" в слове
counter = 0
word = 'Архангельск'
for letter in word:
if letter.lower() == 'а':
counter += 1
print(f'Word {word} has {counter} \'a\' char(s) \n')
# Вывести количество гласных букв в слове
word = 'Архангельск'
vowels =['а', 'о', 'э', 'е', 'и', 'ы', 'у', 'ё', 'ю', 'я']
vowels_counter = 0
for letter in word:
if letter.lower() in vowels:
vowels_counter += 1
print(f'Word {word} has {vowels_counter} vowel(s) \n')
# Вывести количество слов в предложении
sentence = 'Мы приехали в гости'
words = sentence.split()
print(f'Sentence \"{sentence}\" has {len(words)} word(s) \n')
# Вывести первую букву каждого слова на отдельной строке
sentence = 'Мы приехали в гости'
words = sentence.split()
for word in words:
print(f'The first letter of the word \"{word}\" is {word[0]} \n')
# Вывести усреднённую длину слова в предложении
sentence = 'Мы приехали в гости'
words = sentence.split()
count_letter = []
for word in words:
count_letter.append(len(word))
avg = sum(count_letter)/len(sentence.split())
print(avg) |
# from typing import Number
from numbers import Number
def sign(val: float) -> int:
"""Return 1 or -1 to represent the sign of the given value"""
return -1 if val < 0 else 1
|
# codding utf-8
import turtle
#import tkSimpleDialog # 2.x python
import random
import math
def gotoxy(x, y):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
def draw_circle(rad, color):
turtle.fillcolor(color)
turtle.begin_fill()
turtle.circle(rad)
turtle.end_fill()
turtle.speed(0)
# baraban
gotoxy(0, 0)
turtle.circle(80)
gotoxy(0, 160)
draw_circle(5, 'red')
# bullets
phi = 360 / 7
r = 50
for i in range(0, 7):
phi_rad = phi * i * math.pi / 180.0
gotoxy(math.sin(phi_rad)*r, math.cos(phi_rad) * r + 57)
turtle.circle(22)
gotoxy(math.sin(phi_rad)*r, math.cos(phi_rad) * r + 57)
draw_circle(22, 'brown')
turtle.exitonclick()
# answer = ''
# while answer != 'n':
# answer = turtle.textinput("Нарисовать окружность", "y/n")
# # answer = tkSimpleDialog.askstring("Нарисовать окружность", "Y/N") # 2.x python
#
# if answer == 'y':
# # turtle.circle(30)
# turtle.penup()
# turtle.goto(random.randrange(-300, 300), random.randrange(-300, 300))
# turtle.pendown()
# turtle.fillcolor(random.random(), random.random(), random.random())
# turtle.begin_fill()
# turtle.circle(random.randrange(1, 100))
# turtle.end_fill()
# else:
# pass
|
import sys
def checkAnagrams(strA, strB):
if len(strA) != len(strB):
# trivial case
return 'no'
else:
if sorted(strA) == sorted(strB):
return 'yes'
else:
return 'no'
print('enter strings and find out if they are anagrams')
print('exit with ctrl-c\n')
while True:
print('string A: ')
a = sys.stdin.readline()[:-1]
print('string B: ')
b = sys.stdin.readline()[:-1]
print(checkAnagrams(a, b) + '\n')
|
#task01
"""
0. Дан список чисел, заменить каждое число на квадрат этого числа.
[1, 2, 3, 4] -> [1, 4, 9, 16]
"""
spis_OK = [1, 2, 3, 4]
def f(spis_OK):
for i in range(len(spis_OK)):
spis_OK[i] = spis_OK[i] ** 2
return spis_OK
print(f(spis_OK)) |
# Task03
"""
Дан список, содержащий положительные и отрицательные числа.
Заменить все элементы списка на противоположные по знаку.
Например, задан список [1, -5, 0, 3, -4].
После преобразования должно получиться [-1, 5, 0, -3, 4]."""
# a = [-4, -2, -3, 4, -6, 4, 343]
def reverse_values(a):
for i in range(len(a)):
a[i] *= -1
return a
if __name__ == '__main__':
assert reverse_values([-1, -2, -3]) == [1, 2, 3]
assert reverse_values([1, 1, 1]) == [-1, -1, -1]
assert reverse_values([]) == []
assert reverse_values([1, -1, 0]) == [-1, 1, 0] |
#task 05
"""
Напишите программу, запрашивающую имя, фамилия, отчество и номер группы студента и выводящую введённые данные в следующем виде:
************************************
*Лабораторная работа № 1 *
*Выполнил(а): ст. гр. ЗИ-123 *
*Иванов Андрей Петрович *
************************************
"""
# a = str(input("Pls enter student's 1stname\n>"))
# b = str(input("Pls enter student's 2stname\n>"))
# c = str(input("Pls enter student's patronymic\n>"))
# d = str(input("Pls enter student's group No.\n>"))
a = 'Bw'
b = 'sdwer'
c = 'sw'
d = 'DN3221'
string = ['Лабораторная работа N 1', 'Выполнил(а): ст. гр.' + d, "{} {} {}".format(a, b, c)]
def find_max(string):
strs = string[0]
for strs_max in string:
if int(len(strs)) < int(len(strs_max)):
strs = strs_max
return strs
find_max(string)
w = int(len(find_max(string))) + 2
print ('*' * (w + 2))
cstr = "*{:^%s}*" % w
print(cstr.format(string[0]))
print(cstr.format(string[1]))
print(cstr.format(string[2]))
print ('*' * (w + 2)) |
# Task 15
"""
15. Программа переводчик на соленый язык.
Правило: после каждой гласной вставляем с + сама гласная.
Привет -> Приcивеcет
Сальса -> саcальсаcа
"""
vowels = ['а', 'о', 'и', 'е', 'ё', 'э', 'ы', 'у', 'ю', 'я']
a = [i for i in input('Введите фразу по-русски:')]
b = []
s = 'с'
c = ''
for i in range(len(a)):
if str(a[i]) in vowels:
b.append(a[i])
b.append(s)
b.append(a[i])
else:
b.append(a[i])
c = c.join(b)
print(c) |
#task04
"""
Вывести на экран 10 первых простых чисел используя функцию задания 1
Подсказка:
>>if is_prime(num):
print(num)
"""
a = int(input('Введите кол-во простых\n>'))
list = [2]
j = 3
def is_prime(b):
for i in range (2, b):
if b % i is not 0:
i += 1
else: return b
return 0
while int(len(list)) < a:
if is_prime(j) == 0:
list.append(j)
j += 1
else:
j += 1
print(list) |
#Task 02
"""
Создать класс Автосалон содержащий информацию: адрес, имя, список доступных машин.
Реализовать методы для отображения всех доступных машин, добавления новых машин, покупки машин (после покупки машина удаляется из списка) + проверки на наличие такой машины в салоне
Пример
>> car1 = Car(‘Audi’, ‘Red’, ‘1999’, ‘$12000’)
>> car2 = Car(‘BMW’, ‘Black’, ‘2009’, ‘$18000’)
>>
>>showroom = ShowRoom(‘Borshagovska 17’, ‘Volkswagen showroom’)
>>showroom.add_car(car1)
>>showroom.add_car(car2)
>>
>>showroom.show_all()
1
————————-
name: Audi
color: Red
year: 1999
price: $12000
2
—————————
name: BMW
color: Black
year: 2009
price: $18000
>>showroom.sell_car(Car(‘Volvo’, ‘Red’, ’1993’, ‘$20000’))
‘No such car!’
>>showroom.sell_car(car1)
‘Car has been sold!’
>>showroom.show_all()
1
—————————
name: BMW
color: Black
year: 2009
price: $18000
"""
class ShowRoom:
def __init__(self, name_init, address_init):
self.name = name_init
self.address = address_init
self._cars = []
def add_car(self, car):
self._cars.append(car)
def show_all(self):
string = ''
for car in self._cars:
if car.status == 'In stock':
string = string + str(car) + '\n'
# print('\n\n'.join(map(str, self._cars)))
print('Автосалон', self.name, 'на', self.address, ':\n', string)
def reserve_car(self, car):
car.status = 'Reserved'
print('Reserved\n')
def sell_car(self, car):
if car in self._cars:
car.status = 'Sold'
print('Sold\n')
def is_car(self, car):
if car.status == 'In stock':
print('In stock\n')
elif car.status == 'Sold' or 'Reserved':
print('This car has been sold or reserved')
else:
print('Unavailable\n')
class Car:
def __eq__(self, other):
return [self.model, self.year, self.color, self.price, self.status] == \
[other.model, other.year, other.color, other.price, other.status]
def __init__(self, model, color, year, price, status):
self.model = model
self.color = color
self.year = year
self.price = price
self.status = status
def __str__(self):
string = f'status: {self.status}\nmodel: {self.model}\ncolor:' \
f'{self.color}\nyear: {self.year}\nprice: {self.price}\n'
return string
car1 = Car('Audi', 'Red', '1999', '$12000', 'In stock')
car2 = Car('BMW', 'Black', '2009', '$18000', 'In stock')
showroom = ShowRoom('VW showroom', 'Borshagovska 17')
showroom2 = ShowRoom('BMW', 'Khreshatyk 17')
showroom.add_car(car1)
showroom.add_car(car2)
showroom.show_all()
showroom2.add_car(car1)
showroom2.add_car(car2)
showroom2.show_all()
showroom.sell_car(car1)
showroom.show_all()
showroom2.reserve_car(car2)
showroom2.show_all()
showroom2.is_car(car2)
# showroom2.is_car(car2)
|
x=int(input("enter a 3 digit number"))
print(x%10)
x=x//10
print(x%10)
x=x//10
print(x%10)
|
__all__ = ['date_range', 'get_past_date', 'parse_date']
import datetime
def date_range(since=datetime.date.today(), until=datetime.date.today()):
"""Get date range from `since` until `until`.
:type since: datetime.date
:param since: Earliest date of the range.
:type until: datetime.date
:param until: Latest date of the range.
:rtype: iterable
:returns: iterable of datetime.date instances for each date within the range.
"""
while since <= until:
yield until
until -= datetime.timedelta(days=1)
def get_past_date(days=0, weeks=0):
"""Get past n days and m weeks ago date. Defaults to today's date.
:type days: int
:param days: Number of days ago if positive, later if negative.
:type weeks: int
:param weeks: Number of weeks ago if positive, later if negative.
"""
return (datetime.date.today() - datetime.timedelta(days=days, weeks=weeks))
def parse_date(date_string, format='%Y-%m-%d'):
return datetime.datetime.strptime(date_string, format).date()
|
import pandas
def moving_average(series, n):
#calculate moving average
#the outputing numpy ndarray is the output
outcome=pandas.Series(series).rolling(window=n).mean().iloc[n-1:].values
return print(outcome)
#testing array
x = [87, 56, 16, 97, 45, 75, 41, 863, 90.2, 4]
#testing the function with window of 5, feel free to change the window size
moving_average(x,5)
|
import copy
from typing import List, Tuple
from environment import Environment
class Board(object):
"""board for the game
/*
* /////////////////////////////////////////////////
* // //////////////////////// 棋盘表示, 坐标, 一维坐标, 字母
* // Y
* // ^
* // S 18 |
* // R 17 |
* // Q 16 |
* // P 15 |
* // O 14 |
* // N 13 |
* // M 12 |
* // L 11 |
* // K 10 |
* // J 9 |
* // I 8 |
* // H 7 |
* // G 6 |
* // F 5 |
* // E 4 |
* // D 3 |
* // C 2 | 38
* // B 1 | 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
* // A 0 | 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
* // |-------------------------------------------------------------------------------> X
* // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
* // A B C D E F G H I J K L M N O P Q R S
*/
"""
env = None
def __init__(self, ):
self.width = 19
self.height = 19
self.states = {} # 180:"B", 181:"w"
self.str_states = '' # 当前状态的String表示,第二种表示方式(大写字母组合表示)
self.stone_num = 0
if not Board.env:
Board.env = Environment()
self.env = Board.env # 新的棋盘和CPP估值函数
self.character = None
self.availables = None
self.CPP_availables = None
self.is_end = None
self.winner = None
self.players = ['B', 'W'] # 进攻方(黑色) 1, 防守方(白色) -1
self.turn = tuple(['B' if (i % 4 == 0 or i % 4 == 3) else 'W' for i in range(19 * 19)]) # B W W B B W W
self.first_hand = tuple([True if (i % 4 == 1 or i % 4 == 3) else False for i in range(19 * 19)])
self.pos2str = {}
self.str2pos = {}
for y_index, y in enumerate("abcdefghijklmnopqrs".upper()):
for x_index, x in enumerate("abcdefghijklmnopqrs".upper()):
pos = y_index * 19 + x_index
self.str2pos[f"{x}{y}"] = pos
self.pos2str[pos] = f"{x}{y}"
def init_board(self, ):
"""
重新初始化棋盘
"""
self.states = {}
self.str_states = '' # 表示当前的状态表示,第二种表示方式(大写字母组合表示)
self.stone_num = 0
self.character = None
# keep available moves in a list 可以落子的位置
self.availables = list(range(self.width * self.height)) # 是否缩小范围?
self.CPP_availables = list(range(self.width * self.height)) # c++给出的可选动作范围?
self.is_end = False
self.winner = 'NULL'
def next_player(self) -> str:
assert 0 < self.stone_num + 1 < 19 * 19, f"'{self.stone_num + 1}'超出合法范围"
# 下一个玩家
return self.turn[self.stone_num + 1]
def current_player(self) -> str:
# 当前动作的玩家
return self.turn[self.stone_num]
def prev_player(self) -> str:
# 上一手动作的玩家
assert 0 <= self.stone_num - 1 < 19 * 19, f"'{self.stone_num - 1}'超出合法范围"
return self.turn[self.stone_num - 1]
def is_first_hand(self) -> bool:
# 当前玩家是否是第一手(2子分1,2手)
return self.first_hand[self.stone_num]
def cpp_available(self) -> list:
return self.CPP_availables[:]
def move_to_location(self, move: int) -> Tuple[int, int]:
"""
一维坐标 —> 二维的坐标
3*3 board's moves like:
^ y
1 \ 3 4 5
0 \ 0 1 2
\————————>x
0 1 2
and move 5's location is (2, 1)
"""
x = move % self.width
y = move // self.width
return (x, y)
def location_to_move(self, location: Tuple[int, int]) -> int:
"""
二维坐标 转换-> 一维坐标
"""
if len(location) != 2:
return -1
x = location[0]
y = location[1]
move = y * self.width + x
if move not in range(self.width * self.height):
assert 0 <= move < self.width * self.height, "转换坐标非法"
return -1
return move
def current_state(self):
# 从当前玩家的角度返回棋盘状态
return self.character
def current_str_state(self) -> str:
# 从当前玩家的角度返回棋盘状态
return self.str_states
def set_start_board(self, GUI_msg=None):
self.init_board()
if GUI_msg:
# 处理gui传回来的局面信息
# BJJJKKJ WJJJK
GUI_msg = GUI_msg.upper()
print(GUI_msg)
player = GUI_msg[0]
assert player == 'B' or player == 'W', "GUI msg player ERROR!"
board_info = GUI_msg[1:]
# print(board_info)
stone_num = len(board_info) // 2
# print(stone_num)
move_list = []
for i in range(stone_num):
str_move = board_info[2 * i:2 * i + 2]
# print(str_move)
move_list.append(self.str2pos[str_move])
for move in move_list:
self.states[move] = self.current_player()
self.str_states += self.pos2str[move]
self.stone_num += 1
self.availables.remove(move)
curr_player = self.current_player()
assert curr_player == player, "GUI curr player ERROR!"
self.character, self.is_end, self.CPP_availables, reward = self.env.tss_interact(curr_player,
self.str_states)
if reward == 1:
self.winner = self.current_player()
else:
self.winner = "NULL"
else:
# 处理开局的前三颗子,仅训练/评估模式
w1_start, w2_Start = self.env.choice_random_opening(180)
# print("w1:{}, w2{}".format(self.move_to_location(w1_start), self.move_to_location(w2_Start)))
for move in [180, w1_start, w2_Start]:
self.states[move] = self.current_player()
self.str_states += self.pos2str[move]
self.stone_num += 1
self.availables.remove(move)
# 处理棋盘特征
curr_player = self.current_player()
assert curr_player == 'B', "set start board error!"
self.character, _, self.CPP_availables, reward = self.env.tss_interact(curr_player, self.str_states)
self.is_end = False
self.winner = "NULL"
def do_move(self, move: int):
# 在棋盘上落子,并切换当前活动玩家
pos = self.move_to_location(move)
assert 0 <= move < self.width * self.height, f"move 不合法:{move}:{pos}"
# print(f"Board.do_move : move->{move}:{pos}")
self.states[move] = self.current_player() # 记录state
if move not in self.availables:
print(f"move:{move}")
print(f"avlbs:{self.availables}")
print(f"curr:{self.current_player()}")
print(f"hand:{self.is_first_hand()}")
print(f"state:{self.states}")
print(f"str:{self.str_states}")
print(f"cpp:{self.CPP_availables}")
assert False
self.availables.remove(move)
# print(f"Board.do_move : {self.current_player()}->{move}:{pos}")
self.str_states += self.pos2str[move] # 把落子序列保存,后面copy棋盘时用到
# print(f"Board.do_move : str_states:{self.str_states}")
self.stone_num += 1
# print(f"Board.do_move : stone_num:{self.stone_num}")
# 调用C++更新局面, 把解析的state存起来,更新self.availables列表, 更新is_end值,更新has_a_winner值
# np.array(character).reshape((18, 19, 19)), is_end, action_list, reward,
curr_player = self.current_player()
self.character, self.is_end, self.CPP_availables, reward = self.env.tss_interact(curr_player, self.str_states)
if len(self.CPP_availables) == 0:
self.CPP_availables = self.availables[:]
print("let's random")
if reward == 1:
self.winner = self.current_player()
else:
self.winner = "NULL"
# print(f"Board.do_move : is_end:{self.is_end}, winner:{self.winner}")
def undo_move(self, move: int):
# 在棋盘上落子,并切换当前活动玩家
pos = self.move_to_location(move)
assert 0 <= move < self.width * self.height, f"move 不合法:{move}:{pos}"
if self.states.get(move):
del self.states[move]
self.availables.append(move)
self.str_states = self.str_states[:-2]
self.stone_num -= 1
curr_player = self.current_player()
# print(f"now player:{curr_player}")
self.character, self.is_end, self.CPP_availables, reward = self.env.tss_interact(curr_player,
self.str_states)
if reward == 1:
self.winner = self.current_player()
else:
self.winner = "NULL"
else:
print(f"no move :{move} in move")
def game_end(self) -> Tuple[bool, str]:
# 对局是否结束,胜方是谁(1 :player1, 2 :player2, -1 :未分胜负)
if self.is_end:
return True, self.winner
return False, 'NULL'
def deepcopy(self):
copy_board = Board()
copy_board.states = copy.deepcopy(self.states)
copy_board.str_states = self.str_states[:]
copy_board.stone_num = self.stone_num
copy_board.env = self.env # Environment()
copy_board.character = self.character.copy()
copy_board.availables = self.availables[:]
copy_board.CPP_availables = self.CPP_availables[:]
copy_board.is_end = self.is_end
copy_board.winner = self.winner[:]
return copy_board
def show_board(self):
# 棋盘可视化
width = self.width
height = self.height
print(" ", end='')
for x in range(width):
print("{0:3}".format(x), end='')
print()
for i in range(height - 1, -1, -1):
print("{0:4d}".format(i), end='')
for j in range(width):
loc = i * width + j
p = self.states.get(loc, -1)
if p == 'B':
print('B'.center(3), end='')
elif p == 'W':
print('W'.center(3), end='')
else:
print('_'.center(3), end='')
print()
def release(self):
if self.env:
self.env.close()
# if __name__ == "__main__":
# try:
# b = Board()
# b.init_board()
# b.set_start_board("BJJJKKJLKKLIJJI")
# b.show_board()
# b.do_move(0)
# b.show_board()
# b.undo_move( 0)
# b.show_board()
# b.do_move(7)
# b.show_board()
# b.do_move(8)
# b.show_board()
# b.undo_move(7)
# b.show_board()
# b.undo_move(8)
# b.show_board()
#
# except Exception as e:
# print(e)
# finally:
# b.env.close()
|
class Heap:
def __init__(self):
self.storage = []
def insert(self, value):
# add the value to the end of the array
self.storage.append(value)
# bubble it up
self._bubble_up(len(self.storage) - 1)
def delete(self):
# store reference to first heap element
max_val = self.storage[0]
# set value of first heap element to the value of last heap element
self.storage[0] = self.storage[len(self.storage) - 1]
# pop to remove last heap element
self.storage.pop()
# sift down the new top element
self._sift_down(0)
# return the top most element that was removed
return max_val
def get_max(self):
return self.storage[0]
def get_size(self):
return len(self.storage)
def _bubble_up(self, index):
# while at least one child node exists....(meaning there's a parent node)
while index > 0:
# find the parent index, using the parent index formula
parent = (index - 1)//2
# if the value at index is greater than the value at the parent index...
if self.storage[index] > self.storage[parent]:
# swap the values at each index...
self.storage[index], self.storage[parent] = self.storage[parent], self.storage[index]
# ...and then update the index of the value that was just swapped
index = parent
# otherwise, if value is not greater, then break the bubble up function
else:
break
def _sift_down(self, index):
# use heap formulas to determine children indices
left_child_index = 2 * index + 1
right_child_index = 2 * index + 2
# check if left child exists
if len(self.storage) < (left_child_index + 1):
return
# left child exists...
elif len(self.storage) < (left_child_index + 2):
# ....so, check if item at index is less than left child
if self.storage[index] < self.storage[left_child_index]:
# swap item at index and left child
self.storage[index], self.storage[left_child_index] = self.storage[left_child_index], self.storage[index]
# recursively sift down element that was swapped into left child index
self._sift_down(left_child_index)
# if item at index is greater than left child, then no more swaps needed
else:
return
# both right and left children exist
else:
# if item at index is lower than either left child or right child
if self.storage[index] < self.storage[left_child_index] or self.storage[index] < self.storage[right_child_index]:
# if left child is greater than right child
if self.storage[left_child_index] > self.storage[right_child_index]:
# swap item at index and left child
self.storage[index], self.storage[left_child_index] = self.storage[left_child_index], self.storage[index]
# recursively sift down element that was swapped into left child index
self._sift_down(left_child_index)
else:
# right child is larger than left child, so swap parent with right child
self.storage[index], self.storage[right_child_index] = self.storage[right_child_index], self.storage[index]
# recursively sift down element that was swapped into left child index
self._sift_down(right_child_index)
|
# full_name = "Amanda"
# birth_year = input ("Qual ano voce nasceu?")
# year = 2019
# print(year - int(birth_year))
# lbs = input ("Quantas lbs voce quer converter? => ")
# kg = int (lbs) * 0.45
# print (int(kg))
# ----------------------------------------------------------------
# name = "Ana Julia"
# print(name[1:5]) #Printa somente as posições 1-5
# print(len(name)) #Mostra o numero de caracteres
# print(name.find("a")) #Encontra quantos as tem (é sensivel a maiusculas e minusculas)
# print(name.replace("Ana", "Maria")) #Substitui ana por maria
# ----------------------------------------------------------------
# course = "Estação Hack do Facebook"
# print("Hack" in course)
# ----------------------------------------------------------------
# summer = True
# winter = False
# if summer:
# print("Use protetor")
# else:
# print("Suave")
# elif winter: #Elseif é uma mini condição
# print("Poe casaco")
# ----------------------------------------------------------------
# green_bank = True
# criminal = False
# money = True
# if green_bank and money and not criminal:
# print ("Tudo ok!")
# else:
# print ("Deu ruim!")
# ----------------------------------------------------------------
#i=0
# while i < 5:
# print (i)
# i = i+1
# print (".")
# number = 9
# i=0
# while i<3:
# tentativa = int (input("Qual o numero?"))
# if tentativa == number:
# input ("Acertou")
# break
# else :
# print ("Tente novamente")
# i = i+1
# num = [1,2,3,4,5,6]
# num.append(6)
# num.insert(0,1)
# i = 0
# while i<len(num):
# if int (num[i]) == int(num)
# num.remove(num[i])
# i = i + 1
# nova_lista = []
# for number in num:
# if number not in nova_lista:
# nova_lista.append(number)
# #curso = ("Mat", "Geo", "Por") => Isso é uma tupla ou tuple, os itens da lista não podem ser alterados, são constantes
# pessoa = {
# "name": "Hayane",
# "Age" : 26,
# "Address" : "Sao Bernardo",
# "Skills" : ["Python", "Java", "C", "Cobol"]
# }
# print(pessoa["name"])
# print(pessoa["address"])
maior=0
i=0
lista = [1,3,6,50,30,11]
while i<len(lista): # ou for i in lista (vai percorrer todos da lista)
if lista[i] > maior:
maior = lista[i]
i = i + 1
print (maior)
faltas = input("Quantas faltas?")
media = input ("Qual sua média?")
if int(faltas) <=2 and int(media)>=6 :
print("Passou")
else :
print("Reprovou")
|
# Given an integer array nums, find the contiguous subarray (containing at least one number)
# which has the largest sum and return its sum.
#
# Example:
# Input: [-2,1,-3,4,-1,2,1,-5,4],
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
#
# Follow up:
# If you have figured out the O(n) solution, try coding another solution using the divide
# and conquer approach, which is more subtle.
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
if length == 0:
return 0
arr = [float('-inf')] * length
arr[0], maximum = nums[0], nums[0]
for i in range(1, length):
if arr[i - 1] + nums[i] > nums[i]:
arr[i] = arr[i - 1] + nums[i]
else:
arr[i] = nums[i]
if arr[i] > maximum:
maximum = arr[i]
return maximum |
# Description:
# Given a reference of a node in a connected undirected graph.
# Return a deep copy (clone) of the graph.
# Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.
# Constraints:
# 1 <= Node.val <= 100
# Node.val is unique for each node.
# Number of Nodes will not exceed 100.
# There is no repeated edges and no self-loops in the graph.
# The Graph is connected and all nodes can be visited starting from the given node.
from typing import List
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = []):
self.val = val
self.neighbors = neighbors
# Main Code
class Solution:
def cloneGraph(self, node: Node) -> Node:
# dictionary to store created nodes
currGraph = {}
# helper function to iterate through nodes and create nodes
def nodeBuild(node, currGraph):
# check for empty graph or no neighbors
if(node == None):
return None
# check for 1-node graph
if(node.neighbors == []):
return Node(node.val)
# otherwise, go through neighbors DFS
newNode = Node(node.val)
currGraph[node.val] = newNode
for neighbor in node.neighbors:
if(neighbor.val not in currGraph):
newerNode = nodeBuild(neighbor, currGraph)
newNode.neighbors.append(currGraph[neighbor.val])
return newNode
outputGraph = nodeBuild(node, currGraph)
return outputGraph
|
# Description: Given a singly linked list, determine if it is a palindrome.
class Solution:
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return True
def revLL(head):
if head == None:
return None
prev_node, curr_node = None, head
while curr_node != None:
temp = curr_node.next
curr_node.next = prev_node
prev_node = curr_node
curr_node = temp
return prev_node
slow, fast = head, head
numSwaps = 0 # use this to see how many comparisons to make (e.g., 1 for [5,2,5])
while fast!= None and fast.next != None:
slow = slow.next
fast = fast.next.next
numSwaps += 1
# reverse the list from slow and compare numSwaps times starting w/ head
tail = revLL(slow)
front = head
for i in range(numSwaps):
if front.val != tail.val:
return False
front = front.next
tail = tail.next
return True |
# purpose: merge two sorted lists of ints
# e.g., [1,2,4,10] and [3,4,5,8] -> [1,2,3,4,4,5,8,10]
from typing import List
class Solution:
def mergeSortedLists(self, list1: List[int], list2: List[int]) -> List[int]:
len1 = len(list1)
len2 = len(list2)
index1 = 0 # pointer for index in list1
index2 = 0 # pointer for index in list2
sortedList = []
# corner cases
if(len1 == 0):
return list2
elif(len2 == 0):
return list1
while(index1 < len1 and index2 < len2):
if(list1[index1] <= list2[index2]):
sortedList.append(list1[index1])
index1 += 1
else:
sortedList.append(list2[index2])
index2 +=1
# check if more numbers to be added
if(index1 < len1):
for i in range(index1, len1):
sortedList.append(list1[i])
if(index2 < len2):
for i in range(index2, len2):
sortedList.append(list2[i])
return sortedList
if __name__ == '__main__':
soln = Solution()
test1 = soln.mergeSortedLists([],[]) # should be []
test2 = soln.mergeSortedLists([],[2]) # should be [2]
test3 = soln.mergeSortedLists([3],[]) # should be [3]
test4 = soln.mergeSortedLists([1,3,5],[2,4,6]) # should be [1,2,3,4,5,6]
test5 = soln.mergeSortedLists([1],[10,11]) # should be [1,10,11]
test6 = soln.mergeSortedLists([20,21],[1,2,3]) # should be [1,2,3,20,21]
assert test1 == []
assert test2 == [2]
assert test3 == [3]
assert test4 == [1,2,3,4,5,6]
assert test5 == [1,10,11]
assert test6 == [1,2,3,20,21] |
# Purpose: Given an array arr of N integers. Find the contiguous sub-array with maximum sum.
import sys
def maximizeSum(inputArray):
# check for bad inputs
length = len(inputArray)
if (length == 0):
raise Exception("The array cannot be empty")
for i in inputArray:
if (type(i) is not int):
raise Exception("The array must be only integers. '" + str(i) +
"' is not an integer.")
# input array okay, let's go!
sumArray = []
sumArray.append(inputArray[0])
currSum = maxSum = inputArray[0]
for i in range(1, length):
currNum = inputArray[i]
if (currSum < 0):
sumArray.append(currNum)
currSum = currNum
if (currSum > maxSum):
maxSum = currSum
else:
currSum += currNum
sumArray.append(currSum)
if (currSum > maxSum):
maxSum = currSum
return maxSum
if __name__ == "__main__":
# running tests
# test 1: only one number
print("test1: " + str(maximizeSum([-1])) + " | " + str(maximizeSum([4])))
# test 2: negative numbers
print("test2: " + str(maximizeSum([-10,-8,-3,-5,-4])))
# test 3: bunch of 0's
print("test3: " + str(maximizeSum([0,0,0,0,0,0])))
# test 3: up and down sequence
print("test4: " + str(maximizeSum([1,-2,0,3,2,4,-1,-2,10,-20,-20,1,2,3,-1,12,-100])))
# test 4: another up and down sequence
print("test5: " + str(maximizeSum([1,2,3,4,-3,-7,-1,11,12,-24,40])))
#run tests from input file (optional)
try:
testFile = open(sys.argv[1], 'r')
line0 = list(testFile.readline().split(" "))
numTests = int(line0[0])
for i in range (0, numTests):
lenArray = int(list(testFile.readline().split(" "))[0])
secondLine = list(testFile.readline().split(" "))
testArray = []
for j in range(0, lenArray):
testArray.append(int(secondLine[j]))
print("file test # " + str(i+1) + ": " + str(maximizeSum(testArray)) + " || test array is: " + str(testArray))
testFile.close()
except:
print("Either there is no input file given or it is not formatted correctly")
finally:
print("Testing is done.")
|
# Purpose: Given an unsorted array A of size N of non-negative integers,
# find a continuous sub-array which adds to a given number S.
import random
import sys
def findSubArray(fullArray, sum):
size = len(fullArray)
runningSum = 0
# input checks / error handling
if (size == 0):
raise Exception("The array is empty.")
for i in fullArray:
if (i < 0):
raise Exception("The array cannot have negative integers. %i is at fault" % i)
if (type(i) is not int):
raise Exception("The array must be only integers. %i is at fault" % i)
if (type(sum) is not int):
raise Exception("The desired sum S must be an integer. %i is at fault" % i)
# inputs look good, let's proceed!
for i in range(0,size):
# case 1: the ith item is equal to the sum
if (fullArray[i] == sum):
return [fullArray[i]]
# case 2: ith item < sum so we scan the next item(s)
elif (i < sum):
runningSum = fullArray[i]
for j in range (i+1,size):
if (runningSum + fullArray[j] == sum):
return fullArray[i:j+1]
elif (runningSum + fullArray[j] < sum):
runningSum += fullArray[j]
# case 3: ith item > sum, move to the next
# execute some pre-built tests, a random test, and the tests in the input file
if __name__ == "__main__":
print("Test 1: " + str(findSubArray([1,2,3,4,5,6,7,8,9,10], 4)))
# to test if it picks up the first sub-array [2, 3] rather than [5]
print("Test 2: " + str(findSubArray([1,2,3,4,5,6,7,8,9,10], 5)))
# to test where there is no solution
print("Test 3: " + str(findSubArray([1,2,3,4,5,6,7,8,9,10], 0)))
# to test random values
ranLength = random.randint(1,10)
ranSum = random.randint(0,20)
ranArray = []
for i in range(0,ranLength):
ranArray.append(random.randint(1,10))
print("ranArray is: " + str(ranArray) + " || ranSum is: " + str(ranSum))
print("Test 4: " + str(findSubArray(ranArray,ranSum)))
# execute tests from input file
try:
testFile = sys.argv[1]
tests = open(testFile,'r')
numTests = int(tests.readline()[0])
for i in range (0, numTests):
firstLine = list(tests.readline().split(" "))
secondLine = list(tests.readline().split(" "))
lenArray = int(firstLine[0])
desiredSum = int(firstLine[1])
strTestArray = secondLine[0:lenArray]
testArray = []
for item in strTestArray:
testArray.append(int(item))
print("Input file test: " + str(findSubArray(testArray,desiredSum)))
tests.close()
except:
print("There is no input or the input file is not properly formatted")
finally:
print("Testing done") |
# purpose: Given n non-negative integers a1, a2, ..., an , where each represents a point
# at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i
# is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container,
# such that the container contains the most water.
from typing import List
class Solution:
def maxArea(self, height: List[int]) -> int:
# idea: run one pointer from far left and one from far right
# only adjust the pointer toward the middle if it is shorter than the other
# update max volume if required
numLines = len(height)
# corner cases
if (numLines < 2):
return 0
if (numLines == 2):
return (min(height[0],height[1]))
# normal cases
else:
maximumArea = 0
front = 0 # index closer to the far left
back = numLines-1 # index closer to the far right
while(front < back):
currWidth = back - front
if (height[front] >= height[back]):
shorterLine = height[back]
currArea = currWidth * shorterLine
back -= 1
else:
shorterLine = height[front]
currArea = currWidth * shorterLine
front += 1
if (currArea > maximumArea):
maximumArea = currArea
return maximumArea
if __name__ == '__main__':
soln = Solution()
test1 = soln.maxArea([]) #should return 0
test2 = soln.maxArea([1]) #should return 0
test3 = soln.maxArea([0,0]) #should return 0
test4 = soln.maxArea([1,2,3]) # should return 2
test5 = soln.maxArea([4,5,6,6,5,4]) # should return 20
assert test1 == 0, "test1 failed"
assert test2 == 0, "test2 failed"
assert test3 == 0, "test3 failed"
assert test4 == 2, "test4 failed"
assert test5 == 20, "test5 failed" |
# purpose: Given an unsorted array of integers, find the length of longest increasing
# subsequence.
from typing import List
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
listLen = len(nums)
# corner case
if(listLen <= 1):
return listLen
# otherwise, proceed to main code
longest = [1] * (listLen) # use longest[i] to store the longest LIS at nums[i]
for currNum in range(1,listLen):
for prevNum in range(currNum):
if(nums[prevNum] < nums[currNum]):
longest[currNum] = max(longest[currNum],longest[prevNum]+1)
return (max(longest))
if __name__ == '__main__':
soln = Solution()
test1 = soln.lengthOfLIS([]) # should be 0
test2 = soln.lengthOfLIS([1]) # should be 1
test3 = soln.lengthOfLIS([1,2,3]) # should be 3
test4 = soln.lengthOfLIS([10,9,11,12,2,5,3,7,10]) # should be 4
test5 = soln.lengthOfLIS([10,9,11,12,2,5,3,7,10,3,4,5,6]) # should be 5
assert test1 == 0
assert test2 == 1
assert test3 == 3
assert test4 == 4
assert test5 == 5 |
Print("Report card using if elif else statements")
Marks = 90
if Marks >= 90:
print("Your Grand is A+");
elif Marks< 90 and Marks >= 80:
print("Your Grand is A");
elif Marks< 80 and Marks >= 70:
print("Your Grand is B+");
elif Marks< 70 and Marks >= 60:
print("Your Grand is B");
elif Marks< 60 and Marks >= 50:
print("Your Grand is c+");
elif Marks< 50 and Marks >= 40:
print("Your Grand is C");
else
print("Your Grand is F1")
|
# Given an array of strictly the characters 'R', 'G', and 'B', segregate the values of the array so that all the Rs
# come first, the Gs come second, and the Bs come last. You can only swap elements of the array. Do this in linear
# time and in-place. For example,
# given the array ['G', 'B', 'R', 'R', 'B', 'R', 'G'],
# it should become ['R', 'R', 'R', 'G', 'G', 'B', 'B'].
gbr = ['G', 'B', 'R', 'R', 'B', 'R', 'G']
length = len(gbr)
print(gbr)
index = 0
for elm in gbr:
if elm == 'R':
del gbr[index]
gbr.insert(0, 'R')
print(f'{length} - {index} - {elm} - {gbr}')
elif elm == 'B':
del gbr[index]
gbr.append('B')
print(f'{length} - {index} - {elm} - {gbr}')
else:
pass
index += 1
# TODO:
# #35 not done
|
# Find the maximum number in an array of numbers
def find_max(array):
return max(array)
my_array = [-27, 0, 34, -3]
print(find_max(my_array))
|
arr = [1, 2, 3, 4, 5];
n = 1
print("Original array: ",arr);
m = len(arr)
for i in range(0, n):
first = arr[0];
for j in range(0, m-1):
arr[j] = arr[j + 1];
arr[m - 1] = first;
print();
print("Array after left rotation: ");
for i in range(0, m):
print(arr[i]) |
num=int(input("enter number: "))
sum=0
while num>0:
remainder=num%10
sum=sum + remainder
num=num//10
print(sum) |
array=[3,6,12,14]
n=len(array)
sum=0
for i in range (0,n):
sum=sum+array[i]
average=sum/n
print(average)
|
arr = [1, 2, 3, 4, 5]
n = 1;
m=len(arr)
print("Original array: ",arr);
for i in range(0, n):
last = arr[m - 1];
for j in range(m - 1, -1, -1):
arr[j] = arr[j - 1];
arr[0] = last;
print();
print("Array after right rotation: ");
for i in range(0, m):
print(arr[i]) |
array = [2,3,-1,5,7,9,10,15,95]
sum = 0
N=len(array)
for i in range(N):
sum = sum + array[i]
print("Sum : ",sum) |
arr = [1,2,3,4];
print("original array: ",arr)
arr2 =[]
m = len(arr)
print("reversed array: ")
for i in range (m-1,-1,-1):
print(arr[i]) |
name = input('enter user name')
password = input('enter password')
if(name == "asfina" and password == "1234"):
print('Login success')
else:
print('invalid login') |
# a=input('enter a string')
# l=len(a)
# status=0
# for x in range(int(l/2)):
# if(a[x]!=a[l-1-x]):
# status=1
# break
# if(status==0):
# print('palindrome')
# else:
# print('not palindrome')
# fibnoccii
# limit=int(input('enter limit'))
# f1=0
# f2=1
# print(f1,f2,' ',end="")
# i=0
# while(i<=limit):
# f=f1+f2
# i+=1
# print(f,' ',end="")
# f1=f2
# f2=f
# f1=1
# f2=1
# print(f1,f2,end=' ')
# for i in range(limit):
# f=f1+f2
# print(f, end=' ')
# f1=f2
# f2=f
# string=input('enter string')
# ch=input('enter character')
# st=''
# for x in string:
# if(x!=ch):
# st+=x
# print(st)
# string=input('enter string')
# ch=input('enter character')
# c=0
# for x in string:
# if(x==ch):
# c+=1
# print(c)
# a=[4,3,1,5,8,6,9,10]
# # a.sort(reverse=True)
# for i in range(len(a)):
# for j in range(i+1,len(a)):
# if(a[i]>a[j]):
# temp=a[i]
# a[i]=a[j]
# a[j]=temp
# print(a)
# n=int(input('enter size of array'))
# a=[]
# for x in range(n):
# x=int(input('enter value'))
# a.append(x)
# print(a)
# a.sort(reverse=True)
# for i in range(n):
# for j in range(i+1,n):
# if(a[i]>a[j]):
# temp=a[i]
# a[i]=a[j]
# a[j]=temp
# print(a)
# print('missing:',end='')
# for x in range(a[0],a[len(a)-1]):
# if(x not in a):
# print(x)
# a=[52,41,23,61,11,83]
# n=len(a)
# for i in range(n):
# for j in range(i+1,n):
# if(a[i]>a[j]):
# temp=a[i]
# a[i]=a[j]
# a[j]=temp
# res=a[i]
# print(res)
# n=int(input('enter a no'))
# temp=n
# count=0
# while(temp>0):
# count+=1
# temp=temp//10
# temp=n
# sum=0
# while(temp>0):
# rem=temp%10
# sum=sum+rem**count
# temp=temp//10
# if(n==sum):
# print('armstrong')
# else:
# print('not armstrong')
# n=int(input('enter the no'))
# def fact(n):
# if(n==0):
# return 1
# while(n>0):
# return n*fact(n-1)
# print(fact(n))
# fact=1
# i=1
# while(i<=n):
# fact=fact*i
# i+=1
# print(fact)
# a=10
# b=20
# print('a: ',a)
# print()
# print('b: ',b)
# print()
# a=a+b
# b=a-b
# a=a-b
# print('a: ',a)
# print()
# print('b: ',b)
# sum=0
# for x in range(11):
# if(x%2==0):
# sum+=x
# print(sum)
# n=int(input('enter no'))
# status=0
# for x in range(2,n//2+1):
# if(n%x==0):
# status=1
# if(status==1):
# print('not prime')
# else:
# print('prime')
# n=int(input('enter no'))
# if(n>1):
# for x in range(2,int(n/2)+1):
# if(n%x == 0):
# print('not prime')
# break
# else:
# print('prime')
# else:
# print('not prime')
# n=int(input('enter limit'))
# sum=0
# num=1
# for num in range(1,n):
# c=0
# for i in range(2,int(num/2)+1):
# if(num%i == 0):
# c += 1
# break
# if(c==0 and num!=1):
# sum=sum+num
# print(sum)
#prime number btwn 2 limits and sum
# n1=int(input('enter start limit'))
# n2=int(input('enter end limit'))
# sum=0
# for x in range(n1,n2+1):
# c=0
# for i in range(2,int(x/2)+1):
# if(x%i == 0):
# c+=1
# break
# if(c==0 and x!=1):
# print(x)
# sum=sum+x
# print('sum: ',sum)
# n=int(input('enter no'))
# limit=int(input('enter limit'))
# for i in range(1,limit+1):
# print(n,'x',i,'=',n*i)
# rows=int(input('enter limit'))
# for i in range(0,rows):
# for j in range(0,i):
# print('*',end='')
# print()
# rows=int(input('enter limit'))
# for i in range(1,rows+1):
# for j in range(rows,0,-1):
# if(j>i):
# print(' ',end='')
# else:
# print('*',end='')
# print()
# n=int(input('enter limit'))
# for i in range(n,0,-1):
# for j in range(i,0,-1):
# print('*',end='')
# print()
# n=int(input('enter no of rows'))
# list1=[]
# for i in range(1,n+1):
# list1.append('*'*i)
# print('\n'.join(list1))
# n=int(input('enter no of rows'))
# for i in range(1,n):
# for j in range(n,0,-1):
# if(j>i):
# print(' ',end='')
# else:
# print('*',end='')
# print()
# n=int(input('enter no of rows'))
# ch=65
# for y in range(1,n+1):
# for x in range(y):
# print('{0}'.format(chr(ch)),end=' ')
# ch+=1
# print()
# for y in range(n):
# for x in range(n-y-1):
# print('{0}'.format(chr(ch)),end=' ')
# ch+=1
# print()
# sum=0
# for y in range(n):
# for x in range(n-y):
# sum+=1
# print('{:2d}'.format(sum),end=' ')
# print()
# n=int(input('enter no of rows'))
# for i in range(1,n+1):
# for j in range(0,2*n):
# if(j>=i and j<2*n-i):
# print('',end=' ')
# else:
# print('*',end='')
# print()
# for i in range(n-1,0,-1):
# for j in range(0,2*n):
# if(j>=i and j<2*n-i):
# print('',end=' ')
# else:
# print('*',end='')
# print()
# for i in range(0,n):
# for j in range(0,2*n):
# if(j>i and j<2*n-i-1):
# print(' ',end=' ')
# else:
# print('*',end=' ')
# print()
# for i in range(n-1,0,-1):
# for j in range(1,2*n+1):
# if(j>i and j<2*n-i+1):
# print(' ',end=' ')
# else:
# print('*',end=' ')
# print()
# n=int(input('enter no'))
# c=0
# if(n>1):
# for x in range(2,int(n/2)+1):
# if(n%x==0):
# c=1
# print('not a prime')
# break
# else:
# print('prime')
# else:
# print('not prime')
# n=int(input('enter limit'))
# for i in range(1,n+1):
# c=0
# j=1
# if(i>1):
# for j in range(2,int(i/2)+1):
# if(i%j==0):
# c=1
# break
# if(c==0):
# print(i)
# prime number btwn 2 limits and sum
# n1=int(input('enter start limit'))
# n2=int(input('enter end limit'))
# sum=0
# for x in range(n1,n2+1):
# c=0
# i=1
# for i in range(2,int(x/2)+1):
# if(x%i == 0):
# c+=1
# break
# if(c==0 and x!=1):
# print(x)
# sum=sum+x
# print('sum: ',sum)
# n=int(input("enter limit"))
# for x in range(n):
# for y in range(2*n):
# if(y>=x and y<=2*n-x-1):
# print(" ",end=' ')
# else:
# print("*",end=' ')
# print()
# for x in range(n,0,-1):
# for y in range(2*n):
# if(y>=x and y<=2*n-x-1):
# print(" ",end=' ')
# else:
# print("*",end=' ')
# print()
# for x in range(n,0,-1):
# for y in range(2*n):
# if(y>=x and y<=2*n-x):
# print("*",end=' ')
# else:
# print(" ",end=' ')
# print()
# st=input("enter string")
# c=0
# for i in st:
# if(i=="a" or i=="e"or i=="i"or i=="o"or i=="u" ):
# c+=1
# print(c)
# a1=[1,2,3,4,5,6,7]
# a2=[2,3,1,0,5]
# flag=0
# miss=[]
# # print(len(a1))
# for i in range(0,len(a1)):
# for j in range(0,len(a2)):
# if(a1[i]==a2[j]):
# flag+=1
# break
# else:
# miss.append(a1[i])
# print(miss)
# a=[19,17,5,7,5,4]
# for i in range(0,len(a)):
# for j in range(i+1,len(a)):
# if(a[i]<a[j]):
# break
# else:
# print(a[i])
# s=input('enter the string')
# start=int(input('eneter start index'))
# end=int(input('eneter end index'))
# sub=""
# for i in range(start,end):
# # print(s[i])
# sub+=s[i]
# print(sub)
# n=int(input('enter the size of array'))
# a=[]
# b=[]
# for x in range(n):
# a.append(int(input('enter a no')))
# print(a)
# for i in range(n):
# if(i==0):
# t=a[i]*a[i+1]
# b.append(t)
# elif(i==n-1):
# t=a[i]*a[i-1]
# b.append(t)
# else:
# t=a[i-1]*a[i+1]
# b.append(t)
# print(b)
# val1=float(input("enter first no: "))
# val2=float(input("enter second no: "))
# ch=input("enter your choice: + - * / ")
# if(ch=="+"):
# ans=val1+val2
# elif(ch=="-"):
# ans=val1-val2
# elif(ch=="*"):
# ans=val1*val2
# elif(ch=="/"):
# ans=val1/val2
# else:
# print("wrong choice!")
# print(ans)
# n=int(input('enter no: '))
# s=''
# while(n>0):
# x=n%2
# s+=str(x)
# n=int(n/2)
# print(s)
|
# s=input('enter the string')
# ch=input('enter the letter to be removed')
# n=len(s)
# str=''
# for x in s:
# # print(x)
# if(x!=ch):
# str+=x
# print(str)
# find the occurance of a character
s=input('enter the string')
ch=input('enter the letter')
count=0
for x in s:
if(x==ch):
count+=1
print(count) |
'''
Leetcode - 187. Repeated DNA Sequences
Time complexity - O(N)
space complexity - O(1)
Approach - 1) I traverse through the entire string with length 10
2) if that substring is in ptn set, then we append to the res set.
3) finally we convert set to list
'''
class Solution:
def findRepeatedDnaSequences(self, nums: str) -> List[str]:
res=set()
ptn=set()
s=""
for i in range(0,len(nums)-9):
s=nums[i:i+10]
if s in ptn:
res.add(s)
ptn.add(s)
return res
|
# dataset.py
import torch
import numpy as np
from PIL import Image
from PIL import ImageFile
# sometimes, you will have images without an ending bit
# this takes care of those kind of (corrupt) images
ImageFile.LOAD_TRUNCATED_IMAGES = True
class ClassificationDataset:
"""
A general classification dataset class that you can use for all
kinds of image classification problems. For example,
binary classification, multi-class, multi-label classification
"""
def __init__(
self,
image_paths,
targets,
resize=None,
augmentations=None
):
"""
:param image_paths: list of path to images
:param targets: numpy array
:param resize: tuple, e.g. (256, 256), resizes image if not None
:param augmentations: albumentation augmentations
"""
self.image_paths = image_paths
self.targets = targets
self.resize = resize
self.augmentations = augmentations
def __len__(self):
"""
Return the total number of samples in the dataset
"""
return len(self.image_paths)
def __getitem__(self, item):
"""
For a given "item" index, return everything we need
to train a given model
"""
# use PIL to open the image
image = Image.open(self.image_paths[item])
# convert image to RGB, we have single channel images
image = image.convert("RGB")
# grab correct targets
targets = self.targets[item]
# resize if needed
if self.resize is not None:
image = image.resize(
(self.resize[1], self.resize[0]),
resample=Image.BILINEAR
)
# convert image to numpy array
image = np.array(image)
# if we have albumentation augmentations
# add them to the image
if self.augmentations is not None:
augmented = self.augmentations(image=image)
image = augmented["image"]
# pytorch expects CHW instead of HWC
image = np.transpose(image, (2, 0, 1)).astype(np.float32)
# return tensors of image and targets
# take a look at the types!
# for regression tasks,
# dtype of targets will change to torch.float
return {
"image": torch.tensor(image, dtype=torch.float),
"targets": torch.tensor(targets, dtype=torch.long),
}
|
'''A simple program to create an html file froma given string,
and call the default web browser to display the file.'''
contents = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Hello</title>
</head>
<body>
Hello, World!
<form name="search" action="/cgi-bin/CGITest.py" method="get">
<label for="myname">Enter Your Name</label>
<input id="myname" type="text" name="firstname" value="Nada" />
<input type="submit">
</form>
</body>
</html>
'''
def server():
import http.server
import socketserver
import ssl
import os
# web_dir = os.path.join(os.path.dirname(__file__), 'web')
# web_dir = os.getcwd()+'\CGITest.py'
print(str(web_dir))
print('\n')
os.chdir(web_dir)
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile='./server.pem', server_side=True)
print("serving at port", PORT)
httpd.serve_forever()
def main():
browseLocal(contents)
def strToFile(text, filename):
"""Write a file with the given name and the given text."""
output = open(filename,"w")
output.write(text)
output.close()
def browseLocal(webpageText, filename='index.html'):
'''Start your webbrowser on a local file containing the text
with given filename.'''
import webbrowser, os.path
strToFile(webpageText, filename)
main()
server()
|
age = 12
if (age < 4):
print("Your admission cost is $0.")
elif (age < 18):
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
if (age < 4):
price = 0
elif (age < 18):
price = 5
else:
price = 10
print("Your admission cost is $" + str(price) + ".") |
'''
def shortest_line(list):
Min = list[4] - list[0]
for n in range(3):
if list[n+2] - list[n] < Min:
Min = list[n+2] -list[n]
return Min
spots = [1,3,7,20,26]
print("입력된 점 :", spots)
print("최소 선분 길이 :", shortest_line(spots))
temp = 0
for i in range(len(spots)):
for j in range(len(spots)):
if spots[i] < spots[j]:
temp = spots[i]
spots[i] = spots[j]
spots[j] = temp
'''
def shortest_distance(list):
route_f = 0
route_m = 3
route_e = 4
min = ((list[route_f][0] - list[route_m][0]) ** (2) + (list[route_f][1] - list[route_m][1]) ** (2)) ** (1 / 2) + (
(list[route_m][0] - list[route_e][0]) ** (2) + (list[route_m][1] - list[route_e][1]) ** (2)) ** (1 / 2)
for i in range(4):
for j in range(i, 5):
if i != j:
distance_1 = ((list[i][0] - list[j][0]) ** (2) + (list[i][1] - list[j][1]) ** (2)) ** (1 / 2)
next = j
for k in range(5):
if k != next and k != i:
distance_2 = ((list[next][0] - list[k][0]) ** (2) + (list[next][1] - list[k][1]) ** (
2)) ** (1 / 2)
total_distance = distance_1 + distance_2
if min > total_distance:
min = total_distance
route_f = i
route_m = next
route_e = k
print("최단 경로 :",route_f+1,"-",route_m+1,"-",route_e+1)
print("최단 거리 :",min)
spots = [1,2],[10,4],[5,3],[6,6],[10,5]
print("입력된 점 위치 :",spots)
shortest_distance(spots)
# num = 1
# print(i+1,"번째 점과",j+1,"번째 점의 거리",distance_1)
# print(next + 1, "번째 점과", k + 1, "번째 점의 거리", distance_2)
# print(num,"번째 결과값 :",total_distance)
# num += 1 |
# A CircularQueue is Queue, implemented with Python's built in list, with max capacity of 5000
class CircularQueue:
def __init__(self):
self.queue_contents = [None] * 5000
self.queue_len = 0
self.front = -1
self.back = 0
def __eq__(self, other):
return type(other) == CircularQueue and self.queue_contents == other.queue_contents and \
self.queue_len == other.queue_len and self.front == other.front and self.back == other.back
def __repr__(self):
if self.queue_len == 0:
return "[]"
if self.back > self.front:
return self.queue_contents[self.back:].__repr__() + self.queue_contents[:self.front + 1].__repr__()
return self.queue_contents[self.back:self.front+1].__repr__()
# None -> CircularQueue
# returns an empty CircularQueue
def empty_queue():
return CircularQueue()
# Queue, Value -> Queue
# returns a Queue with the value added, if queue is max capacity, then raises IndexError
def enqueue(queue, value):
if queue.queue_len == queue.queue_contents.__len__():
raise IndexError
if queue.front == queue.queue_contents.__len__() - 1:
queue.front = -1
queue.front += 1
queue.queue_len += 1
queue.queue_contents[queue.front] = value
return queue
# Queue -> Queue
# returns a Queue with the next value removed, raises IndexError if empty
def dequeue(queue):
if queue.queue_len == 0:
raise IndexError
temp = queue.queue_contents[queue.back]
queue.queue_contents[queue.back] = None
queue.back += 1
queue.queue_len -= 1
if queue.back == queue.queue_contents.__len__():
queue.back = 0
return temp, queue
# Queue -> value
# returns the next value in the Queue
def peek(queue):
if queue.queue_len == 0:
raise IndexError
return queue.queue_contents[queue.back]
# Queue -> int
# returns the size of the Queue
def size(queue):
return queue.queue_len
# Queue -> Boolean
# returns True if Queue is empty, false if otherwise
def is_empty(queue):
return queue.queue_len == 0
|
import unittest
# * Section 1 (Lists)
# * dd: NumList Data Definition
# A Head is a number representing a value in a List
# A Tail is a NumList
# A NumList is one of:
# - "mt"
# - a Pair(Head, Tail)
class Pair:
def __init__(self, head, tail):
self.head = head # a Head
self.tail = tail # a Tail
def __eq__(self, other):
return type(other) == Pair and self.head == other.head and self.tail == other.tail
def __repr__(self):
return "%r, %r" % (self.head, self.tail)
# * 1:
# NumList -> int
# returns the length of a given NumList
def length(num_list, size=0):
if num_list == "mt":
return size
return length(num_list.tail, size+1)
# * 2:
# NumList -> int
# returns the summed value of all the numbers in a given NumList
def sum(num_list):
if num_list == "mt":
return 0
return sum(num_list.tail) + num_list.head
# * 3:
# NumList, int -> int
# returns a number representing the number of elements greater than a given threshold in a given NumList
def count_greater_than(num_list, threshold):
counter = 0
if num_list == "mt":
return counter
if num_list.head > threshold:
counter += 1
return counter + count_greater_than(num_list.tail, threshold)
# * 4:
# NumList, int -> int
# returns index of a given value from a given NumList, returns "mt" if not in the list
def find(num_list, value, index=0):
if num_list == "mt":
return None
if num_list.head == value:
return index
return find(num_list.tail, value, index + 1)
# * 5:
# NumList -> NumList
# returns a NumList which each value is one less than a given NumList
def sub_one_map(num_list):
if num_list == "mt":
return "mt"
return Pair(num_list.head - 1, sub_one_map(num_list.tail))
# * 6:
# NumList, int -> NumList
# returns a sorted NumList with a given SORTED NumList, and an addition of a given int
def insert(num_list, value):
if num_list == "mt":
return Pair(value, "mt")
if num_list.head < value:
return Pair(num_list.head, insert(num_list.tail, value))
else:
return Pair(value, num_list)
# * Tests : the test case class for the list functions
class TestCase(unittest.TestCase):
def test_List(self):
pair1 = Pair(1, Pair(2, "mt"))
pair2 = Pair(1, Pair(2, "mt"))
self.assertEqual(pair1, pair2)
self.assertEqual(pair1.__repr__(), "1, 2, 'mt'")
def test_length(self):
self.assertEqual(length("mt"), 0)
self.assertEqual(length(Pair(2, "mt")), 1)
self.assertEqual(length(Pair(1, Pair(2, "mt"))), 2)
self.assertEqual(length(Pair(2, Pair(1, Pair(4, "mt")))), 3)
def test_sum_list(self):
self.assertEqual(sum(Pair(2, Pair(1, Pair(4, "mt")))), 7)
self.assertEqual(sum(Pair(1, Pair(1, Pair(1, "mt")))), 3)
self.assertEqual(sum(Pair(200, Pair(100, Pair(40, "mt")))), 340)
self.assertEqual(sum(Pair(0, Pair(0, Pair(0, "mt")))), 0)
self.assertEqual(sum("mt"), 0)
def test_count_greater_than(self):
self.assertEqual(count_greater_than(Pair(1, Pair(3, Pair(5, "mt"))), 2), 2)
self.assertEqual(count_greater_than(Pair(1, Pair(3, Pair(5, "mt"))), 3), 1)
self.assertEqual(count_greater_than(Pair(1, Pair(3, Pair(5, "mt"))), 5), 0)
self.assertEqual(count_greater_than(Pair(1, Pair(3, Pair(5, "mt"))), 0), 3)
self.assertEqual(count_greater_than(Pair(0, Pair(0, Pair(0, "mt"))), 0), 0)
self.assertEqual(count_greater_than("mt", 2), 0)
def test_find(self):
self.assertEqual(find(Pair(1, "mt"), 1), 0)
self.assertEqual(find(Pair(1, "mt"), 0), None)
self.assertEqual(find("mt", 0), None)
self.assertEqual(find(Pair(1, Pair(10, "mt")), 10), 1)
self.assertEqual(find(Pair(1, Pair(10, Pair(2, "mt"))), 2), 2)
self.assertEqual(find(Pair(0, Pair(0, Pair(0, "mt"))), 0), 0)
def test_sub_one_map(self):
pair1 = Pair(1, Pair(10, Pair(2, "mt")))
pair2 = sub_one_map(pair1)
pair3 = sub_one_map(pair2)
pair4 = sub_one_map("mt")
self.assertIsInstance(pair2, Pair)
self.assertEqual(pair2, Pair(0, Pair(9, Pair(1, "mt"))))
self.assertEqual(pair3, Pair(-1, Pair(8, Pair(0, "mt"))))
self.assertEqual(pair4, "mt")
def test_insert(self):
list1 = Pair(1, Pair(2, Pair(4, Pair(5, Pair(8, Pair(10, "mt"))))))
list2 = "mt"
list3 = Pair(1, Pair(1, Pair(1, Pair(1, Pair(2, Pair(5, "mt"))))))
self.assertEqual(insert(list1, 3), Pair(1, Pair(2, Pair(3, Pair(4, Pair(5, Pair(8, Pair(10, "mt"))))))))
self.assertEqual(insert(list2, 0), Pair(0, "mt"))
self.assertEqual(insert(list1, 12), Pair(1, Pair(2, Pair(4, Pair(5, Pair(8, Pair(10, Pair(12, "mt"))))))))
self.assertEqual(insert(list3, 1), Pair(1, Pair(1, Pair(1, Pair(1, Pair(1, Pair(2, Pair(5, "mt"))))))))
if __name__ == "__main__":
unittest.main()
|
import unittest
from list_queue import *
class TestQueue(unittest.TestCase):
def test_class(self):
test_queue = empty_queue()
test_queue = enqueue(test_queue, "Test")
test_queue = enqueue(test_queue, "foo")
test_queue2 = empty_queue()
test_queue2 = enqueue(test_queue2, "Test")
test_queue2 = enqueue(test_queue2, "foo")
self.assertEqual(test_queue, test_queue2)
self.assertEqual(test_queue.__repr__(), "{'Test', None}{'foo', None}")
def test_empty(self):
test_queue = empty_queue()
self.assertEqual(test_queue.front, None)
self.assertEqual(test_queue.reverse, None)
self.assertEqual(test_queue.queue_len, 0)
def test_enqueue(self):
test_queue = empty_queue()
test_queue = enqueue(enqueue(enqueue(test_queue, "Test1"), "Test2"), "Test3")
self.assertEqual(test_queue.front, Pair("Test1", None))
self.assertEqual(test_queue.reverse, Pair("Test3", Pair("Test2", None)))
self.assertEqual(test_queue.queue_len, 3)
test_queue = dequeue(test_queue)[1]
self.assertEqual(test_queue.front, Pair("Test2", Pair("Test3", None)))
self.assertEqual(test_queue.queue_len, 2)
test_queue = enqueue(test_queue, "Test4")
self.assertEqual(test_queue.reverse, Pair("Test4", None))
self.assertEqual(test_queue.queue_len, 3)
def test_dequeue(self):
test_queue = empty_queue()
with self.assertRaises(IndexError):
dequeue(test_queue)
test_queue = enqueue(test_queue, "Test")
test_queue = enqueue(test_queue, "foo")
test_queue = enqueue(test_queue, "fuu")
test_queue = dequeue(test_queue)[1]
self.assertEqual(test_queue.front, Pair("foo", Pair("fuu", None)))
self.assertEqual(test_queue.reverse, None)
test_queue = dequeue(test_queue)[1]
self.assertEqual(test_queue.front, Pair("fuu", None))
test_queue = dequeue(test_queue)[1]
self.assertEqual(test_queue, empty_queue())
def test_peek(self):
test_queue = empty_queue()
with self.assertRaises(IndexError):
peek(test_queue)
test_queue = enqueue(enqueue(enqueue(test_queue, "Test1"), "Test2"), "Test3")
self.assertEqual(peek(test_queue), "Test1")
_, test_queue = dequeue(test_queue)
self.assertEqual(peek(test_queue), "Test2")
def test_size(self):
test_queue = empty_queue()
test_queue = enqueue(enqueue(enqueue(test_queue, "Test1"), "Test2"), "Test3")
self.assertEqual(size(empty_queue()), 0)
self.assertEqual(size(test_queue), 3)
_, test_queue = dequeue(test_queue)
self.assertEqual(size(test_queue), 2)
def test_is_empty(self):
test_queue = empty_queue()
test_queue = enqueue(enqueue(enqueue(test_queue, "Test1"), "Test2"), "Test3")
self.assertTrue(is_empty(empty_queue()))
self.assertFalse(is_empty(test_queue))
_, test_queue = dequeue(test_queue)
_, test_queue = dequeue(test_queue)
_, test_queue = dequeue(test_queue)
self.assertTrue(is_empty(test_queue))
def test00_interface(self):
test_queue = empty_queue()
test_queue = enqueue(test_queue, "foo")
peek(test_queue)
_, test_queue = dequeue(test_queue)
size(test_queue)
is_empty(test_queue)
if __name__ == "__main__":
unittest.main()
|
# TODO: 3 (all), 4 (all)
# from array_list import *
from linked_list import *
import sys
# None -> None
# function loads a given file name, and throws exceptions if not found, or if no file name is given
# Handles IOError if file not found, and IndexError if no command-line argument given
def main():
try:
file_name = sys.argv[1]
file = open(file_name)
run_program(process_file(file))
file.close()
except IOError:
print("File is not found")
except IndexError:
print("Error: Please enter a text file name")
# A songName, Artist, and Album are all Strings, representing the Song Name, artist, and album from a song, respectively
# An Index is a UNIQUE int to a song, IE, no other song should have the same index
# A Song represents a song in a Music Playlist with fields songName, Artist, Album, and Index
class Song:
def __init__(self, song_name, artist, album, index):
self.song_name = song_name # a songName
self.artist = artist # an Artist
self.album = album # an Album
self.index = index # an Index
def __repr__(self):
return "%d--%s--%s--%s" % (self.index, self.song_name, self.artist, self.album)
def __eq__(self, other):
return type(other) == Song and self.song_name == other.song_name and self.artist == other.artist \
and self.album == other.album and self.index == other.index
# A List is one of:
# - an AnyList
# - an ArrayList
# A Database is a List containing Songs, which correspond to songs in a music playlist
# a FileString is a String from a file that corresponds to a song, that should be in the form:
# index--songName--artist--album
# File, Database (optional), Index (Only if inputted database) -> Database
# returns a database filled with songs from a given formatted file. If database given, Songs from file are added to end
# Note: Index should correspond to Index of song
def process_file(file, database=empty_list(), index=0):
line = 0
file_string = "\n"
while file_string != "":
file_string = file.readline()
line += 1
if file_string != '\n' and file_string != '':
temp_song = splice_line(file_string, line, index)
if temp_song is not None:
database = add(database, index, temp_song)
index += 1
return database
# a Line is an int corresponding to which line a FileString is from
# FileString, Line, Index -> Song (or None)
# Helper function to Process file, if properly formatted, returns a Song from given String, None otherwise
# Note: a Line does not always equal Index, if a line is formatted wrong, the index DOES NOT increment
def splice_line(file_string, line, index):
if "\n" in file_string:
file_string = file_string[0:-1]
temp_arr = [None] * 3
i = 0
while "--" in file_string:
temp_arr[i] = file_string[0: file_string.index("--")]
file_string = file_string[file_string.index("--") + 2:]
i += 1
temp_arr[i] = file_string
if temp_arr.__contains__(None) or i != 2:
print("Line %d: malformed song information" % line)
return None
return Song(temp_arr[0], temp_arr[1], temp_arr[2], index)
# Database -> None
# The "Main Menu" of the Music Catalog. Takes a Database to display the Songs. ~Handles~ EOFError
def run_program(database):
sort_order = 0
searching_database = empty_list() # A Database, sorted by lineNumber ALWAYS
for i in range(length(database)):
searching_database = add(searching_database, i, get(database, i))
while True:
try:
print("Song Catalog\n" +
" 1) Print Catalog\n" +
" 2) Song Information\n" +
" 3) Sort\n" +
" 4) Add Songs\n" +
" 0) Quit\n" +
"Enter selection: ")
user_input = input()
if user_input == "0":
break
elif user_input == "1":
print_catalog(database)
elif user_input == "2":
song_information(searching_database)
elif user_input == "3":
temp = sort_database(database, sort_order)
sort_order, database = temp[1], temp[0]
elif user_input == "4":
searching_database = add_songs(searching_database)
database = searching_database
if sort_order != 0:
database = sort_help(database, sort_order)
else:
print("Invalid option")
except EOFError:
sys.exit()
# Database -> None
# Prints the contents of the Database to the console
def print_catalog(database):
foreach(database, print)
print()
# Database -> None
# Prompts the user for a song to fetch information from, and prints the song information to console
# Note: Database HAS to be sorted by line number. Handles ValueError if input is not an int
def song_information(database):
print("Enter song number: ")
try:
user_input = int(input())
if 0 <= user_input < length(database):
temp = get(database, user_input)
if temp.index == user_input:
print("Number: %d\n" % temp.index +
"Title: %s\n" % temp.song_name +
"Artist: %s\n" % temp.artist +
"Album: %s\n" % temp.album)
else:
print("Invalid song Number")
except ValueError:
print("Invalid song Number")
# Database, int -> (Database, int)
# returns a tuple with the Database and the sort order after exiting the program
# Prompts the user for how they want a Database sorted, sorts the database if it is a valid entry, otherwise lets the
# user know that it is not a valid choice
# Note: No effect can be seen until user 'Prints Catalog', 'Sort Order' int correspondence can be seen with String
# that is printed to the console. Handles a raised ValueError
def sort_database(database, sort_order):
print("Sort songs \n" +
" 0) By Number\n" +
" 1) By Title\n" +
" 2) By Artist\n" +
" 3) By Album\n" +
"Sort by: ")
sort_choice = input()
try:
sort_order = int(sort_choice)
database = sort_help(database, sort_order)
except ValueError:
print("Invalid Sort Option")
finally:
return database, sort_order
# Database, int -> Database, raises ValueError
# returns Database sorted according to a sort order. Helper function to 'Sort'. Raises ValueError if invalid sortOrder
def sort_help(database, sort_order):
if sort_order == 0:
database = sort(database, less_than_by_number)
elif sort_order == 1:
database = sort(database, less_than_by_title)
elif sort_order == 2:
database = sort(database, less_than_by_artist)
elif sort_order == 3:
database = sort(database, less_than_by_album)
else:
raise ValueError
return database
# Song, Song -> Boolean
# returns True if song 1's index is less than song2. False if otherwise (including equal)
def less_than_by_number(song1, song2):
return song1.index < song2.index
# Song, Song -> Boolean
# compares Songs in this order: SongName, Artist, Album, Index. Only moves on to next item if equal (except Index)
# returns True if finds comparison item is less than, False if greater than, otherwise moves onto next comparison item
def less_than_by_title(song1, song2):
if song1.song_name < song2.song_name:
return True
elif song1.song_name == song2.song_name:
if song1.artist < song2.artist:
return True
elif song1.artist == song2.artist:
if song1.album < song2.album:
return True
elif song1.album == song2.album:
return song1.index < song2.index
return False
# Song, Song -> Boolean
# compares Songs in this order: Artist, Album, SongName Index. Only moves on to next item if equal (except Index)
# returns True if finds comparison item is less than, False if greater than, otherwise moves onto next comparison item
def less_than_by_artist(song1, song2):
if song1.artist < song2.artist:
return True
elif song1.artist == song2.artist:
if song1.album < song2.album:
return True
elif song1.album == song2.album:
if song1.song_name < song2.song_name:
return True
elif song1.song_name == song2.song_name:
return song1.index < song2.index
return False
# Song, Song -> Boolean
# compares Songs in this order: Album, Artist, SongName, Index. Only moves on to next item if equal (except Index)
# returns True if finds comparison item is less than, False if greater than, otherwise moves onto next comparison item
def less_than_by_album(song1, song2):
if song1.album < song2.album:
return True
elif song1.album == song2.album:
if song1.artist < song2.artist:
return True
elif song1.artist == song2.artist:
if song1.song_name < song2.song_name:
return True
elif song1.song_name == song2.song_name:
return song1.index < song2.index
return False
# Database -> Database
# Returns a Database, and adds in songs from a user prompted song file.
# Note: Database HAS TO BE sorted by INDEX number. Handles IOError, if user given file is not found
def add_songs(database):
print("Enter name of file to load: ")
file_name = input()
try:
file = open(file_name)
database = process_file(file, database, length(database))
file.close()
except IOError:
print("'" + file_name + "': No such file name or directory")
finally:
return database
if __name__ == '__main__':
main()
|
"""
Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.
"""
def removeDuplicates(nums):
"""
:type nums: List[int]
:rtype: int
"""
max = len(nums)
i = 0
j = 0
while j < max:
while nums[i] == nums[j]:
j += 1
if j >= max:
return max if max == 0 else (i + 1)
i += 1
nums[i] = nums[j]
j += 1
return max if max == 0 else (i + 1)
arr = [1, 1, 2, 2, 2, 3, 3, 3, 3, 4]
# arr = []
print(arr)
print(removeDuplicates(arr))
print (arr)
|
"""
326. Power of Three
Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
"""
Max3PowerInt = 1162261467 # 3^19, 3^20 = 3486784401 > MaxInt32
MaxInt32 = 2147483647 # 2^31 - 1
def isPowerOfThree(n):
"""
:type n: int
:rtype: bool
"""
# if (n <= 0 or n > Max3PowerInt):
# return False
# return Max3PowerInt % n == 0
m = n
while m > 1:
if m % 3 != 0:
return False
else:
m = m / 3
return True if m == 1 else False
print(isPowerOfThree(3))
|
def valid_placement_exists(team1, team2):
for i, j in zip(sorted(team1), sorted(team2)):
print(i, j)
if i > j:
return False
return True
team1 = [1, 2, 3, 4, 5]
team2 = [4, 3, 3, 1, 6]
print(valid_placement_exists(team1, team2))
|
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
# Base case:
# Initialize first row and col with value r, c.
# No of steps to convert a string to an empty string is equal to the size of the string.
# Formula:
# if word[i] == word[j]:
# dp[i][j] = dp[i-1][j-1]
# else:
# dp[i][j] = min(dp[i-1][j-1]+dp[i][j-1]+dp[i-1][j])+1
cols, rows = len(word1), len(word2)
dp = [[0 for _ in range(cols+1)] for _ in range(rows+1)]
# base case
for c in range(cols+1):
dp[0][c] = c
for r in range(rows+1):
dp[r][0] = r
# formula
for r in range(1, rows+1):
for c in range(1, cols+1):
if word1[c-1] == word2[r-1]:
dp[r][c] = dp[r-1][c-1]
else:
dp[r][c] = min(dp[r-1][c-1], dp[r][c-1], dp[r-1][c]) + 1
return dp[-1][-1]
|
def intersection(A, B):
A = A + B
A.sort(key=lambda x: x[0])
n = len(A)
result = []
for i in range(1, n):
if A[i - 1][1] >= A[i][0]:
result.append([A[i][0], min(A[i - 1][1], A[i][1])])
A[i][1] = max(A[i - 1][1], A[i][1])
return result
def intersection2(A, B):
n, m = len(A), len(B)
A = [[0, 2], [5, 10], [13, 23], [24, 25]]
B = [[1, 5], [8, 12], [15, 24], [25, 26]]
print (intersection(A, B))
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
# N {digits} * M {digits}=
# N "12345" M "425"
'''
425 (M)
12345
------
'''
def get_multiplication(N, M):
nlen, mlen = len(N), len(M)
if nlen == 0 or mlen == 0:
return "0"
res = [0] * (nlen+mlen)
carry = 0
for i in range(nlen - 1, -1, -1):
for j in range(mlen - 1, -1, -1):
prod = res[i+j+1] + carry + int(N[i]) * int(M[j])
digit = prod % 10
carry = prod // 10
res[i+j+1] = digit
if carry:
prod = res[i+j] + carry
res[i+j] = prod % 10
carry = prod // 10
if carry:
prod = res[i+j] + carry
res[i+j] = prod % 10
carry = prod // 10
res = list(map(str, res))
ret = ''.join(res).lstrip("0")
return "0" if len(ret) == 0 else ret
def testcases(input, output):
output = str(output)
if input != output:
raise ValueError()
print (get_multiplication("99", "99"), 99 * 99)
print (get_multiplication("0", "123"), 0 * 123)
print (get_multiplication("42", "123"), 42 * 123)
print (get_multiplication("123", "42"), 123 * 42)
print (get_multiplication("12345", "425"), 12345 * 425)
# 42
# 123
# 126
# 84
'''
try:
testcases(get_multiplication("12345", "425"), 12345 * 425)
print("TEST PASSED")
except:
print ("TEST FAILED")
'''
# print(get_multiplication("12", "2") == 12 * 2) # 24
'''
try:
testcases(get_multiplication("12", "2"), 12 * 2)
print("TEST PASSED")
except:
print ("TEST FAILED")
try:
testcases(get_multiplication("12", "2"), 25)
print("TEST PASSED")
except:
print ("TEST FAILED")
'''
|
import threading
import time
import random
def executeThread(i):
print(f"Thread {i} started\n")
sleepTime = random.randint(1,10)
time.sleep(sleepTime)
print(f"Thread {i} finished executing\n")
thread = {}
#start 10 threads
for i in range(10):
thread[i] = threading.Thread(target=executeThread, args=(i,))
thread[i].start()
'''
print("Active Threads:")
for t in threading.enumerate():
print (t)
'''
# wait for all 10 threads to finish
for i in range(10):
thread[i].join()
# end of main thread
print ("End of main thread!!!")
|
def is_num_prime(num, ndict):
if num in ndict:
return ndict[num]
if num < 2:
ndict[num] = False
else:
ndict[num] = True
i = 2
while i * i <= num:
if num % i == 0:
ndict[num] = False
break
i += 1
return ndict[num]
def get_prime_in_array(A):
ndict = {}
result = []
for num in A:
if is_num_prime(num, ndict):
result.append(num)
return result
print (get_prime_in_array([20, 13, 4, 22, 425, 224, 31, 344, 6]))
def get_prime(n):
primes = []
is_prime = [False, False] + [True] * (n - 1)
for p in range(2, n + 1):
if is_prime[p]:
primes.append(p)
for i in range(p, n + 1, p):
is_prime[i] = False
return primes
print(get_prime(70))
|
import threading
import time
import random
readers = 0
resource_lock = threading.Lock()
readers_lock = threading.Lock()
item = 0
def write_lock():
resource_lock.acquire()
def write_unlock():
resource_lock.release()
def read_lock():
global readers
readers_lock.acquire()
try:
readers += 1
if readers == 1:
resource_lock.acquire()
finally:
readers_lock.release()
def read_unlock():
global readers
readers_lock.acquire()
try:
readers -= 1
if readers == 0:
resource_lock.release()
finally:
readers_lock.release()
def reader1():
# while True:
for i in range(10):
print ("reader1 is waiting...")
try:
read_lock()
print (f"reader1 notify: consumed item {item}")
finally:
read_unlock()
def reader2():
while True:
# for i in range(10):
print ("reader2 is waiting...")
try:
read_lock()
print (f"reader2 notify: consumed item {item}")
finally:
read_unlock()
def writer():
global item
for i in range(10):
# time.sleep(1)
try:
write_lock()
item = random.randint(0, 10000)
print ("producer notify: produced item {0}".format(item))
finally:
write_unlock()
def main():
t0 = time.time()
thread1 = threading.Thread(target=reader1)
# thread2 = threading.Thread(target=reader2)
thread3 = threading.Thread(target=writer)
thread1.start()
# thread2.start()
thread3.start()
thread1.join()
# thread2.join()
thread3.join()
t1 = time.time()
print("Execution Time {}".format(t1 - t0))
if __name__ == '__main__':
main()
|
'''
file = open("testfile.txt", "w+")
file.write("Hello World\n")
file.write("This is our new text file\n")
file.write("and this is another line.\n")
file.write("Why? Because we can.\n")
file.close()
file = open("testfile.txt", "r")
print(file.read())
print(file.name)
file.close()
'''
# context manager
with open("testfile.txt", "r") as f:
pass
# 1 read the full content of the file
with open("testfile.txt", "r") as f:
content = f.read()
print (content)
# 2 read the file line by line
with open("testfile.txt", "r") as f:
for line in f:
print (line, end='')
# 3 f.readlines reads the full file and returns an array of all lines
with open("testfile.txt", "r") as f:
print (f.readlines())
f.seek(0)
# 4 f.readline will read one line
with open("testfile.txt", "r") as f:
content = f.readline()
while len(content) > 0:
print (content)
print (f.readline())
# 5 read the file data by size
with open("testfile.txt", "r") as f:
size = 10
f_content = f.read(size)
print (f_content)
while len(f_content) > 0:
f_content = f.read(size)
print (f_content, end='')
# 6 f.seek and f.tell
with open("testfile.txt", "r") as f:
f_content = f.read(size)
print (f_content)
print (f.tell())
f.seek(0)
f_content = f.read(size)
print (f_content)
# 7 seek can reset the position for writing
with open("test.txt", "w+") as f:
f.write('Testing123\n')
f.seek(0)
f.write('Testing\n')
# 8 test write
with open("test.txt", "w+") as f:
f.write('Testing file write\n')
# 9 copy the content from one file to other line by line
with open("test.txt", 'r') as rf:
with open('test_copy.txt', 'w') as wf:
for line in rf:
wf.write(line)
# 10 copy the content from one file to other chunk by chunk
with open("test.txt", 'r') as rf:
with open('test_copy2.txt', 'w') as wf:
chunk_size = 4096
rf_chunk = rf.read(chunk_size)
while len(rf_chunk) > 0:
wf.write(rf_chunk)
rf_chunk = rf.read(chunk_size)
# 11 to read and write the image file open the file in the binary format
# append b in the 'r' 'w' to 'rb', 'wb'
|
"""
What is this pattern about?
The Facade pattern is a way to provide a simpler unified interface to
a more complex system. It provides an easier way to access functions
of the underlying system by providing a single entry point.
This kind of abstraction is seen in many real life situations. For
example, we can turn on a computer by just pressing a button, but in
fact there are many procedures and operations done when that happens
(e.g., loading programs from disk to memory). In this case, the button
serves as an unified interface to all the underlying procedures to
turn on a computer.
"""
import time
SLEEP = 0.1
# Complex Parts
class TC1:
def run(self):
print(u"###### In Test 1 ######")
time.sleep(SLEEP)
print(u"Setting up")
time.sleep(SLEEP)
print(u"Running test")
time.sleep(SLEEP)
print(u"Tearing down")
time.sleep(SLEEP)
print(u"Test Finished\n")
class TC2:
def run(self):
print(u"###### In Test 2 ######")
time.sleep(SLEEP)
print(u"Setting up")
time.sleep(SLEEP)
print(u"Running test")
time.sleep(SLEEP)
print(u"Tearing down")
time.sleep(SLEEP)
print(u"Test Finished\n")
class TC3:
def run(self):
print(u"###### In Test 3 ######")
time.sleep(SLEEP)
print(u"Setting up")
time.sleep(SLEEP)
print(u"Running test")
time.sleep(SLEEP)
print(u"Tearing down")
time.sleep(SLEEP)
print(u"Test Finished\n")
# Facade
class TestRunner:
def __init__(self):
self.tc1 = TC1()
self.tc2 = TC2()
self.tc3 = TC3()
self.tests = [self.tc1, self.tc2, self.tc3]
def runAll(self):
[i.run() for i in self.tests]
# Client
if __name__ == '__main__':
testrunner = TestRunner()
testrunner.runAll()
|
''' 70. Climbing Stairs
Formula:
dp[0] = 1
dp[n] = dp[n-1] + dp[n-2]
'''
def climb_stairs(n):
dp = [0] * (n + 1)
dp[0] = 1
for i in range(n + 1):
for step in [1, 2]:
if i - step >= 0:
dp[i] = dp[i] + dp[i - step]
return dp[-1]
# print (climb_stairs(15))
###################################################
''' 198. House Robber
Formula:
dp[1] = nums[0]
dp[n] = max(dp[n-1], dp[n-2]+nums[n-1])
'''
def house_robber(nums):
n = len(nums)
dp = [0] * (n + 1)
dp[1] = nums[0]
for i in range(2, n + 1):
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i - 1])
return dp[n]
# print (house_robber([1, 2, 3, 1])) # 4
# print (house_robber([2, 7, 9, 3, 1])) # 12
######################################################
''' 322. Coin Change
Formula
dp[0] = 0
dp[n] = min((dp[i-d0], dp[i-d1].... dp[i-di], ... dp[i-dn-1]) + 1
'''
def coin_change(coins, amount):
dp = [float("inf")] * (amount + 1)
dp[0] = 0
for i in range(amount + 1):
for coin in coins:
if i - coin >= 0:
dp[i] = min(dp[i], dp[i - coin]) + 1
if dp[amount] == float("inf"):
return -1
return dp[amount]
# print (coin_change([1, 2, 5], 11))
# print (coin_change([2], 3))
######################################################
''' 518. Coin Change 2 https://leetcode.com/problems/coin-change-2/description/
Formula
The outer loop should be for coin. So that came coin should not be counted multiple time for different amounts
# dp[0] = 1
# dp[n] = sum((dp[i-d0], dp[i-d1].... dp[i-di], ... dp[i-dn-1]) (i-dk >=0)
'''
def coin_change2(coins, amount):
dp = [0] * (amount + 1)
dp[0] = 1
for coin in coins:
for i in range(amount + 1):
if i - coin >= 0:
dp[i] = dp[i] + dp[i - coin]
return dp[amount]
# print (coin_change2([1, 2, 5], 5))
# print (coin_change2([2], 3))
######################################################
'''
64. Minimum Path Sum
Formula:
dp[n-1][m-1] = grid[n-1][m-1]
dp[r][c] = min(dp[r + 1][c], dp[r][c + 1]) + grid[r][c]
'''
def min_path_sum(grid):
n = len(grid)
m = len(grid[0])
dp = [[float("inf") for _ in range(m + 1)] for _ in range(n + 1)]
for r in range(n - 1, -1, -1):
for c in range(m - 1, -1, -1):
if r == n - 1 and c == m - 1:
dp[r][c] = grid[r][c]
continue
dp[r][c] = min(dp[r + 1][c], dp[r][c + 1]) + grid[r][c]
return dp[0][0]
arr = [[1, 3, 1], [1, 50, 10], [4, 2, 1]]
# print(min_path_sum(arr))
######################################################
'''
62. Unique Paths
Formula:
dp[rows-1][cols-1] = 1
dp[r][c] = dp[r+1][c] + dp[r][c+1]
'''
def unique_paths(cols, rows):
dp = [[0 for _ in range(cols + 1)] for _ in range(rows + 1)]
for r in range(rows - 1, -1, -1):
for c in range(cols - 1, -1, -1):
if r == rows - 1 and c == cols - 1:
dp[r][c] = 1
continue
dp[r][c] = dp[r + 1][c] + dp[r][c + 1]
return dp[0][0]
# print (unique_paths(3, 2)) # 3
# print (unique_paths(7, 3)) # 28
######################################################
'''
63. Unique Paths II https://leetcode.com/problems/unique-paths-ii/description/
Formula:
# dp[rows-1][cols-1] = 1
# dp[r][c] = dp[r+1][c] + dp[r][c+1]
if grid[r][c] == 1 continue 0=>OK 1=>Obstracles
'''
def unique_paths(grid):
rows = len(grid)
cols = len(grid[0])
dp = [[0 for _ in range(cols + 1)] for _ in range(rows + 1)]
for r in range(rows - 1, -1, -1):
for c in range(cols - 1, -1, -1):
if grid[r][c] == 1:
continue
if r == rows - 1 and c == cols - 1:
dp[r][c] = 1
continue
dp[r][c] = dp[r + 1][c] + dp[r][c + 1]
return dp[0][0]
arr = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
# print (unique_paths(arr))
######################################################
'''
583. Delete Operation for Two Strings (Longest Common Subsequence)
https://leetcode.com/problems/delete-operation-for-two-strings/description/
Formula:
dp[i][j] = dp[i-1][j-1] + 1 if word1[i-1] == word2[j-1]
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) else
'''
def lcs(word1, word2):
n1, n2 = len(word1), len(word2)
dp = [[0 for _ in range(n2 + 1)] for _ in range(n1 + 1)]
for i in range(1, n1 + 1):
for j in range(1, n2 + 1):
if word1[i - 1] == word2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[n1][n2]
# print (lcs("aabcdex", "abcdefg"))
'''
97. Interleaving String
https://leetcode.com/problems/interleaving-string/description/
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Formula:
dp[i][j] = True if dp[i-1][j] and s1[i-1] == s3[i+j-1]
or dp[i][j-1] and s2[j-1] == s3[i+j-1]
'''
def isInterleave(s1, s2, s3):
n1, n2, n3 = len(s1), len(s2), len(s3)
if n1 + n2 != n3:
return False
dp = [[False for _ in range(n2 + 1)] for _ in range(n1 + 1)]
dp[0][0] = True
for i in range(0, n1 + 1):
for j in range(0, n2 + 1):
if ((i > 0 and dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or
(j > 0 and dp[i][j - 1] and s2[j - 1] == s3[i + j - 1])):
dp[i][j] = True
return dp[n1][n2]
s1, s2, s3 = "aabcc", "dbbca", "aadbbcbcac"
# print (isInterleave(s1, s2, s3))
s1, s2, s3 = "aabcc", "dbbca", "aadbbbaccc"
# print (isInterleave(s1, s2, s3))
'''
221. Maximal Square
https://leetcode.com/problems/maximal-square/description/
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Formula:
dp[n][0] = grid[n][0] # not required if dp table size is n+1, m+1
dp[0][m] = grid[0][m] # not required if dp table size is n+1, m+1
dp[r][c] = min(dp[r-1][c-1], dp[r-1][c], dp[r][c-1]) +1
'''
def maximalSquare(matrix):
n, m = len(matrix), len(matrix[0])
dp = [[0 for _ in range(m + 1)] for _ in range(n + 1)]
max_square = 0
for i in range(1, n + 1):
for j in range(1, m + 1):
if matrix[i - 1][j - 1] == '1':
dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1
max_square = max(max_square, dp[i][j])
return max_square * max_square
matrix = [["1", "0", "1", "0", "0"], ["1", "0", "1", "1", "1"], ["1", "1", "1", "1", "1"], ["1", "0", "0", "1", "0"]]
# print (maximalSquare(matrix))
'''
416. Partition Equal Subset Sum
https://leetcode.com/problems/partition-equal-subset-sum/description/
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Formula:
'''
def canPartition(nums):
return False
print (canPartition([1, 5, 11, 5]))
print (canPartition([1, 2, 3, 5]))
|
def get_max_sum_brute_force(lst, k):
l = len(lst)
max_sum = 0
for i in range(l - k + 1):
current_sum = 0
for j in range(i, i + k):
current_sum += lst[j]
max_sum = max(max_sum, current_sum)
return (max_sum)
def get_max_sum_sliding_window(lst, k):
l = len(lst)
max_sum = 0
current_sum = 0
for i in range(k):
current_sum += lst[i]
for i in range(k, l):
current_sum += lst[i] - lst[i - k]
max_sum = max(max_sum, current_sum)
return max_sum
lst = [100, 200, 300, 400]
print(get_max_sum_sliding_window(lst, k=2))
|
def alternatve_pos_neg(nums):
pos_count, neg_count = 0, 0
pos, neg = [], []
for num in nums:
if num < 0:
neg_count += 1
neg.append(num)
else:
pos_count += 1
pos.append(num)
if not pos_count or not neg_count:
return nums
nums = []
i, j, turn = 0, 0, 1
while i < pos_count and j < neg_count:
nums.append(pos[i])
nums.append(neg[j])
i, j = i + 1, j + 1
if i != pos_count:
nums += pos[i:]
if j != neg_count:
nums += neg[j:]
return nums
print (alternatve_pos_neg([2, 3, -4, -9, -1, -7, 1, -5, -6]))
|
"""
6. ZigZag Conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
"""
n = 2
0 3 6
P A H N
A P L S I I G
n = 3
0 4 8 12
Y I S K nrows - 0
A P L S I I G
Y I R T 4
n = 4
0 7
A P L S I I G
Y I R T 6
A P L S I I G
Y I R T 6
def convert(s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
str1 = ""
str2 = ""
str3 = ""
k = 0
while k < len(s):
if k % (numRows + 1) == 0:
str1 += s[k]
print (str1)
if k % 2 == 1:
str2 += s[k]
print (str2)
if k >= 2 and (k - 2) % (numRows + 1) == 0:
str3 += s[k]
print (str3)
k += 1
return str1 + str2 + str3
print (convert("PAYPALISHIRING", 3))
|
class Vertex:
def __init__(self, label):
self.neighbors = []
self.label = label
class Graph:
def __init__(self):
self.vertex_list = []
def add_edge(self, u, v):
u.neighbors.append(v)
self.vertex_list.append(u)
def explore_bfs(cur, seen, component):
seen.add(cur.label)
component.append(cur.label)
q = [cur]
while q:
cur = q.pop(0)
for nxt in cur.neighbors:
if nxt.label not in seen:
component.append(nxt.label)
seen.add(nxt.label)
q.append(nxt)
def bfs(vertex_list):
seen = set()
for vertex in vertex_list:
if vertex.label not in seen:
component = []
explore_bfs(vertex, seen, component)
print(component)
# v1 = Vertex(1)
# v2 = Vertex(2)
# v3 = Vertex(3)
# v4 = Vertex(4)
# v5 = Vertex(5)
# v6 = Vertex(6)
# v7 = Vertex(7)
# graph = Graph()
# graph.add_edge(v1, v2)
# graph.add_edge(v2, v5)
# graph.add_edge(v1, v3)
# graph.add_edge(v1, v4)
# graph.add_edge(v6, v7)
v1 = Vertex(1)
v2 = Vertex(2)
v3 = Vertex(3)
v4 = Vertex(4)
v5 = Vertex(5)
graph = Graph()
graph.add_edge(v1, v2)
graph.add_edge(v2, v3)
graph.add_edge(v4, v5)
seen = bfs(graph.vertex_list)
# print(seen)
|
class Node:
def __init__(self, val):
self.data = val
self.prev = None
self.next = None
def get_data(self):
return self.data
class DList:
def __init__(self):
self.head = None
self.tail = None
def push(self, val):
new_node = Node(val)
if self.head:
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
else:
self.head = new_node
self.tail = new_node
return new_node
def append(self, val):
new_node = Node(val)
self.tail.next = new_node
new_node.prev = self.tail
self.tail = new_node
return new_node
def remove_from_last(self):
if self.tail is None:
raise KeyError('ther is no entry to remove.')
ret_key = self.tail.data
print ("dlist", ret_key)
# dlist has only one entry
if self.tail.prev is None:
self.tail = None
self.head = None
return ret_key
# dlist has more than one entry.
prev = self.tail.prev
prev.next = None
self.tail = None
self.tail = prev
return ret_key
def print_front_to_back(self):
tmp = self.head
print('Front to Back ', end=' ')
while tmp is not None:
print(tmp.data, end=' ')
tmp = tmp.next
print('')
def print_back_to_front(self):
print('Back to Front ', end=' ')
tmp = self.tail
while tmp is not None:
print(tmp.data, end=' ')
tmp = tmp.prev
print('')
def move_to_front(self, node):
if self.head is None:
raise KeyError ('Invalid node entry')
# if first node then return
if node.prev is None:
return
# if this is last node
if node.next is None:
self.tail = node.prev
# remove this node from dll first
prev = node.prev
next = node.next
prev.next = next
# if not the last node
if next:
next.prev = prev
# add this node in the front of the dll
node.prev = None
node.next = self.head
self.head.prev = node
self.head = node
def revese(self):
pass
def main():
# linked list program without using inbuilt list() ds
dlist = DList()
dlist.push(40)
node = dlist.push(30)
dlist.push(20)
dlist.push(10)
dlist.append(100)
dlist.append(200)
dlist.print_front_to_back()
dlist.remove_from_last()
dlist.print_front_to_back()
dlist.remove_from_last()
dlist.print_front_to_back()
print("move {0} to front.".format(node.data))
dlist.move_to_front(node)
dlist.print_front_to_back()
#print(node, node.data)
#dlist.print_back_to_front()
'''
#linked list program by using inbuilt list() ds
dlist = list()
dlist.insert(0, 40)
dlist.insert(0, 30)
dlist.insert(0, 20)
dlist.insert(0, 10)
dlist.append(100)
dlist.append(200)
print(dlist)
dlist.reverse()
print(dlist)
'''
if __name__ == "__main__":
main()
|
"""
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
Example 1:
Input:
s: "cbaebabacd" p: "abc"
Output:
[0, 6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
"""
import string
from string import ascii_lowercase
def isAnagram(s, p):
"""
:type s: str
:type t: str
:rtype: bool
"""
for i in string.ascii_lowercase:
if s.count(i) != p.count(i):
return False
return True
def findAnagrams(s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
l = list()
plen = len(p)
slen = len(s)
if plen > slen:
return l
nset = set()
for i in range(0, slen):
if (i + plen) <= slen:
if s[i: (i + plen)] in nset:
l.append(i)
elif isAnagram(s[i: (i + plen)], p) is True:
nset.add(s[i: (i + plen)])
l.append(i)
return l
str1 = "cbaebabacd"
str2 = "abc"
print(findAnagrams(str1, str2))
# str1 = "abab"
# str2 = "ab"
# print(findAnagrams(str1, str2))
# str1 = "cbaebabacd"
# str2 = "abc"
# print(findAnagrams(str1, str2))
str1 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
str2 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
print(findAnagrams(str1, str2))
|
class Solution:
def check_valid(self, col_placement, row1, col1):
for row2 in range(row1):
col2 = col_placement[row2]
if col1 == col2:
return False
if abs(col2 - col1) == abs(row2 - row1):
return False
return True
def helper(self, col_placement, n, row):
count = 0
if row == n:
# All queens are legally placed
return 1
for col in range(n):
if self.check_valid(col_placement, row, col):
col_placement[row] = col
count += self.helper(col_placement, n, row+1)
return count
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
col_placement = [0] * n
count = self.helper(col_placement, n, 0)
return count
s = Solution()
print (s.totalNQueens(10))
|
def shortestDistance(words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
l = len(words)
idx1 = -1
idx2 = -1
ans = l
for i in range(0, l):
if words[i] == word1:
idx1 = i
elif words[i] == word2:
idx2 = i
if idx1 != -1 and idx2 != -1:
ans = ans if ans < abs(idx1 - idx2) else abs(idx1 - idx2)
return ans
wl = ["a", "c", "b", "b", "a"]
w1 = "a"
w2 = "b"
print(shortestDistance(wl, w1, w2))
wl = ["a", "b", "c", "d", "d"]
w1 = "a"
w2 = "d"
print(shortestDistance(wl, w1, w2))
wl = ["practice", "makes", "perfect", "coding", "makes"]
w1 = "makes"
w2 = "coding"
print(shortestDistance(wl, w1, w2))
w1 = "coding"
w2 = "practice"
print(shortestDistance(wl, w1, w2))
|
#python3 ~/lang/python/lang/functools.py
import functools
#functools.reduce (function, iterable[, initializer])
print ("functools.reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) -> ((((1+2)+3)+4)+5)")
print (functools.reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]))
print ("functools.reduce(lambda x, y: x+y, [1, 2, 3, 4, 5], 100) -> ((((1+2)+3)+4)+5+100)")
print (functools.reduce(lambda x, y: x+y, [1, 2, 3, 4, 5], 100))
|
'''A multi-producer, multi-consumer queue.
https://github.com/python/cpython/blob/3.7/Lib/queue.py
'''
import threading
from collections import deque
from heapq import heappush, heappop
from time import monotonic as time
class Full(Exception):
'Exception raised by Queue.put(block=0)/put_nowait().'
pass
class Queue:
def __init__(self, maxsize=0):
self.maxsize = maxsize
self.queue = deque()
self.mutex = threading.Lock()
self.not_empty = threading.Condition(self.mutex)
self.not_full = threading.Condition(self.mutex)
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
with self.all_tasks_done:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
def join(self):
with self.all_tasks_done:
while self.unfinished_tasks:
self.all_tasks_done.wait()
def qsize(self):
with self.mutex:
return self._qsize()
def empty(self):
with self.mutex:
return not self._qsize()
def full(self):
with self.mutex:
return 0 < self.maxsize <= self._qsize()
def put(self, item, block=True, timeout=None):
with self.not_full:
if self.maxsize > 0:
while self._qsize() >= self.maxsize:
self.not_full.wait()
self.queue.append(item)
self.unfinished_tasks += 1
self.not_empty.notify()
def get(self, block=True, timeout=None):
with self.not_empty:
while not self._qsize():
self.not_empty.wait()
item = self.queue.popleft()
self.not_full.notify()
return item
def _qsize(self):
return len(self.queue)
|
"""
Given a array of 'n' elements with numbers in the range of 1-n
There is exactly 1 number missing that we need to find
"""
arr = [1, 2, 3, 4, 5, 7]
# Method 1: Get the sum using n * (n+1)/ 2 and subtract the sum of the array
n = len(arr) + 1
range_sum = n * (n + 1) // 2
sum = 0
for i in arr:
sum = sum + i
print (range_sum - sum)
# Method 2: Add the array element in a set and then just run the loop for n element and if the element is not in the set then print it and break from the loop.
data = set()
for i in arr:
data.add(i)
for i in range(1, n + 1):
if i not in data:
print (i)
break
|
"""
Given an 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?
"""
def singleNumber(nums):
final = nums[0]
for i in range(1, len(nums)):
final = final ^ nums[i]
return final
arr = [2, 2, 3, 3, 4, 5, 6, 5, 6]
print (singleNumber(arr))
|
"""
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
"""
def reverseString(s):
fstr = ""
bstr = ""
mstr = ""
n = len(s)
for i in range(0, n // 2):
fstr = s[i] + fstr
bstr = bstr + s[n - 1 - i]
if n % 2 != 0:
mstr = s[n // 2 + 1]
return bstr + mstr + fstr
def reverseWords(s):
"""
:type s: str
:rtype: str
"""
wlist = s.split(' ')
max = len(wlist)
finalstr = ""
j = 0
for i in wlist:
finalstr = finalstr + reverseString(i) + ("" if (j == (max - 1)) else " ")
j += 1
return finalstr
data = "Let's take LeetCode contest"
print (data)
print (reverseWords(data))
|
"""
Implement a UNIX TAIL command
"""
def tail(file_name, n):
f = open(file_name, 'rb')
f.seek(0, 2)
file_size = f.tell()
newline_cnt = 0
print ("file size: ", file_size, " # of line:", n)
last_n_lines = ""
for i in range(1,file_size):
f.seek(-i, 2)
c = f.read(1).decode('utf-8')
if c == '\n': newline_cnt += 1
if (newline_cnt >= n): break
last_n_lines += c
f.close()
return last_n_lines[::-1]
print (tail("epi_7_13_tail.py", 10))
|
import threading
import queue
import time
import random
queue = queue.Queue()
def producer():
""" Producer: Add the item in the Queue """
for i in range(10):
item = random.randint(0, 256)
queue.put(item)
print (f'producer notify: item {item} is added to queue')
time.sleep(1)
def consumer(thread_id):
""" Consumer: Take the item out of the queue and notify that task is done using task_done() """
while True:
item = queue.get()
print (f'consumer {thread_id} notify: item {item} is popped from queue')
queue.task_done()
def main():
t0 = time.time()
threads=[]
threads.append(threading.Thread(target=producer))
for i in range(3):
threads.append(threading.Thread(target=consumer, args=(i,)))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
t1 = time.time()
print("Execution Time {}".format(t1 - t0))
if __name__ == '__main__':
main()
|
def is_palindrome(n):
nstr = str(n)
l = len(nstr)
for i in range(l // 2):
if nstr[i] != nstr[l - 1 - i]:
return False
return True
def is_prime(n):
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
n = 1
i = n
while 1:
if is_palindrome(i) is True and is_prime(i) is True:
print(i)
break
i = i + 1
print(is_palindrome(n))
print(is_prime(n))
print
|
import pandas as pd
import numpy as np
import sklearn
from sklearn import linear_model
from sklearn.utils import shuffle
data = pd.read_csv("student-mat.csv", sep=";")
# print(data.head()) #prints out all the data
data = data[["G1", "G2", "G3", "studytime", "failures", "absences"]]
# print(data.head()) #prints out only the above 6 now
#predict is also known as the label .
predict = "G3"
#all of our features/attr
x = np.array(data.drop([predict], 1))
#all of our labels
y = np.array(data[predict])
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.1)
linear = linear_model.LinearRegression()
linear.fit(x_train, y_train)
acc = linear.score(x_test, y_test)
print(f"Accuracy: {acc}")
print(f"Coefficients:\n {linear.coef_}")
print(f"Intercept:\n {linear.intercept_}")
predictions = linear.predict(x_test)
print("Answer\t[Beginning-Grade]\t[End-Grade]\t[Study-Time]\t[Failures]\t[Absences]\t[Actual Grade] ")
for x in range(len(predictions)):
print(predictions[x], x_test[x], y_test[x])
|
class Solution:
def Met(n):
i=2;
st='1';
if n == 1:
print(st);
else:
while i<=n:
st=st+" "+str(i)+" "+st
i+=1;
print(st)
if __name__ == "__main__":
Solution.Met(3);
print();
Solution.Met(2);
print();
Solution.Met(4); |
"""
Unicode Transformation Format – 8-bit
As the name suggests UTF-8 was designed to encode data in a stream of bytes.
It works by splitting the bits up in multiples of eight. This is achieved by inserting headers to mark in how many bytes the bits were split. If the bits need to be split in two, the header 110 is added as prefix leaving five bits of the byte for the rest of the data. Followed by a continuation byte.
A continuation byte always start with 10 leaving six bits for data. For a three-way split: the header 1110 is added with two continuation bytes and for four: 11110 with three continuation bytes. The number of ones at the start of the first byte denotes the number of bytes the data was split in.
Task
Your task is to write two functions:
to_utf8_binary: which encodes a string to a bitstring using UTF-8 encoding.
from_utf8_binary: which does the reverse.
Layout of UTF-8 byte sequences:
"""
def to_utf8_binary(string: str) -> str:
return ''.join(bin(char)[2:].rjust(8,'0') for char in string.encode('utf8'))
def from_utf8_binary(binary: str) -> str:
return bytearray(int(binary[i*8:(i+1)*8], 2) for i in range(len(binary) // 8)).decode('utf8') |
"""
In mathematics, the symbols Δ and d are often used to denote the difference between two values.
Similarly, differentiation takes the ratio of changes (ie. dy/dx) for a linear relationship.
This method can be applied multiple times to create multiple 'levels' of rates of change.
(A common example is x (position) -> v (velocity) -> a (acceleration)).
Today we will be creating a similar concept. Our function delta will take a sequence of values and a positive
integer level, and return a sequence with the 'differences' of the original values.
(Differences here means strictly b - a, eg. [1, 3, 2] => [2, -1]) The argument level is the 'level'
of difference, for example acceleration is the 2nd 'level' of difference from position. The specific
encoding of input and output lists is specified below.
The example below shows three different 'levels' of the same input.
input = [1, 2, 4, 7, 11, 16, 22]
list(delta(input, 1)) # [1, 2, 3, 4, 5, 6]
list(delta(input, 2)) # [1, 1, 1, 1, 1]
list(delta(input, 3)) # [0, 0, 0, 0]
We do not assume any 'starting value' for the input, so the output for each subsequent level will be one item shorter than the previous (as shown above).
If an infinite input is provided, then the output must also be infinite.
Input/Output encoding
Input and output can be any, possibly infinite, iterable. Possibilities include finite lists and possibly infinite generator objects, but any iterable must be accepted as input and is acceptable as output.
Difference implementation
delta must work for iterables of any objects/types that implement __sub__ (eg int, float, set, etc).
Additional Requirements/Notes:
delta must work for inputs which are infinite
values will always be valid, and will always produce consistent classes/types of object
level will always be valid, and 1 <= level <= 400
"""
def delta(values, n):
if n == 0:
yield from values
else:
v = delta(values, n-1)
prev = next(v)
for num in v:
yield num - prev
prev = num |
"""
How many times we create a python class and in the init method we just write:
self.name1 = name1
self.name2 = name2
.....
for all arguments.....
How boring!!!!
Your task here is to implement a metaclass that let this instantiation be done automatically.
But let's see an example:
class Person(metaclass=LazyInit):
def __init__(self, name, age): pass
When we create a Person object like:
a_person = Person('John', 25)
The expected behavior will be:
print(a_person.name) # this will print John
print(a_person.age) # this will print 25
Obviously the number of arguments might be different from class to class.
Don't worry about **kwargs you will never be given keyword arguments in this kata!!!
A little hint: a decorator could help you out doing the job!!!
"""
# the metaclass to be used
class LazyInit(type):
def __call__(self, *args):
""" Вызов класса создает новый объект. """
# Перво-наперво создадим сам объект...
obj = type.__call__(self, *args)
# и добавим ему переданные в вызове аргументы в качестве атрибутов.
for field, value in zip(obj.__init__.__code__.co_varnames[1:], args):
setattr(obj, field, value)
# вернем готовый объект
return obj
|
#-----------------OS model----------------------------
#The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s
# standard utility modules. This module provides a portable way of using operating system-dependent
# functionality. The *os* and *os.path* modules include many functions to interact with the file system.
#-------------------Handling the Current Working Directory-----------------------------------
#Consider Current Working Directory(CWD) as a folder, where the Python is operating. Whenever the files are
# called only by their name, Python assumes that it starts in the CWD which means that name-only reference will
# be successful only if the file is in the Python’s CWD.
#Note: The folder where the Python script is running is known as the Current Directory. This is not the path
# where the Python script is located.
#--------------Getting the Current working directory------------------------------------------
#To get the location of the current working directory os.getcwd() is used.
# Python program to explain os.getcwd() method
# importing os module
import os
# Get the current working
# directory (CWD)
cwd = os.getcwd()
# Print the current working
# directory (CWD)
print("Current working directory:", cwd)
print('Changing the Current working directory------------------------------------------------')
#----------------Changing the Current working directory-----------------------------------------
#To change the current working directory(CWD) os.chdir() method is used. This method changes the CWD to a
# specified path. It only takes a single argument as a new directory path.
#Note: The current working directory is the folder in which the Python script is operating.
# Python program to change the current working directory
import os
# Function to Get the current
# working directory
def current_path():
print("Current working directory before")
print(os.getcwd())
print()
# Driver's code
# Printing CWD before
current_path()
# Changing the CWD
""" os.chdir('../') """ #can uncomment later to see how it works for real
# Printing CWD after
current_path()
print('Listing out Files and Directories with Python---------------------------------------------------')
#os.listdir() method in Python is used to get the list of all files and directories in the specified directory.
# If we don’t specify any directory, then list of files and directories in the current working directory will
# be returned.
# Python program to explain os.listdir() method
# importing os module
import os
# Get the list of all files and directories
# in the root directory
path = "/"
dir_list = os.listdir(path)
print("Files and directories in '", path, "' :")
# print the list
print(dir_list) |
#Build a list,check the name on the list, check against another list and get the index of the particular list
name=input('What is your name? \n')
allowedUsers=['Rossi','James','Sandra']
allowedPassword=['passwordRossi','passwordJames','passwordSandra']
if name in allowedUsers:
password=input('Your password? \n')
userId=allowedUsers.index(name)
if password==allowedPassword[userId]:
print('Welcome %s'%name)
else:
print('Password Incorrect, please try again')
else:
print('Name not found, please try again') |
#A way to receive input from the user is by using input() function
#To star from the next line use \n
name=input('What is your name? \n')
allowedUers=['Rossi','Toria','Ada'] #List of allowed users
AllowedPassword='Password'#Password is static for ni
if name in allowedUers:
password=input('Your password? \n')
if password==AllowedPassword:
print('Welcome %s' %name)
else:
print('Password Incorrect, please try again')
else:
print('Name not found, please try again') |
#Object oriented deep dive class
class Animal:
# Class attribute
animal_type='insects'
# instance(object) attribute
def __init__ (self,name,number_of_legs):
self.name=name
self.number_of_legs=number_of_legs
#This a method (an instance method)
def can_run(self):
print(f'Animal {self.name} runs with {self.number_of_legs} legs')
animal_one= Animal ('hen',2)
animal_two= Animal ('Cat',4)
#Calling the method can_run on the instance of the animal_one and animal_two
animal_one.can_run()
animal_two.can_run()
print('='* 40)
print(animal_one.animal_type)
print(animal_two.animal_type)
#We have three type of method in python
#1. Instance method
#2. class method
#3.Static method
print('1. Insatance method=======================================================')
#Instance method: This is a very basic and easy method that we use regularly when we create classes in python.
# If we want to print an instance variable or instance method we must create an object of that required class.
#If we are using self as a function parameter or in front of a variable, that is nothing but the calling
# instance itself.
#As we are working with instance variables we use self keyword.
#Look at the code below
#Instance Method Example in Python
class Student:
def __init__(self,a,b):
self.a=a
self.b=b
#This an instance method
def avg(self):
return (self.a + self.b)/2
s1=Student(10,20)
print(s1.avg())
#In the above program, a and b are instance variables and these get initialized when we create an object
# for the Student class. If we want to call avg() function which is an instance method, we must create an
# object for the class.
#If we clearly look at the program, the self keyword is used so that we can easily say that those are
# instance variables and methods.
print('2. Class method ============================================================================')
#The purpose of the class methods is to set or get the details (status) of the class. That is why they
# are known as class methods. They can’t access or modify specific instance data. They are bound to the
# class instead of their objects.
# class method modify the general state of the class specific details.
# Two important things about class methods:
# In order to define a class method, you have to specify that it is a class method with the help of the
# @classmethod decorator
#Class methods also take one default parameter- cls, which points to the class. Again, this not mandatory
# to name the default parameter “cls”. But it is always better to go with the conventions
class ANIMAL:
# Class attribute
animal_type='INSECTS'
# instance(object) attribute
def __init__ (self,name,number_of_legs):
self.name=name
self.number_of_legs=number_of_legs
#This a class method
@classmethod
def can_see(cls):
print(f'Animal can see')
animal_one= ANIMAL ('hen',2)
animal_two= ANIMAL ('Cat',4)
#calling the class method in animal_one and animal_two
animal_one.can_see()
animal_two.can_see() #it displays animal can see in but state of animal_one and animal_two
print('3. Static method ==================================================================================')
#static method:Static methods cannot access the class data. In other words, they do not need to access the
# class data. They are self-sufficient and can work on their own. Since they are not attached to any class
# attribute, they cannot get or set the instance state or class state.
#static methd Cannot access anything else in the class.They are totally self-contained code.
#In order to define a static method, we can use the @staticmethod decorator (in a similar way we used
# @classmethod decorator). Unlike instance methods and class methods, we do not need to pass any special
# or default parameters.
# Static Method Implementation in python
class STUDENT:
name = 'STUDENT'
def __init__(self, a, b):
self.a = a
self.b = b
@staticmethod
def info():
return "This is a student class"
print(STUDENT.info())
#Check when to use each of the method |
num1, num2, num3 = map(int,input("정수 3개를 입력해주세요:").split())
if num1>num2 and num1>num3 : #첫 번째 수 num1이 가장 커야함
print("True")
else :
print("False")
if num1==num2==num3 : #세 수가 모두 같아야함
print("True")
else :
print("False") |
# 두 개의 정수를 입력받아 두 정수 사이(두 정수를 포함)에 3의 배수이거나 5의 배수인 수들의 합과 평균을 출력하는 프로그램을 작성하시오.
# 평균은 반올림하여 소수 첫째자리까지 출력한다.
# 입력 예: 10 15
# 출력 예: sum : 37 avg : 12.3
num1, num2 = map(int, input("두개 정수 입력:").split())
sum = 0
count = 0
temp =0
if num1 > num2: # num2 가 더 큰수로 치환
temp = num1
num1 = num2
num2 = temp
while num1 <= num2: # num2까지 반복
if num1%3==0 or num1%5==0:
sum = sum + num1 # 3, 5 배수 인 수 합
count += 1 # 평균 구할 때 몇개 더했는지 확인
num1 += 1
avg = sum/count
print("sum: {} avg: {}".format(sum, round(avg,1)))
|
# "FizzBuzz"문제
# 1에서 100까지의 숫자를 출력하되,
# 만약 해당 숫자가 '3'으로 나누어지면 숫자 대신에 "Fizz"를 출력하고,
# 만약 해당 숫자가 '5'로 나누어지면 숫자 대신에 "Buzz"를 출력하며,
# 만약 해당 숫자가 '3'과 '5'로 모두 나누어지면 숫자 대신에 "FizzBuzz"를 출력
# 입력 예1: 5
# 출력 예1: "Buzz"
# 입력 예2: 3
# 출력 예2: "Fizz"
# 입력 예3: 15
# 출력 예3: "FizzBuzz"
num = int(input("1~100까지의 숫자를 입력:"))
if num <= 100:
# 3이랑 5로 동시에 나눠져야하므로 나머지가 0
if num%3 ==0 and num%5 ==0:
print("FizzBuzz")
elif num%3 ==0:
print("Fizz")
elif num%5 ==0:
print("Buzz")
else:
print("1~100까지의 수를 입력해주세요:") |
# 아래와 같은 모양으로 출력하는 프로그램을 작성하시오.
# 사용자에게 숫자를 입력받아 입력 받은 높이 만큼의 삼각형을 출력하시오.
# 입력 예: 5
# *****
# ****
# ***
# **
# *
num = int(input("정수를 입력하시오:"))
for line in range(num,0,-1):
print(" "*(num-line) + "*"*line)
|
# 공백을 포함한 문자열을 입력받아 각 단어로 분리하여 문자열 배열에 저장한 후 입력순서의 반대 순서로 출력하는 프로그램을 작성하시오. 문자열의 길이는 100자 이하이다.
# 입력 예: C++ Programing jjang!!
# 출력 예:
# jjang!!
# Programing
# C++
str_list = input("100자 이하 문자열을 입력해주세요:").split()
str_list_len = len(str_list)
#리스트 각각의 인덱스에 저장된 값 합치고 길이가 100이하인지 확인
if len(' '.join(str_list)) <= 100:
for i in range(str_list_len,0,-1):
# 길이가 리스트의 인덱스 끝번보다 1 크기때문에 -1해준다.
print(str_list[i-1])
else:
print("100자가 넘습니다. 다시 입력해주세요") |
# 정수를 입력받아서 3의 배수가 아닌 경우에는 아무 작업도 하지 않고, 3의 배수인 경우에는 3으로 나눈몫을 출력하는 작업을 반복하다가 -1이 입력되면 종료하는 프로그램을 작성하시오.
# 예시:
# 5
# 12
# 4
# 21
# 7
# 100
# -1
num=1
while num!=-1:
num = int(input("정수 입력:"))
if num % 3 ==0:
num=num/3
print(int(num)) |
class Employee:
def __init__(self, irum, nai):
self.irum = irum
self.nai = nai
def pay(self):
pass
def data_print(self):
pass
def irumnai_print(self):
pass
class Regular(Employee):
def __init__(self,irum, nai, salary):
super().__init__(irum, nai)
self.salary = salary
def __str__(self):
return "이름:{}, 나이:{}, 월급{}".format(self.irum, self.nai, self.salary)
class Salesman(Regular):
def __init__(self,irum,nai,salary,sales,commission):
super().__init__(irum, nai, salary)
self.sales = sales
self.commission = commission
def __str__(self):
return "이름:{}, 나이:{}, 수령액:{}".format(self.irum, self.nai, int(self.salary + self.sales*self.commission))
class Temporary(Employee):
def __init__(self,irum,nai, ilsu, ildang):
super().__init__(irum, nai)
self.ilsu = ilsu
self.ildang = ildang
def __str__(self):
return "이름:{}, 나이:{}, 월급:{}".format(self.irum, self.nai, self.ilsu * self.ildang)
t=Temporary("홍길동", 25, 20, 15000)
s=Regular("한국인", 27, 3500000)
u=Salesman("손오공", 29, 1200000, 5000000, 0.25)
print(t)
print(s)
print(u)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.