text
stringlengths 37
1.41M
|
---|
'''
7562 λμ΄νΈμ μ΄λ
μκ³ λ¦¬μ¦:
1. λμ΄νΈκ° κ° μ μλ 8λ°©ν₯μ μ’νλ₯Ό μ μνκ³ , μ΅μμ΄λμ΄λ―λ‘ bfsμ¬μ©
2. bfsμ μ’
λ£ μ‘°κ±΄ μ€μ ν μκ°μ λͺ»ν΄λλ€ --> νμμ λΉΌλΈ κ°μ΄ κ°μΌλ©΄ μ’
λ£ν΄λλλ€
'''
from collections import deque
def bfs(x, y):
q = deque()
q.append([x, y])
chess[x][y] = 1
while q:
x, y = q.popleft()
if x == dox and y == doy:
return (chess[x][y] - 1)
for i in range(8):
nx = dx[i] + x
ny = dy[i] + y
if (0<= nx < L) and (0 <= ny < L) and chess[nx][ny] == 0:
chess[nx][ny] = chess[x][y] + 1
q.append([nx, ny])
T = int(input())
dx = [-2, -2, -1, -1, 1, 1, 2, 2]
dy = [-1, 1, -2, 2, -2, 2, -1, 1]
for i in range(T):
L = int(input())
chess = [[0] * L for i in range(L)]
x, y = map(int, input().split())
dox, doy = map(int, input().split())
print(bfs(x, y))
|
'''
10867 μ€λ³΅ λΉΌκ³ μ λ ¬νκΈ°
1. μ€λ³΅μ μμ μΌ νλκΉ dict μλ£νμ μ¬μ©
(set ν¨μλ₯Ό μ°λ €λ€κ° λͺ» μΌλ€)
+) sorted(list(set(array))) λ‘ setμ listλ‘ λ³ννκ³ κ·Έ λ€μμ μ λ ¬νλ©΄ λλ€
'''
import sys
N = int(input())
array = list(map(int, sys.stdin.readline().split()))
dict = {}
for i in array:
if i not in dict.keys():
dict[i] = 1
array = sorted(dict.items(), key = lambda x :x[0])
for i in array:
print(i[0], end = ' ')
|
'''
1439 λ€μ§κΈ°
μκ³ λ¦¬μ¦:
1. μ
λ ₯λ°μ λ¬Έμμ΄μ 0μ κΈ°μ€μΌλ‘ λΆλ¦¬νκ³ , 1μ κΈ°μ€μΌλ‘ λΆλ¦¬ν΄μ κ°κ° listμ λ£λλ€
2. κ° λ¦¬μ€νΈμ κΈΈμ΄λ μ«μλ₯Ό κ°κ² λ§λ€λλ‘ λ€μ§μ λμ μ°μ° νμμ΄λ€
3. λ°λΌμ, κΈΈμ΄κ° μ§§μ 리μ€νΈλ₯Ό κ³ λ₯΄λ©΄ λλ€
'''
s = input()
zerolist = s.split('1')
onelist = s.split('0')
# 리μ€νΈμμ λΉ λ¬Έμμ΄λ€μ μ κ±°νλ λ°©λ²
zerolist = [v for v in zerolist if v]
onelist = [v for v in onelist if v]
if len(zerolist) > len(onelist):
count = len(onelist)
else:
count = len(zerolist)
print(count)
|
# Find pairs in an integer array whose sum is equal to 10
# Bonus: do it in linear time
import sys
def pairs_sum_to_10(arr, n, sum):
m = [0] * 1000
# Store counts of all elements in map m
for i in range(0, n):
m[arr[i]]
m[arr[i]] += 1
twice_count = 0
# Iterate through each element and increment
# the count (Notice that every pair is
# counted twice)
for i in range(0, n):
twice_count += m[sum - arr[i]]
# if (arr[i], arr[i]) pair satisfies the
# condition, then we need to ensure that
# the count is decreased by one such
# that the (arr[i], arr[i]) pair is not
# considered
if (sum - arr[i] == arr[i]):
twice_count -= 1
# return the half of twice count
return int(twice_count / 2)
def main():
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = len(arr)
sum = 10
print("Count of pairs is", pairs_sum_to_10(arr, n, sum))
main()
"""
The Explanation:
This creates a map to store frequency of each number in the array (in a
single traversal). In the next traversal, for each element check if it can
be combined with any other element (other than itself) to give the desired
sum. Increment the counter accordingly. After completion of second
traversal, we'd have twice the required value stored in counter because
every pair is counted two times. Hence divide the count by 2 and return.
"""
|
# Prints out the binary form of an integer
def conv_to_bin(num):
return bin(num)
print conv_to_bin(1)
print conv_to_bin(2)
print conv_to_bin(3)
print conv_to_bin(4)
def int_to_bin_string(i):
if i == 0:
return "0"
s = ''
while i:
if i & 1 == 1:
s = "1" + s
else:
s = "0" + s
i //= 2
return s
print int_to_bin_string(1)
print int_to_bin_string(2)
print int_to_bin_string(3)
print int_to_bin_string(4)
"""
Explanation:
Python has a built-in bin() method that you can call to convert from int to
its binary representation.
However, if we're not allowed to use that method, we can write our own
method. Take the input string and use logic operations to convert the
digits into its binary representation.
"""
|
from datetime import date
user_vm=""
logged_in = False
def login():
username=input("Username:# ")
password=input("Password:# ")
# Logging in module
with open('user.txt','r') as users:
for row in users:
if username and password in row:
print ("Login successful!")
global user_vm
user_vm=username
global logged_in
logged_in = True
return logged_in
print ("Your username or password is invalid. Please enter valid credentials")
username=input("Username:# ")
password=input("Password:# ")
user_db = True
def check_user(x):
with open('user.txt','r+') as tasks:
for row in tasks.readlines():
row_list=row.split(',')
if x == row_list[0]:
print("User already created. Please use another name")
global user_db
user_db=False
tasks.close()
return user_db
def reg_user():
with open('user.txt','a+') as add_users:
add=input("Do you want to add a user y/n ")
while add == "y":
global user_db
user_db = True
add_user=input("Please enter a Username:# ")
log=check_user(add_user)
if log == False:
print(" Please enter 'y' to add a user")
#add=input("Do you want to add a user y/n")
elif log == True:
add_pass=input("Enter your Password:# ")
user_rec=add_user+", "+add_pass
add_users.write(user_rec)
add_users.write("\n")
add=input("Do you want to add a user y/n ")
add_users.close()
return
def key_generator():
counter=0
with open('tasks.txt') as f:
for line in f:
pass
counter+=1
# last_line = line
f.close()
return counter
def add_task():
with open('tasks.txt','a+') as tasks:
add_task=input("Do you want to add a task y/n ")
id_key=key_generator()
while add_task == "y":
id_key=id_key+1
username_task=input("Enter the username of the assigned ")
title_task=input("Enter the title of the task ")
descr_task=input("Enter the description of the task ")
due_date_task=input("Enter the due date dd-mm-yy ")
creation_date=date.today()
complete="N"
task_rec="000"+str(id_key)+", "+username_task+", "+title_task+", "+descr_task+", "+due_date_task+", "+str(creation_date)+", "+complete
tasks.write(task_rec)
tasks.write('\n')
add_task=input("Do you want to add another task y/n ")
tasks.close()
return
def view_all():
with open('tasks.txt','r') as tasks:
for row in tasks.readlines():
print(row)
tasks.close()
return
def view_mine():
with open('tasks.txt','r') as tasks:
for row in tasks.readlines():
if user_vm in row:
print (row)
def admin_user():
current_date=str(date.today())
number_of_lines_tasks=0
number_of_lines_users=0
with open('tasks.txt','r') as tasks:
for line in tasks:
line = line.strip("\n")
number_of_lines_tasks += 1
print ( "NUMBER OF TASKS as of "+current_date +" is "+str(number_of_lines_tasks))
print("\n")
with open('user.txt','r') as read_users:
for line in read_users:
line = line.strip("\n")
number_of_lines_users += 1
print ( "NUMBER OF USERS as of "+current_date +" is "+str(number_of_lines_users))
print("\n")
return
log = login()
while log:#Display menu options
print("Print select one of the following options : \n r- register \n a - add task \n va - view all tasks \n vm - view my tasks \n gr - generate reports \n ds - display statistics \n e - exit ")
menu=input("Enter an option ")
#Enter menu option
if menu=="r":
#user registration module
if user_vm=="admin":
reg_user()
else:
print("\n")
print("Only admin is allowed to register users")
print("\n")
elif menu=="a":
#Add a task module
add_task()
elif menu=="va":
#View all tasks module
view_all()
print("\n")
elif menu=="vm":
#view your tasks module
view_mine()
print("\n")
elif menu=="m":
#Administrator module
if user_vm=="admin":
admin_user()
print("\n")
else:
print("\n")
print("Only Admin user is allowed into this menu")
print("\n")
else:
#exit
log=False
|
import unittest
from app.models.game import Game
from app.models.player import Player
class TestGame(unittest.TestCase):
def setUp(self):
self.player1 = Player("Katie", "paper")
self.player2 = Player("Tom", "rock")
self.player3 = Player("Liam", "rock")
self.player4 = Player("Maria", "scissors")
self.player5 = Player("Claire", "rock")
self.player6 = Player("David", "rock")
self.player7 = Player("John", "rock")
self.player8 = Player("Peter", "paper")
self.player9 = Player("Donald", "paper")
self.player10 = Player("Nancy", "scissors")
self.player11 = Player("Edwin", "paper")
self.player12 = Player("Charlie", "paper")
self.player13 = Player("Fran", "scissors")
self.player14 = Player("Sarah", "rock")
self.player15 = Player("Chris", "scissors")
self.player16 = Player("Bernie", "scissors")
self.player17 = Player("Tamika", "scissors")
self.player18 = Player("Jim", "paper")
self.game1 = Game(self.player1, self.player2)
self.game2 = Game(self.player3, self.player4)
self.game3 = Game(self.player5, self.player6)
self.game4 = Game(self.player7, self.player8)
self.game5 = Game(self.player9, self.player10)
self.game6 = Game(self.player11, self.player12)
self.game7 = Game(self.player13, self.player14)
self.game8 = Game(self.player15, self.player16)
self.game9 = Game(self.player17, self.player18)
def test_player1_paper_beats_player2_rock(self):
self.game1.return_winner(self.player1, self.player2)
self.assertEqual(self.player1, self.game1.return_winner(self.player1, self.player2))
def test_player1_rock_beats_player_2_scissors(self):
self.game2.return_winner(self.player3, self.player4)
self.assertEqual(self.player3, self.game2.return_winner(self.player3, self.player4))
def test_player_1_rock_draws_with_player_2_rock(self):
self.game3.return_winner(self.player5, self.player6)
self.assertEqual(None, self.game3.return_winner(self.player5, self.player6))
def test_player_1_rock_loses_to_player_2_paper(self):
self.game4.return_winner(self.player7, self.player8)
self.assertEqual(self.player8, self.game4.return_winner(self.player7, self.player8))
def test_player_1_paper_loses_to_player_2_scissors(self):
self.game5.return_winner(self.player9, self.player10)
self.assertEqual(self.player10, self.game5.return_winner(self.player9, self.player10))
def test_player_1_paper_draws_with_player_2_paper(self):
self.game6.return_winner(self.player11, self.player12)
self.assertEqual(None, self.game6.return_winner(self.player11, self.player12))
def test_player_1_scissors_loses_to_player_2_rock(self):
self.game7.return_winner(self.player13, self.player14)
self.assertEqual(self.player14, self.game7.return_winner(self.player13, self.player14))
def test_player_1_scissors_draws_with_player_2_scissors(self):
self.game8.return_winner(self.player15, self.player16)
self.assertEqual(None, self.game8.return_winner(self.player15, self.player16))
def test_player_1_scissors_beats_player_2_paper(self):
self.game9.return_winner(self.player17, self.player18)
self.assertEqual(self.player17, self.game9.return_winner(self.player17, self.player18))
|
"""
Task. You are given a binary tree with integers as its keys. You need to test whether it is a correct binary
search tree. Note that there can be duplicate integers in the tree, and this is allowed. The definition of
the binary search tree in such case is the following: for any node of the tree, if its key is π₯, then for any
node in its left subtree its key must be strictly less than π₯, and for any node in its right subtree its key
must be greater than or equal to π₯. In other words, smaller elements are to the left, bigger elements
are to the right, and duplicates are always to the right. You need to check whether the given binary
tree structure satisfies this condition. You are guaranteed that the input contains a valid binary tree.
That is, it is a tree, and each node has at most two children.
Input Format. The first line contains the number of vertices π. The vertices of the tree are numbered
from 0 to π β 1. Vertex 0 is the root. The next π lines contain information about vertices 0, 1, ..., πβ1 in order.
Each of these lines contains three integers πππ¦π , πππ π‘π and πππβπ‘π β πππ¦π is the key of the π-th vertex, πππ π‘π is the
index of the left child of the π-th vertex, and πππβπ‘π is the index of the right child of the π-th vertex. If π doesnβt
have left or right child (or both), the corresponding πππ π‘π or πππβπ‘π (or both) will be equal to β1.
Constraints. 0 β€ π β€ 105 ; β2 31 β€ πππ¦π β€ 2 31 β 1; β1 β€ πππ π‘π , πππβπ‘π β€ π β 1. It is guaranteed that the
input represents a valid binary tree. In particular, if πππ π‘π ΜΈ= β1 and πππβπ‘π ΜΈ= β1, then πππ π‘π ΜΈ= πππβπ‘π. Also, a
vertex cannot be a child of two different vertices. Also, each vertex is a descendant of the root vertex.
Note that the minimum and the maximum possible values of the 32-bit integer type are allowed to be keys in the tree β
beware of integer overflow!
Output Format. If the given binary tree is a correct binary search tree (see the definition in the problem
description), output one word βCORRECTβ (without quotes). Otherwise, output one word βINCORRECTβ (without quotes).
"""
import sys
import threading
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**25) # new thread will get stack of such size
def is_bst(node, min_value, max_value, tree):
if node == -1:
return True
node_value = tree[node][0]
if (min_value and node_value < min_value) or (max_value and node_value >= max_value):
return False
left = tree[node][1]
right = tree[node][2]
return is_bst(left, min_value, tree[node][0], tree) and is_bst(right, tree[node][0], max_value, tree)
def is_binary_search_tree(tree):
if len(tree) == 0:
return True
left = tree[0][1]
right = tree[0][2]
return is_bst(left, None, tree[0][0], tree) and is_bst(right, tree[0][0], None, tree)
def main():
nodes = int(sys.stdin.readline().strip())
tree = []
for i in range(nodes):
tree.append(list(map(int, sys.stdin.readline().strip().split())))
if is_binary_search_tree(tree):
print("CORRECT")
else:
print("INCORRECT")
threading.Thread(target=main).start()
|
"""
Task. You have a program which is parallelized and uses π independent threads to process the given list
of π jobs. Threads take jobs in the order they are given in the input. If there is a free thread,
it immediately takes the next job from the list. If a thread has started processing a job, it doesnβt
interrupt or stop until it finishes processing the job. If several threads try to take jobs from the list
simultaneously, the thread with smaller index takes the job. For each job you know exactly how long
will it take any thread to process this job, and this time is the same for all the threads. You need to
determine for each job which thread will process it and when will it start processing.
Input Format. The first line of the input contains integers π and π.
The second line contains π integers π‘π β the times in seconds it takes any thread to process π-th job.
The times are given in the same order as they are in the list from which threads take jobs.
Threads are indexed starting from 0.
Constraints. 1 β€ π β€ 105 ; 1 β€ π β€ 105 ; 0 β€ π‘π β€ 109.
Output Format. Output exactly π lines. π-th line (0-based index is used) should contain two spaceseparated integers β
the 0-based index of the thread which will process the π-th job and the time in
seconds when it will start processing that job.
"""
class JobQueue:
def __init__(self):
self._num_workers, m = map(int, input().split())
self.workers_heap = Heap([[i, 0] for i in range(self._num_workers)], self._num_workers)
self.jobs = list(map(int, input().split()))
assert m == len(self.jobs)
self.assigned_workers = []
self.start_times = []
def write_response(self):
for i in range(len(self.jobs)):
print(self.assigned_workers[i], self.start_times[i])
def assign_jobs(self):
for i, j in enumerate(self.jobs):
thread, start_time = self.workers_heap.extract_max(j)
self.assigned_workers.append(thread)
self.start_times.append(start_time)
def solve(self):
self.assign_jobs()
self.write_response()
class Heap:
def __init__(self, workers, size):
self._workers = workers
self._size = size
def extract_max(self, job_time):
thread = self._workers[0][0]
start_time = self._workers[0][1]
self._workers[0][1] += job_time
self.shift_down(0)
return thread, start_time
def swap(self, i, j):
self._workers[i], self._workers[j] = self._workers[j], self._workers[i]
def shift_down(self, i):
min_index = i
left = i*2+1
if left < self._size and self.less_than(left, min_index):
min_index = left
right = i*2+2
if right < self._size and self.less_than(right, min_index):
min_index = right
if min_index != i:
self.swap(i, min_index)
self.shift_down(min_index)
def less_than(self, i, j):
if self._workers[i][1] < self._workers[j][1]:
return True
if self._workers[i][1] > self._workers[j][1]:
return False
return self._workers[i][0] < self._workers[j][0]
if __name__ == '__main__':
job_queue = JobQueue()
job_queue.solve()
|
"""
Task. Given π gold bars, find the maximum weight of gold that fits into a bag of capacity π.
Input Format. The first line of the input contains the capacity π of a knapsack and the number π of bars
of gold. The next line contains π integers π€0, π€1, . . . , π€πβ1 defining the weights of the bars of gold.
Constraints. 1 β€ π β€ 104 ; 1 β€ π β€ 300; 0 β€ π€0, . . . , π€πβ1 β€ 105.
Output Format. Output the maximum weight of gold that fits into a knapsack of capacity π.
"""
def init_matrix(rows, cols):
matrix = []
for i in range(rows + 1):
row = []
for j in range(cols + 1):
row.append(0)
matrix.append(row)
return matrix
def optimal_weight(capacity, weights):
wn = len(weights)
v = init_matrix(capacity, wn)
for i in range(capacity + 1):
for j in range(wn+1):
if i != 0 and j != 0:
if weights[j - 1] > i:
v[i][j] = v[i][j-1]
else:
d1 = v[i - weights[j - 1]][j - 1] + weights[j - 1]
d2 = v[i][j - 1]
v[i][j] = max(d1, d2)
return v[capacity][wn]
if __name__ == '__main__':
total, n, *w = list(map(int, input().split()))
print(optimal_weight(total, w))
|
"""
Task. Given two integers π and π, find their greatest common divisor.
Input Format. The two integers π, π are given in the same line separated by space.
Constraints. 1 β€ π, π β€ 2 Β· 109.
Output Format. Output GCD(π, π).
"""
def get_gcd_naive(a, b):
gcd = 1
for d in range(2, min(a, b) + 1):
if a % d == 0 and b % d == 0:
gcd = d
return gcd
def get_gcd_fast(a, b):
if a > b:
a, b = b, a
if a == 0:
return b
else:
b = b - b//a*a
return get_gcd_fast(b, a)
def sanity_check():
import random
while True:
a, b = random.randint(1, 100), random.randint(1, 100)
res_fast, res_naive = get_gcd_fast(a, b), get_gcd_naive(a, b)
if res_fast != res_naive:
print(a, b, res_fast, res_naive)
break
else:
print('OK')
if __name__ == "__main__":
input_ab = input()
a_, b_ = map(int, input_ab.split())
print(get_gcd_fast(a_, b_))
|
"""
Task. Construct the BurrowsβWheeler transform of a string.
Input Format. A string Text ending with a β$β symbol.
Constraints. 1 β€ |Text| β€ 1 000; except for the last symbol, Text contains symbols A, C, G, T only.
Output Format. BWT(Text).
"""
def bwt(text):
n = len(text)
cycle_matrix = []
s = text
for _ in range(n):
cycle_matrix.append(s)
s = s[-1]+s[:-1]
cycle_matrix = sorted(cycle_matrix)
res = ""
for k in cycle_matrix:
res = res + k[-1]
return res
if __name__ == '__main__':
t = input().strip()
print(bwt(t))
|
"""
Input Format.
The first line contains an integer π.
The second line contains an integer π.
The third line specifies an integer π.
Finally, the last line contains integers stop1,stop2, . . . ,stopπ.
Output Format. Assuming that the distance between the cities is π miles, a car can travel at most π miles
on a full tank, and there are gas stations at distances stop1,stop2, . . . ,stopπ along the way, output the
minimum number of refills needed. Assume that the car starts with a full tank. If it is not possible to
reach the destination, output β1.
Constraints. 1 β€ π β€ 105. 1 β€ π β€ 400. 1 β€ π β€ 300. 0 < stop1 < stop2 < Β· Β· Β· < stopπ < π.
"""
def pre_process(distance, tank, stops):
stops = [0]+stops+[distance]
return get_minimum_number_of_refills(tank, stops)
# with distance appended to stops
def get_minimum_number_of_refills(tank, stops, refills=0):
# sitting on the destination
if len(stops) == 1:
return refills
# impossible to reach destination
if stops[1] > stops[0]+tank:
return -1
# reached destination no refill
if stops[-1] <= stops[0]+tank:
return refills
# find farthest possible stop
n = 2
while stops[n] > stops[0]+tank and n < len(stops):
n += 1
n -= 1
refills += 1
stops = stops[n:]
return get_minimum_number_of_refills(tank, stops, refills)
if __name__ == '__main__':
d, m, _, *s = map(int, input().split())
print(pre_process(d, m, s))
|
"""
Task. In this task your goal is to implement a hash table with lists chaining. You are already given the
number of buckets π and the hash function. It is a polynomial hash function
where π[π] is the ASCII code of the π-th symbol of π, π = 1 000 000 007 and π₯ = 263. Your program
should support the following kinds of queries:
β add string β insert string into the table. If there is already such string in the hash table, then
just ignore the query.
β del string β remove string from the table. If there is no such string in the hash table, then
just ignore the query.
β find string β output βyes" or βno" (without quotes) depending on whether the table contains
string or not.
β check π β output the content of the π-th list in the table. Use spaces to separate the elements of
the list. If π-th list is empty, output a blank line.
When inserting a new string into a hash chain, you must insert it in the beginning of the chain.
Input Format. There is a single integer π in the first line β the number of buckets you should have. The
next line contains the number of queries π. Itβs followed by π lines, each of them contains one query
in the format described above.
Constraints. 1 β€ π β€ 105; π/5 β€ π β€ π. All the strings consist of latin letters. Each of them is non-empty
and has length at most 15.
Output Format. Print the result of each of the find and check queries, one result per line, in the same
order as these queries are given in the input.
Time Limits. C: 1 sec, C++: 1 sec, Java: 5 sec, Python: 7 sec. C#: 1.5 sec, Haskell: 2 sec, JavaScript:
7 sec, Ruby: 7 sec, Scala: 7 sec.
Memory Limit. 512Mb.
"""
class Query:
def __init__(self, query):
self.type = query[0]
if self.type == 'check':
self.ind = int(query[1])
else:
self.s = query[1]
class QueryProcessor:
_multiplier = 263
_prime = 1000000007
def __init__(self, m):
self.m = m
# store all strings in one list
self.hash = [list() for _ in range(m)]
def add(self, s):
pos = self._hash_func(s)
if s not in self.hash[pos]:
self.hash[pos] = [s] + self.hash[pos]
def find(self, s):
pos = self._hash_func(s)
return s in self.hash[pos]
def delete(self, s):
pos = self._hash_func(s)
if s in self.hash[pos]:
for i, hash_s in enumerate(self.hash[pos]):
if hash_s == s:
self.hash[pos].pop(i)
def check(self, i):
return self.hash[i]
def _hash_func(self, s):
ans = 0
for c in reversed(s):
ans = (ans * self._multiplier + ord(c)) % self._prime
return ans % self.m
@staticmethod
def write_search_result(was_found):
print('yes' if was_found else 'no')
@staticmethod
def write_chain(chain):
print(' '.join(chain))
@staticmethod
def read_query():
return Query(input().split())
def process_query(self, query):
if query.type == "check":
self.write_chain(self.check(query.ind))
else:
if query.type == 'find':
self.write_search_result(self.find(query.s))
elif query.type == 'add':
self.add(query.s)
else:
self.delete(query.s)
def process_queries(self):
n = int(input())
for i in range(n):
self.process_query(self.read_query())
if __name__ == '__main__':
bucket_count = int(input())
proc = QueryProcessor(bucket_count)
proc.process_queries()
|
"""
Task. Construct the suffix tree of a string.
Input Format. A string Text ending with a β$β symbol.
Constraints. 1 β€ |Text| β€ 5 000; except for the last symbol, Text contains symbols A, C, G, T only.
Output Format. The strings labeling the edges of SuffixTree(Text) in any order.
"""
def max_substring(text_1, text_2):
n_text_1 = len(text_1)
n_text_2 = len(text_2)
n = min(n_text_1, n_text_2)
for i in range(n+1):
if text_1[:i] != text_2[:i]:
return i-1
return n
class Queue:
def __init__(self):
self._array = []
def next(self):
return self._array.pop(0)
def add(self, v):
self._array.append(v)
def empty(self):
return len(self._array) == 0
class Children:
def __init__(self):
self.dic = dict()
self.__id = 0
def add(self, child):
self.dic[self.__id] = child
self.__id += 1
return child
def reset(self):
self.__id = 0
self.dic = dict()
def get_node(self, idx):
return self.dic[idx]
def find(self, string, text):
for k, v in self.items():
if v.edge(text, 1) == string[0]:
return k
return -1
def items(self):
return self.dic.items()
def values(self):
return self.dic.values()
def copy(self):
c = Children()
c.dic = self.dic.copy()
c.__id = self.__id
return c
class Node:
def __init__(self, start=None, size=None):
self.children = Children()
self.start = start
self.size = size
def add_child(self, start, size):
new_node = Node(start, size)
return self.children.add(new_node)
def edge(self, text, size=-1):
size = self.size if size == -1 else size
return text[self.start:self.start+size]
def split(self, k):
if 0 < k < self.size:
new_node = Node(self.start+k, self.size-k)
new_node.inherit_children(self)
self.size = k
self.children.add(new_node)
def inherit_children(self, node):
self.children = node.children.copy()
node.children.reset()
def build_suffix_tree(text):
tree_root = Node()
n = len(text)
for start in range(n):
current_node = tree_root
child_index = current_node.children.find(text[start:], text)
while child_index != -1:
current_node = current_node.children.get_node(child_index)
k = max_substring(text[start:], current_node.edge(text))
current_node.split(k)
start += k
child_index = current_node.children.find(text[start:], text)
if child_index != n:
current_node.add_child(start, n-start)
return breadth_first_edges(tree_root, text)
def breadth_first_edges(tree_root, text):
result = []
q = Queue()
for c in tree_root.children.values():
q.add(c)
while not q.empty():
current_node = q.next()
result.append(current_node.edge(text))
for c in current_node.children.values():
q.add(c)
return result
if __name__ == '__main__':
input_text = input().strip()
res = build_suffix_tree(input_text)
print("\n".join(res))
|
C = eval(input("Digite los grados celsius"))
F = C + 32
print(C,"Β°C a Fahrenheit es: ", F,"Β°F")
|
n = int(input('ΠΠ²Π΅Π΄ΠΈΡΠ΅ ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ²: '))
i = 0
range_number = 1
sum = 0
while i < n:
sum += range_number
range_number /= -2
i += 1
print(f'Π‘ΡΠΌΠΌΠ° {sum}')
|
from neo4j import GraphDatabase
from random import randint
import csv
def create_subjects(tx, filename, faculty_name):
"""
Creates subjects and randomly creates Requires relation between them.
Subjects are divided into tiers. Subject from higher can only require subjects from lower tier.
As a result, we can be sure that there aren't any cycles in graph structure, because this
would make some of the courses impossible to sign up.
"""
infile = open(filename, "r")
csvimport = csv.reader(infile)
for row in csvimport:
print(row[0])
result = tx.run("MATCH (n:Subject { name : $name }) RETURN n", name=row[0])
if not result.single():
rand_tier = randint(1, 7)
rand_free_places = randint(15,25)
tx.run("CREATE (a:Subject) SET a.name = $name, a.tier = $tier, a.free_places=$free", name=row[0], tier = rand_tier, free=rand_free_places)
tx.run("MATCH (a:Subject { name : $name }),(b:Faculty { name : $faculty }) CREATE (a)-[r:BelongsTo]->(b)", name=row[0], faculty=faculty_name)
else:
tx.run("MATCH (a:Subject { name : $name }),(b:Faculty { name : $faculty }) CREATE (a)-[r:BelongsTo]->(b)", name=row[0], faculty=faculty_name)
basics_1 = tx.run("MATCH (s:Subject { tier : $tier}) RETURN id(s) as id", tier=1).data()
basics_2 = tx.run("MATCH (s:Subject { tier : $tier}) RETURN id(s) as id", tier=2).data()
basics_3 = tx.run("MATCH (s:Subject { tier : $tier}) RETURN id(s) as id", tier=3).data()
basics_4 = tx.run("MATCH (s:Subject { tier : $tier}) RETURN id(s) as id", tier=4).data()
basics_5 = tx.run("MATCH (s:Subject { tier : $tier}) RETURN id(s) as id", tier=5).data()
basics_6 = tx.run("MATCH (s:Subject { tier : $tier}) RETURN id(s) as id", tier=6).data()
infile = open(filename, "r")
csvimport = csv.reader(infile)
for row in csvimport:
tx.run("Match (a:Subject), (b:Subject) where a.name = $name and a.tier = 2 and id(b) = $id Create (a)-[r:Require]->(b)", name = row[0], id = basics_1[randint(0, len(basics_1)-1)]['id'])
tx.run("Match (a:Subject), (b:Subject) where a.name = $name and a.tier = 3 and id(b) = $id Create (a)-[r:Require]->(b)", name = row[0], id = basics_2[randint(0, len(basics_2)-1)]['id'])
tx.run("Match (a:Subject), (b:Subject) where a.name = $name and a.tier = 4 and id(b) = $id Create (a)-[r:Require]->(b)", name = row[0], id = basics_3[randint(0, len(basics_3)-1)]['id'])
tx.run("Match (a:Subject), (b:Subject) where a.name = $name and a.tier = 5 and id(b) = $id Create (a)-[r:Require]->(b)", name = row[0], id = basics_4[randint(0, len(basics_4)-1)]['id'])
tx.run("Match (a:Subject), (b:Subject) where a.name = $name and a.tier = 6 and id(b) = $id Create (a)-[r:Require]->(b)", name = row[0], id = basics_5[randint(0, len(basics_5)-1)]['id'])
tx.run("Match (a:Subject), (b:Subject) where a.name = $name and a.tier = 7 and id(b) = $id Create (a)-[r:Require]->(b)", name = row[0], id = basics_6[randint(0, len(basics_6)-1)]['id'])
def create_tutors(tx, lecturers_file, faculty_name):
"""Creates tutors and randomly make them teach several courses."""
infile = open(lecturers_file, "r")
csvimport = csv.reader(infile)
subjectnum = tx.run("MATCH (a:Subject)-[r:BelongsTo]->(b:Faculty { name : $faculty }) WITH count(a) AS value RETURN value", faculty=faculty_name).single()[0]
subjects = list(tx.run("MATCH (a:Subject)-[r:BelongsTo]->(b:Faculty {name : $faculty}) RETURN a", faculty=faculty_name).__iter__())
print(subjectnum)
for row in csvimport:
print(row[0])
tx.run("CREATE (a:Tutor) SET a.firstname = $firstname, a.lastname = $lastname, a.mail = $mail, a.degree = $degree", firstname=row[1], lastname=row[0], mail=row[3], degree=row[2])
tx.run("MATCH (a:Tutor { firstname: $firstname, lastname: $lastname}), (b:Faculty { name : $faculty }) CREATE (a)-[r:WorksIn]->(b)", firstname=row[1], lastname=row[0], faculty=faculty_name)
numberofsubjects = randint(1,5)
for i in range(numberofsubjects):
randomnum = randint(0, subjectnum-1)
tx.run("MATCH (a:Tutor { firstname: $firstname, lastname: $lastname}), (s:Subject { name : $subject }) CREATE (a)-[r:Teaches]->(s)", firstname=row[1], lastname=row[0], subject=subjects[randomnum]["a"]["name"])
def add_students(tx, filename):
"""Creates students from csv file."""
infile = open(filename, "r")
csvimport = csv.reader(infile)
for row in csvimport:
tx.run("CREATE (s:Student) SET s.firstname = $firstname, s.lastname = $lastname, s.pesel = $pesel, s.student_nr= $student_nr ", firstname=row[0], lastname=row[1], pesel=row[2], student_nr=row[3])
def sign_students(tx, filename):
"""Randomly creates Completed relation between students and courses."""
infile = open(filename, "r")
csvimport = csv.reader(infile)
tiers = []
for i in range(1,8):
tiers.append(tx.run("MATCH (s:Subject { tier : $tier}) RETURN s.name as id", tier=i).data())
print(tiers)
for row in csvimport:
print(row[2], end=' ')
randnum = randint(1,100)
print(randnum)
if(randnum < 6):
continue
randnum2 = randint(0, len(tiers[0])-1)
tx.run("MATCH (s:Student {pesel: $pesel}), (b:Subject) WHERE b.name=$subid CREATE (s)-[r:Completed]->(b)", pesel=row[2], subid=tiers[0][randnum2]['id'])
thresholds = [6, 30, 40, 50, 60, 70,80, 90]
for i in range(1,8):
courses_ava = tx.run("match (s:Student {pesel: $pesel})-[:Completed]->(:Subject)<-[:Require]-(sub:Subject) return distinct sub.name as id", pesel=row[2]).data()
courses1 = [item['id'] for item in courses_ava]
completed_courses_dict = tx.run("match (s:Student {pesel: $pesel})-[:Completed]->(sub:Subject) return sub.name as id", pesel=row[2]).data()
completed_courses = [item['id'] for item in completed_courses_dict]
courses = list(set(courses1) - set(completed_courses))
print(courses)
if courses:
if(randnum > thresholds[i]):
randomcourse = randint(0,len(courses)-1)
print(courses[randomcourse])
tx.run("MATCH (s:Student {pesel: $pesel}), (b:Subject) WHERE b.name=$subid CREATE (s)-[r:Completed]->(b)", pesel=row[2], subid=courses[randomcourse])
def set_attends_rel(tx, filename):
"""Randomly creates Attends relation between students and courses"""
infile = open(filename, "r")
csvimport = csv.reader(infile)
for row in csvimport:
courses_ava = tx.run("match (s:Student {pesel: $pesel})-[:Completed]->(:Subject)<-[:Require]-(sub:Subject) return distinct sub.name as id", pesel=row[2]).data()
courses1 = [item['id'] for item in courses_ava]
completed_courses_dict = tx.run("match (s:Student {pesel: $pesel})-[:Completed]->(sub:Subject) return sub.name as id", pesel=row[2]).data()
completed_courses = [item['id'] for item in completed_courses_dict]
courses = list(set(courses1) - set(completed_courses))
how_many = randint(0, len(courses))
print(row[2] + " " + str(how_many))
print(courses)
for i in range(how_many):
tx.run("MATCH (s:Student {pesel: $pesel}), (sb:Subject {name: $name}) CREATE (s)-[:Attends]->(sb)", pesel=row[2], name=courses[i])
if __name__ == '__main__':
driver1 = GraphDatabase.driver("bolt://bazy.flemingo.ovh:7687", auth=("neo4j", "marcjansiwikania"))
with driver1.session() as session:
session.write_transaction(create_subjects, "data/przedmioty.csv", "Informatyki")
session.write_transaction(create_subjects, "data/przedmioty2.csv", "Elektroniki")
session.write_transaction(create_subjects, "data/przedmioty3.csv", "Fizyki Medycznej")
session.write_transaction(create_tutors, "data/wykladowcy.csv", "Informatyki")
session.write_transaction(create_tutors, "data/wykladowcy2.csv", "Elektroniki")
session.write_transaction(create_tutors, "data/wykladowcy3.csv", "Fizyki Medycznej")
session.write_transaction(add_students, "data/students.csv")
session.write_transaction(sign_students, "data/students.csv")
set_attends_rel(session, "data/students.csv")
|
print "Mary had a little lamb."
print "Its fleece was white as %s." % "snow"
print "And everywhere that Mary went."
print "." * 20 # Repeats "." 20 times (including the first time!)
char1 = "C"
char2 = "h"
char3 = "e"
char4 = "e"
char5 = "s"
char6 = "e"
char7 = "b"
char8 = "u"
char9 = "r"
char10 = "g"
char11 = "e"
char12 = "r"
print char1 + char2 + char3 + char4 + char5 + char6, # , before next print will print same line
print char7 + char8 + char9 + char10 + char11 + char12 # prints BURGER next to CHEESE
|
import socket
import sys
#Create socket object
try:
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print("Could not create socket")
#Use host that user input
script,host = sys.argv
#Connect to a remote socket at specified host address
socket.connect((host, 6869))
#Initial response
response="WAIT"
"""Client loop. Always either waiting for further instructions and not taking user input
or taking user input and returning server response"""
while True:
while "WAIT" in response:
response=socket.recv(4096)
print response
#Take user input from command line interface
userInput=raw_input("ttt->")
if(userInput==''):
continue
#Send user input to server, and collect response
socket.send(userInput)
response=socket.recv(4096)
#Error handling
if response=="400 ERR":
print "Invalid command"
#If response is valid, print it
else:
print response
#Exit loop and quit program if user chooses to exit
if response=="DISC":
sys.exit()
socket.close()
|
from random import randrange
from input_number_between import input_number_between
def play():
START_MONEY = 100
MIN_MONEY_TO_WIN = 200
FACTOR_WIN = 2
money = START_MONEY
print "At any time, bet 0 to quit. Quit above %d to win 1/%d of your coins in money" % (MIN_MONEY_TO_WIN, FACTOR_WIN)
while True:
print "You have %d." % money
bet = input_number_between(" Your bet ?", 0, money)
draw = randrange(1, 7) + randrange(1, 7)
if draw in [7, 11]:
money += bet
print " %d: Natural... You win!" % draw
elif draw in [2, 3, 12]:
money -= bet
print " %d: Snake eye... You lose!" % draw
elif money == 0:
print "You have 0, you lose!"
return 0
elif bet == 0:
if money > FACTOR_WIN * START_MONEY:
print "You win %d money." % money / FACTOR_WIN
return money /FACTOR_WIN
else:
print "You have under %d coins, sorry." % MIN_MONEY_TO_WIN
return 0
else:
print " %d: Try to draw it again... The real fun begins!" % draw
money += repeat(draw) * bet
def repeat(objectif):
print " Press ENTER to roll the dice..."
while True:
if raw_input() == "":
draw = randrange(1, 7) + randrange(1, 7)
if draw == objectif:
print " %d: Your objective... Congrats!" % draw
return 1
if draw == 7:
print " 7: CRAPS... You lose!"
return -1
print " %d: Press ENTER to roll again..." % draw
|
from binarysearchtree import BinarySearchTree
def testBST():
bst1 = BinarySearchTree()
n=int(raw_input("Enter number of elements: "))
for i in range(n):
bst1.insertElement(int(raw_input()))
print "INORDER:"
bst1.inorderTraverse(bst1.root)
print
print "PREORDER:"
bst1.preorderTraverse(bst1.root)
print
print "POSTORDER:"
bst1.postorderTraverse(bst1.root)
def main():
testBST()
if __name__ == '__main__':
main()
|
import hashlib
file = open('words.txt','r')
content = file.readlines()
file.close()
word_list = []
for line in content:
line = line.strip()
word_list.append(line)
username= input("Username: ")
realm = "Boutique Cassee"
#178ec06684f4d2ca85f4d704eff5ac1d
hashToFind = input("Password hash: ")
for word in word_list:
u_p = username+":"+realm+":"+word
hash = hashlib.md5(u_p.encode()).hexdigest()
if hash == hashToFind:
print('The password is: ',word)
|
#!/usr/bin/python3
#input number
number = 112345678911234566
#count the twos
Number2 = number.count(2)
#print the number of 2s
print(βThere are %d twos in %d.β % (Number2,number))
|
import pandas as pd
"""Plan
Part 1: The user can log how many reps/km they did. IF they don't wish to log the day then the result given will be 0 for the exercises that day.
after 3 days have been logged the program will stop and congratulate the
user on doing their weeks worth of exercise.
Part 2: the week logging can be run again and again all while updating a user profile will gives awards depending on if the user passed goals or not. """
def pressup_value():
"""get quantity of pressups achieved in a day"""
while True:
try:
pressups_value = int(input("\nHow many pressups have you done today? "))
except ValueError:
print("\nNo value entered, enter 0 if no pressups done")
continue
else:
return pressups_value
def run_value():
"""get run distance achieved in a day"""
while True:
try:
runs_value = int(input("How many Km have you run today? "))
except ValueError:
print("\nNo value entered, enter 0 if no Km run")
continue
else:
return runs_value
def situp_value():
"""get quantity of situps achieved in a day"""
while True:
try:
situps_value = int(input("How many situps have you done today? "))
except ValueError:
print("\nNo value entered, enter 0 if no situps done")
continue
else:
return situps_value
def squat_value():
"""get quantity of Squats achieved in a day"""
while True:
try:
squats_value = int(input("How many squats have you done today? "))
except ValueError:
print("\nNo value entered, enter 0 if no squats done")
continue
else:
return squats_value
def log_numbers(pressups_value, runs_value, situps_value, squats_value):
"""Find out if they would like to log the exercise list, if they say no, the results for the exercises will be 0"""
log = input("\nDo you wish to log your workout (y/n)? ").lower()
if log == 'y':
#log to the exercise list
pressups.append(pressups_value)
runs.append(runs_value)
situps.append(situps_value)
squats.append(squats_value)
#log to the prize list
log_pressups.append(pressups_value)
log_runs.append(runs_value)
log_situps.append(situps_value)
log_squats.append(squats_value)
return pressups_value, runs_value, situps_value, squats_value
else:
pressups.append(0)
runs.append(0)
situps.append(0)
squats.append(0)
log_pressups.append(0)
log_runs.append(0)
log_situps.append(0)
log_squats.append(0)
return pressups_value, runs_value, situps_value, squats_value
def ex_log(pressups, runs, situps, squats):
"""append values from list to dictionary """
exercise['Pressups'].append(pressups[-1])
exercise['Runs'].append(runs[-1])
exercise['Situps'].append(situps[-1])
exercise['Squats'].append(squats[-1])
def dict_prize():
#log prizes for pressups
if log_pressups[-1] >= 20:
prize['Pressups Prize'].append("Gold")
elif log_pressups[-1] >= 15 and log_pressups[-1] < 20:
prize['Pressups _Prize'].append("Silver")
elif log_pressups[-1] >= 5 and log_pressups[-1] < 15:
prize['Pressups Prize'].append("Bronze")
else:
prize['Pressups Prize'].append("Fail")
#log prizes for running
if log_runs[-1] >= 10:
prize['Running Prize'].append("Gold")
elif log_runs[-1] >= 6 and log_runs[-1] < 10:
prize['Running Prize'].append("Silver")
elif log_runs[-1] >= 2 and log_runs[-1] < 6:
prize['Running Prize'].append("Bronze")
else:
prize['Running Prize'].append("Fail")
#log prizes for situps
if log_situps[-1] >= 20:
prize['Situps Prize'].append("Gold")
elif log_situps[-1] >= 15 and log_situps[-1] < 20:
prize['Situps Prize'].append("Silver")
elif log_situps[-1] >= 5 and log_situps[-1] < 15:
prize['Situps Prize'].append("Bronze")
else:
prize['Situps Prize'].append("Fail")
#log prizes for squats
if log_squats[-1] >= 20:
prize['Squats Prize'].append("Gold")
elif log_squats[-1] >= 15 and log_squats[-1] < 20:
prize['Squats Prize'].append("Silver")
elif log_squats[-1] >= 5 and log_squats[-1] < 15:
prize['Squats Prize'].append("Bronze")
else:
prize['Squats Prize'].append("Fail")
#Give prizes according to exercises achieved
def prizeGiven():
"""gives a value to the prize lists, after 7 days of exercise, a summary will be given of the prizes achieved in the week."""
if len(prize['Pressups Prize']) == 7 or len(prize['Pressups Prize']) == 14 or len(prize['Pressups Prize']) == 21 or len(prize['Pressups Prize']) == 28:
for value in prize['Pressups Prize']:
if value == "Gold":
gold.append(1)
elif value == "Silver":
silver.append(1)
elif value == "Bronze":
bronze.append(1)
else:
fail.append(1)
for value in prize['Running Prize']:
if value == "Gold":
gold.append(1)
elif value == "Silver":
silver.append(1)
elif value == "Bronze":
bronze.append(1)
else:
fail.append(1)
for value in prize['Situps Prize']:
if value == "Gold":
gold.append(1)
elif value == "Silver":
silver.append(1)
elif value == "Bronze":
bronze.append(1)
else:
fail.append(1)
for value in prize['Squats Prize']:
if value == "Gold":
gold.append(1)
elif value == "Silver":
silver.append(1)
elif value == "Bronze":
bronze.append(1)
else:
fail.append(1)
goldSum = sum(gold)
silverSum = sum(silver)
bronzeSum = sum (bronze)
failSum = sum(fail)
print("\nSummary of prizes for the week")
print("This week you have earned " + str(goldSum) + " Golds, " + str(silverSum) + " Silvers, " + str(bronzeSum) + " Bronzes, and " + str(failSum) + " Fails.")
#lists for the exercise table
pressups = []
runs = []
situps = []
squats = []
#lists for the prize table
log_pressups = []
log_runs = []
log_situps = []
log_squats = []
#goku = []
gold = []
silver = []
bronze = []
fail = []
exercise = {'Pressups': [], 'Runs': [], 'Situps': [], 'Squats': []}
prize = {'Pressups Prize':[], 'Running Prize':[], 'Situps Prize':[], 'Squats Prize':[]}
P_prize_total = []
repeat = []
#main code
"""intro to the tracker"""
print("Welcome to the fitness tracker")
print("Follow your progress of your exercises for the month with weekly summaries.\n")
training = True
while training:
print("\nPressups levels: Gold = 20+ Silver = 15-19 Bronze = 5-14 Fail = < 5")
print("Runs (Km) levels: Gold = 10+ Silver = 6-9 Bronze = 2-5 Fail = < 2")
print("Situps levels: Gold = 20+ Silver = 15-19 Bronze = 5-14 Fail = < 5")
print("Squats levels: Gold = 20+ Silver = 15-19 Bronze = 5-14 Fail = < 5")
print("\n\tIF YOU DON'T LOG YOU WORKOUT, VALUES WILL BE 0 FOR THE DAY\n")
"""collect values for the days exercises"""
press = pressup_value()
run = run_value()
situp = situp_value()
squat = squat_value()
"""log the numbers to the lists"""
log = log_numbers(press, run, situp, squat)
update_dict = ex_log(pressups, runs, situps, squats)
"""log the prizes for each exercise"""
dict_prize()
"""put values into the table"""
ex_table = pd.DataFrame(exercise)
prize_table = pd.DataFrame(prize)
"""print out the tables"""
print("\n------------------------------------------------------------------")
print(ex_table)
print("\n\t-------------------------------------------------\n")
print(prize_table)
print("--------------------------------------------------------------------")
prizeGiven()
#set conditions for continuing or closing the program
if len(prize['Pressups Prize']) == 7 or len(prize['Pressups Prize']) == 14 or len(prize['Pressups Prize']) == 21 or len(prize['Pressups Prize']) == 28:
again = input("\nDo you wish to log exercises for another week? (y/n) (selecting no will end the program): \n").lower()
if again != "y":
repeat.append(1)
if repeat[0] == 1 and len(prize["Pressups Prize"]) == 7:
print("\nYou have completed a weeks training, good job.")
break
elif repeat[0] == 1 and len(prize["Pressups Prize"]) == 14:
print("\nYou have completed 2 weeks training, good job.")
break
elif repeat[0] == 1 and len(prize["Pressups Prize"]) == 21:
print("\nYou have completed 3 weeks training, good job.")
break
elif repeat[0] == 1 and len(prize["Pressups Prize"]) == 28:
print("\nYou have completed 4 weeks training, good job.")
ended = input("\nPress Enter to end the program")
break
if len(prize["Pressups Prize"]) == 28:
print("\nYou have completed a months training, Relax!")
ended = input("\nPress Enter to end the program")
break
|
import json
from collections import defaultdict
class Search():
"""
Class that is used to find documents that contain given terms.
Attributes:
doc2id : dict(str, int)
dictionary that maps document celex numbers to ids
id2doc : dict(int, str)
dictionay that maps ids to document celex numbers
index : dict(word, list(int))
dictionary containing words and document ids in which the word appears in
"""
def __init__(self):
"""
We unload the data from index.json file.
"""
with open('index2.json', 'r', encoding='utf-8') as infile:
data = json.load(infile)
self.doc2id = data['doc2id']
self.id2doc = data['id2doc']
self.index = data['index']
def find_documents_given_query(self, query):
"""
Function that will based on the given query return document ids that contain it.
Parameters:
query : list of strings
list of words that we are looking for
Returns:
list of celex number of found documents sorted by best to worst match
"""
document_id_frequency = defaultdict(int)
# We iterate through every word and for each document id we count how many of the query words
# it contatins. The more the better.
for word in query:
if word in self.index:
for document_id in self.index[word]:
document_id_frequency[document_id] += 1
highest_frequency = [(freq, doc_id) for doc_id, freq in document_id_frequency.items()]
highest_frequency.sort(reverse=True)
# Transform ids to celex
transformed_to_celex = [self.id2doc[str(docid)] for _,docid in highest_frequency[:10] if str(docid) in self.id2doc]
return transformed_to_celex
if __name__ == '__main__':
mysearch = Search()
res = mysearch.find_documents_given_query(['environment', 'water', 'oil'])
print(res)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
count = 0
ksmall = -9999999999 # store the Kth smallest
curr = root # to store the current node
while curr!=None:
if curr.left == None:
count += 1
if count == k:
ksmall = curr.val
curr = curr.right
else:
pre = curr.left
while (pre.right != None and pre.right != curr):
pre = pre.right
if pre.right == None:
pre.right = curr
curr = curr.left
else:
pre.right = None
count += 1
if count == k:
ksmall = curr.val
curr = curr.right
return ksmall
|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 28 11:00:37 2021
@author: KushagraK7
"""
print("You will be asked to enter two numbers.")
print("Then the computer will swap the values of the variables storing them")
A = int(input("Enter a number to store in variable 'A' "))
B = int(input("Enter a number to store in variable 'B' "))
print("Before swapping:")
print(" A = ", A, " B = ", B)
A, B = B, A
print("After swapping:")
print(" A = ", A, " B = ", B)
|
from datetime import datetime
from math import atan2, sqrt
from pathlib import Path
from typing import List, Tuple, Dict
DATA_PATH = Path('data.txt')
def read_data_file() -> List[Tuple[int, int]]:
"""Reading points from a file.
Returns:
List[Tuple[int, int]]: List of points, e.g. [(x,y)]
"""
points = DATA_PATH.read_text().strip().split('\n')
points_list = [eval(triangle) for triangle in points]
return points_list
def determine_position_from_line(line_point_left: Tuple,
line_point_right: Tuple,
point: Tuple) -> int:
"""Determine the position of a point,
relative to the first two that form a straight line.
Args:
line_point_left (Tuple): Left point of the straight line
line_point_right (Tuple): Right point of a straight line
point (Tuple): Point to determine position
Returns:
int: Returns a number:
if negative, then the point lies on the left,
if positive, then on the right,
if zero, then on a straight line
"""
lx, ly = line_point_left
rx, ry = line_point_right
px, py = point
return (px-lx)*(ry-ly) - (py-ly)*(rx-lx)
def distance_between_points(first_point: Tuple, second_point: Tuple) -> float:
"""Return the distance between points
Args:
first_point (Tuple): First point
second_point (Tuple): Second point
Returns:
float: Distance
"""
fx, fy = first_point
sx, sy = second_point
return sqrt((sy-fy)**2 + (sx-fx)**2)
def sign(side_1: int, side_2: int) -> bool:
if (side_1 > 0 and side_2 > 0) or (side_1 < 0 and side_2 < 0) or (side_1 == side_2):
return True
else:
return False
def distance_from_point_to_line(orientation: int,
distance: int) -> float:
"""Distance from point to line
Args:
orientation (int): Point position
distance (int): Distance
Returns:
float: Distance
"""
return abs(orientation) / distance
def build_quick_hull(points: List[Tuple]) -> Tuple:
"""Builds a quick hull.
Args:
points (List[Tuple]): Point List
Returns:
Tuple: Returns the (leftmost, rightmost, top point sets, bottom point sets).
"""
def find_hull_point(points: List[Tuple], left_point: Tuple, right_point: Tuple) -> List:
"""Returns a list of points that belong to the top/bot shell
Args:
points (List[Tuple]): Point.
left_point (Tuple): Left point of the line.
right_point (Tuple): Right point of the line.
Returns:
List: Point List
"""
if points:
hulls = []
hull_point = None
default_distance = float('-inf')
line_length = distance_between_points(left_point, right_point)
for point in points:
point_orientation = determine_position_from_line(left_point, right_point, point)
dist_point_to_line = distance_from_point_to_line(point_orientation, line_length)
if dist_point_to_line == 0:
continue
default_distance = max(dist_point_to_line, default_distance)
if default_distance == dist_point_to_line:
hull_point = point
if hull_point:
hulls.append(hull_point)
upper_set = []
bottom_set = []
upper_point_orientation = determine_position_from_line(left_point, hull_point, right_point)
bottom_point_orientation = determine_position_from_line(hull_point, right_point, left_point)
for point in points:
if point not in hulls:
if (not sign(determine_position_from_line(left_point, hull_point, point),
upper_point_orientation)
and determine_position_from_line(left_point, hull_point, point) != 0):
upper_set.append(point)
if (not sign(determine_position_from_line(hull_point, right_point, point),
bottom_point_orientation)
and determine_position_from_line(hull_point, right_point, point) != 0):
bottom_set.append(point)
up_set = find_hull_point(upper_set, left_point, hull_point)
bot_set = find_hull_point(bottom_set, hull_point, right_point)
return hulls + bot_set + up_set
else:
return []
else:
return []
upper_set = []
bottom_set = []
points.sort(key=lambda x: (x[0], x[1]))
left_point, right_point = points[0], points[-1]
x, y = left_point
upper_left_point = (x, y+1)
upper_side_of_line = determine_position_from_line(left_point, right_point, upper_left_point)
for point in points:
if point not in [left_point, right_point]:
side_of_line = determine_position_from_line(left_point, right_point, point)
if sign(side_of_line, upper_side_of_line) and side_of_line != 0:
upper_set.append(point)
else:
bottom_set.append(point)
if upper_set:
upper_set = find_hull_point(upper_set, left_point, right_point)
if bottom_set:
bottom_set = find_hull_point(bottom_set, left_point, right_point)
return left_point, right_point, upper_set, bottom_set
def make_indexes(points: List[Tuple]) -> Dict[Tuple, int]:
"""Specifies indices for original points
Args:
points (List[Tuple]): Points list
Returns:
Dict[Tuple, int]: Dictionary, where the key is the coordinates of the points, and the value is its index.
"""
indexes = {}
index = 0
for point in points:
indexes[point] = index
index += 1
return indexes
def quick_hull():
"""Builds a quick hull."""
points = read_data_file()
indexes = make_indexes(points)
start_time = datetime.now()
left_point, right_point, upper_set, bottom_set = build_quick_hull(points)
print(f"Estimated time: {datetime.now() - start_time} msc.")
result = []
result.append(left_point)
result.extend(upper_set)
result.extend(bottom_set)
result.append(right_point)
sum_x = sum_y = 0
for point in result:
x, y = point
sum_x += x
sum_y += y
sort_x, sort_y = sum_x/len(result), sum_y/len(result)
result.sort(key=lambda x: (atan2(x[1]-sort_y, x[0]-sort_x)))
print("Result:")
for res_index, res_point in enumerate(result):
try:
if res_point != result[res_index + 1]:
print(f"{indexes[res_point]} - {indexes[result[res_index + 1]]}")
except IndexError:
print(f"{indexes[res_point]} - {indexes[result[0]]}")
if __name__ == "__main__":
quick_hull()
|
# Neural Network - Simple example
import numpy as np
import pickle
round_digits = 4
# SIGMOID FUNCTION
def sigmoid(x):
# activation function: f(x) = 1 / (1 + e^(-x))
return round(1 / (1 + np.exp(-x)), round_digits)
# SIGMOID DERIVATIVE FUNCTION
def deriv_sigmoid(x):
# Derivative of sigmoid: f'(x) = f(x) * (1 - f(x))
fx = sigmoid(x)
return round(fx * (1 - fx), round_digits)
# MEDIUM SQUARE ERROR LOSS
def mse_loss(y_true, y_pred):
# 1/n * SUM((y_true - y_pred)^2)
return round(((y_true - y_pred)**2).mean(), round_digits)
# --- NEURON CLASS ---
class Neuron:
# init of weights
def __init__(self, weights, bias, output_neuron, seq, layer="/"):
if output_neuron:
self.name = "O{}".format(str(seq))
else:
self.name = "L{}N{}".format(str(layer), str(seq))
self.h_layer = layer
self.output_neuron = output_neuron
self.weights = weights
self.bias = bias
def setWeights(self, weights):
self.weights = weights
def setBias(self, bias):
self.bias = bias
# maths operations
def feedforward(self, inputs):
# { (inputs * weights) + bias }, then use activation function
tot = np.dot(self.weights, inputs) + self.bias
return round(tot, round_digits), sigmoid(tot)
def printInfo(self):
print("\nName:", self.name)
if not self.output_neuron:
print("H_Layer:", self.h_layer)
print("Weights:", self.weights)
print("Bias:", self.bias)
# --- NEURAL NETWORK ---
class NeuralNetwork:
def __init__(self, input_dim):
self.input_dim = input_dim
#self.init_output()
self.output_num = 1
self.init_hidden_layers()
#self.h_layers = 2
self.init_neurons()
self.init_output_neuron()
self.printInfo()
# INITIALIZATION FUNCTIONS
def init_output(self):
print("\nHow many Output?")
self.output_num = int(input("-> "))
def init_hidden_layers(self):
print("\nHow many Hidden Layers?")
self.h_layers = int(input("-> "))
def init_neurons(self):
self.weights = []
self.bias = []
self.num_neurons = []
self.num_neurons.append(self.input_dim) # pos[0] = input_dimension
self.neurons = []
for layer in range(self.h_layers):
print("\nHow many Neurons in Layer" + str(layer+1) + "?")
num = int(input("-> "))
self.num_neurons.append(num)
n_prev_neur = self.num_neurons[layer] # number of neurons in previously layer
for neuron in range(num):
# init Weights, Biases
for weight in range(n_prev_neur):
self.weights.append(round(np.random.normal(), round_digits))
self.bias.append(round(np.random.normal(), round_digits))
# init Neuron
neur = Neuron(self.weights[-n_prev_neur:], self.bias[-1], False, neuron, layer)
self.neurons.append(neur)
def init_output_neuron(self):
for output in range(self.output_num):
# init Weights, Biases
n_prev_neur = self.num_neurons[-1]
for neuron in range(n_prev_neur):
self.weights.append(round(np.random.normal(), round_digits))
self.bias.append(round(np.random.normal(), round_digits))
# init Neuron
neur = Neuron(self.weights[-n_prev_neur:], self.bias[-1], True, output)
self.neurons.append(neur)
def setNetworkWeight(self, pos, new_value):
self.weights[pos] = new_value
def setNetworkBias(self, pos, new_value):
self.bias[pos] = new_value
# PRINT INFO OF NETWORK
def printInfo(self):
print("\n--- Network Info ---")
print("\nInput_Dimension:", self.input_dim)
print("Num_of_Hidden_Layers:", self.h_layers)
print("Num_of_Outputs:", self.output_num)
for layer in range(self.h_layers):
print("\n-H_Layer " + str(layer) + ":")
print(" > Neurons:", self.num_neurons[layer+1])
#print("\nWeights:", self.weights)
#print("Bias:", self.bias, "\n")
index = 0
for layer in range(self.h_layers):
print("\n\n -- #HIDDEN LAYER " + str(layer) + " --")
num_neurons_per_layer = self.num_neurons[layer+1]
for neuron in self.neurons[index:index+num_neurons_per_layer]:
neuron.printInfo()
index += num_neurons_per_layer
print("\n\n -- #OUTPUT LAYER --")
for neuron in self.neurons[-self.output_num:]:
neuron.printInfo()
def feedforward(self, x, loss_calc=True):
#print("\n- FEED FORWARD -")
out_h = []
h_values = []
x_sums = []
idx = 0
out_h = x
for layer in range(self.h_layers):
#print("\nLayer", layer)
n_neur = self.num_neurons[layer+1]
#print("Num_Neurons:", n_neur)
result = []
for neuron in self.neurons[idx:idx+n_neur]:
x_value, tot = neuron.feedforward(out_h)
x_sums.append(x_value)
result.append(tot)
out_h = result
h_values.append(out_h)
#print("h_values:", h_values)
idx += n_neur
#print("\nOUTPUT LAYER")
result = []
for neuron in self.neurons[-self.output_num:]:
x_value, tot = neuron.feedforward(out_h)
x_sums.append(x_value)
result.append(tot)
h_values.append(result)
#print("h_values:", h_values)
if loss_calc:
return h_values[-1]
else:
return x_sums, h_values, result
def partial_derivatives(self, x, y_true, y_pred, x_sums, h_values):
#print("\n- PARTIAL DERIVATIVES -")
derivatives = [] #array used to return all the values
d_L_d_ypred = -2 * (y_true - y_pred) #y_pred is an array, could be containing multiple values
derivatives.append(d_L_d_ypred)
#print("\nd_L_d_ypred:", d_L_d_ypred)
d_h_d_w = []
d_h_d_b = []
index = 0
neur_cnt = 0
inputs = x
for layer in range(self.h_layers):
#print("\nLayer", layer)
num_neur = self.num_neurons[layer+1]
for neuron in self.neurons[index:index+num_neur]:
dh_dw = []
for val in inputs:
deriv = val * deriv_sigmoid(x_sums[neur_cnt])
dh_dw.append(round(deriv, round_digits))
d_h_d_w.append(dh_dw)
d_h_d_b.append(deriv_sigmoid(x_sums[neur_cnt]))
neur_cnt+=1
index+=num_neur
inputs = h_values[layer]
derivatives.append(d_h_d_w)
derivatives.append(d_h_d_b)
#print("d_h_d_w:", d_h_d_w)
#print("d_h_d_b:", d_h_d_b)
# Partial derivatives OUTPUT LAYER
d_ypred_d_w = []
d_ypred_d_b = []
d_ypred_d_h = []
#print("\nOutput Layer")
for neuron in self.neurons[-self.output_num:]:
dy_dw = []
for val in inputs:
deriv = val * deriv_sigmoid(x_sums[neur_cnt])
dy_dw.append(round(deriv, round_digits))
d_ypred_d_w.append(dy_dw)
d_ypred_d_b.append(deriv_sigmoid(x_sums[neur_cnt]))
dy_dh = []
for weight in neuron.weights:
deriv = weight * deriv_sigmoid(x_sums[neur_cnt])
dy_dh.append(round(deriv, round_digits))
d_ypred_d_h.append(dy_dh)
neur_cnt+=1
derivatives.append(d_ypred_d_w)
derivatives.append(d_ypred_d_b)
derivatives.append(d_ypred_d_h)
#print("d_ypred_d_w:", d_ypred_d_w)
#print("d_ypred_d_b:", d_ypred_d_b)
#print("d_ypred_d_h:", d_ypred_d_h)
return derivatives
def update_w_b(self, learn_rate, d_L_d_ypred, d_h_d_w, d_h_d_b, d_ypred_d_w, d_ypred_d_b, d_ypred_d_h):
#print("\n- UPDATE WEIGHTS AND BIASES -")
index = 0
neur_cnt = 0
pos = 0
for layer in range(self.h_layers):
#print("\n\nLayer", layer)
num_neur = self.num_neurons[layer+1]
last_layer_neur_cnt = 0
for neuron in self.neurons[index:index+num_neur]:
#print("\n Neuron", neur_cnt)
new_weights = []
weight_cnt = 0
for weight in neuron.weights:
if(layer == self.h_layers-1):
decr_val = learn_rate * d_L_d_ypred[0] * d_h_d_w[neur_cnt][weight_cnt] * d_ypred_d_h[0][last_layer_neur_cnt]
else:
decr_val = learn_rate * d_L_d_ypred[0] * d_h_d_w[neur_cnt][weight_cnt]
new_val = weight - decr_val
#print(" decr_val_weight:", decr_val)
new_weights.append(round(new_val, round_digits))
self.setNetworkWeight(pos, round(new_val, round_digits))
weight_cnt+=1
pos+=1
neuron.setWeights(new_weights)
#print(" new_weights:", neuron.weights)
# New Bias
decr_val = learn_rate * d_L_d_ypred[0] * d_h_d_b[neur_cnt]
new_val = neuron.bias - decr_val
#β¦print(" decr_val_bias:", decr_val)
neuron.setBias(round(new_val,round_digits))
self.setNetworkBias(neur_cnt, round(new_val,round_digits))
#print(" new_bias:", neuron.bias)
neur_cnt+=1
if(layer == self.h_layers-1):
last_layer_neur_cnt+=1
index+=num_neur
# OUTPUT LAYER
#print("\n\nOutput Layer")
neur_cnt = 0
pos_bias = len(self.bias) - self.output_num
for neuron in self.neurons[-self.output_num:]:
new_weights = []
weight_cnt = 0
for weight in neuron.weights:
decr_val = learn_rate * d_L_d_ypred[0] * d_ypred_d_w[neur_cnt][weight_cnt]
new_val = weight - decr_val
new_weights.append(round(new_val, round_digits))
self.setNetworkWeight(pos, round(new_val, round_digits))
weight_cnt+=1
pos+=1
neuron.setWeights(new_weights)
#print(" new_weights:", neuron.weights)
# New Bias
decr_val = learn_rate * d_L_d_ypred[neur_cnt] * d_ypred_d_b[neur_cnt]
new_val = neuron.bias - decr_val
#print("decr_val_bias:", decr_val)
neuron.setBias(round(new_val,round_digits))
self.setNetworkBias(pos_bias, round(new_val,round_digits))
#print(" new_bias:", neuron.bias)
pos_bias+=1
neur_cnt+=1
# TRAINING FUNCTION
def train(self, data, y_trues):
learn_rate = 0.1
epochs = 1000 #number of loops
print("\n\n--- TRAINING ---")
for epoch in range(epochs):
for x, y_true in zip(data, y_trues):
#print("\n\n-- NEW DATA --")
x_sums, h_values, y_pred = self.feedforward(x, False)
#print("\nData:", x, y_true)
#print("x_sums:", x_sums)
#print("h_values:", h_values)
#print("y_pred:", y_pred)
# Partial derivatives
derivatives = self.partial_derivatives(x, y_true, y_pred, x_sums, h_values)
d_L_d_ypred = derivatives[0]
d_h_d_w = derivatives[1]
d_h_d_b = derivatives[2]
d_ypred_d_w = derivatives[3]
d_ypred_d_b = derivatives[4]
d_ypred_d_h = derivatives[5]
#print("d_L_d_ypred:", d_L_d_ypred)
#print("d_h_d_w:", d_h_d_w)
#print("d_h_d_b:", d_h_d_b)
#print("d_ypred_d_w:", d_ypred_d_w)
#print("d_ypred_d_b:", d_ypred_d_b)
#print("d_ypred_d_h:", d_ypred_d_h)
#Update weights and biases
self.update_w_b(learn_rate, d_L_d_ypred, d_h_d_w, d_h_d_b, d_ypred_d_w, d_ypred_d_b, d_ypred_d_h)
if epoch % 10 == 0:
print("\n- LOSS CALCULATION -")
y_preds = np.apply_along_axis(self.feedforward, 1, data)
loss = mse_loss(y_trues, y_preds)
print("Epoch {} - Loss: {}".format(epoch, loss))
def saveData(self, filename="./network_datas.pkl"):
datas = [self.weights, self.bias]
try:
with open (filename, "wb") as f:
pickle.dump(datas, f)
except IOError:
print("\nError trying to Save data.")
return -1
print("\nWeights and Biases saved!")
return 0
def loadData(self, filename="./network_datas.pkl"):
try:
with open(filename, "rb") as f:
weights, biases = pickle.load(f)
except IOError:
print("\nError trying to Load data.")
return -1
print("\nWeights and Biases loaded!")
self.weights = weights
self.bias = biases
return 0
# --- MAIN METHODS ---
def basicNetwork():
print("\n\n--- EXAMPLE 2: basic network ---\n")
data = np.array([
[-2, -1], # Alice
[25, 16], # Bob
[17, 9], # Charlie
[-15, -6], # Diana
])
y_trues = np.array([
1, # Alice
0, # Bob
0, # Charlie
1, # Diana
])
# Building the Network
input_dim = 2
network = NeuralNetwork(input_dim)
network.train(data, y_trues)
network.printInfo()
#network.saveData()
#network.loadData()
# Make some predictions
emily = np.array([-7, -3])
frank = np.array([20, 2])
pred_emily = network.feedforward(emily)
pred_frank = network.feedforward(frank)
print("\nEmily:", pred_emily, ("F" if pred_emily[0] > 0.5 else "M"))
print("Frank:", pred_frank, ("F" if pred_frank[0] > 0.5 else "M"))
# --- TEST MSE ---
def test_mse():
print("\n\n--- EXAMPLE 3: test MSE Loss ---\n")
y_true = np.array([1,0,0,1])
y_pred = np.array([0,0,0,0])
print("MSE Loss:", mse_loss(y_true, y_pred))
# --- MAIN ---
#test_mse()
basicNetwork()
|
from measurement.measures import Speed
from . import activity
class VO2:
_value: float
"""float: Estimated VO2 reserve value
"""
def __init__(self, o2_cost_horiz: float, o2_cost_vert: float, speed: Speed, grade = 0.0):
"""Initializes instance.
Args:
o2_cost_horiz (float): Oxygen cost of moving each kg of bodyweight horizontally
o2_cost_vert (float): Oxygen cost of moving each kg of bodyweight vertically
speed (Speed): Speed the subject was moving at
grade (float): Overall % grade of the surface an activity was performed on
"""
self._value = self._calculate_vo2(o2_cost_horiz, o2_cost_vert, speed, grade)
def _calculate_vo2(self, o2_cost_horiz: float, o2_cost_vert: float, speed: Speed, grade = 0.0) -> float:
"""Calculates the estimated VO2 reserve value. The equation is:
VO2 = (o2_cost_horiz x speed) + (o2_cost_vert x speed) + 3.5
Where speed is expressed in meters/min.
Args:
o2_cost_horiz (float): Oxygen cost of moving each kg of bodyweight horizontally
o2_cost_vert (float): Oxygen cost of moving each kg of bodyweight vertically
speed (Speed): Speed the subject was moving at
grade (float): Overall % grade of the surface an activity was performed on
Returns:
float: Estimated VO2 reserve value
"""
meters_per_min = (speed.kph * 1000) / 60
return (o2_cost_horiz * meters_per_min) + (o2_cost_vert * meters_per_min * grade) + 3.5
def get_value(self) -> float:
"""Gets the estimated VO2 reserve value
Returns:
float: VO2 reserve value
"""
return self._value
O2_COST_HORIZ_WALK = 0.1
"""float: Constant estimated oxygen cost of moving each kg of bodyweight horizontally while walking
"""
O2_COST_VERT_WALK = 1.8
"""float: Constant estimated oxygen cost of moving each kg of bodyweight vertically while walking
"""
O2_COST_HORIZ_RUN = 0.2
"""float: Constant estimated oxygen cost of moving each kg of bodyweight vertically while walking
"""
O2_COST_VERT_RUN = 0.9
"""float: Constant estimated oxygen cost of moving each kg of bodyweight horizontally while running
"""
def get_VO2(activity: activity.Activity, speed: Speed, grade = 0.0) -> VO2:
"""Factory method for instantiating a VO2 instance
Args:
activity (activity.Activity): Activity performed
speed (Speed): Average speed of the activity
grade (float): Percentage grade expressed as a decimal
Returns:
VO2: Instance of VO2 for the given activity
Raises:
Exception: If an invalid or unsupported activity is given as input
"""
if activity.get_name() == 'walk':
return VO2(o2_cost_horiz=O2_COST_HORIZ_WALK, o2_cost_vert=O2_COST_VERT_WALK, speed=speed, grade=grade)
if activity.get_name() == 'run':
return VO2(o2_cost_horiz=O2_COST_HORIZ_RUN, o2_cost_vert=O2_COST_VERT_RUN, speed=speed, grade=grade)
raise Exception('Invalid or unsupported Activity')
|
colors = ["red", "green", "blue", "purple"]
ratios = [0.2, 0.3, 0.1, 0.4]
for i, color in enumerate(colors):
ratio = ratios[i]
print("{}% {}".format(ratio * 100, color))
lst = ['A','B','C','D']
print({k: v for v, k in enumerate(lst)})
dictionary = dict(zip(colors, ratios))
print(dictionary)
for i in colors:
p = i
print(dict(i = ratios[p]))
|
'''
Practice: Companies and Employees
Instructions
Create an Employee type that contains information about employees of a company. Each employee must have a name, job title, and employment start date.
Create a Company type that employees can work for. A company should have a business name, address, and industry type.
Create two companies, and 5 people who want to work for them.
Assign 2 people to be employees of the first company.
Assign 3 people to be employees of the second company.
Output a report to the terminal the displays a business name, and its employees.
For example:
Acme Explosives is in the chemical industry and has the following employees
* Michael Chang
* Martina Navritilova
Jetways is in the transportation industry and has the following employees
* Serena Williams
* Roger Federer
* Pete Sampras
'''
class Employee :
def __init__ (self, name, title, start_date):
self.name = name
self.title = title
self.start_date = start_date
class Company:
def __init__ (self, name, address, industry):
self.name = name
self.address = address
self.industry = industry
self.employees = list()
guy = Employee("Guy Cherkesky", "CEO", "01/01/2018")
samuel = Employee("Samuel Jackson", "CFO", "01/02/2018")
tammy = Employee("Tammy Harris", "CTO", "01/03/2018")
jordan = Employee("Jordan Tang", "Secretary", "01/04/2018")
yeezy = Employee("Yeezy Little", "Driver", "01/05/2018")
nss = Company("NSS", "301 Plus Park Blvd", "Software")
abc = Company("ABC", "302 Plus Park Blvd", "Hardware")
nss.employees.append(guy)
nss.employees.append(samuel)
nss.employees.append(tammy)
abc.employees.append(jordan)
abc.employees.append(yeezy)
print(f'{nss.name} is in the {nss.industry} industry and has the following employees:')
for employee in nss.employees:
print(f'* {employee.name}')
print ("")
print(f'{abc.name} is in the {abc.industry} industry and has the following employees:')
for employee in abc.employees:
print(f'* {employee.name}')
|
def buildCoder(shift):
"""
Returns a dict that can apply a Caesar cipher to a letter.
The cipher is defined by the shift value. Ignores non-letter characters
like punctuation, numbers, and spaces.
shift: 0 <= int < 26
returns: dict
"""
### TODO
import string
CodeDict = {}
for index in range(len(string.ascii_lowercase)):
CodeDict[string.ascii_lowercase[index]] = string.ascii_lowercase[(index+shift)%26]
for index in range(len(string.ascii_uppercase)):
CodeDict[string.ascii_uppercase[index]] = string.ascii_uppercase[(index+shift)%26]
return CodeDict
|
def findBestShift(wordList, text):
"""
Finds a shift key that can decrypt the encoded text.
text: string
returns: 0 <= int < 26
"""
### TODO
bestShift = 0
bestCorrectWordNumber = 0
words = text.split()
for shift in range(26):
correctWordNumber = 0
for word in words:
if isWord(wordList, applyShift(word,shift)):
correctWordNumber +=1
if bestCorrectWordNumber < correctWordNumber:
bestCorrectWordNumber, bestShift = correctWordNumber, shift
return bestShift
|
from math import *
class User_interface:
def __init__(self, conf_file_name):
self.area = []
self.activators = []
# +y forward, +x right, [cm]
self.parse_conf(conf_file_name)
self.pressed = [False]*len(self.activators)
self.activation = 0
def parse_conf(self, file_name):
f = open(file_name, "r")
first = True
for line in f:
line = line.strip()
if len(line) == 0:
continue
# comment in configuration file
if line[0] == "#":
continue
line = line.split(",")
if first and len(line) == 4:
self.area = [float(line[0]), float(line[1]), float(line[2]), float(line[3])]
first = False
elif len(line) == 5:
self.activators.append([float(line[0]), float(line[1]), float(line[2]),
float(line[3]), int(line[4])])
else:
raise "Syntax error in configuration file", line
def in_area(self, pt):
if pt[0] > self.area[0] and pt[1] < self.area[1] and \
pt[0] < self.area[2] and pt[1] > self.area[3]:
return True
return False
def is_in_circle(self, pt, circle, old_status):
if old_status == 1:
r = circle[3]
else:
r = circle[2]
l = sqrt((pt[0]-circle[0])**2 + (pt[1]-circle[1])**2)
#print pt, circle
#print l, r
if l < r:
return True
else:
return False
def cartesian(self, pt):
y = pt[1]/10*cos(pt[0]*pi/180)
x = pt[1]/10*sin(pt[0]*pi/180)
return (x,y)
def update(self, laser_meas, mouse_pos_cm):
for i in range(len(self.activators)):
old_status = self.pressed[i]
self.pressed[i] = False
for pt in laser_meas:
pt_pos_cm = self.cartesian(pt)
if not self.in_area(pt_pos_cm):
continue
status = self.is_in_circle(pt_pos_cm, self.activators[i], old_status)
if status == True:
self.pressed[i] = True
break
status2 = self.is_in_circle(mouse_pos_cm, self.activators[i], old_status)
if status2 == True:
self.pressed[i] = True
return self.pressed, self.video_activation()
def video_activation(self):
#all_released = True
for i in range(len(self.pressed)):
#if self.pressed[i]:
# all_released = False
if self.pressed[i] and self.activation == 0:
self.activation = self.activators[i][4]
break
elif not self.pressed[i] and self.activation == self.activators[i][4]:
self.activation = 0
#if all_released:
# self.activation = -1
return self.activation
def get_bounding_box(self):
return self.area
def get_circles(self):
return self.activators
if __name__ == "__main__":
ui = User_interface("conf.ini")
laser_points = []
for i in range(-20, 20):
laser_points.append([i, 1000])
print ui.get_bounding_box()
print ui.get_circles()
print ui.update(laser_points)
|
# We have a list of points on the plane. Find the K closest points to the origin (0, 0).
#
# (Here, the distance between two points on a plane is the Euclidean distance.)
#
# You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)
#
#
#
# Example 1:
#
# Input: points = [[1,3],[-2,2]], K = 1
# Output: [[-2,2]]
# Explanation:
# The distance between (1, 3) and the origin is sqrt(10).
# The distance between (-2, 2) and the origin is sqrt(8).
# Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
# We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].
# Example 2:
#
# Input: points = [[3,3],[5,-1],[-2,4]], K = 2
# Output: [[3,3],[-2,4]]
# (The answer [[-2,4],[3,3]] would also be accepted.)
#
#
# Note:
#
# 1 <= K <= points.length <= 10000
# -10000 < points[i][0] < 10000
# -10000 < points[i][1] < 10000
# νλ©΄ μμ points λͺ©λ‘μ΄ μμ λ μμ (0, 0)μμ K λ² κ°κΉμ΄ μ λͺ©λ‘μ μμλλ‘ μΆλ ₯νλΌ.
# νλ©΄ μ λ μ μ 거리λ μ ν΄λ¦¬λ κ±°λ¦¬λ‘ νλ€.
# Kλ² μΆμΆμ΄λΌλ λ¨μ΄μμ λ°λ‘, μ°μ μμ νλ₯Ό λ μ¬λ¦΄ μ μλ€.
import heapq
from typing import List
class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
heap = []
for (x, y) in points:
dist = x ** 2 + y ** 2
heapq.heappush(heap, (dist, x, y))
result = []
for _ in range(K):
dist, x, y = heapq.heappop(heap)
result.append([x, y])
return result
# 83 / 83 test cases passed.
# Status: Accepted
# Runtime: 720 ms
# Memory Usage: 19.5 MB
#
# Your runtime beats 73.64 % of python3 submissions.
# Your memory usage beats 27.85 % of python3 submissions.
|
# Given a non-empty array of integers, every element appears twice except for one. Find that single one.
#
# Note:
#
# Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
#
# Example 1:
#
# Input: [2,2,1]
# Output: 1
# Example 2:
#
# Input: [4,1,2,1,2]
# Output: 4
# λ± νλλ₯Ό μ μΈνκ³ λͺ¨λ μ리먼νΈλ 2κ°μ© μλ€. 1κ°μΈ μ리먼νΈλ₯Ό μ°ΎμλΌ.
# λ± 1κ°μ μ리먼νΈλ₯Ό μ°Ύλλ° μ λΉν μ°μ°μ: XOR
# λ λ² λ±μ₯ν μ리먼νΈλ 0μΌλ‘ μ΄κΈ°νλκ³ , νλ²λ§ γ
λ±μ₯νλ μ리먼νΈλ κ·Έ κ°μ μ¨μ ν 보쑴νλ€. (κ·Έ κ°μ λν΄μ€λ€)
# λ°°μ΄μ λͺ¨λ κ°μ XOR νλ©΄ λ¨ ν λ²λ§ λ±μ₯νλ μ리먼νΈλ§ κ·Έ κ°μ΄ λ¨κ² λλ€.
from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
result = 0
for num in nums:
result ^= num
return result
# 16 / 16 test cases passed.
# Status: Accepted
# Runtime: 84 ms
# Memory Usage: 16.3 MB
#
# Your runtime beats 89.98 % of python3 submissions.
# Your memory usage beats 58.97 % of python3 submissions.
|
# Design a data structure that supports adding new words and finding if a string matches any previously added string.
#
# Implement the WordDictionary class:
#
# WordDictionary() Initializes the object.
# void addWord(word) Adds word to the data structure, it can be matched later.
# bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.
#
#
# Example:
#
# Input
# ["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
# [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
# Output
# [null,null,null,null,false,true,true,true]
#
# Explanation
# WordDictionary wordDictionary = new WordDictionary();
# wordDictionary.addWord("bad");
# wordDictionary.addWord("dad");
# wordDictionary.addWord("mad");
# wordDictionary.search("pad"); // return False
# wordDictionary.search("bad"); // return True
# wordDictionary.search(".ad"); // return True
# wordDictionary.search("b.."); // return True
#
#
# Constraints:
#
# 1 <= word.length <= 500
# word in addWord consists lower-case English letters.
# word in search consist of '.' or lower-case English letters.
# At most 50000 calls will be made to addWord and search.
class WordDictionary:
"""
μ λ¨μ΄λ₯Ό μΆκ°ν μ μκ³ ,
λ¬Έμμ΄μ΄ μ΄μ μ μΆκ°λ λ¬Έμμ΄κ³Ό μΌμΉνλμ§ μ¬λΆλ₯Ό νμΈν μ μλ λ°μ΄ν° ꡬ쑰λ₯Ό μ€κ³νλΌ
λ¨μ΄ μ¬μ ν΄λμ ꡬν
- WordDictionary(): κ°μ²΄λ₯Ό μ΄κΈ°ννλ€.
- addWord(word): λ°μ΄ν° ꡬ쑰μ λ¨μ΄λ₯Ό μΆκ°νλ©΄, λμ€μ λ§€μΉν μ μλ€.
- search(word): λ°μ΄ν° ꡬ쑰μ λ¨μ΄μ μΌμΉνλ λ¬Έμμ΄μ΄ μμ κ²½μ° trueλ₯Ό λ°ννκ±°λ, κ·Έλ μ§ μμΌλ©΄ falseλ₯Ό λ°ννλ€. λ¨μ΄λ€μ μ΄λ€ λ¬Έμμλ μΌμΉμν¬ μ μλ . μ ν¬ν¨ν μ μλ€.
"""
# Trie ꡬ쑰
# νΈλΌμ΄λ λ¬Έμμ΄μ μ¬μ©ν ν¨μ¨μ μΈ λμ μΆκ°/κ²μ μμ
μ μ£Όλ‘ μ¬μ©λλ κ²μ μμ νΈλ¦¬ λ°μ΄ν° ꡬ쑰μ μΌμ’
μ΄λ€.
# μλ μμ± κ²μ, μ² μ κ²μ¬, T9 μμΈ‘ ν
μ€νΈ, IP λΌμ°ν
(κ°μ₯ κΈ΄ μ λμ¬ μΌμΉ), μΌλΆ GCC 컨ν
μ΄λ λ±μ λ리 μ¬μ©λλ€.
def __init__(self):
"""
Initialize your data structure here.
"""
self.trie = {}
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
node = self.trie
for char in word:
if not char in node:
node[char] = {}
node = node[char]
# node = node.setdefault(char, {})
node['#'] = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
# DFS νμ
def search_in_node(word, node) -> bool:
for i, char in enumerate(word):
if not char in node:
if char == ".":
for child in node:
if child != '#' and search_in_node(word[i + 1:], node[child]):
return True
return False
else:
node = node[char]
return '#' in node
return search_in_node(word, self.trie)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
# 13 / 13 test cases passed.
# Status: Accepted
# Runtime: 320 ms
# Memory Usage: 24.4 MB
#
# Your runtime beats 75.32 % of python3 submissions.
# Your memory usage beats 67.79 % of python3 submissions.
|
# Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
#
# If possible, output any possible result. If not possible, return the empty string.
#
# Example 1:
#
# Input: S = "aab"
# Output: "aba"
# Example 2:
#
# Input: S = "aaab"
# Output: ""
# Note:
#
# S will consist of lowercase letters and have length in range [1, 500].
class Solution:
"""
λ¬Έμμ΄μ΄ SμΈ κ²½μ° μΈμ ν λ λ¬Έμκ° κ°μ§ μλλ‘ λ¬Έμλ₯Ό λ€μ μ λ ¬ν μ μλμ§ νμΈνμμμ€.
κ°λ₯ν κ²½μ° κ°λ₯ν κ²°κ³Όλ₯Ό μΆλ ₯νμμμ€. λΆκ°λ₯ν κ²½μ° λΉ λ¬Έμμ΄μ λ°ννμμμ€.
"""
def reorganizeString(self, S: str) -> str:
"""
νμ μΈλ±μ€μ μ΅μ κ³΅ν΅ λ¬Έμλ₯Ό λ£κ³ μ§μ μΈλ±μ€(λΉλ μμμ λ°λΌ μΌμͺ½μμ μ€λ₯Έμͺ½μΌλ‘ λͺ¨λ)μ κ°μ₯ μΌλ°μ μΈ λ¬Έμλ₯Ό λ£λλ€. μ΄λ€ λ¬Έμκ° λ무 μμ£Ό λνλ κ²½μ°μλ§ μμ
μ΄ λΆκ°λ₯νλ©°, μ΄ κ²½μ° λͺ¨λ μ§μ μΈλ±μ€μ μ΅μν λ§μ§λ§ νμ μΈλ±μ€λ₯Ό μ°¨μ§νκ² λλ―λ‘ λ§μ§λ§ λ μΈλ±μ€λ₯Ό 체ν¬νλ€.
"""
a = sorted(sorted(S), key=S.count)
half = len(S) // 2
a[1::2], a[::2] = a[:half], a[half:]
if a[-1] == a[-2]:
return ''
return ''.join(a)
# 62 / 62 test cases passed.
# Status: Accepted
# Runtime: 28 ms
# Memory Usage: 14.1 MB
# Your runtime beats 89.86 % of python3 submissions.
|
#
# Given a 32-bit signed integer, reverse digits of an integer.
#
# Example 1:
#
# Input: 123
# Output: 321
# Example 2:
#
# Input: -123
# Output: -321
# Example 3:
#
# Input: 120
# Output: 21
# Note:
# Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range:
# [β231, 231 β 1].
# For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
class Solution:
@staticmethod
def reverse(self, x: int) -> int:
str_x: str = str(x)
result: str = ''
for i in range(1, len(str_x) + 1):
if str_x[-i] == '-':
continue
result += str_x[-i]
if x < 0:
result = '-' + result
result = int(result)
if result > (2 ** 31) - 1 or result < -(2 ** 31):
return 0
return result
|
# graph traversal
# adjacency List
graph = {
1: [2, 3, 4],
2: [5],
3: [5],
4: [],
5: [6, 7],
6: [],
7: [3],
}
# DFS (depth-first search)
# recursive
def recursive_dfs(v, discovered=[]):
discovered.append(v) # discoveredμ μ μ μΆκ°
for destination in graph[v]: # κ·Έ μ μ μμ μΆλ°νλ λμ°©μ§ λͺ©λ‘μ νλμ© μννλ©΄μ
if destination not in discovered: # λμ°©μ§κ° discoveredμ ν¬ν¨μ΄ μλμ΄ μμΌλ©΄
discovered = recursive_dfs(destination, discovered) # κ·Έ λμ°©μ§ μ μ κ³Ό discovered λͺ©λ‘μ λ€μ λ£μ΄μ μ¬κ·μ μΌλ‘ ν¨μ νΈμΆ.
return discovered # μ΅μ’
discovered 리μ€νΈ λ°ν.
# discovered
# [1],
# [1, 2],
# [1, 2, 5],
# [1, 2, 5, 6],
# [1, 2, 5, 6, 7],
# [1, 2, 5, 6, 7, 3],
# [1, 2, 5, 6, 7, 3, 4]
# iterative
def iterative_dfs(start_v):
discovered = []
stack = [start_v] # μ€νμ 첫 μΆλ° μ μ μ μ½μ
while stack: # μ€νμ μμ΄ν
μ΄ νλλΌλ μμΌλ©΄
v = stack.pop() # μ€νμμ top=κ°μ₯ λ€μ λ£μ κ²μ λ½μλ
if v not in discovered: # μ€νμμ λ½μ μ μ μ΄ discoveredμ ν¬ν¨μ΄ μλμ΄ μμΌλ©΄
discovered.append(v) # discoveredμ μΆκ°
for destination in graph[v]: # κ·Έ μ μ μμ μΆλ°νλ λμ°©μ§ μ μ λ€ λ¦¬μ€νΈλ₯Ό νλμ μννλ©°
stack.push(destination) # κ·Έ λμ°©μ§ μ μ λ€μ μ€νμ μΆκ°
return discovered
# discovered
# [1]
# [1, 4],
# [1, 4, 3]
# [1, 4, 3, 5]
# [1, 4, 3, 5, 7]
# [1, 4, 3, 5, 7, 6]
# [1, 4, 3, 5, 7, 6, 2]
# stack
# [1]
# [2, 3, 4]
# [2, 3]
# [2]
# [2, 5]
# [2, 6, 7]
# [2, 6, 3]
# [2, 6]
# [2]
# []
|
# 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.
#
# class Node {
# public int val;
# public List<Node> neighbors;
# }
#
#
# Test case format:
#
# For simplicity sake, each node's value is the same as the node's index (1-indexed). For example, the first node with val = 1, the second node with val = 2, and so on. The graph is represented in the test case using an adjacency list.
#
# Adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
#
# The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.
#
#
#
# Example 1:
#
#
# Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
# Output: [[2,4],[1,3],[2,4],[1,3]]
# Explanation: There are 4 nodes in the graph.
# 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
# 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
# 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
# 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
# Example 2:
#
#
# Input: adjList = [[]]
# Output: [[]]
# Explanation: Note that the input contains one empty list.
# The graph consists of only one node with val = 1 and it does not have any neighbors.
# Example 3:
#
# Input: adjList = []
# Output: []
# Explanation: This an empty graph, it does not have any nodes.
# Example 4:
#
#
# Input: adjList = [[2],[1]]
# Output: [[2],[1]]
#
#
# 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.
# Definition for a Node.
import collections
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
class Solution:
# 1. DFS recursively
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return node
memo = {node: Node(node.val)}
self.dfs(node, memo)
return memo[node]
def dfs(self, node, memo):
for neighbor in node.neighbors:
if neighbor not in memo:
memo[neighbor] = Node(neighbor.val)
self.dfs(neighbor, memo)
memo[node].neighbors.append(
memo[neighbor]) # κ·Έλ₯ neighborκ° μλλΌ, memoμ μλ neighborλ₯Ό append ν΄μ€μΌ ν¨. κ·ΈλμΌ referenceκ° μλ deepcopyκ° λ¨.
# 2. DFS iteratively
def cloneGraph2(self, node):
if not node:
return node
memo = {node: Node(node.val)}
stack = [node]
while stack:
item = stack.pop()
for neighbor in item.neighbors:
if neighbor not in memo:
memo[neighbor] = Node(neighbor.val)
stack.append(neighbor)
memo[item].neighbors.append(memo[neighbor])
return memo[node]
# 3. BFS
def cloneGraph3(self, node):
if not node:
return node
memo = {node: Node(node.val)}
deque = collections.deque([node])
while deque:
item = deque.popleft()
for neighbor in item.neighbors:
if neighbor not in memo:
memo[neighbor] = Node(neighbor.val)
deque.append(neighbor)
memo[item].neighbors.append(memo[neighbor])
return memo[node]
# 21 / 21 test cases passed.
# Status: Accepted
# DFS recursively
# Runtime: 40 ms
# Memory Usage: 14 MB
# Your runtime beats 64.94 % of python3 submissions.
# Your memory usage beats 73.37 % of python3 submissions.
# DFS iteratively
# Runtime: 40 ms
# Memory Usage: 13.8 MB
# Your runtime beats 64.94 % of python3 submissions.
# Your memory usage beats 98.85 % of python3 submissions.
|
# The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
#
# F(0) = 0, F(1) = 1
# F(N) = F(N - 1) + F(N - 2), for N > 1.
# Given N, calculate F(N).
#
#
#
# Example 1:
#
# Input: 2
# Output: 1
# Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
# Example 2:
#
# Input: 3
# Output: 2
# Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
# Example 3:
#
# Input: 4
# Output: 3
# Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
#
#
# Note:
#
# 0 β€ N β€ 30.
# νΌλ³΄λμΉ μλ₯Ό ꡬνλΌ.
# κ° μλ 0κ³Ό 1μμλΆν° μμλ μ λ μ«μμ ν©μ΄ λλ€.
import collections
class Solution:
memo = collections.defaultdict(int)
def fib(self, N: int) -> int:
# 1. κΈ°λ³Έ μ¬κ· => μκ°μ΄ λ§€μ° μ€λ κ±Έλ¦Ό.
# if N < 2:
# return N
# return self.fib(N-1) + self.fib(N-2)
# 2. μν₯μ = νλ·Έλ μ΄μ
. iterative
# memo = collections.defaultdict(int)
# memo[0] = 0
# memo[1] = 1
# for i in range(2, N+1):
# memo[i] = memo[i-2] + memo[i-1]
# return memo[N]
# 3. νν₯μ = λ©λͺ¨μ΄μ μ΄μ
. recursive. ν΄λμ€μ λ©€λ²λ³μμ μ μ₯곡κ°.
# μλ λΈλ£¨νΈν¬μ€ νμ΄μ μ μ¬νκ² μ¬κ·μΈλ°, μ΄λ―Έ κ³μ°ν κ°μ μ μ₯ν΄λλ€κ° λ°λ‘ 리ν΄.
# μ΅μ’
μΌλ‘ μ°Ύλ κ°λΆν° μμν΄μ μ λ°μΌλ‘ νκ³ λ€μ΄κ°λ κ².
# if N < 2:
# return N
# if self.memo[N]:
# return self.memo[N]
# self.memo[N] = self.fib(N-1) + self.fib(N-2)
# return self.memo[N]
# 4. λ λ³μλ§ μ¬μ©ν΄μ κ³΅κ° μ μ½νκΈ°. 곡κ°λ³΅μ‘λ = O(1)
x, y = 0, 1
for i in range(N):
x, y = y, x + y
# N=1, i=0: x = 1, y 1,
# N=2, i=1: x = 1, y 2
# N=3, i=2: x = 2, y 3
return x
# 5. νλ ¬μμΌλ‘ νννκΈ°. μκ°λ³΅μ‘λ O(log n)
# μ νλμ κ΄μ μμ νλ ¬μ nμΉμ κ³μ°νλ λ°©μμΌλ‘, νλ ¬ κ³μ°μ νΈλ¦¬νκ² νκΈ° μν΄ numpy λͺ¨λμ μ¬μ©νμΌλ―λ‘, leetcodeμμ λμνμ§ μμ.
# M = np.matrix([[0, 1], [1, 1]])
# vec = np.array([[0, 1]])
#
# return np.matmul(M ** n, vec)[0]
# 31 / 31 test cases passed.
# Status: Accepted
# Runtime: 16 ms
# Memory Usage: 13.7 MB
#
# Your runtime beats 99.90 % of python3 submissions.
# Your memory usage beats 86.94 % of python3 submissions.
|
# BFS (breath-first Search)
graph = {
1: [2, 3, 4],
2: [5],
3: [5],
4: [],
5: [6, 7],
6: [],
7: [3],
}
def iterative_bfs(start_v):
discovered = [start_v] # discoveredμ 첫 μΆλ° μ μ μ½μ
queue = [start_v] # νμ 첫 μΆλ° μ μ μ½μ
while queue: # νμ μμ΄ν
μ΄ νλλΌλ μμ λ
v = queue.pop(0) # νμ 맨 μμ μλ μ μ μ μΆμΆ
for destination in graph[v]: # κ·Έ μ μ μμ μΆλ°νλ λμ°©μ§ λ¦¬μ€νΈλ₯Ό μννλ©°
if destination not in discovered: # λμ°©μ§ μ μ λ€μ΄ discoveredμ μμΌλ©΄
discovered.append(destination) # κ·Έ λμ°©μ§ μ μ μ discoveredμ μΆκ°
queue.append(destination) # λμ°©μ§ μ μ μ νμλ μΆκ°
return discovered
# discovered
# [1]
# [1, 2, 3, 4]
# [1, 2, 3, 4, 5]
# [1, 2, 3, 4, 5, 6, 7]
# queue
# [1]
# []
# [2, 3, 4]
# [3, 4]
# [3, 4, 5]
# [4, 5]
# [5]
# []
# [6, 7]
# [7]
# []
|
# Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
#
# You need to find the shortest such subarray and output its length.
#
# Example 1:
# Input: [2, 6, 4, 8, 10, 9, 15]
# Output: 5
# Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
# Note:
# Then length of the input array is in range [1, 10,000].
# The input array may contain duplicates, so ascending order here means <=.
from typing import List
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
result = [i for i, (a, b) in enumerate(zip(nums, sorted(nums))) if a != b]
return 0 if not result else result[-1] - result[0] + 1
# 307 / 307 test cases passed.
# Status: Accepted
# Runtime: 216 ms
# Memory Usage: 15 MB
#
# Your runtime beats 74.34 % of python3 submissions.
# Your memory usage beats 63.87 % of python3 submissions.
|
# Given a list of scores of different students, return the average score of each student's top five scores in the order of each student's id.
#
# Each entry items[i] has items[i][0] the student's id, and items[i][1] the student's score. The average score is calculated using integer division.
#
#
#
# Example 1:
#
# Input: [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]
# Output: [[1,87],[2,88]]
# Explanation:
# The average of the student with id = 1 is 87.
# The average of the student with id = 2 is 88.6. But with integer division their average converts to 88.
#
#
# Note:
#
# 1 <= items.length <= 1000
# items[i].length == 2
# The IDs of the students is between 1 to 1000
# The score of the students is between 1 to 100
# For each student, there are at least 5 scores
from typing import List
class Solution:
def highFive(self, items: List[List[int]]) -> List[List[int]]:
items.sort(reverse=True)
curr = []
res = []
idx = items[0][0]
for i, score in items:
if i == idx:
if len(curr) < 5:
curr.append(score)
else:
res.append([idx, sum(curr) // len(curr)])
curr = [score]
idx = i
res.append([idx, sum(curr) // len(curr)])
return res[::-1]
|
# Given a string, your task is to count how many palindromic substrings in this string.
#
# The substrings with different start indexes or end indexes are counted as different substrings
# even they consist of same characters.
#
# Example 1:
#
# Input: "abc"
# Output: 3
# Explanation: Three palindromic strings: "a", "b", "c".
#
#
# Example 2:
#
# Input: "aaa"
# Output: 6
# Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
#
#
# Note:
#
# The input string length won't exceed 1000.
from typing import List
class Solution:
def countSubstrings(self, s: str) -> int:
# 1. expand around center. O(n^2)
# N = len(S)
# ans = 0
# for center in range(2*N - 1):
# left = center // 2
# right = left + center % 2
# while left >= 0 and right < N and S[left] == S[right]:
# ans += 1
# left -= 1
# right += 1
# return ans
# 2. manacher's algorithm
def manacher(s: str) -> List:
A = '@#' + '#'.join(s) + '#$'
Z = [0] * len(A) # palindrome_length_of each index. # κ° λ¬Έμλ₯Ό μ€μ¬μΌλ‘ ν ν°λ¦°λ둬 λ°μ§λ¦μ μΈλ±μ€ λ§λ€ μ μ₯
center = right = 0
for i in range(len(A) - 1):
if i < right: # λ°λ‘ μμ ν°λ¦°λ둬μ ν¬ν¨λλ€λ κ².
i_mirror = center - (i - center) #
Z[i] = min(Z[i_mirror], right - i)
# iλ₯Ό μ€μ¬μΌλ‘ νλ ν°λ¦°λ둬 λ°μ§λ¦μ μ΄κΈ°κ°. centerλ‘λΆν° λμΉλλ i_mirrorμ ν°λ¦°λ둬 λ°μ§λ¦κ³Ό right-i λ₯Ό λΉκ΅ν΄ λ μμ κ°μ΄ μ΄κΈ°κ°.
while A[i + Z[i] + 1] == A[i - Z[i] - 1]: # # iλ₯Ό μ€μ¬μΌλ‘ μΌμͺ½ μ€λ₯Έμͺ½ νμΉΈμ© λ¨μ΄μ§ κ°μ΄ λμΌνλ©΄ ν°λ¦°λ둬μ νμ₯μν΄
Z[i] += 1 # ν°λ¦°λ둬μ λ°μ§λ¦μ 1 μ¦κ°
# κΈ°μ‘΄μ right κ²½κ³λ₯Ό λ²μ΄λλ©΄? νμ¬ μΈλ±μ€λ₯Ό μ€μ¬μΌλ‘ ν ν°λ¦°λ둬μ μ€λ₯Έμͺ½λμ΄ μλ‘μ΄ rightμ΄ λ¨.
if i + Z[i] > right:
# μ΄μ μ max Center, right κ°λ³΄λ€ νμ¬ i μ iλ₯Ό μ€μ¬μΌλ‘ ν ν°λ¦°λ둬 λ°μ§λ¦μ ν©μ΄ λ ν¬λ€λ©΄, centerμ rightμ νμ¬ μΈλ±μ€λ‘ μ
λ°μ΄νΈ
center = i
right = i + Z[i]
return Z
return sum((length + 1) // 2 for length in manacher(s))
# μ¬μ΄μ¬μ΄μ #μ λ£μ΄μ κΈΈμ΄λ₯Ό λλ°°λ‘ λ§λ€μ΄μ κ³μ°νκΈ° λλ¬Έμ ν°λ¦°λ둬μ μ§κ²½μ΄ κ°κ° λλ°°κ° λμ. λ€μ 2λ‘ λλμ΄μ£Όκ³ , κ°κ°μ κ°λ€μ λͺ¨λ ν©μ°.
# 130 / 130 test cases passed.
# Status: Accepted
# Runtime: 48 ms
# Memory Usage: 14.1 MB
#
# Your runtime beats 96.72 % of python3 submissions.
# Your memory usage beats 39.62 % of python3 submissions.
|
# Reverse a linked list from position m to n. Do it in one-pass.
#
# Note: 1 β€ m β€ n β€ length of list.
#
# Example:
#
# Input: 1->2->3->4->5->NULL, m = 2, n = 4
# Output: 1->4->3->2->5->NULL
# Definition for singly-linked list.
# μΈλ±μ€ mμμ nκΉμ§λ₯Ό μμμΌλ‘ λ§λ€μ΄λΌ. μΈλ±μ€ mμ 1λΆν° μμνλ€.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
# λ°λ³΅ κ΅¬μ‘°λ‘ λ
Έλ λ€μ§κΈ°
root = start = ListNode(None)
root.next = head
# start, end μ§μ . μ΄λ κ² ν λΉλ startμ endλ λκΉμ§ κ°μ΄ λ³νμ§ μλλ€.
for _ in range(m - 1):
start = start.next # startλ λ³κ²½μ΄ νμν mμ λ°λ‘ μ μ§μ μ κ°λ¦¬ν€κ² ν¨
end = start.next
# λ°λ³΅νλ©΄μ λ
Έλ μ°¨λ‘λλ‘ λ€μ§κΈ°
# start.next (2)λ₯Ό tempμ μ μ₯ν΄λ .
# start.nextμλ end.next(3)κ° λ€μ΄μ¨λ€ 1.next μ end(2)μ nextμΈ 3μ΄ μ μ₯λ¨
# end.next (μλ 3)μλ end.next.next(4)κ° μ μ₯λ¨
# κ·Έλ¦¬κ³ start.next.nextλ₯Ό temp (2)λ₯Ό μ μ₯.
# 1 -> 3 -> 2 -> 4κ° λμ.
for _ in range(n - m):
temp = start.next
start.next = end.next
end.next = end.next.next
start.next.next = temp
return root.next
# 44 / 44 test cases passed.
# Status: Accepted
# Runtime: 36 ms
# Memory Usage: 13.9 MB
#
# Your runtime beats 42.07 % of python3 submissions.
# Your memory usage beats 79.54 % of python3 submissions.
# <νμ΄μ¬ μκ³ λ¦¬μ¦ μΈν°λ·°> μ°Έκ³ .
|
# Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
#
# Example 1:
#
# Input:
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
# ]
# Output: [1,2,3,6,9,8,7,4,5]
# Example 2:
#
# Input:
# [
# [1, 2, 3, 4],
# [5, 6, 7, 8],
# [9,10,11,12]
# ]
# Output: [1,2,3,4,8,12,11,10,9,5,6,7]
from typing import List
class Solution:
# m x n νλ ¬μ΄ μ£Όμ΄μ§ λ, νλ ¬μ λͺ¨λ μμλ₯Ό λμ ν μμλ‘ λ°ννλΌ.
# Here's how the matrix changes by always extracting the first row and
# rotating the remaining matrix counter-clockwise:
# |1 2 3| |6 9| |8 7| |4| => |5| => ||
# |4 5 6| => |5 8| => |5 4| => |5|
# |7 8 9| |4 7|
# Now look at the first rows we extracted:
# |1 2 3| |6 9| |8 7| |4| |5|
# Those concatenated are the desired result.
# Another visualization
# spiral_order([[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]])
# = [1, 2, 3] + spiral_order([[6, 9],
# [5, 8],
# [4, 7]])
# = [1, 2, 3] + [6, 9] + spiral_order([[8, 7],
# [5, 4]])
# = [1, 2, 3] + [6, 9] + [8, 7] + spiral_order([[4],
# [5]])
# = [1, 2, 3] + [6, 9] + [8, 7] + [4] + spiral_order([[5]])
# = [1, 2, 3] + [6, 9] + [8, 7] + [4] + [5] + spiral_order([])
# = [1, 2, 3] + [6, 9] + [8, 7] + [4] + [5] + []
# = [1, 2, 3, 6, 9, 8, 7, 4, 5]
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
# zipμ΄ μ΄ν°λ μ΄ν°λ₯Ό 리ν΄. 리μ€νΈλ‘ λ§λ€μ΄μ€μΌ ν¨. 리μ€νΈλ₯Ό λ§λ€ λλ * μ΄κ±Έ μ¨μ νλμ© νμ΄μ€λ€μμ listλ‘ μΈκΈ°
return [*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1])
# 22 / 22 test cases passed.
# Status: Accepted
# Runtime: 28 ms
# Memory Usage: 14.1 MB
#
# Your runtime beats 79.31 % of python3 submissions.
|
# Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
#
# Note:
#
# If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
# All airports are represented by three capital letters (IATA code).
# You may assume all tickets form at least one valid itinerary.
# One must use all the tickets once and only once.
# Example 1:
#
# Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
# Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]
# Example 2:
#
# Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
# Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
# Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
# But it is larger in lexical order.
import collections
from typing import List
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
# graph ꡬν
graph = collections.defaultdict(list)
for a, b in sorted(tickets, reverse=True):
graph[a].append(b)
route = []
# recursive
def dfs(a):
# 첫λ²μ§Έ κ°μ μ½μ΄μ μ΄νμμΌλ‘ λ°©λ¬Ένλ€. (sortedμμ reverse=False μΌ λ. pop(0)μΌλ‘ ν μ²λΌ μ°μ°)
# λ§μ§λ§ κ°μ μ½μ΄μ μ΄νμμΌλ‘ λ°©λ¬Έ
while graph[a]:
dfs(graph[a].pop())
route.append(a)
dfs('JFK')
# iterative
# stack = ['JFK']
# while stack: # λ§μ§λ§ λ°©λ¬Έμ§κ° λ¨μ§ μμ λκΉμ§
# while graph[stack[-1]]: # κ·Έλνμ κ°μ΄ μμΌλ©΄
# spot = graph[stack[-1]].pop(0) # pop(0)μΌλ‘ 맨 μ²μ κ°μ μΆμΆ.
# stack.append(spot) # μ€νμ λ£λλ€. = ν μ°μ°
# route.append(stack.pop()) # μ¬κ·μ λ¬λ¦¬ λ°λ³΅μΌλ‘ νμ΄νλ €λ©΄, μ΄μ²λΌ νλ² λ νμ΄λΌ μ μλ λ³μκ° νμνλ€.
# # κ²½λ‘κ° ν리면μ κ±°κΎΈλ‘ λ΄κΈ°κ² λ¨.
# λ€μ λ€μ§μ΄μ μ΄νμμΌλ‘ λ°ν.
return route[::-1]
# 80 / 80 test cases passed.
# Status: Accepted
# Runtime: 76 ms
# Memory Usage: 14.1 MB
#
# Your runtime beats 94.37 % of python3 submissions.
# Your memory usage beats 64.04 % of python3 submissions.
# <νμ΄μ¬ μκ³ λ¦¬μ¦ μΈν°λ·°> μ°Έκ³ .
|
# Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
#
#
#
# Example 1:
#
#
# Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
# Output: 6
# Explanation: The maximal rectangle is shown in the above picture.
# Example 2:
#
# Input: matrix = []
# Output: 0
# Example 3:
#
# Input: matrix = [["0"]]
# Output: 0
# Example 4:
#
# Input: matrix = [["1"]]
# Output: 1
# Example 5:
#
# Input: matrix = [["0","0"]]
# Output: 0
# κ°μ₯ ν° μ§μ¬κ°νμ λ©΄μ μ ꡬνλΌ.
from typing import List
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
# dynamic programming and stack
# μμΈ μ²λ¦¬
if not matrix or not matrix[0]:
return 0
# μλ£ κ΅¬μ‘°
heights = [0] * (len(matrix[0]) + 1)
result = 0
# μν
for row in matrix:
for col in range(len(matrix[0])):
# height update
heights[col] = heights[col] + 1 if row[col] == '1' else 0
stack = [-1]
for col in range(len(matrix[0]) + 1):
while heights[col] < heights[stack[-1]]: # height[i] λ³΄λ€ height[i-1]μ΄ μμ λ μμ μ§μ¬κ°ν μ¬μ΄μ¦λ₯Ό κ³μ°
h = heights[stack.pop()]
w = col - stack[-1] - 1
result = max(result, h * w)
stack.append(col)
return result
# 66 / 66 test cases passed.
# Status: Accepted
# Runtime: 180 ms
# Memory Usage: 14.6 MB
#
# Your runtime beats 99.72 % of python3 submissions.
# Your memory usage beats 24.94 % of python3 submissions.
|
# Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
#
# The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
#
# Note:
#
# Your returned answers (both index1 and index2) are not zero-based.
# You may assume that each input would have exactly one solution and you may not use the same element twice.
#
#
# Example 1:
#
# Input: numbers = [2,7,11,15], target = 9
# Output: [1,2]
# Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
# Example 2:
#
# Input: numbers = [2,3,4], target = 6
# Output: [1,3]
# Example 3:
#
# Input: numbers = [-1,0], target = -1
# Output: [1,2]
#
#
# Constraints:
#
# 2 <= nums.length <= 3 * 104
# -1000 <= nums[i] <= 1000
# nums is sorted in increasing order.
# -1000 <= target <= 1000
# λ μμ ν© 2
# μ λ ¬λ λ°°μ΄μ λ°μ λ§μ
νμ¬ νκ²μ λ§λ€ μ μλ λ°°μ΄μ λ μ«μ μΈλ±μ€λ₯Ό 리ν΄νλΌ.
# μ΄ λ¬Έμ μμ λ°°μ΄μ 0μ΄ μλ 1λΆν° μμνλ κ²μΌλ‘ νλ€.
from bisect import bisect
from typing import List
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
# binery search
# for k, v in enumerate(numbers):
# left = k+1
# right = len(numbers) -1
# expected = target - v
# while left <= right:
# mid = left + (right - left) // 2
# if numbers[mid] < expected:
# left = mid + 1
# elif expected < numbers[mid]:
# right = mid - 1
# else:
# return k+1, mid+1
# using bisect
# for k, v in enumerate(numbers):
# expected = target - v
# i = bisect.bisect_left(numbers, expected, lo=k + 1)
# if i < len(numbers) and numbers[i] == expected:
# return [k + 1, i + 1]
# two pointers
left, right = 0, len(numbers) - 1
while not left == right:
if numbers[left] + numbers[right] < target:
left += 1
elif numbers[left] + numbers[right] > target:
right -= 1
else:
return [left + 1, right + 1]
# 17 / 17 test cases passed.
# Status: Accepted
# Runtime: 68 ms
# Memory Usage: 14.4 MB
#
# bisect
# Your runtime beats 62.26 % of python3 submissions.
# Your memory usage beats 40.28 % of python3 submissions.
# <νμ΄μ¬ μκ³ λ¦¬μ¦ μΈν°λ·°> μ°Έκ³ .
# two pointer
# Your runtime beats 62.26 % of python3 submissions.
# Your memory usage beats 98.44 % of python3 submissions.
|
# # merge sort
#
#
# Sort a linked list in O(n log n) time using constant space complexity.
#
# Example 1:
#
# Input: 4->2->1->3
# Output: 1->2->3->4
# Example 2:
#
# Input: -1->5->3->4->0
# Output: -1->0->3->4->5
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# using merge sort
class Solution:
# def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# if l1 and l2:
# if l1.val > l2.val:
# l1, l2 = l2, l1
# l1.next = self.mergeTwoLists(l1.next, l2)
#
# return l1 or l2
#
# def sortList(self, head: ListNode) -> ListNode:
# if not (head and head.next):
# return head
#
# # λ°λ κΈ°λ² νμ©
# half, slow, fast = None, head, head
# while fast and fast.next:
# half, slow, fast = slow, slow.next, fast.next.next
#
# half.next = None
#
# # λΆν μ¬κ· νΈμΆ
# l1 = self.sortList(head)
# l2 = self.sortList(slow)
#
# return self.mergeTwoLists(l1, l2)
def sortList(self, head: ListNode) -> ListNode:
# μ°κ²°λ¦¬μ€νΈ -> νμ΄μ¬ List
pointer = head
list_ = []
while pointer:
list_.append(pointer.val)
pointer = pointer.next
# μ λ ¬
list_.sort()
# νμ΄μ¬ 리μ€νΈ -> μ°κ²°λ¦¬μ€νΈ
pointer = head
for i in range(len(list_)):
pointer.val = list_[i]
pointer = pointer.next
return head
# sort() λ΄μ₯ ν¨μ μ΄μ©
# Runtime: 88 ms, faster than 98.81% of Python3 online submissions for Sort List.
# Memory Usage: 21.2 MB, less than 99.81% of Python3 online submissions for Sort List.
# merge sort νμ©
# Runtime: 276 ms
# Memory Usage: 40.3 MB
# Your runtime beats 45.33 % of python3 submissions.
# Your memory usage beats 6.39 % of python3 submissions.
|
# There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.
#
# Example 1:
#
# Input:
# [
# "wrt",
# "wrf",
# "er",
# "ett",
# "rftt"
# ]
#
# Output: "wertf"
# Example 2:
#
# Input:
# [
# "z",
# "x"
# ]
#
# Output: "zx"
# Example 3:
#
# Input:
# [
# "z",
# "x",
# "z"
# ]
#
# Output: ""
#
# Explanation: The order is invalid, so return "".
# Note:
#
# You may assume all letters are in lowercase.
# If the order is invalid, return an empty string.
# There may be multiple valid order of letters, return any one of them is fine.
from collections import defaultdict, Counter, deque
from typing import List
class Solution:
def alienOrder(self, words: List[str]) -> str:
# 1. BFS
# 1) extracting as mush information about the alphabet order as we can out of the input word list
# 2) representing that information in a meaningful way
# 3) assembling a valid alphabet ordering
# Step 0: create data structures + the in_degree of each unique letter to 0.
# μλ£κ΅¬μ‘° μ μΈ
# 1 μΈμ 리μ€νΈ (set)
# 2.λ€μ΄μ€λ μ°¨μ counter
adj_list = defaultdict(set)
in_degree = Counter({char: 0 for word in words for char in word})
# Step 1: We need to populate adj_list and in_degree.
# For each pair of adjacent words...
# ["wrt","wrf","er","ett","rftt"]
# ["wrf","er","ett","rftt"]
# words λ₯Ό λ λ¨μ΄λ‘ λ¬Άμ΄μ λΉκ΅νλ©΄μ μΈμ 리μ€νΈμ in_degree λμ
λ리 μ±μ°κΈ°
for first_word, second_word in zip(words, words[1:]):
for c, d in zip(first_word, second_word):
if c != d: # t != f
if d not in adj_list[c]:
adj_list[c].add(d) # adj_list[t] = (f)
in_degree[d] += 1 # in_degree[f] += 1
break # λ€μ λ¬Έμλ€μ λΉκ΅ν νμ μμ.
# for λ¬Έμ΄ break λμ§ μκ³ λκΉμ§ μνλλ©΄ else λ¬Έ μ€ν.
else: # Check that second word isn't a prefix of first word.
if len(second_word) < len(first_word): return "" # invalid case
# Step 2: We need to repeatedly pick off nodes with an indegree of 0.
# in_degree κ°μ΄ 0μΈ λ
Έλλ€μ queueμ μ§μ΄λ£κ³ λΉΌλ©΄μ outputμ 차곑차곑 μκΈ°
output = []
queue = deque([char for char in in_degree if in_degree[char] == 0]) # deque : popleft() μκ°λ³΅μ‘λκ° O(1)
while queue:
char = queue.popleft()
output.append(char)
for d in adj_list[char]:
in_degree[d] -= 1
if in_degree[d] == 0:
queue.append(d)
# If not all letters are in output, that means there was a cycle and so
# no valid ordering. Return "" as per the problem description.
if len(output) < len(in_degree):
return ""
# Otherwise, convert the ordering we found into a string and return it.
return "".join(output)
# 119 / 119 test cases passed.
# Status: Accepted
# Runtime: 32 ms
# Memory Usage: 13.9 MB
#
# Your runtime beats 81.45 % of python3 submissions.
# Your memory usage beats 34.53 % of python3 submissions.
|
# Given a collection of distinct integers, return all possible permutations.
#
# Example:
#
# Input: [1,2,3]
# Output:
# [
# [1,2,3],
# [1,3,2],
# [2,1,3],
# [2,3,1],
# [3,1,2],
# [3,2,1]
# ]
import itertools
from typing import List
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
# return list(itertools.permutations(nums))
result = []
prev_elements = []
def dfs(elements):
# 리ν λ
ΈλμΌ λ κ²°κ³Όμ μΆκ°
if len(elements) == 0:
result.append(prev_elements[:])
# μμ΄ μμ± μ¬κ· νΈμΆ
for e in elements:
next_elements = elements[:]
next_elements.remove(e)
prev_elements.append(e)
dfs(next_elements)
prev_elements.pop()
dfs(nums)
return result
#
# dfs([1, 2, 3])
#
# == μμ리 1μΌ λ
# e = 1
# next_element = [2, 3]
# prev_element = [1]
# dfs([2, 3])
# e = 2
# next_element = [3]
# prev_element = [1, 2]
# dfs([3])
# e = 3
# next_element = []
# prev_element = [1, 2, 3]
# dfs([])
# result.append(prev_elements)
#
# prev_element.pop() // elements = [3]μΌ λ.
# prev_element = [1, 2]
#
# prev_element.pop() // elements = [2, 3] μΌ λ.
# prev_element = [1]
# e = 3
# next_element = [2]
# prev_element = [1, 3]
# dfs([2])
# e = 2
# next_element = []
# prev_element = [1, 3, 2]
# dfs([])
# result.append(prev_elements)
#
# prev_element.pop() // elements = [2] μΌ λ.
# prev_element = [1, 3]
#
# prev_element.pop() //
# prev_element = [1] // elements = [1, 2, 3] μΌ λλ‘ λμμ΄.
#
# ===== μ¬κΈ°μ λΆν° μμ리 2
# e = 2
# next_element = [1, 3]
# prev_element = [2]
# dfs([1,3])
# e = 1
# next_element = [3]
# prev_element = [2, 1]
# dfs([3])
# e = 3
# next_element = []
# prev_element = [2, 1, 3]
# dfs([])
# result.append(prev_element)
#
# prev_element.pop() // elements = [3] μΌ λ
# prev_element = [2, 1]
#
# prev_element.pop() // elements = [1, 3]μΌ λ
# prev_element = [2]
#
# e = 3
# next_element = [1]
# prev_element = [2, 3]
# dfs([1])
# e = 1
# next_element = []
# prev_element = [2, 3, 1]
# dfs([])
# result.append(prev_element)
#
# prev_element.pop() // elements = [1]μΌ λ
# prev_element = [2, 3]
#
# prev_element.pop() // elements = [1, 3] μΌ λ
# prev_element = [2]
#
# prev_element.pop()
# prev_element = []
#
# --- μ¬κΈ°μλΆν° μμ리 3
#
# e = 3
# next_element = [1, 2]
# prev_element = [3]
# 25 / 25 test cases passed.
# Status: Accepted
# Runtime: 44 ms
# Memory Usage: 14.1 MB
#
# Your runtime beats 61.51 % of python3 submissions.
# Your memory usage beats 29.41 % of python3 submissions.
# using itertools
# Your runtime beats 92.69 % of python3 submissions.
# Your memory usage beats 85.54 % of python3 submissions.
|
# Design a HashMap without using any built-in hash table libraries.
#
# To be specific, your design should include these functions:
#
# put(key, value) : Insert a (key, value) pair into the HashMap.
# If the value already exists in the HashMap, update the value.
# get(key): Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
# remove(key) : Remove the mapping for the value key if this map contains the mapping for the key.
#
# Example:
#
# MyHashMap hashMap = new MyHashMap();
# hashMap.put(1, 1);
# hashMap.put(2, 2);
# hashMap.get(1); // returns 1
# hashMap.get(3); // returns -1 (not found)
# hashMap.put(2, 1); // update the existing value
# hashMap.get(2); // returns 1
# hashMap.remove(2); // remove the mapping for 2
# hashMap.get(2); // returns -1 (not found)
#
# Note:
#
# All keys and values will be in the range of [0, 1000000].
# The number of operations will be in the range of [1, 10000].
# Please do not use the built-in HashMap library.
import collections
class ListNode:
def __init__(self, key=None, value=None):
self.key = key
self.value = value
self.next = None
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 1000
self.table = collections.defaultdict(ListNode)
def put(self, key: int, value: int) -> None:
"""
value will always be non-negative.
"""
index = key % self.size
if self.table[index].value is None: # μ‘΄μ¬νμ§ μλ μΈλ±μ€λ‘ μ‘°ννλ©΄ κ·Έ μ리μμ λ°λ‘ λν΄νΈ κ°μ²΄μΈ λΉ listNodeλ₯Ό μμ±
self.table[index] = ListNode(key, value)
return
else:
node = self.table[index]
while node:
if node.key == key: # ν€κ° κ°μΌλ©΄ κ°μ μ
λ°μ΄νΈ
node.value = value
return
if node.next is None:
break
node = node.next # ν€κ° λ€λ₯΄κ³ λ€μ λ
Έλκ° μμΌλ©΄, κ³μ λ€μ λ
Έλλ‘ μ΄λ
node.next = ListNode(key, value) # λ€μ λ
Έλκ° μμΌλ©΄ κ·Έ μ리μ μ 리μ€νΈλ
Έλ μμ±
def get(self, key: int) -> int:
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
"""
index = key % self.size
if self.table[index].value is None:
return -1
node = self.table[index]
while node:
if node.key == key:
return node.value
node = node.next
return -1
def remove(self, key: int) -> None:
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
"""
index = key % self.size
if self.table[index].value is None:
return
node = self.table[index]
# μΈλ±μ€μ 첫 λ²μ§Έ λ
ΈλμΌ λ λ°λ‘ μμ
if node.key == key:
self.table[index] = ListNode() if node.next is None else node.next
return
# μ°κ²°λ¦¬μ€νΈ λ
Έλ μμ
prev = node
while node:
if node.key == key:
prev.next = node.next
return
prev, node = node, node.next
# n = prev.next.next
# prev.next = n
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)
# 33 / 33 test cases passed.
# Status: Accepted
# Runtime: 232 ms
# Memory Usage: 16.9 MB
#
# Your runtime beats 81.92 % of python3 submissions.
# Your memory usage beats 58.41 % of python3 submissions.
|
"""Π£Π·Π½Π°ΠΉΡΠ΅ Ρ ΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΠ΅Π»Ρ ΡΠΈΡΠ»ΠΎ n. ΠΠ°ΠΉΠ΄ΠΈΡΠ΅ ΡΡΠΌΠΌΡ ΡΠΈΡΠ΅Π» n + nn + nnn.
ΠΠ°ΠΏΡΠΈΠΌΠ΅Ρ, ΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΠ΅Π»Ρ Π²Π²ΡΠ» ΡΠΈΡΠ»ΠΎ 3. Π‘ΡΠΈΡΠ°Π΅ΠΌ 3 + 33 + 333 = 369.
"""
n = int(input('enter your number '))
nn = int(str(n)*2)
nnn = int(str(n)*3)
result = n + nn + nnn
print(result)
|
import RPi.GPIO as GPIO
from time import sleep
class FourSeven:
"""
Default Pins:
Type Seg Pin Reg Pin
---- ------- -------
Digit 1 1 pin 9 pin
Digit 2 2 pin 10 pin
Digit 3 6 pin 11 pin
Digit 4 8 pin 12 pin
Seg A 14 pin 1 pin
Seg B 16 pin 2 pin
Seg C 13 pin 3 pin
Seg D 3 pin 4 pin
Seg E 5 pin 5 pin
Seg F 11 pin 6 pin
Seg G 15 pin 7 pin
Defines values are all "off by one" to be inserted into range starting at 0.
"""
DIGIT_ONE = 8
DIGIT_TWO = 9
DIGIT_THREE = 10
DIGIT_FOUR = 11
SEG_A = 0
SEG_B = 1
SEG_C = 2
SEG_D = 3
SEG_E = 4
SEG_F = 5
SEG_G = 6
digits = [DIGIT_ONE, DIGIT_TWO, DIGIT_THREE, DIGIT_FOUR]
def __init__(self, shifter):
self.shifter = shifter
def show_number(self, number):
self.clear()
if number < 0:
self.show_passive()
return
digit = 3
while digit > -1:
# for value in FourSeven.digits:
# self.shifter.set_pin(value, GPIO.LOW)
# self.shifter.write()
self.light_number(number % 10)
self.shifter.set_pin(FourSeven.digits[digit], GPIO.HIGH)
self.shifter.write()
self.shifter.set_pin(FourSeven.digits[digit], GPIO.LOW)
self.light_number(10)
digit = digit - 1
number = number / 10
def show_passive(self):
digit = 3
while digit > -1:
self.light_dash()
self.shifter.set_pin(FourSeven.digits[digit], GPIO.HIGH)
self.shifter.write()
for value in FourSeven.digits:
self.shifter.set_pin(value, GPIO.LOW)
self.shifter.write()
digit = digit - 1
def clear(self):
digit = 3
while digit > -1:
self.light_number(10)
self.shifter.set_pin(FourSeven.digits[digit], GPIO.HIGH)
for value in FourSeven.digits:
self.shifter.set_pin(value, GPIO.LOW)
self.shifter.write()
digit = digit - 1
def light_number(self, number):
if number == 0:
self.shifter.set_pin(FourSeven.SEG_A, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_B, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_C, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_D, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_E, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_F, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_G, GPIO.HIGH)
elif number == 1:
self.shifter.set_pin(FourSeven.SEG_A, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_B, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_C, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_D, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_E, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_F, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_G, GPIO.HIGH)
elif number == 2:
self.shifter.set_pin(FourSeven.SEG_A, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_B, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_C, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_D, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_E, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_F, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_G, GPIO.LOW)
elif number == 3:
self.shifter.set_pin(FourSeven.SEG_A, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_B, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_C, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_D, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_E, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_F, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_G, GPIO.LOW)
elif number == 4:
self.shifter.set_pin(FourSeven.SEG_A, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_B, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_C, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_D, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_E, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_F, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_G, GPIO.LOW)
elif number == 5:
self.shifter.set_pin(FourSeven.SEG_A, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_B, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_C, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_D, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_E, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_F, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_G, GPIO.LOW)
elif number == 6:
self.shifter.set_pin(FourSeven.SEG_A, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_B, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_C, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_D, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_E, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_F, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_G, GPIO.LOW)
elif number == 7:
self.shifter.set_pin(FourSeven.SEG_A, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_B, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_C, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_D, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_E, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_F, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_G, GPIO.HIGH)
elif number == 8:
self.shifter.set_pin(FourSeven.SEG_A, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_B, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_C, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_D, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_E, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_F, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_G, GPIO.LOW)
elif number == 9:
self.shifter.set_pin(FourSeven.SEG_A, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_B, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_C, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_D, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_E, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_F, GPIO.LOW)
self.shifter.set_pin(FourSeven.SEG_G, GPIO.LOW)
elif number == 10:
self.shifter.set_pin(FourSeven.SEG_A, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_B, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_C, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_D, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_E, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_F, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_G, GPIO.HIGH)
def light_dash(self):
self.shifter.set_pin(FourSeven.SEG_A, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_B, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_C, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_D, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_E, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_F, GPIO.HIGH)
self.shifter.set_pin(FourSeven.SEG_G, GPIO.LOW)
|
# Python program to rename all file
# names in your directory
import os
for count, f in enumerate(os.listdir()):
f_name, f_ext = os.path.splitext(f)
f_name = f_name.replace(" ","")
new_name = f'{f_name}{f_ext}'
os.rename(f, new_name)
|
#Result is 232792560
number = 20 * 19 * 9 * 17 * 8 * 15 * 14 * 13 * 6 * 11
i = 20
while 1:
i = i + 20
ok = 1
for x in range(1, 20):
if i % x != 0:
ok = 0
break
if ok == 1:
number = i
break
print "What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"
print number
|
""" Experiments with traing comma """
a = [1, 2, 3]
print len(a)
a2 = [1, 2, 3, ]
print len(a2)
t = ()
print type(t), len(t) # <type 'tuple'> 0
t2 = (1,)
print type(t2), len(t2) # <type 'tuple'> 1
t3 = (1)
print type(t3) # <type 'int'>
d = {1: '1', }
print len(d) # 1
|
# Runtime: 32 ms
# Memory Usage: 14 MB
# Given a column title as appear in an Excel sheet, return its corresponding column number.
# For example:
# A -> 1
# B -> 2
# C -> 3
# ...
# Z -> 26
# AA -> 27
# AB -> 28
# ...
# Input: "A"
# Output: 1
# Input: "AB"
# Output: 28
# Input: "ZY"
# Output: 701
class Solution:
def titleToNumber(self, s: str) -> int:
s = s[::-1]
ans = 0
for i, char in enumerate(s):
ans += (ord(char) - 64) * (26 ** i)
return ans
|
# Runtime: 596 ms
# Memory Usage: 38.1 MB
# Implement the StreamChecker class as follows:
# StreamChecker(words): Constructor, init the data structure with the given words.
# query(letter): returns true if and only if for some k >= 1, the last k characters queried
# (in order from oldest to newest, including this letter just queried) spell one of the words
# in the given list.
# Example:
# StreamChecker streamChecker = new StreamChecker(["cd","f","kl"]); // init the dictionary.
# streamChecker.query('a'); // return false
# streamChecker.query('b'); // return false
# streamChecker.query('c'); // return false
# streamChecker.query('d'); // return true, because 'cd' is in the wordlist
# streamChecker.query('e'); // return false
# streamChecker.query('f'); // return true, because 'f' is in the wordlist
# streamChecker.query('g'); // return false
# streamChecker.query('h'); // return false
# streamChecker.query('i'); // return false
# streamChecker.query('j'); // return false
# streamChecker.query('k'); // return false
# streamChecker.query('l'); // return true, because 'kl' is in the wordlist
class StreamChecker:
def __init__(self, words):
T = lambda: collections.defaultdict(T)
self.trie = T()
for w in words: reduce(dict.__getitem__, w[::-1], self.trie)['#'] = True
self.S = ""
self.W = max(map(len, words))
def query(self, letter):
self.S = (letter + self.S)[:self.W]
cur = self.trie
for c in self.S:
if c in cur:
cur = cur[c]
if cur['#'] == True:
return True
else:
break
return False
# Your StreamChecker object will be instantiated and called as such:
# obj = StreamChecker(words)
# param_1 = obj.query(letter)
|
# Runtime: 40 ms
# Memory Usage: 13.9 MB
# Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add
# spaces in s to construct a sentence where each word is a valid dictionary word. Return all such
# possible sentences.
# Note:
# The same word in the dictionary may be reused multiple times in the segmentation.
# You may assume the dictionary does not contain duplicate words.
# Input:
# s = "catsanddog"
# wordDict = ["cat", "cats", "and", "sand", "dog"]
# Output:
# [
# "cats and dog",
# "cat sand dog"
# ]
# Input:
# s = "pineapplepenapple"
# wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
# Output:
# [
# "pine apple pen apple",
# "pineapple pen apple",
# "pine applepen apple"
# ]
# Explanation: Note that you are allowed to reuse a dictionary word.
# Input:
# s = "catsandog"
# wordDict = ["cats", "dog", "sand", "and", "cat"]
# Output:
# []
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
if set(Counter(s).keys()) > set(Counter("".join(wordDict)).keys()):
return []
wordSet = set(wordDict)
dp = [[]] * (len(s)+1)
dp[0] = [""]
for endIndex in range(1, len(s)+1):
sublist = []
# fill up the values in the dp array.
for startIndex in range(0, endIndex):
word = s[startIndex:endIndex]
if word in wordSet:
for subsentence in dp[startIndex]:
sublist.append((subsentence + ' ' + word).strip())
dp[endIndex] = sublist
return dp[len(s)]
|
# Runtime: 80 ms
# Memory Usage: 14.4 MB
# Given an array A of non-negative integers, return an array consisting of all the even elements of
# A, followed by all the odd elements of A.
# You may return any answer array that satisfies this condition.
# Input: [3,1,2,4]
# Output: [2,4,3,1]
# The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
ans_even = []
ans_odd = []
for i in A:
if i%2==0:
ans_even.append(i)
else:
ans_odd.append(i)
return ans_even + ans_odd
|
# Author: Zoljargal Gatnumur
# Runtime: 40 ms
# Memory Usage: 14.3 MB
# Given an input string, reverse the string word by word.
# Example 1:
# Input: "the sky is blue"
# Output: "blue is sky the"
# Example 2:
# Input: " hello world! "
# Output: "world! hello"
# Explanation: Your reversed string should not contain leading or trailing spaces.
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(s.split()[::-1])
|
# Author: Zoljargal Gantumur
# Runtime: 20ms
# Memory Usage: 13.9MB
#Input: x = 1, y = 4
#Output: 2
#Explanation:
# 1 (0 0 0 1)
# 4 (0 1 0 0)
# β β
#The above arrows point to positions where the corresponding bits are different.
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
a = bin(x^y)[2:]
count = 0
for i in a:
if i == '1':
count+=1
return count
|
'''
Think of an iterator as a generator(fire hose of data)
It streams the data to the output and does not return a list
but rather an iterable stream of characters
'''
class alphabator:
def __init__(self, l):
self.lst = l
self.items = len(self.lst)
self.count = -1
def __iter__(self):
return self
def __next__(self):
try:
self.count += 1
self.val = self.lst[self.count]
if isinstance(self.val, int) and self.val in range(1, 27):
self.val = chr(96 + self.val).upper()
except IndexError:
print(StopIteration)
raise StopIteration
return self.val
if __name__ == "__main__":
m = [1, '2', 'A', 'b', 26, 19, 100, 1000001, 27]
print(alphabator(m))
print("alphabator is " + str(list(alphabator(m))))
|
'''
Created on Nov 26, 2013
@author: rduval
'''
# !C:\Python33
import random
from datetime import datetime
import datetime as dt
num = ""
inputMsg = "Input must be a number."
questions = []
def question(num):
question_num = num
correct = "wrong"
b = random.randrange(1, 11)
a = random.randrange(1, 10)
print("What is the sum of ", a, "and", b, "?")
correct_answer = a + b
start = datetime.now()
answ = input("Enter Answer: ")
while not answ.isdigit():
print(inputMsg)
answ = input("Enter a Number Answer: ")
stop = dt.datetime.now()
if int(answ) == correct_answer:
correct = "right"
diff = stop - start
result = (question_num, correct, diff.seconds, start, stop)
return result
if __name__ == '__main__':
test_start = datetime.now()
time_on_q = 0
for q in range(1, 3):
r = question(q)
print(r)
questions.append(r)
test_stop = datetime.now()
total_time = test_stop - test_start
print(questions)
for question in questions:
print("Question #%s took about %s seconds to complete and was %s." % (question[0], question[2], question[1]))
# (question[0],question[2],question[1]))
time_on_q = time_on_q + question[2]
# print(time_on_q)
print("You took %s seconds to finish the quiz." % total_time.seconds)
print("Your average time was %s seconds per question." % float(time_on_q / len(questions)))
|
'''
Created on Jul 30, 2012
@author: rduvalwa2
'''
#!/usr/local/bin/python3
"""factorial.py
two loops
outer loops, variable c counts upward
inner loop generates the factorial based on value of counter
The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. from WikiPedia
"""
counter = 0
factorial = 1
while (factorial < 1000):
print(factorial)
counter += 1
factorial = 1
for n in range (counter, 0, -1): # generate factorial
factorial = factorial * n
|
#!/usr/local/bin/python3
"""program input_counter.py
This program breaks input sentences into sets of words and tracks when
in order of discovery they were discovered
"""
discovery = 0
setLength = 0
set_s = set([]) # Empty set
dict_d = {} # Empty dict
sentence = input("Enter text: ")
while len(sentence) > 0: # Test for empty string
# list = split the string up and add to list
wordList = sentence.split() # split string up into words delimited by white space
# print(" The List: ", wordList) debug
for word in wordList:
set_s.add(word) #list.append but set.add
# print("The set:", set_s, "Length: ", len(set_s)) debug
if len(set_s) > setLength:
discovery += 1
dict_d[word] = discovery # add the word as index and value = discovery
setLength = len(set_s) # increment setLength
# print(dict_d) debug
for word in dict_d:
print(word, dict_d[word]) # print the index word and value
sentence = input("Enter text: ")
print("Finished")
|
"""
control.py: Creates queues, starts output and worker threads,
and pushes inputs into the input queue.
"""
from queue import Queue
from output import OutThread
from worker import WorkerThread
WORKERS = 10
inq = Queue(maxsize=int(WORKERS * 1.5))
outq = Queue(maxsize=int(WORKERS * 1.5))
ot = OutThread(WORKERS, outq)
ot.start()
for i in range(WORKERS):
w = WorkerThread(inq, outq)
w.start()
instring = input("Words of wisdom: ")
for work in enumerate(instring):
inq.put(work)
print("Start in Q size: ", inq.qsize())
for i in range(WORKERS):
inq.put(None)
inq.join()
print("Control thread terminating")
|
'''
Created on Apr 17, 2014
@author: rduvalwa2
'''
import unittest
from Py4_Homework13 import sstr, NumberSize
class TestSstr(unittest.TestCase):
def test_sstr(self):
s1 = sstr("abcde")
self.assertEqual(s1 << 0, 'abcde')
self.assertEqual(s1 >> 0, 'abcde')
self.assertEqual(s1 >> 2, 'deabc')
self.assertEqual(s1 << 2, 'cdeab')
self.assertEqual(s1 >> 5, 'abcde')
self.assertEqual(s1 << 5, 'abcde')
self.assertEqual((s1 >> 5) << 5, 'abcde')
def test_errorRightShift(self):
s1 = sstr("abcde")
try:
s1 >> 6
except NumberSize:
self.assertTrue(NumberSize, "Number too big")
def test_errorLeftShift(self):
s1 = sstr("abcde")
try:
s1 << 6
except NumberSize:
self.assertTrue(NumberSize, "Number too big")
if __name__ == "__main__":
unittest.main()
|
'''
https://docs.python.org/2.7/library/mmap.html
Created on Apr 26, 2014
@author: rduvalwa2
Here are your instructions:
Write a program that creates a:
1. ten megabyte data file in:
2. two different ways
3. time each method
The first technique should
- create a memory-mapped file and write the data by setting one chunk at a time
- using successively higher indexes
The second technique should
- create an empty binary file
- and repeatedly use the write() method to write a chunk of data
Show how the timings vary with the size of the chunk.
'''
import struct
import mmap
import sys
import os
import timeit
import time
class Homework15:
def firstTechnique(self, FileSize, Chunks, FileName):
start = time.clock()
self.fileName = FileName
self.fileSize = FileSize
self.chunks = Chunks
self.chunkSize = int(self.fileSize / self.chunks)
self.fmt = self.getFormat()
with open(self.fileName, "wb") as f:
f.write(b'\0' * self.fileSize) # have to define size of file
f.close()
with open(self.fileName, "r+b") as f:
mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_WRITE)
offset = 0
chunkLabel = 0
for c in range(self.chunks):
mm[offset:self.chunkSize + offset ] = self.packChunk(chunkLabel, b'*' * self.chunkSize)[1:]
offset = offset + self.chunkSize
chunkLabel += 1
if chunkLabel == 255:
chunkLabel = 0
"Prove mmap was written to"
# mm.tell()
# mm.seek(self.fileSize - int (self.fileSize/10))
# print("Print last 1/10 characters", mm.read())
# mm.seek(0)
# fileLength = len(mm.read(self.fileSize))
# print("End of write, File length ", fileLength, "Chunks ", self.chunks, "Chunk Size ", self.chunkSize)
sys.stdout.flush()
mm.close()
os.unlink(self.fileName)
end = time.clock()
return end - start / 1000
def secondTechnique(self, FileSize, Chunks, FileName):
start = time.clock()
self.fileSize = FileSize
self.chunks = Chunks
self.fileName = FileName
self.chunkSize = int(self.fileSize / self.chunks)
with open(self.fileName, "wb") as f:
f.write(b'')
f.close()
with open(self.fileName, "r+b") as f:
try:
mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
except ValueError:
# print("ValueError: cannot mmap an empty file")
f.close()
with open(self.fileName, "w+b") as f:
self.fmt = self.getFormat()
f.write(self.packChunk(0, b'\)' * self.chunkSize)[1:])
f.close()
with open(self.fileName, "r+b") as f:
chunkLabel = 0
for i in range(self.chunks):
mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_WRITE)
if mm.size() < self.chunkSize:
mm.resize(mm.size() + self.chunkSize)
mm.write(self.packChunk(chunkLabel, b'*' * self.chunkSize)[1:])
chunkLabel += 1
else:
mm.write(self.packChunk(chunkLabel, b'*' * self.chunkSize)[1:])
if chunkLabel == 255:
chunkLabel = 0
sys.stdout.flush()
mm.close()
end = time.clock()
return end - start / 1000
def packChunk(self, c, s):
"""Generate slot string from individual data elements."""
return struct.pack(self.fmt, c, s)
def getFormat(self):
# self.chunkSize = chunkSize
if self.chunkSize == 1: # 10000000 chunks
return b"B1s"
if self.chunkSize == 10: # 1000000 chunks
return b"B10s"
elif self.chunkSize == 104: # 100000 chunks
return b"B104s"
elif self.chunkSize == 1048: # 10000 chunks
return b"B1048s"
elif self.chunkSize == 10485: # 10000 chunks
return b"B10485s"
elif self.chunkSize == 20971:
return b"B20971s"
elif self.chunkSize == 52428:
return b"B52428s"
elif self.chunkSize == 104857: # 100 hunks
return b"B104857s"
elif self.chunkSize == 1048576: # 10 chunks
return b"B1048576s"
elif self.chunkSize == 10485760:
return b"B10485760s"
else:
sys.exit("Chunk Size not covered Exit")
if __name__ == "__main__":
import timeit
debug = False
timeResults = []
if debug == False:
chunks = [1, 10, 100, 1000, 10000 , 100000, 1000000, 10000000] # ,100000000]
file_size = 1024 * 1024 * 10
fileNameX = "meth1.txt"
fileNameY = "emptyFile.txt"
for chunk in chunks:
x = Homework15
y = Homework15
timeResults.append(("1st", chunk, x().firstTechnique(file_size, chunk, fileNameX)))
timeResults.append(("2nd", chunk, y().secondTechnique(file_size, chunk, fileNameY)))
for result in timeResults:
print(result)
if debug == True:
fileNameX = "meth1.txt"
fileNameY = "emptyFile.txt"
chunk = 100
file_size = 1024 * 1024 * 10
x = Homework15
print(x().firstTechnique(file_size, chunk, fileNameX))
# x = Homework15.firstTechnique(file_size,chunk,fileNameX)
# x.firstTechnique(file_size,chunk,fileNameX)
# y = Homework15().secondTechnique(file_size,chunk,fileNameY)
# print("Technique_1 ",timeit("x().firstTechnique(file_size,chunk,fileNameX)","from __main__ import x,files_size,chunk,fileNameX"))
# print("Technique_2 ",timeit("y","from __main__ import y"))
'''
Timeit did not work very well, it obviously was not timing correctly
('1st', 1, 0.126701843)
('2nd', 1, 0.22505519599999999)
('1st', 10, 0.26942779099999997)
('2nd', 10, 0.300107321)
('1st', 100, 0.336407595)
('2nd', 100, 0.353348258)
('1st', 1000, 0.390697299)
('2nd', 1000, 0.43394591699999996)
('1st', 10000, 0.492036647)
('2nd', 10000, 0.76424048)
('1st', 100000, 0.954846251)
('2nd', 100000, 3.472563362)
('1st', 1000000, 4.9907244649999996)
('2nd', 1000000, 29.650599777)
('1st', 10000000, 43.76100739)
('2nd', 10000000, 291.175604313)
'''
|
'''
Created on Mar 14, 2013
Question 1:
Write an expression that takes two lists of equal length, k and v, and produces a dict where the keys
are the elements of k and the corresponding values are the elements of v.
>>> keys = ['a', 'b', 'c']
>>> values = [1, 2, 3]
>>> dictionary = dict(zip(keys, values))
>>> print dictionary
'''
v = ['one', 'two', 'three', 'four', 'five', 'six', 'seven']
k = [1, 2, 3, 4, 5]
dick = dict(zip(k, v))
tup = zip(k, v)
for i in tup:
print(i)
print(dick)
print(sorted(dick))
|
#!/usr/local/bin/python3
""" multuple.py
formating problem """
myTuple = [(1,1),(2,2),(3,3),(5,5),(7,7),(11,11),(3,101),(101,33)]
for element in myTuple:
product = element[0] * element[1]
n = {'value': product, 'multiplicand': element[0], 'multiplier': element[1]}
print("{0[value]:4d} = {0[multiplicand]:3d} x {0[multiplier]:3d}".format(n))
|
'''
CHere are your instructions:
Modify the Subscriber.process() method so that the instance counts the number of times the method has been called.
If, after processing the current message, it has processed three messages, it unsubscribes itself.
Remove the unsubscribe code from the loop at the end of the main program, since it should no longer be necessary.
Insert print() statements in your modified program until you think you have worked out why it no longer operates correctly,
and see if you can suggest a way to fix it (whether or not you are able to implement your suggestion).
'''
class Publisher:
def __init__(self):
self.subscribers = []
def subscribe(self, subscriber):
if subscriber in self.subscribers:
raise ValueError("Multiple subscriptions are not allowed")
self.subscribers.append(subscriber)
def unsubscribe(self, subscriber):
if subscriber not in self.subscribers:
raise ValueError("Can only unsubscribe subscribers")
self.subscribers.remove(subscriber)
def publish(self, s):
for subscriber in self.subscribers:
# subscriber.process(s)
subscriber(s)
if __name__ == '__main__':
def multiplier(s):
print(2 * s)
class SimpleSubscriber:
def __init__(self, name, publisher):
# publisher.subscribe(self)
self.name = name
self.publisher = publisher
publisher.subscribe(self.process)
def process(self, s):
print(self, ":", s.upper())
def __repr__(self):
return self.name
publisher = Publisher()
publisher.subscribe(multiplier)
for i in range(6):
newsub = SimpleSubscriber("Sub" + str(i), publisher)
line = input("Input {}: ".format(i))
publisher.publish(line)
if len(publisher.subscribers) > 3:
publisher.unsubscribe(publisher.subscribers[0])
'''
Input 0: pub
pubpub
Sub0 : PUB
Input 1: and
andand
Sub0 : AND
Sub1 : AND
Input 2: sub
subsub
Sub0 : SUB
Sub1 : SUB
Sub2 : SUB
Input 3: and
Sub0 : AND
Sub1 : AND
Sub2 : AND
Sub3 : AND
Input 4: dub
Sub1 : DUB
Sub2 : DUB
Sub3 : DUB
Sub4 : DUB
Input 5: and
Sub2 : AND
Sub3 : AND
Sub4 : AND
Sub5 : AND
'''
|
"""This program fileTypeCounter.py reads in:
1. the files in the local directory into a list
2. it then counts the type of files
3. finally it prints out a report of the file types and each type count
"""
import glob
import os
def fileTypeCounter(path="."):
counts = {}
files = glob.glob(os.path.join(path, "*")) # get all files in path
for file in files:
if os.path.isfile(file):
path_ext = os.path.splitext(file)
if path_ext[1] in counts:
counts[path_ext[1]] += 1
else:
counts[path_ext[1]] = 1
print("File Extensions in:",os.path.abspath(path))
for i in counts:
print(i,":", counts[i])
return counts
|
'''
Created on Jan 19, 2014
@author: rduvalwa2
'''
class mapEx:
def init(self, mapp={'A':1, 'B':2}):
self.inA = {}
def upDate(self, key, value):
self.inA.update({key:value})
def removeKey(self, key):
del self.inA[key]
def printInit(self):
for key, item in self.inA.items():
print(key, " : ", item)
if __name__ == '__main__':
myMap = {'Aa':100, 'Bb':200, 'Cc':300}
for key, item in myMap.items():
print(key, " : ", item)
print(myMap)
aMap = mapEx(myMap)
# a(myMap)
aMap.printInit()
'''
>>> inA = {'Aa':100,'Bb':200,'Cc':300}
>>> for key in inA:
... print(inA[key])
...
100
200
300
>>> for key in inA:
... print(key , inA[key])
...
Aa 100
Bb 200
Cc 300
>>> for key in inA:
... print(key , inA[key])
...
Dd 400
Aa 100
Bb 200
Cc 300
D d
>>> inA.update({'Dd':400})
>>> for key in inA:
... print(key , inA[key])
...
Dd 400
Cc 300
Bb 200
D d
Aa 100
>>> inA.update({'Dd':450})
>>> for key in inA:
... print(key , inA[key])
...
Dd 450
Cc 300
Bb 200
D d
Aa 100
>>> for key, item in inA.items():
... print(key, ":" , item)
...
Dd : 450
Cc : 300
Bb : 200
D : d
Aa : 100
>>> del inA['D']
>>> for key, item in inA.items():
... print(key, ":" , item)
...
Dd : 450
Cc : 300
Bb : 200
Aa : 100
>>> inA.update({'Ee':540})
>>> for key, item in inA.items():
... print(key, ":" , item)
...
Dd : 450
Cc : 300
Bb : 200
Aa : 100
Ee : 540
>>>
'''
|
"""
Test list-of-list array implementations using tuple subscripting.
"""
import unittest
import arr_dict3D
class TestArray(unittest.TestCase):
def test_zeroes(self):
for N in range(4):
a = arr_dict3D.array(N, N, N)
for i in range(N):
for j in range(N):
for d in range(N):
self.assertEqual(a[i, j, d], 0)
def test_identity(self):
for N in range(4):
a = arr_dict3D.array(N, N, N)
for i in range(N):
a[i, i, i] = 1
for i in range(N):
for j in range(N):
for d in range(N):
print("d is ", d)
print("i is", i)
print("j is ", j)
print(a[i, j, d])
print("i==j==d", i == j == d)
self.assertEqual(a[i, j, d], i == j == d)
def _index(self, a, r, c, d):
return a[r, c, d]
def test_key_validity(self):
a = arr_dict3D.array(10, 10, 10)
self.assertRaises(KeyError, self._index, a , -1, 1, 1)
self.assertRaises(KeyError, self._index, a , 10, 1, 1)
self.assertRaises(KeyError, self._index, a , 1, -1, 1)
self.assertRaises(KeyError, self._index, a , 1, 10, 1)
if __name__ == "__main__":
unittest.main()
|
'''
Created on May 25, 2014
@author: rduvalwa2
'''
from timeit import timeit
from pprint import pprint
"""Callable Example
Function and Method Callls
The __call__() method is interestingβits name implies that it has something to do with function calling, and this is correct.
The interpreter calls any callable object by making use of its __call__() method. You can actually call this method directly if you want to; it's exactly
the same as calling the function directly.
"""
def f(x):
x = x ** 2
print("f1({}) called".format(x))
print(f.__call__(23)) # should be equivalent to f1(23)
# f1(23) called
f(23)
if __name__ == "__main__":
""" Time it example of callable function"""
print(timeit("for x in range(3): f(x)", "from __main__ import f", number=1))
'''
number = 2
f1(529) called
None
f1(529) called
f1(0) called
f1(1) called
f1(4) called
f1(0) called
f1(1) called
f1(4) called
7.986299999999946e-05
number =1
f1(529) called
None
f1(529) called
f1(0) called
f1(1) called
f1(4) called
6.843699999999758e-05
'''
|
#!/usr/local/bin/python3
"""secret_code.py
this code uses simple encoding, adding 1 to the original ordinal values of the input letter for the output
and making that the output value. The output string is then reversed """
debug = False
user_input = input('Enter text: ')
user_output = []
r_out = []
for letter in user_input:
num_out = ord(letter)+1
user_output.append(chr(num_out))
print("Input was: " + user_input)
if debug:
mystring = "".join(user_output)
print(mystring)
for i in reversed(user_output):
r_out.append(i)
rev_string = "".join(r_out)
else:
for i in reversed(user_output):
r_out.append(i)
rev_string = "".join(r_out)
print(rev_string)
|
'''
Cres1ted on s1pr 16, 2014
@s1uthor: rduvs1lws12
http://sts1ckoverflow.com/questions/2267466/overlos1ding-s1ugmented-s1rithmetic-s1ssignments-in-python
http://www.decs1ls1ge.info/en/python/print_list
http://sts1ckoverflow.com/questions/6771428/most-efficient-ws1y-to-reverse-s1-numpy-s1rrs1y
http://sts1ckoverflow.com/questions/931092/reverse-s1-string-in-python
http://teches1rth.net/python/index.php5?title=Python:Bs1sics:Slices
'''
class NumberSize(Exception):
def __init__(self, message):
self.message = message
class sstr(str):
def __init__(self, inString):
self.myString = inString
self.inarray = list(self.myString)
self.outarray = []
def __lshift__(self, num):
if num <= 0 | num == len(self.inarray):
self.myString = ''.join(self.inarray)
return self
elif num > len(self.inarray):
raise NumberSize("Number too big")
else:
self.outarray = list(self.myString[num:len(self.myString)])
for i in range(num):
self.outarray.append(self.inarray[i])
return ''.join(self.outarray)
def __rshift__(self, num):
if num <= 0 | num == len(self.inarray):
return self
elif num > len(self.inarray):
raise NumberSize("Number too big")
else:
self.inarray = list(self.myString)
self.outarray = list(self.myString[len(self.inarray) - num:])
for i in range(len(self.inarray) - num):
self.outarray.append(self.inarray[i])
return "".join(self.outarray)
if __name__ == "__main__":
s1 = sstr("abcde")
print("s1 << 0", s1 << 0)
print("Type ", type(s1 << 0))
print("s1 << 1", s1 << 1)
print("s1 << 2", s1 << 2)
print("s1 << 3", s1 << 3)
print("s1 << 4", s1 << 4)
print("s1 << 5", s1 << 5)
print("Type" , type(s1 << 5))
s1 << 6
print("s1 << 6", s1 << 6)
print("s1 >> 0", s1 >> 0)
print("s1 >> 1", s1 >> 1)
print("s1 >> 2", s1 >> 2)
print("s1 >> 3", s1 >> 3)
print("s1 >> 5", s1 >> 5)
print("Type" , type(s1 >> 5))
s1 >> 6
print(((s1 >> 5) << 5 == 'abcde'))
|
"""Compare my title function to str.title()"""
import unittest
def title(s):
"How closes is this function to str.title()"""
the_return = []
for word in s.split():
new_word = ''
for ch in word:
if ch[0]:
new_word + ch.upper()
else:
new_word + ch.lowere()
the_return.append(word.title())
return ' '.join(the_return)
class TestTitle(unittest.TestCase):
def test_good_match(self):
str = 'moby dick And Captian Ahab'
message = title(str) + " does not match " + str.title()
self.assertEqual(title(str), str.title(), message)
def test_single_letter_match(self):
str = 'a'
message = title(str) + " does not match " + str.title()
self.assertEqual(title(str), str.title(), message)
def test_apostophe_match(self):
str = 'Don\'t look now'
message = title(str) + " does not match " + str.title()
self.assertEqual(title(str), str.title(), message)
def test_not_lower_match(self):
str = 'What gooD IS aLL thIs EFFORT.'
message = title(str) + " matched lower " + str.lower()
self.assertNotEqual(title(str), str.lower(), message)
""" force failure for example look
def test_not_upper_match(self):
str = 'What gooD IS aLL thIs EFFORT?'
message = title(str) + " matched upper " + str.upper()
self.assertEqual(title(str), str.upper(), message)
"""
if __name__ == "__main__":
unittest.main()
|
#snake water and gun project -1
import random
def gamewin(comp, user):
if comp == user:
return None
elif comp == 's': #WHEN COMPUTER CHOOSES
if user == 'g':
return True
elif user == 'w':
return False
elif comp == ' w': #WHEN COMPUTER CHOOSES WATER
if user == 's':
return True
elif user == 'g':
return False
elif comp == 'g': #WHEN COMPUTER CHOOSES GUN
if user == 'w':
return True
elif user == 's':
return False
print("****YOU ARE PLAYING WITH THE COMPUTER!!....")
print("****CHOOSE SNAKE with (s),WATER with (w),GUN with (g) when your turn comes...")
width = 50
print(" LET'S START THR GAME!! ".center(width,"*"))
print("Computer's turn: CHOOSE SNAKE(s), WATER(w), GUN(g)?: " )
randomNo = random.randint(1,3)
if randomNo == 1:
comp = 's'
elif randomNo == 2:
comp = 'w'
if randomNo == 3:
comp = 'g'
user = input("Your's turn:CHOOSE SNAKE(s), WATER(w), GUN(g)?: ")
print(f"COMPUTER chooses:{comp}")
print(f"YOU chooses:{user}")
w = "ππ"
f = "π₯π₯"
t = "π"
result = gamewin(comp, user)
if result == None:
print ("RESULTS: THERE IS A TIE!!" + t)
elif result == True:
print ("RESULTS: YOU WON!!"+ w)
if result == False:
print ("RESULTS: YOU LOSE!!"+ f)
|
# Hanna Magan
# Course: CS151-02, Dr. Rajeev
# Date: 10/4/21
# Programming Assignment: 2
# Program Inputs: Month (1-12) and year
# Program Outputs: Number of days in the month
month = input("Input month (1-12):")
year = input("Input year")
leapYear = False
#Program calculates if the year is a leap year.
if year % 4 == 0:
leapYear = True
#Program calculates if the year is a leap year.
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
print(" 31 days .")
elif month == 4 or month == 6 or month == 9 or month == 11:
print("30 days .")
elif month == 2 and year % 4:
print(" 29 days.")
elif month == 2 and not year % 4:
print("28 days in month.")
|
from macros import BOARDW
from macros import BOARDH
# FUNCTIONS
def drawBoard(board):
for row in board:
print("\n" + '-' * 13 + "\n| ", end = "")
for char in row:
print(char + " | ", end = "")
print("\n" + '-' * 13, end = '\n\n')
def gameover():
return 0
def checkGameover():
return 0
# VARIABLES
class player:
turn = False
char = 'X'
board = [[' ', ' ', ' '],
[' ', ' ' ,' '],
[' ', ' ', ' ']]
# MAIN
print(" Welcome to Tic-Tac-Toe!\n" + "-" * 25)
while (True):
print("Select the your character (X/o):", end = ' ')
usr = input()
if (usr != 'x' and usr != 'X' and usr != 'o' and usr != 'O'):
print("Please input X or O")
else:
player.char = usr.upper()
if usr == 'o' or usr == 'O':
player.turn = False
break
while (not checkGameover):
drawBoard(board)
|
# Importing the required Modules
import os
import csv
import sys
# Assuming CSV file and main.py files will be stored in the same directory
# Defining the file object
# os.path.join(sys.path[0] pointing to the same path as the main.py exists in
budget_data_csv = os.path.join(sys.path[0], 'budget_data.csv')
# Declaring the Vaiables and assiging initial values
total_months = 0
total_amount = 0
row_count = 0
profit_losses_value = 0
profit_losses_change = 0
time_period = []
profit_losses = []
# Opening the file for windows
with open(budget_data_csv, newline="", encoding='utf-8') as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
#Reading the header row to skip
csv_header = next(csvreader)
# Reading from second row to last row to get the expected output
for row in csvreader:
#Increasing the number months by 1 for each record in the file
total_months += 1
# Adding each row's amount
total_amount += int(row[1])
if row_count == 0:
profit_losses_value = int(row[1])
elif row_count != 0:
profit_losses_change =int(row[1]) - profit_losses_value
profit_losses.append(profit_losses_change)
time_period.append(row[0])
row_count += 1
profit_losses_value = int(row[1])
greatest_increase = max(profit_losses)
greatest_descrease = min(profit_losses)
greatest_increase_index = profit_losses.index(greatest_increase)
greatest_descrease_index = profit_losses.index(greatest_descrease)
greatest_increase_date = time_period[greatest_increase_index]
greatest_decrease_date = time_period[greatest_descrease_index]
avaerage_change = sum(profit_losses) / len(profit_losses)
#Printing Output to the terminal
print('Financial Analysis')
print('------------------------------------')
print(f"Total Months: {str(total_months)}")
print(f"Total Amount: {str(total_amount)}")
print(f"Avarage Change: {str(round(avaerage_change,2))}")
print(f"Greatest Increase in Profits: {greatest_increase_date} (${str(greatest_increase)})")
print(f"Greatest Decrease in Profits: {greatest_decrease_date} (${str(greatest_descrease)})")
# Exporting the data into a text file
# Defining the file name and path
output_file = os.path.join(sys.path[0], 'Financial_Analysis_Summary.txt')
# Opening the file and writing into the file
with open(output_file,"w") as output_file:
output_file.write('Financial Analysis\n')
output_file.write('------------------------------------\n')
output_file.write(f"Total Months: {str(total_months)}\n")
output_file.write(f"Total Amount: {str(total_amount)}\n")
output_file.write(f"Avarage Change: {str(round(avaerage_change,2))}\n")
output_file.write(f"Greatest Increase in Profits: {greatest_increase_date} (${str(greatest_increase)})\n")
output_file.write(f"Greatest Decrease in Profits: {greatest_decrease_date} (${str(greatest_descrease)})\n")
# End of the program
|
from tkinter import*
from tkinter.messagebox import*
import math as m
# creating a window
window=Tk()
window.title('My Calculator')
window.geometry('380x400')
#text label
headinglabel=Label(window , text='CALCULATOR' , font=('Courier New ' , 25 , 'bold'))
headinglabel.pack(side=TOP)
#Text field
textfield=Entry(window,font=('Courier new' , 16 , 'bold') , justify=CENTER)
textfield.pack(side=TOP , pady=10,padx=10 , fill=X)
#frame
frame=Frame(window)
frame.pack(side=TOP)
#function
def click(event):
b=event.widget
text=b['text']
if(text=='='):
try:
ex=textfield.get()
answer=eval(ex)
textfield.delete(0,END)
textfield.insert(0,answer)
except Exception as e:
print('error',e)
showerror('error',e)
return
textfield.insert(END , text)
def all_clr():
textfield.delete(0,END)
def clr():
ex=textfield.get()
ex=ex[0:len(ex)-1]
textfield.delete(0,END)
textfield.insert(0,ex)
#button
temp=1
for i in range(0,3):
for j in range(0,3):
btn=Button(frame , text=str(temp) , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4)
btn.grid(row=i , column=j , padx=5 , pady=5)
temp+=1
btn.bind('<Button-1>' ,click)
zerobtn = Button(frame , text='0' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4)
zerobtn.grid(row=3 , column=0 , padx=5 , pady=5)
dotbtn = Button(frame , text='.' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4)
dotbtn.grid(row=3 , column=1 , padx=5 , pady=5)
eqlbtn = Button(frame , text='=' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4)
eqlbtn.grid(row=3 , column=2 , padx=5 , pady=5)
addbtn = Button(frame , text='+' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4)
addbtn.grid(row=0 , column=3 , padx=5 , pady=5)
subbtn=Button(frame , text='-' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4)
subbtn.grid(row=1 , column=3 , padx=5 , pady=5)
mulbtn=Button(frame , text='*' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4)
mulbtn.grid(row=2 , column=3 , padx=5 , pady=5)
divbtn=Button(frame , text='/' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4)
divbtn.grid(row=3 , column=3 , padx=5 , pady=5)
clrbtn=Button(frame , text='<--' , font=('Courier New', 16 , 'bold') ,width=12 ,bd=4 , command =clr)
clrbtn.grid(row=4 , column=0 , pady=5 , columnspan=2)
allclrbtn=Button(frame , text='AC' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4 , command=all_clr)
allclrbtn.grid(row=4 , column=2 , padx=5 , pady=5)
#binding all button
addbtn.bind('<Button-1>' ,click)
subbtn.bind('<Button-1>' ,click)
mulbtn.bind('<Button-1>' ,click)
divbtn.bind('<Button-1>' ,click)
dotbtn.bind('<Button-1>' ,click)
eqlbtn.bind('<Button-1>' ,click)
zerobtn.bind('<Button-1>' ,click)
def enterClick(event):
print('hi')
e = Event()
e.widget = equalBtn
click(e)
textfield.bind('<Return>', enterClick)
#################################################################################
#function of scientific
scframe=Frame(window)
sqrtbtn=Button(scframe , text='β' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4 )
sqrtbtn.grid(row=0, column=0 )
powbtn=Button(scframe , text='^' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4)
powbtn.grid(row=0 , column=1 )
factbtn=Button(scframe , text='x!' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4 )
factbtn.grid(row=0 , column=2 )
radbtn=Button(scframe , text='rad' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4 )
radbtn.grid(row=0 , column=3 )
degbtn=Button(scframe , text='deg' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4 )
degbtn.grid(row=1 , column=0 )
sinbtn=Button(scframe , text='sinΞ' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4 )
sinbtn.grid(row=1 , column=1 )
cosbtn=Button(scframe , text='cosΞ' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4 )
cosbtn.grid(row=1 , column=2 )
tanbtn=Button(scframe , text='tanΞ' , font=('Courier New', 16 , 'bold') ,width=5 ,bd=4 )
tanbtn.grid(row=1 , column=3 )
normalcalc = True
def calculate_sc(event):
print('btn..')
btn = event.widget
text=btn['text']
print(text)
ex=textfield.get()
answer = ''
if text == 'deg':
answer=str(m.degrees(float(ex)))
elif text == 'rad':
answer=str(m.radians(float(ex)))
elif text == 'x!':
answer= str(m.factorial(int(ex)))
elif text == 'sinΞ':
answer = str(m.sin(m.radians(int(ex))))
elif text == 'cosΞ':
answer = str(m.cos(m.radians(int(ex))))
elif text == 'tanΞ':
answer= str(m.tan(m.radians(int(ex))))
elif text == 'β':
answer= m.sqrt(int(ex))
elif text == '^':
print('pow')
base,pow=ex.split('.')
print(base)
print(pow)
answer=m.pow(int(base),int(pow))
textfield.delete(0, END)
textfield.insert(0, answer)
def sc_click():
global normalcalc
if normalcalc:
frame.pack_forget()
scframe.pack(side=TOP)
frame.pack(side=TOP)
window.geometry('380x500')
print('scientific')
normalcalc=False
else:
print('normal')
scframe.pack_forget()
window.geometry('380x400')
normalcalc=True
#binding sc button
sqrtbtn.bind("<Button-1>", calculate_sc)
powbtn.bind("<Button-1>", calculate_sc)
radbtn.bind("<Button-1>", calculate_sc)
factbtn.bind("<Button-1>", calculate_sc)
degbtn.bind("<Button-1>", calculate_sc)
sinbtn.bind("<Button-1>", calculate_sc)
cosbtn.bind("<Button-1>", calculate_sc)
tanbtn.bind("<Button-1>", calculate_sc)
menubar=Menu(window)
mode=Menu(menubar , font=('',10) , tearoff=0)
mode.add_checkbutton(label='Scientific Calculator' , command=sc_click)
menubar.add_cascade(label='Mode' , menu=mode)
window.config(menu=menubar)
window.mainloop()
|
#Q.1- Write a program to create a tuple with different data types and do the following operations.
#1. Find the length of tuples
keyword=(2,5,3,'Aman','Deep')
print(len(keyword))
#Q.2-Find largest and smallest elements of a tuples.
numbers=(3,4,6,2,43,)
print(max(numbers))
print(min(numbers))
#Q.3- Write a program to find the product of all elements of a tuple.
tuple_elements=(1*3*7,5*8*5)
print(tuple_elements)
#Q.1- Create two set using user defined values.
#1. Calculate difference between two sets.
set_a=set([1,2,4,5,])
set_b=set([4,5,])
set_final=set_a-set_b
print(set_final)
#2. Compare two sets.
set_a=set((1,2,3,4,5,6,7,8,9))
set_b=set((2,3,4,5))
set_c=set_a>=set_b
set_d=set_a<=set_b
print(set_c)
print(set_d)
#3. Print the result of intersection of two sets.
set_e=set_a&set_b
print(set_e)
#Q.1- Create a dictionary to store name and marks of 10 students by user input.
user_name=input("Enter Your Name")
user_age=input("Enter Your Age")
user_data={'Name':user_name,'Age':user_age}
print(user_data)
#Q.3- Count the number of occurrence of each letter in word "MISSISSIPPI". Store count of every letter with the letter in a dictionary.
keyword=("MISSISSIPPI")
check_m=keyword.count("M")
check_i=keyword.count("I")
check_s=keyword.count("S")
check_p=keyword.count("P")
keyword_result={'Numbers Of M':check_m,'Numbers Of I':check_i,'Numbers Of S':check_s, 'Numbers Of p':check_p,}
print(keyword_result)
|
#:: Insertion sort with a complexity of O(n2)
#:: basically you are partioning the array into a sorted and unsorted part
def insertionSort(array):
for i in range(1, len(array)):
value = array[i]
hole = i
while hole > 0 and array[hole-1] > value:
array[hole] = array[hole-1]
hole = hole-1
array[hole] = value
a = [1, 3, 4, 6, 0, 8, 7, 4, 4, 5, 6,7]
# selectionSort(a)
insertionSort(a)
print(a)
|
import random
"""This program plays a game of Rock, Paper, Scissors between two Players,
and reports both Player's scores each round."""
moves = ['rock', 'paper', 'scissors']
class Player:
def move(self):
return 'rock'
def learn(self, my_move, their_move):
self.their_move = their_move
self.my_move = my_move
class RandomPlayer(Player):
def move(self):
return random.choice(moves)
class HumanPlayer(Player):
def move(self):
while True:
human_move = input("rock, paper, scissors?")
if human_move in moves:
return human_move
break
else:
print("invalid move, try again")
class ReflectPlayer(Player):
def __init__(self):
Player.__init__(self)
self.their_move = None
def move(self):
if self.their_move is None:
return random.choice(moves)
else:
return self.their_move
class CyclePlayer(Player):
def __init__(self):
Player.__init__(self)
self.my_move = None
def move(self):
if self.my_move is None:
return random.choice(moves)
else:
index = moves.index(self.my_move) + 1
if index == len(moves):
index = 0
return moves[index]
def beats(one, two):
return ((one == 'rock' and two == 'scissors') or
(one == 'scissors' and two == 'paper') or
(one == 'paper' and two == 'rock'))
class Game:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
self.score_p1 = 0
self.score_p2 = 0
def play_round(self):
move1 = self.p1.move()
move2 = self.p2.move()
print(f"Player 1: {move1} Player 2: {move2}")
self.p1.learn(move1, move2)
self.p2.learn(move2, move1)
if beats(move1, move2):
print("Player 1 Wins!")
self.score_p1 += 1
elif move1 == move2:
print("Tie!")
else:
print("Player 2 Wins!")
self.score_p2 += 1
print(self.score_p1)
print(self.score_p2)
def play_game(self):
print("Game start!")
while True:
try:
rounds = int(input("How many rounds?"))
for round in range(rounds):
print(f"Round {round+1}:")
self.play_round()
if self.score_p1 > self.score_p2:
print("Player 1 Wins!")
print("Game over!")
break
elif self.score_p2 > self.score_p1:
print("Player 2 Wins!")
print("Game over!")
break
else:
print("Its a tie!")
print("Game over!")
break
except ValueError:
print("invalid number, try again")
if __name__ == '__main__':
game = Game(HumanPlayer(), random.choice(
[CyclePlayer(), ReflectPlayer(), RandomPlayer(), Player()]))
game.play_game()
|
#!/usr/bin/python3
################################################################
#Let the user know what the program does and what info it needs#
################################################################
print("Welcome to Mr. BMI")
#########################################################################
#Get height in feet and inches, if it is only inches then put 0 for feet#
#########################################################################
print("Enter your height. First enter feet then inches")
feet= input("Feet: ")
inches= input("Inches: ")
######################
#Get weight in pounds#
######################
print("Enter your weight in pounds")
weight= input("Pounds: ")
############################################
#convert into kilograms and meters squared#
#1meter=39.3701 inches #
#1kg = 2.2 pounds #
#use int() to convert string to integer #
############################################
feet2inches= int(feet) * 12
totalinches= int(inches) + feet2inches
meters= totalinches / 39.3701
kilograms = int(weight) / 2.2
###############
#calculate bmi#
###############
bmi = kilograms / (meters * meters)
#######################
#round to two decimals#
#######################
bmi = round(bmi,0)
####################################################
#Create a list to hold the different health status'#
####################################################
chartlist = ['Underweight','Healthy','Overweight','Obese','Extreme Obese']
###################################
#Initiate variable for conditional#
###################################
status=''
##########################################
#check bmi condition to get health status#
##########################################
if bmi<=18:
status = chartlist[0]
elif bmi>18 and bmi<=24:
status = chartlist[1]
elif bmi>24 and bmi<=29:
status = chartlist[2]
elif bmi>29 and bmi<=39:
status= chartlist[3]
else:
status = chartlist[4]
###################################################################
#print out the results. Make sure to convert integers into strings#
###################################################################
print("Your BMI: " + str(bmi) + " and you are " + status)
|
#This program downloads the data from the last 2 years of 13F-HR filings from a pre-selected group of hedge funds.
#Each funds filings will be saved in a .json file contained in a folder called 'filings' in the working directory.
import auto_run as ar
import demo_run as dr
def run_auto_or_demo():
print("Type demo and press Enter if you want to try demo.")
print("Type auto and press Enter if you want the code to all run automatically.")
auto_or_demo = str(input())
auto_or_demo = auto_or_demo.upper()
if(auto_or_demo == "AUTO"):
ar.run_auto()
elif (auto_or_demo == "DEMO"):
dr.run_demo()
else:
run_auto_or_demo()
run_auto_or_demo()
|
__author__ = '[email protected] <asfmegas.github.io>'
import sys
try:
import sqlite3
sqlite3.version
except Exception as erro:
print('Problema com o sqlite3. Verifique se ele estΓ‘ instalado.')
sys.exit()
class Database(object):
def __init__(self):
self.db = None
self.cursor = None
self.__conection()
def __conection(self):
try:
self.db = sqlite3.connect(r'dados.db')
self.cursor = self.db.cursor()
except Exception as erro:
print('Erro ao tentar conexΓ£o com banco de dados:', erro)
print('Tipo do erro:', type(erro))
def createTable(self):
try:
self.cursor.execute("CREATE TABLE IF NOT EXISTS snake (id int UNIQUE, score_total int, shoots int, hits int, mode int, data varchar(30))")
except Exception as erro:
print('Erro ao criar tabela:', erro)
print('Tipo de erro:', type(erro))
def saveData(self, ID=1, pontos=0, tentativas=0, acertos=0, modo=5, data='01/01/1990'):
try:
self.cursor.execute("INSERT INTO snake VALUES (?, ?, ?, ?, ?, ?)", (ID, pontos, tentativas, acertos, modo, data,))
self.db.commit()
except Exception as erro:
print('Erro ao salvar dados:', erro)
print('Tipo de erro:', type(erro))
def closeConnection(self):
try:
self.cursor.close()
self.db.close()
except Exception as erro:
print('Erro ao tentar fechar conexao:', erro)
print('Tipo de erro:', type(erro))
def getList(self):
try:
return self.cursor.execute('SELECT * FROM snake ORDER BY score_total DESC')
except Exception as erro:
print('Erro ao listar dados:', erro)
print('Tipo de erro:', type(erro))
return False
def getTotal(self):
count = 0
try:
dados = self.cursor.execute('SELECT * FROM snake')
for linha in dados:
count += 1
return count
except Exception as erro:
print('Erro ao listar dados:', erro)
print('Tipo de erro:', type(erro))
return count
|
z=input("Enter your mRNA: ")
b=input("Enter your DNA: ")
print("/////////////////////////////////////////////////////////////////////////")
#counts all the ATCG's of mRNA
Z=z .count("G")
c=z .count("C")
P=z .count("A")
O=z .count("T")
#counts all the ATCG's of DNA
B=b .count("G")
D=b .count("C")
K=b .count("A")
M=b .count("T")
#makes a sum to count up the GC's for mRNA
H= int(Z) + int(c)
#makes a sum to count up the GC's for DNA
G= int(B) + int(D)
#makes a sum to count up all the ATCG's for mRNA
Q= int(Z) + int(c) + int(P) + int(O)
#makes a sum to count up all the ATCG's for DNA
W= int(B) + int(D) + int(K) + int(M)
#prints all the info of the sums above
print("Amount of GC in mRna:")
print(H)
print("Amount of GC in DNA:")
print(G)
print("Full size mRna:")
print(Q)
print("Full size DNA:")
print(W)
#divides the amount of GC's mRNA by the full size and makes it an precantage
F= int(H)/int(Q)*int(100)
print("GC% mRna:")
print(F,"%")
#divides the amount of GC's DNA by the full size and makes it an precantage
f= int(G)/int(W)*int(100)
print("GC% DNA:")
print(f,"%")
#divides DNA size by mRNA size
L= int(W)/int(Q)
print("The amount of times mRNA fits in DNA:")
print(L)
#shows difference in length of DNA and mRNA
#by subtracting the mRNA size of the DNA size
l= int(W)-int(Q)
print("Difference in length between DNA en mRna:")
print(l)
|
print("Give me an amount of money in whole ponds and I will tell you how many notes and/or coins it would convert to:")
cash = int(input("Enter an amount of money in whole ponuds: Β£"))
twenty = cash // 20
remainder = cash % 20
ten = remainder // 10
remainder = remainder % 10
five = remainder // 5
remainder = remainder % 5
two = remainder // 2
remainder = remainder % 2
one = remainder
print("|x{0} Β£20 note(s)|x{1} Β£10 note(s)|x{2} Β£5 note(s)|x{3} Β£2 coin(s)|x{4} Β£1 coin(s)".format(twenty, ten, five, two, one))
|
#Paul Njenje
#15/09/2014
#Class_exercise Revision
#1
#ask for 4 numbers
number1 = int(input("Enter a number: "))
number2 = int(input("Enter another number: "))
number3 = int(input("Enter another one: "))
number4 = int(input("Enter one last number: "))
#create a variable that is the sum of the 4 numbers
answer1 = number1 + number2 + number3 + number4
#display the numbers
print("The sum of your numbers is {0}.".format(answer1))
|
import csv
from datetime import datetime, timedelta
def get_data(date_start, date_end):
"""
Get meter usage data for between the start and end date
"""
# csv filename
filename = "meterusage.csv"
# user specified start date
start = datetime.strptime(date_start, '%Y-%m-%d')
# user specified end date
end = datetime.strptime(date_end, '%Y-%m-%d')
# add 1 day to end date to make it inclusive
end += timedelta(days=1, minutes=-15)
# initialize return dictionary
usage_dict = {}
# open csv file
with open(filename, 'r') as meterusage_file:
meterusage_reader = csv.reader(meterusage_file)
# skip header row
next(meterusage_reader)
# loop through all rows
for row in meterusage_reader:
datetime_obj = datetime.strptime(row[0], "%Y-%m-%d %H:%M:%S")
# if datetime falls within range
if datetime_obj >= start and datetime_obj <= end:
date = datetime_obj.date().strftime("%Y-%m-%d")
time = datetime_obj.time().strftime("%H:%M:%S")
# add to dictionary
if date in usage_dict:
usage_dict[date].append({'time': time, 'value': row[1]})
else:
usage_dict[date] = [{'time': time, 'value': row[1]}]
# return dictionary formatted as a string
if not usage_dict:
return str("")
return str(usage_dict)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.