Finishing 7 new elements

This commit is contained in:
Clement Desmidt 2020-01-09 17:35:57 +01:00
parent 1dcfd757e8
commit f6539aedaa
7 changed files with 404 additions and 0 deletions

66
Dropbox/3-chefs.py Normal file
View File

@ -0,0 +1,66 @@
class AbstractCook:
def __init__(self):
self.food_name = ""
self.drink_name = ""
self.food = 0
self.drink = 0
def add_food(self, amount, price):
self.food += amount * price
def add_drink(self, amount, price):
self.drink += amount * price
def total(self):
return "{}: {}, {}: {}, Total: {}".format(
self.food_name,
str(self.food),
self.drink_name,
str(self.drink),
str(self.drink + self.food)
)
class JapaneseCook(AbstractCook):
def __init__(self):
super().__init__()
self.food_name = "Sushi"
self.drink_name = "Tea"
class RussianCook(AbstractCook):
def __init__(self):
super().__init__()
self.food_name = "Dumplings"
self.drink_name = "Compote"
class ItalianCook(AbstractCook):
def __init__(self):
super().__init__()
self.food_name = "Pizza"
self.drink_name = "Juice"
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
client_1 = JapaneseCook()
client_1.add_food(2, 30)
client_1.add_food(3, 15)
client_1.add_drink(2, 10)
client_2 = RussianCook()
client_2.add_food(1, 40)
client_2.add_food(2, 25)
client_2.add_drink(5, 20)
client_3 = ItalianCook()
client_3.add_food(2, 20)
client_3.add_food(2, 30)
client_3.add_drink(2, 10)
assert client_1.total() == "Sushi: 105, Tea: 20, Total: 125"
assert client_2.total() == "Dumplings: 90, Compote: 100, Total: 190"
assert client_3.total() == "Pizza: 100, Juice: 20, Total: 120"
print("Coding complete? Let's try tests!")

View File

@ -0,0 +1,21 @@
def to_camel_case(name):
name = name[0].upper() + name[1:]
while True:
try:
index = name.index("_")
name = name[0:index] + name[index+1].upper() + name[index+2:]
except ValueError:
break
return name
if __name__ == '__main__':
print("Example:")
print(to_camel_case('name'))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert to_camel_case("my_function_name") == "MyFunctionName"
assert to_camel_case("i_phone") == "IPhone"
assert to_camel_case("this_function_is_empty") == "ThisFunctionIsEmpty"
assert to_camel_case("name") == "Name"
print("Coding complete? Click 'Check' to earn cool rewards!")

View File

@ -0,0 +1,36 @@
from datetime import date, timedelta
def most_frequent_days(a):
week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
days = {"Monday": 0, "Tuesday": 0, "Wednesday": 0, "Thursday": 0, "Friday": 0, "Saturday": 0, "Sunday": 0}
plus_a_day = timedelta(days=1)
first_date = date(a, 1, 1)
last_date = date(a, 12, 31)
while first_date <= last_date:
days[week[first_date.weekday()]] += 1
first_date += plus_a_day
return [day for day, count in days.items() if count == max(days.values())]
if __name__ == '__main__':
print("Example:")
print(most_frequent_days(1084))
# These "asserts" are used for self-checking and not for an auto-testing
assert most_frequent_days(1084) == ['Tuesday', 'Wednesday']
assert most_frequent_days(1167) == ['Sunday']
assert most_frequent_days(1216) == ['Friday', 'Saturday']
assert most_frequent_days(1492) == ['Friday', 'Saturday']
assert most_frequent_days(1770) == ['Monday']
assert most_frequent_days(1785) == ['Saturday']
assert most_frequent_days(212) == ['Wednesday', 'Thursday']
assert most_frequent_days(1) == ['Monday']
assert most_frequent_days(2135) == ['Saturday']
assert most_frequent_days(3043) == ['Sunday']
assert most_frequent_days(2001) == ['Monday']
assert most_frequent_days(3150) == ['Sunday']
assert most_frequent_days(3230) == ['Tuesday']
assert most_frequent_days(328) == ['Monday', 'Sunday']
assert most_frequent_days(2016) == ['Friday', 'Saturday']
print("Coding complete? Click 'Check' to earn cool rewards!")

21
Dropbox/unlucky-days.py Normal file
View File

@ -0,0 +1,21 @@
from datetime import date
def checkio(year: int) -> int:
count = 0
for month in range(1, 13):
current_date = date(year, month, 13)
if current_date.weekday() == 4:
count += 1
return count
if __name__ == '__main__':
print("Example:")
print(checkio(2015))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio(2015) == 3, "First - 2015"
assert checkio(1986) == 1, "Second - 1986"
assert checkio(2689) == 2, "Third"
print("Coding complete? Click 'Check' to earn cool rewards!")

189
IceBase/the-healers.py Normal file
View File

@ -0,0 +1,189 @@
# Taken from mission The Lancers
# Taken from mission The Vampires
# Taken from mission The Defenders
# Taken from mission Army Battles
# Taken from mission The Warriors
class Warrior:
def __init__(self):
self.health = 50
self.attack = 5
self.is_alive = True
self.defense = 0
self.vampirism = 0
self.healing = 0
def hit(self, other_unit) -> bool:
hit_points = self.attack - other_unit.defense
hit_points = hit_points if hit_points > 0 else 0
other_unit.health -= hit_points
other_unit.is_alive = other_unit.health > 0
self.health += (hit_points * self.vampirism)
return other_unit.is_alive
class Knight(Warrior):
def __init__(self):
super().__init__()
self.attack = 7
class Defender(Warrior):
def __init__(self):
super().__init__()
self.health = 60
self.attack = 3
self.defense = 2
class Vampire(Warrior):
def __init__(self):
super().__init__()
self.health = 40
self.attack = 4
self.vampirism = 0.5
class Rookie(Warrior):
def __init__(self, *args, **kwargs):
super().__init__()
self.health = 50
self.attack = 1
class Lancer(Warrior):
def __init__(self):
super().__init__()
self.attack = 6
class Healer(Warrior):
def __init__(self):
super().__init__()
self.health = 60
self.attack = 0
self.healing = 2
def heal(self, unit: Warrior):
unit.health += self.healing
def fight(unit_1, unit_2):
while unit_1.is_alive and unit_2.is_alive:
if not unit_1.hit(unit_2):
return True
if not unit_2.hit(unit_1):
return False
class Army:
def __init__(self):
self.units = []
def add_units(self, unit_type, quantity):
for i in range(quantity):
self.units.append(unit_type())
class Battle:
@staticmethod
def fight(army_1: Army, army_2: Army) -> bool:
while len(army_1.units) > 0 and len(army_2.units) > 0:
current_unit_1 = army_1.units[0]
current_unit_2 = army_2.units[0]
while current_unit_1.is_alive and current_unit_2.is_alive:
current_unit_1_attack = current_unit_1.hit(current_unit_2)
if len(army_1.units) > 1 and isinstance(army_1.units[1], Healer):
current_unit_1.health += army_1.units[1].healing
if isinstance(current_unit_1, Lancer) and len(army_2.units) > 1:
army_2.units[1].health -= current_unit_1.attack * 0.5
if not current_unit_1_attack:
army_2.units.pop(0)
break
current_unit_2_attack = current_unit_2.hit(current_unit_1)
if len(army_2.units) > 1 and isinstance(army_2.units[1], Healer):
current_unit_2.health += army_2.units[1].healing
if isinstance(current_unit_2, Lancer) and len(army_1.units) > 1:
army_1.units[1].health -= current_unit_2.attack * 0.5
if not current_unit_2_attack:
army_1.units.pop(0)
break
return len(army_1.units) > 0
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
# fight tests
chuck = Warrior()
bruce = Warrior()
carl = Knight()
dave = Warrior()
mark = Warrior()
bob = Defender()
mike = Knight()
rog = Warrior()
lancelot = Defender()
eric = Vampire()
adam = Vampire()
richard = Defender()
ogre = Warrior()
freelancer = Lancer()
vampire = Vampire()
priest = Healer()
assert fight(chuck, bruce) == True
assert fight(dave, carl) == False
assert chuck.is_alive == True
assert bruce.is_alive == False
assert carl.is_alive == True
assert dave.is_alive == False
assert fight(carl, mark) == False
assert carl.is_alive == False
assert fight(bob, mike) == False
assert fight(lancelot, rog) == True
assert fight(eric, richard) == False
assert fight(ogre, adam) == True
assert fight(freelancer, vampire) == True
assert freelancer.is_alive == True
assert freelancer.health == 14
priest.heal(freelancer)
assert freelancer.health == 16
# battle tests
my_army = Army()
my_army.add_units(Defender, 2)
my_army.add_units(Healer, 1)
my_army.add_units(Vampire, 2)
my_army.add_units(Lancer, 2)
my_army.add_units(Healer, 1)
my_army.add_units(Warrior, 1)
enemy_army = Army()
enemy_army.add_units(Warrior, 2)
enemy_army.add_units(Lancer, 4)
enemy_army.add_units(Healer, 1)
enemy_army.add_units(Defender, 2)
enemy_army.add_units(Vampire, 3)
enemy_army.add_units(Healer, 1)
army_3 = Army()
army_3.add_units(Warrior, 1)
army_3.add_units(Lancer, 1)
army_3.add_units(Healer, 1)
army_3.add_units(Defender, 2)
army_4 = Army()
army_4.add_units(Vampire, 3)
army_4.add_units(Warrior, 1)
army_4.add_units(Healer, 1)
army_4.add_units(Lancer, 2)
battle = Battle()
assert battle.fight(my_army, enemy_army) == False
assert battle.fight(army_3, army_4) == True
print("Coding complete? Let's try tests!")

12
OReilly/remove-accents.py Normal file
View File

@ -0,0 +1,12 @@
import unicodedata
def checkio(in_string):
"""remove accents"""
return ''.join(c for c in unicodedata.normalize('NFD', in_string) if unicodedata.category(c) != 'Mn')
if __name__ == '__main__':
assert checkio(u"préfèrent") == u"preferent"
assert checkio(u"loài trăn lớn") == u"loai tran lon"
print('Done')

View File

@ -0,0 +1,59 @@
def simplify_path(path):
"""
simplifying a given path
"""
folders = path.split("/")
new_folders = []
for folder in folders:
if folder == "" or folder == ".":
continue
elif folder == "..":
try:
if new_folders[-1] != "..":
new_folders.pop()
else:
new_folders.append("..")
except IndexError:
if path[0] == "/":
print("you can't go deeper than root folder")
else:
new_folders.append("..")
else:
new_folders.append(folder)
new_folders = "/".join(new_folders)
if not path[0].isalpha() and path[0] != ".":
new_folders = path[0] + new_folders
if len(new_folders) == 0:
new_folders = "."
print(new_folders)
return new_folders
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
# last slash is not important
assert simplify_path('/a/') == '/a'
# double slash can be united in one
assert simplify_path('/a//b/c') == '/a/b/c'
# double dot - go to previous folder
assert simplify_path('dir/fol/../no') == 'dir/no'
assert simplify_path('dir/fol/../../no') == 'no'
# one dot means current dir
assert simplify_path('/a/b/./ci') == '/a/b/ci'
assert simplify_path('vi/..') == '.'
assert simplify_path('./.') == '.'
# you can't go deeper than root folder
assert simplify_path('/for/../..') == '/'
assert simplify_path('/for/../../no/..') == '/'
# not all double-dots can be simplyfied in related path
assert simplify_path('for/../..') == '..'
assert simplify_path('../foo') == '../foo'
assert simplify_path(".././..") == "../.."
print('Simply enough! Let\'s check it now!!')