Skip to content

yaniv_HW #71

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions content/week05/5.1.no_vinnigrete.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import random
from datetime import datetime, timedelta
import pytest
import builtins


def no_vinnigrete(date1: str, date2: str) -> str:
'''
Asks the user for two dates and returns a random date between them.
If the random date is a Monday, it returns a message saying that there is no vinegret sauce for you.
:return: str, random date or message
'''

rand_date = get_random_date(date1, date2)

if datetime.strptime(rand_date, "%Y-%m-%d").weekday() == 0: # 0 is monday
return f'\nthis date:{rand_date} is a monday! no vinegret sauce for you!'
return f'Random date : {rand_date}'


def get_random_date(date1: str, date2: str) -> str:
'''
returns a random date between date1 and date2
:param date1: str, format: 'YYYY-MM-DD'
:return str, format: 'YYYY-MM-DD'
'''
try:
date1 = datetime.strptime(date1, "%Y-%m-%d")
date2 = datetime.strptime(date2, "%Y-%m-%d")
except ValueError:
raise ValueError('Invalid date format, please use "YYYY-MM-DD"')

min_date, max_date = sorted([date1, date2])
delta = max_date - min_date
random_date = min_date + timedelta(days=random.randint(0, delta.days))
return random_date.strftime("%Y-%m-%d")


def test():

start_date = datetime.strptime('2020-12-31', '%Y-%m-%d')
end_date = datetime.strptime('2025-01-01', '%Y-%m-%d')
rand_test = get_random_date('2020-12-31', '2025-01-01')
rand_test = datetime.strptime(rand_test, '%Y-%m-%d')

assert rand_test >= start_date and rand_test <= end_date
assert get_random_date('2025-01-01', '2025-01-01') == '2025-01-01'
assert no_vinnigrete('2024-05-06', '2024-05-06') == '\nthis date:2024-05-06 is a monday! no vinegret sauce for you!'
assert no_vinnigrete('2024-05-06', '2024-05-06')

with pytest.raises(ValueError): # I tryed pytest just for fun
get_random_date('2025-01-01', '20251-01')

print('All test cases passed !\n')


if __name__ == '__main__':
test()
print('Enter two dates in format "YYYY-MM-DD"')
date1 = input('Enter date1: ')
date2 = input('Enter date2: ')
rand_date = no_vinnigrete(date1, date2)
print(rand_date)
25 changes: 25 additions & 0 deletions content/week05/5.1.thats_the_way.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import os


def thats_the_way(directory_path: str) -> list[str]:
'''
Returns a list of files starting with 'deep' in the directory
:param directory_path: str, path to the directory
:return: list of str, files starting with 'deep'
'''
if not os.path.exists(directory_path):
raise FileNotFoundError(f'{directory_path} not found')

return [f for f in os.listdir(directory_path) if f.startswith('deep')]


if __name__ == '__main__':

try:
path = 'content\week05\images'
files_starting_with_deep = thats_the_way(path)
print(f'\nFiles starting with "deep" in the directory {path} :\n{files_starting_with_deep}')
except FileNotFoundError as e:
print(e)
except Exception as e:
print(e)
57 changes: 57 additions & 0 deletions content/week05/5.2.cup_of_join.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from typing import List


def cup_of_join(*lists: list, sep: str = '-') -> list:
# I added this func just because the assignment required a function named cup_of_join and a func named join...
return join(*lists, sep=sep)


def join(*lists: list, sep: str = '-') -> list:
'''
Joins the lists with the separator
:param lists: list, lists to join
:param sep: str, separator
:return: list, joined list
'''
if not isinstance(sep, str):
raise TypeError('The separator must be a string')
if not all(isinstance(lst, List) for lst in lists):
raise TypeError('All the arguments must be lists')
if not lists:
return None

result = list(lists[0])

for lst in lists[1:]:
result.append(sep)
result.extend(lst)

return result


def test_join():
assert cup_of_join([1, 2], [8], [9, 5, 6], sep='@') == [1, 2, '@', 8, '@', 9, 5, 6]
assert cup_of_join([1, 2], [8], [9, 5, 6]) == [1, 2, '-', 8, '-', 9, 5, 6]
assert cup_of_join([1]) == [1]
assert cup_of_join() == None

try:
cup_of_join([1, 2], [8], [9, 5, 6], sep=1)
except TypeError:
pass
else:
assert False

try:
cup_of_join([1, 2], {3}, sep='@')
except TypeError:
pass
else:
assert False

print('All test cases passed')


if __name__ == '__main__':
test_join()

20 changes: 20 additions & 0 deletions content/week05/5.2.piece_of_cake.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

def piece_of_cake(prices, **quantities):
optionals = quantities.pop('optionals', [])

total_price = 0
for ingredient, quantity in quantities.items():
if ingredient not in optionals and ingredient in prices:
total_price += (quantity / 100) * prices[ingredient]

return total_price

def test_get_recipe_price():
assert piece_of_cake({'chocolate': 18, 'milk': 8}, chocolate=200, milk=100) == 44
assert piece_of_cake({'chocolate': 18, 'milk': 8}, optionals=['milk'], chocolate=300) == 54
assert piece_of_cake({}) == 0

print('All tests passed!')

if __name__ == '__main__':
test_get_recipe_price()
35 changes: 35 additions & 0 deletions content/week05/5.3.parsle_tongue.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import re
import time


def find_secret_messages(filename: str, timeout: int = 10) -> list:
'''
Finds the secret messages in the file
:param filename: str, file path
:param timeout: int, timeout in seconds
:return: list, secret messages
'''

result = []
buffer_size = 8192
overlap_size = 20
pattern = re.compile(b'[a-z]{5,}!')
start_time = time.time()

with open(filename, 'rb') as file:
buffer = file.read(buffer_size)
while buffer:
if time.time() - start_time > timeout:
print("Timeout reached\n")
break
for match in pattern.finditer(buffer):
result.append(match.group().decode('utf-8'))
print(f'Found secret message: {match.group().decode("utf-8")}')

next_chunk = file.read(buffer_size - overlap_size)
buffer = buffer[len(next_chunk):] + next_chunk
return result


if __name__ == '__main__':
print(find_secret_messages('content\\week05\\resources\\logo.jpg', timeout=15))
39 changes: 39 additions & 0 deletions content/week05/5.4.communicating_vessels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from itertools import zip_longest

def interleave(*iterables):
'''
Interleave the elements of the given iterables.
:param iterables: one or more iterables
:return: an iterator that yields elements from the given iterables interleaved
'''
for iter in zip_longest(*iterables, fillvalue=None):
for item in iter:
if item is not None:
yield item


def test():
result = list(interleave('abc', [1, 2, 3], ('!', '@', '#')))
assert result == ['a', 1, '!', 'b', 2, '@', 'c', 3, '#']

result = list(interleave('abc', [1, 2, 3, 4], ('!', '@', '#')))
assert result == ['a', 1, '!', 'b', 2, '@', 'c', 3, '#', 4]

result = list(interleave('abc', [1, 2, 3], ('!', '@', '#'), [4, 5, 6]))
assert result == ['a', 1, '!', 4, 'b', 2, '@', 5, 'c', 3, '#', 6]

result = list(interleave('abc', [1, 2, 3], ('!', '@', '#'), [4, 5]))
assert result == ['a', 1, '!', 4, 'b', 2, '@', 5, 'c', 3, '#']

result = list(interleave('abc', [1, 2, 3], ('!', '@', '#'), [4, 5, 6, 7]))
assert result == ['a', 1, '!', 4, 'b', 2, '@', 5, 'c', 3, '#', 6, 7]

result = list(interleave('abc', [1, 2, 3], ('!', '@', '#'), [4, 5, 6, 7], [8, 9, 10]))
assert result == ['a', 1, '!', 4, 8, 'b', 2, '@', 5, 9, 'c', 3, '#', 6, 10, 7]

print('All tests passed')

if __name__ == '__main__':
test()
result = list(interleave('abc', [1, 2, 3], ('!', '@', '#')))
print(result)