Finishing 12 new elements

This commit is contained in:
2020-01-03 14:31:18 +01:00
parent f81e9d7ae3
commit da0609f315
12 changed files with 450 additions and 0 deletions

47
Github/building-base.py Normal file
View File

@@ -0,0 +1,47 @@
class Building:
def __init__(self, south, west, width_WE, width_NS, height=10):
self.x = west
self.y = south
self.width = width_WE
self.height = width_NS
self.depth = height
def corners(self):
return {
"south-west": [self.y, self.x],
"south-east": [self.y, self.x + self.width],
"north-west": [self.y + self.height, self.x],
"north-east": [self.y + self.height, self.x + self.width],
}
def area(self):
return self.width * self.height
def volume(self):
return self.area() * self.depth
def __repr__(self):
return "Building({}, {}, {}, {}, {})".format(
self.y,
self.x,
self.width,
self.height,
self.depth
)
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
def json_dict(d):
return dict((k, list(v)) for k, v in d.items())
b = Building(1, 2, 2, 3)
b2 = Building(1, 2, 2, 3, 5)
assert b.area() == 6, "Area"
assert b.volume() == 60, "Volume"
assert b2.volume() == 30, "Volume2"
assert json_dict(b.corners()) == {'north-east': [4, 4], 'south-east': [1, 4],
'south-west': [1, 2], 'north-west': [4, 2]}, "Corners"
assert str(b) == "Building(1, 2, 2, 3, 10)", "String"

View File

@@ -0,0 +1,22 @@
def from_camel_case(name):
new_name = ""
for i, letter in enumerate(name):
if i == 0:
new_name += letter.lower()
elif letter.lower() != letter:
new_name += "_"+letter.lower()
else:
new_name += letter
return new_name
if __name__ == '__main__':
print("Example:")
print(from_camel_case("Name"))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert from_camel_case("MyFunctionName") == "my_function_name"
assert from_camel_case("IPhone") == "i_phone"
assert from_camel_case("ThisFunctionIsEmpty") == "this_function_is_empty"
assert from_camel_case("Name") == "name"
print("Coding complete? Click 'Check' to earn cool rewards!")

View File

@@ -0,0 +1,48 @@
from datetime import datetime
import math
class Person:
def __init__(self, first_name, last_name, birth_date, job, working_years, salary, country, city, gender='unknown'):
self.first_name = first_name
self.last_name = last_name
self.birth_date = birth_date
self.job = job
self.working_years = working_years
self.salary = salary
self.country = country
self.city = city
self.gender = gender
def name(self):
return "{} {}".format(self.first_name, self.last_name)
def age(self):
d1 = datetime.strptime(self.birth_date, "%d.%m.%Y")
# d2 = datetime.now()
d2 = datetime.strptime("01.01.2018", "%d.%m.%Y")
return math.floor(abs((d2 - d1).days) / 365)
def work(self):
return "{} a {}".format(
"He is" if self.gender == "male" else "She is" if self.gender == "female" else "Is",
self.job)
def money(self):
return f'{self.salary * 12 * self.working_years:,}'.replace(",", " ")
def home(self):
return "Lives in {}, {}".format(self.city, self.country)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
p1 = Person("John", "Smith", "19.09.1979", "welder", 15, 3600, "Canada", "Vancouver", "male")
p2 = Person("Hanna Rose", "May", "05.12.1995", "designer", 2.2, 2150, "Austria", "Vienna")
assert p1.name() == "John Smith", "Name"
assert p1.age() == 40, "Age"
assert p2.work() == "Is a designer", "Job"
assert p1.money() == "648 000", "Money"
assert p2.home() == "Lives in Vienna, Austria", "Home"
print("Coding complete? Let's try tests!")

56
Github/flatten-dict.py Normal file
View File

@@ -0,0 +1,56 @@
def flatten(dictionary, children=None):
if children is None:
children = []
new_dict = {}
for name, value in dictionary.items():
if isinstance(value, dict):
if len(value) != 0:
children.append(name)
new_dict.update(flatten(value, children))
children.pop()
elif len(children) == 0:
new_dict[name] = ""
else:
new_dict["/".join(children) + "/" + name] = ""
elif len(children) == 0:
new_dict[name] = value
else:
new_dict["/".join(children) + "/" + name] = value
return new_dict
if __name__ == '__main__':
test_input = {"key": {"deeper": {"more": {"enough": "value"}}}}
print(' Input: {}'.format(test_input))
print('Output: {}'.format(flatten(test_input)))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert flatten({"key": "value"}) == {"key": "value"}, "Simple"
assert flatten(
{"key": {"deeper": {"more": {"enough": "value"}}}}
) == {"key/deeper/more/enough": "value"}, "Nested"
assert flatten({"empty": {}}) == {"empty": ""}, "Empty value"
assert flatten({"name": {
"first": "One",
"last": "Drone"},
"job": "scout",
"recent": {},
"additional": {
"place": {
"zone": "1",
"cell": "2"}}}
) == {"name/first": "One",
"name/last": "Drone",
"job": "scout",
"recent": "",
"additional/place/zone": "1",
"additional/place/cell": "2"}
var = {"job/1": "scout", "recent/places/earth/NY": "2017", "job/3": "writer", "job/2": "worker", "job/5": "learner",
"job/4": "reader", "recent/places/earth/NP": "", "recent/places/earth/Louvre": "2015",
"recent/times/XX/1964": "Yes", "recent/times/XXI/2064": "Nope", "name/first": "Second", "name/last": "Drone",
"name/nick": ""}
assert flatten({"name": {"first": "Second", "last": "Drone", "nick": {}},
"job": {"1": "scout", "2": "worker", "3": "writer", "4": "reader", "5": "learner"},
"recent": {"places": {"earth": {"Louvre": "2015", "NY": "2017", "NP": ""}},
"times": {"XX": {"1964": "Yes"}, "XXI": {"2064": "Nope"}}}}) == var
print('You all set. Click "Check" now!')

26
Github/loading-cargo.py Normal file
View File

@@ -0,0 +1,26 @@
import itertools
def best_balance(stoneset):
balances = []
for i in range(1, len(stoneset)):
left = stoneset[0:-(len(stoneset) - i)]
right = stoneset[i:len(stoneset)]
balances.append(abs(sum(left) - sum(right)))
return min(balances)
def checkio(stones):
if len(stones) == 1:
return stones[0]
return min(set(map(best_balance, list(itertools.permutations(stones)))))
if __name__ == '__main__':
assert checkio([10, 10]) == 0, 'First, with equal weights'
assert checkio([10]) == 10, 'Second, with a single stone'
assert checkio([5, 8, 13, 27, 14]) == 3, 'Third'
assert checkio([5, 5, 6, 5]) == 1, 'Fourth'
assert checkio([12, 30, 30, 32, 42, 49]) == 9, 'Fifth'
assert checkio([1, 1, 1, 3]) == 0, "Six, don't forget - you can hold different quantity of parts"
print('All is ok')

View File

@@ -0,0 +1,55 @@
class VoiceCommand:
def __init__(self, channels):
self.channels = channels
self.current = 0
def first_channel(self):
self.current = 0
return self.channels[0]
def last_channel(self):
self.current = len(self.channels) - 1
return self.channels[self.current]
def turn_channel(self, channel):
self.current = channel - 1
return self.current_channel()
def next_channel(self):
self.current += 1
if self.current >= len(self.channels):
self.current = 0
return self.current_channel()
def previous_channel(self):
self.current -= 1
if self.current < 0:
self.current = len(self.channels) - 1
return self.current_channel()
def current_channel(self):
return self.channels[self.current]
def is_exist(self, channel):
if isinstance(channel, int):
return "Yes" if 0 <= channel < len(self.channels) else "No"
else:
return "Yes" if channel in self.channels else "No"
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
CHANNELS = ["BBC", "Discovery", "TV1000"]
controller = VoiceCommand(CHANNELS)
assert controller.first_channel() == "BBC"
assert controller.last_channel() == "TV1000"
assert controller.turn_channel(1) == "BBC"
assert controller.next_channel() == "Discovery"
assert controller.previous_channel() == "BBC"
assert controller.current_channel() == "BBC"
assert controller.is_exist(4) == "No"
assert controller.is_exist("TV1000") == "Yes"
print("Coding complete? Let's try tests!")