Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions 02ex01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#!/usr/bin/env python3

"""Calculate deposit percent yield based on time period.

Imagine your friend wants to put money on a deposit.
He has got many offers from different banks:
- First bank declares +A% each day;
- Second bank promises +B% each month;
- Third bank offers +C% by the end of the year;
- The 4th bank promotes +D% in a 10-year term;
- ... and so on ...

Your friend gets a terrible headache calculating all this stuff,
and asks you to help checking everything. You quickly realize
it is a common task and having a simple script is a great idea.

Let's implement this.

A simplified task:
Given the SUM amount of money, and PERCENT yield promised in a
FIXED_PERIOD of time, calculate the TOTAL equivalent of money
in a SET_PERIOD of time.

Math formula:
p = PERCENT / 100
TOTAL = SUM * ((1 + p) ** (SET_PERIOD / FIXED_PERIOD))
"""


# TODO: add lines to calculate yields for some common periods
# of time (e.g. 1 month, 1 year, 5 years, 10 years)
# TODO: change the script to output the 1-year percent yield
# as well
# TODO: (extra) Output only percents if the initial SUM is
# not known at the moment the script is run


USAGE = """USAGE: {script} initial_sum percent fixed_period set_period

\tCalculate deposit yield. See script source for more details.
"""
USAGE = USAGE.strip()


def deposit(initial_sum, percent, fixed_period, set_period):
"""Calculate deposit yield."""
per = percent / 100
growth = (1 + per) ** (set_period / fixed_period)
return initial_sum * growth


def main(args):
"""Gets called when run as a script."""
if len(args) != 4 + 1:
exit(USAGE.format(script=args[0]))

args = args[1:]
initial_sum, percent, fixed_period, set_period = map(float, args)

# same as
# initial_sum = float(args[0])
# percent = float(args[1])
# ...

res = deposit(initial_sum, percent, fixed_period, set_period)
print(res)


if __name__ == '__main__':
import sys

main(sys.argv)

97 changes: 97 additions & 0 deletions 02ex02.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
#!/usr/bin/env python3

"""The famous Vikings restoraunt from the Monthy Python sketch.

See the sketch origins video first:
https://www.youtube.com/watch?v=zLih-WQwBSc
"""

import random

DEF_CHOICE = 8 # how many times to repeat a dish
MENU = ['spam', 'egg', 'sausage', 'bacon'] # that's all combinations
MENU_MULTI = MENU + ['eggs', 'sausages'] # including plurals
JOINTS = [', and ', ', ', ' and ', ' with ', ' and double portion of ']
PREFERED = MENU[0] # that's what promoted most
FORBIDDEN = {'not', 'without', 'no'}

SONG = ', '.join([PREFERED.capitalize()] + [PREFERED] * DEF_CHOICE) + '!'

D_WELCOME = ('Welcome to the Vikings restaurant.\n'
'What would you like to eat?')
D_CHOICE = '> '
D_PROMOTE = "We highly recommend {dishes}" + f', and {PREFERED}...'
D_GOOD = "That's a perfect choice. Let's have more {dishes}" + f', and {PREFERED}!'
D_BAD = "Disgusting. Who eats {dishes}?"
D_UNAVAILABLE = "That's not on our menu.\nWe have {dishes}."


def dialog(num_choice=DEF_CHOICE):
"""User dialog logic."""
print(D_WELCOME)

entry = input(D_CHOICE).strip() # user entry
words = entry.lower().split()

def promote():
print(D_PROMOTE.format(dishes=get_dishes(num_choice)))

if set(words) & set(MENU_MULTI):
# user named something on the menu - do further check
if set(words) & set(FORBIDDEN):
# user asked not to put common dishes - blame
print(D_BAD.format(dishes=entry))
promote()
else:
# user asked for what's on menu - compliment
print(D_GOOD.format(dishes=entry))
print(f'Vikings: "{SONG}"')
return

if not words:
# user haven't selected anything - promote a good menu
promote()
return

print(D_UNAVAILABLE.format(dishes=get_dishes(num_choice)))
return


def get_dishes(number):
"""Form a random combination of dishes"""
sel = list(MENU)

res = []
for i in range(number):
rnd = random.choice(sel)
#sel.remove(rnd)
res.append(rnd)
res.append(random.choice(JOINTS))
res = res[:-1] # remove last element

return ''.join(res)


TIP = """Next time call "{script} num" to set number of dishes."""

def main(args):
script, *args = args

"""Gets called when run as a script."""
if len(args) > 1:
exit('Too many arguments. ' + TIP.format(script=script))

num = DEF_CHOICE
if len(args) > 0:
num = int(args[0])

dialog(num)

if len(args) < 1:
print('\tTip:', TIP.format(script=script))


if __name__ == '__main__':
import sys

main(sys.argv)
5 changes: 5 additions & 0 deletions AverageValue.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
def avg(*args):
return sum(*args) / len(*args)



50 changes: 50 additions & 0 deletions Cards.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import random


class Cards:
RANKS = list(range(2, 11)) + list('JQKA')
SUITS = ['\u2660', '\u2665', '\u2666', '\u2663']

def __init__(self):
self.rank = self.RANKS
self.suits = self.SUITS

def __repr__(self):
return f"{self.magic_cards()}"

@classmethod
def create_deck(cls):
deck = []
deck_list = [(str(i), j) for i in cls.RANKS for j in cls.SUITS]
for i in deck_list:
deck.append("".join(i))
return deck

@classmethod
def generate_card(cls, n=1):
cards_list = []
for i in range(n):
cards_list.append(random.choice(cls.create_deck()))
return cards_list

def magic_cards(self):
from datetime import datetime
print(f"Pick from one to four cards from the deck and I'll tell you what tomorrow should be. \n"
f"How many cards will you get?\n -->")
num_cards = input()
try:
int(num_cards)
if 0 < int(num_cards) < 5:
week_days_list = ['monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
get_cards = self.generate_card(int(num_cards))
num_cards -= 1
print(f"You got the following cards : \n {' '.join(get_cards)}\nand tomorrow...... \nshould be.........\n"
f"--->>>{week_days_list[datetime.now().weekday()]}<<<---")
else:
print('too many cards you probably need to see a fortune teller')
except ValueError:
print("it seems that tomorrow......\n you will learn how letters differ from numbers")

x = Cards()
print(x.generate_card())
print(x.magic_cards())
27 changes: 27 additions & 0 deletions HW Lacture#8/Exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Errors(Exception):
pass


class CityNameError(Errors):
error_message = ('City name must contain only letters')

def __init__(self):
super().__init__()
self.msg = self.error_message

def __str__(self):
return self.msg


class CoordError(Errors):
error_message = ("Invalid Coords. Try again")

def __init__(self):
super().__init__()
self.msg = self.error_message

def __str__(self):
return self.msg



71 changes: 71 additions & 0 deletions HW Lacture#8/WeatherClases.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
from urllib.request import urlopen
import json
from Exeptions import CityNameError, CoordError
# https://api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}
# https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
TOKEN = '18c6e0f43541c0148fa43fbd483f79b4'


class City():
def __init__(self, name, latitude=None, longitude=None):
self._name = name
self._latitude = latitude
self._longitude = longitude
if self._latitude is None and self._longitude is None:
self.set_coords()

def get_coords(self):
if self._name.isalpha():
url = f'http://api.openweathermap.org/geo/1.0/direct?q={self._name}&appid={TOKEN}'
response = urlopen(url)
data = response.read()
data = data.decode('utf-8')
res = json.loads(data)
lat = res[0]['lat']
lon = res[0]['lon']
else:
raise CityNameError


return lat, lon

def set_coords(self):
self._latitude, self._longitude = self.get_coords()

def __str__(self):
return f'City {self._name} has latitude:{self._latitude} ' \
f'and longitude{self._longitude}'


class Weather():

def __init__(self, city, coords=None):
self.city = city
self.coords = coords

def current_weather(self):
if self.coords:
try:
float(self.coords[0])
float(self.coords[1])
except ValueError:
raise CoordError()


else:
self.coords = City(self.city).get_coords()

url = f'https://api.openweathermap.org/data/2.5/weather?lat={self.coords[0]}&lon={self.coords[1]}&units=metric&appid={TOKEN}'
response = urlopen(url).read().decode('utf-8')
res = json.loads(response)
# print(res)
return (f"Температура: {res['main']['temp']} "
f"відчувається як: {res['main']['feels_like']} "
f"швидкість вітру: {res['wind']['speed']}")

def __str__(self):
return self.current_weather()




3 changes: 3 additions & 0 deletions HW#10 Lecture#13/.idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions HW#10 Lecture#13/.idea/HW#10 Lecture#13.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions HW#10 Lecture#13/.idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions HW#10 Lecture#13/.idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions HW#10 Lecture#13/.idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions HW#10 Lecture#13/red-Arrow/database/employees.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[{"first_name": "test", "last_name": "test", "email": "test@test.com", "phone": "+380971750340", "work_id": "1", "type": "plant", "id": 1}, {"first_name": "test", "last_name": "test", "email": "turupru8@gmail.com", "phone": "+380971750340", "work_id": "1", "type": "plant", "id": 2}, {"first_name": "Roman", "last_name": "Rostotskyi", "email": "roman.rostotskyi@vnv.solutions", "phone": "+380685553001", "work_id": 1, "type": "salon", "id": 3}]
1 change: 1 addition & 0 deletions HW#10 Lecture#13/red-Arrow/database/plants.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[{"name": "Azovstal", "address": "Ukraine, Mariupol, st. Address", "id": 1}, {"name": "Silmash", "address": "Ukraine, Ivano-Frankivsk, st. Address 2", "id": 2}]
1 change: 1 addition & 0 deletions HW#10 Lecture#13/red-Arrow/database/sales_departament.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[]
1 change: 1 addition & 0 deletions HW#10 Lecture#13/red-Arrow/database/salons.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[{"name": "Ford", "address": "Ukraine, Lviv, Doroshenka st.", "id": 1}, {"name": "Mersedes", "address": "Ukraine, Bakhmut, Geroyiv UPA st.", "id": 2}]
2 changes: 2 additions & 0 deletions HW#10 Lecture#13/red-Arrow/helpers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from .helpers import *
from .system_helpers import *
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading