Skip to content

Python Ex1 Added #70

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 1 commit 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
24 changes: 24 additions & 0 deletions content/week05/5.1.no_vinnigrette.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from datetime import datetime, timedelta
import random

def no_vinnigrete(date_src, date_dst):
# also excepts non-zero padded days and months. to achieve only zero padded we can use helper bool func with regex
date_format = "%Y-%m-%d"
delta = (datetime.strptime(date_dst, date_format) - datetime.strptime(date_src, date_format)).days
if delta < 0:
print("Didn't figure how to turn time backwards yet...")
return
date_middle = datetime.strptime(date_src,date_format) + timedelta(days = random.randint(0,delta))
day = date_middle.strftime("%A")
if day == "Monday":
print("Ain't gettin' no vinaigrette today :(")
else:
print(date_middle.strftime(date_format))

def main():
no_vinnigrete("2024-05-06", "2024-05-06") # certainly monday
no_vinnigrete("1994-03-24", "1996-04-27") # some day
no_vinnigrete("1996-04-27", "1994-03-24") # back to the future

if __name__ == '__main__':
main()
11 changes: 11 additions & 0 deletions content/week05/5.1.thats_the_way.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from pathlib import Path
import re

# using regex to match the prefix of a filename
def thats_the_way (path):
return [f.name for f in Path(path).iterdir() if f.is_file() and re.match(r'^deep.*$',f.name)]

def main():
print(thats_the_way("images"))


12 changes: 12 additions & 0 deletions content/week05/5.2.cup_of_join.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
def cup_of_join(*lists, sep = None):
if sep is None:
return [item for lst in lists for item in lst]
else:
return [item for lst in lists for item in (lst + [sep])]

def main():
print(cup_of_join([1,2,3],['a','b'],[True, False]))
print(cup_of_join([1, 2, 3], ['a', 'b'], [True, False], sep = '-'))

if __name__ == '__main__':
main()
21 changes: 21 additions & 0 deletions content/week05/5.2.piece_of_cake.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# why use optionals if can just skip writing one of the args and the outcome will be the same?
def piece_of_cake(prices, optionals = [], **kwargs):
acc = 0
for key in kwargs:
if key not in optionals:
acc += (float(prices[key])/100.0) * kwargs[key]
return acc

# version without optionals
def piece_of_cake_2(prices, **kwargs):
acc = 0
for key in kwargs:
acc += (float(prices[key])/100.0) * kwargs[key]
return acc

def main():
print(piece_of_cake({'chocolate':18, 'milk':20}, optionals=['milk'], chocolate=100))
print(piece_of_cake_2({'chocolate': 18, 'milk': 20}, chocolate=200))

if __name__ == '__main__':
main()
29 changes: 29 additions & 0 deletions content/week05/5.3.parsle_tongue.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
def parsle_tongue():
chunk_size = 1024
chars = []
data = []
is_sequential = False
with open('resources\logo.jpg','rb') as file:
while True:
chunk = file.read(chunk_size)
for byte in chunk:
if byte == ord('!') and is_sequential:
if len(chars) >= 5:
data.append(''.join(chars))
chars.clear()
is_sequential = False
elif ord('a') <= byte <= ord('z'):
chars.append(chr(byte))
is_sequential = True
else:
is_sequential = False
chars.clear()
if not chunk:
break
return data

def main():
print(' '.join(parsle_tongue()))

if __name__ == '__main__':
main()
18 changes: 18 additions & 0 deletions content/week05/5.4.communicating_vessels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# could simply use zip but decided to make recursion in a functional programming style using map to strip iterables
def communicating_vessels(*iterables):
if all(not itr for itr in
iterables): # returns if no more items in any of the iterables (in case of uneven iterables)
return
for itr in iterables:
try:
yield next(iter(itr))
except StopIteration:
continue
yield from interleave(*(map(lambda it: it[1:], iterables)))

def main():
for it in interleave('ab', [1,2,3], ('@','%')):
print(it)

if __name__ == '__main__':
main()
95 changes: 95 additions & 0 deletions content/week05/Functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
from pathlib import Path
from datetime import datetime, timedelta
import random
import re


# using regex to match the prefix of a filename
def thats_the_way (path):
return [f.name for f in Path(path).iterdir() if f.is_file() and re.match(r'^deep.*$',f.name)]


def no_vinnigrete(date_src, date_dst):
# also excepts non-zero padded days and months. to achieve only zero padded we can use helper bool func with regex
date_format = "%Y-%m-%d"
delta = (datetime.strptime(date_dst, date_format) - datetime.strptime(date_src, date_format)).days
if delta < 0:
print("Didn't figure how to turn time backwards yet...")
return
date_middle = datetime.strptime(date_src,date_format) + timedelta(days = random.randint(0,delta))
day = date_middle.strftime("%A")
if day == "Monday":
print("Ain't gettin' no vinaigrette today :(")
else:
print(date_middle.strftime(date_format))


# why use optionals if can just skip writing one of the args and the outcome will be the same?
def get_recipe_price(prices, optionals = [], **kwargs):
acc = 0
for key in kwargs:
if key not in optionals:
acc += (float(prices[key])/100.0) * kwargs[key]
return acc


# version without optionals
def get_recipe_price_2(prices, **kwargs):
acc = 0
for key in kwargs:
acc += (float(prices[key])/100.0) * kwargs[key]
return acc


'''
list comprehension looks tricky but in reality the logic is:
for lst in lists: (outer loop)
for item in list: (inner loop)
item (append the item to the new list)
'''

def join(*lists, sep = None):
if sep is None:
return [item for lst in lists for item in lst]
else:
return [item for lst in lists for item in (lst + [sep])]


def parsle_tongue():
chunk_size = 1024
chars = []
data = []
is_sequential = False
with open('resources\logo.jpg','rb') as file:
while True:
chunk = file.read(chunk_size)
for byte in chunk:
if byte == ord('!') and is_sequential:
if len(chars) >= 5:
data.append(''.join(chars))
chars.clear()
is_sequential = False
elif ord('a') <= byte <= ord('z'):
chars.append(chr(byte))
is_sequential = True
else:
is_sequential = False
chars.clear()
if not chunk:
break
return data


# could simply use zip but decided to make recursion in a functional programming style using map to strip iterables
def interleave(*iterables):
if all(not itr for itr in iterables): # returns if no more items in any of the iterables (in case of uneven iterables)
return
for itr in iterables:
try:
yield next(iter(itr))
except StopIteration:
continue
yield from interleave(*(map(lambda it: it[1:], iterables)))



1 change: 1 addition & 0 deletions content/week05/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"# exercise-1-modules-functions-generators-BorisG1993"