Finishing 12 new elements

This commit is contained in:
Clement Desmidt 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!")

32
OReilly/cipher-map2.py Normal file
View File

@ -0,0 +1,32 @@
def recall_password(cipher_grille, ciphered_password):
password = ""
for rotation in range(4):
for i, row in enumerate(cipher_grille):
for j, cell in enumerate(row):
if cell == "X":
password += ciphered_password[i][j]
cipher_grille = list(zip(*cipher_grille[::-1]))
return password
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert recall_password(
('X...',
'..X.',
'X..X',
'....'),
('itdf',
'gdce',
'aton',
'qrdi')) == 'icantforgetiddqd', 'First example'
assert recall_password(
('....',
'X..X',
'.X..',
'...X'),
('xhwc',
'rsqx',
'xqzz',
'fyzr')) == 'rxqrwsfzxqxzhczy', 'Second example'

View File

@ -0,0 +1,29 @@
def create_intervals(data: set):
"""
Create a list of intervals out of set of ints.
"""
if len(data) == 0:
return []
results = []
data = sorted(data)
start = None
current_number = None
for number in data:
if start is None:
start = number
current_number = start
continue
if number != start and number != (current_number + 1):
results.append((start, current_number))
start = number
current_number = number
results.append((start, current_number))
return results
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert create_intervals({1, 2, 3, 4, 5, 7, 8, 12}) == [(1, 5), (7, 8), (12, 12)], "First"
assert create_intervals({1, 2, 3, 6, 7, 8, 4, 5}) == [(1, 8)], "Second"
assert create_intervals({7, 9, 10, 11, 12}) == [(7, 7), (9, 12)], "Third"
print('Almost done! The only thing left to do is to Check it!')

21
OReilly/days-diff.py Normal file
View File

@ -0,0 +1,21 @@
from datetime import datetime
def days_diff(a, b):
[a_year, a_month, a_days] = list(map(str, a))
[b_year, b_month, b_days] = list(map(str, b))
d1 = datetime.strptime("{}-{}-{}".format(a_year.rjust(4, "0"), a_month.rjust(2, "0"), a_days.rjust(2, "0")), "%Y-%m-%d")
d2 = datetime.strptime("{}-{}-{}".format(b_year.rjust(4, "0"), b_month.rjust(2, "0"), b_days.rjust(2, "0")), "%Y-%m-%d")
return abs((d2 - d1).days)
if __name__ == '__main__':
print("Example:")
print(days_diff((1982, 4, 19), (1982, 4, 22)))
# These "asserts" are used for self-checking and not for an auto-testing
assert days_diff((1982, 4, 19), (1982, 4, 22)) == 3
assert days_diff((2014, 1, 1), (2014, 8, 27)) == 238
assert days_diff((2014, 8, 27), (2014, 1, 1)) == 238
assert days_diff([1, 1, 1], [9999, 12, 31]) == 3652058
print("Coding complete? Click 'Check' to earn cool rewards!")

30
OReilly/median.py Normal file
View File

@ -0,0 +1,30 @@
from typing import List
import math
def checkio(data: List[int]) -> [int, float]:
data.sort()
data_len = len(data)
if data_len % 2 == 0:
if data_len != 2:
cut = int(data_len / 2 - 1)
data = data[cut:-cut]
return sum(data) / len(data)
middle = math.floor(data_len / 2)
return data[middle]
# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
print("Example:")
print(checkio([1, 2, 3, 4, 5]))
assert checkio([1, 2, 3, 4, 5]) == 3, "Sorted list"
assert checkio([3, 1, 2, 5, 3]) == 3, "Not sorted list"
assert checkio([1, 300, 2, 200, 1]) == 2, "It's not an average"
assert checkio([3, 6, 20, 99, 10, 15]) == 12.5, "Even length"
print("Start the long test")
assert checkio(list(range(1000000))) == 499999.5, "Long."
assert checkio([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) == 5, "5."
assert checkio([999999, 1]) == 5, "5."
print("Coding complete? Click 'Check' to earn cool rewards!")

51
OReilly/text-editor.py Normal file
View File

@ -0,0 +1,51 @@
import copy
class Text:
def __init__(self):
self.lines = ""
self.font = ""
def write(self, lines):
self.lines += lines
def set_font(self, font_name):
self.font = font_name
def show(self):
return "[{}]{}[{}]".format(self.font, self.lines, self.font) if self.font != "" else self.lines
def restore(self, version):
self.font = version.font
self.lines = version.lines
class SavedText:
def __init__(self):
self.texts = []
def save_text(self, texts):
self.texts.append(copy.deepcopy(texts))
def get_version(self, version):
return self.texts[version]
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
text = Text()
saver = SavedText()
text.write("At the very beginning ")
saver.save_text(text)
text.set_font("Arial")
saver.save_text(text)
text.write("there was nothing.")
assert text.show() == "[Arial]At the very beginning there was nothing.[Arial]"
text.restore(saver.get_version(0))
assert text.show() == "At the very beginning "
print("Coding complete? Let's try tests!")

33
OReilly/worth-of-words.py Normal file
View File

@ -0,0 +1,33 @@
VALUES = {'e': 1, 'a': 1, 'i': 1, 'o': 1, 'n': 1, 'r': 1,
't': 1, 'l': 1, 's': 1, 'u': 1, 'd': 2, 'g': 2,
'b': 3, 'c': 3, 'm': 3, 'p': 3, 'f': 4, 'h': 4,
'v': 4, 'w': 4, 'y': 4, 'k': 5, 'j': 8, 'x': 8,
'q': 10, 'z': 10}
def worth_of_words(words):
highest_word = None
highest_score = 0
for word in words:
score = word_score(word)
if score > highest_score:
highest_score = score
highest_word = word
return highest_word
def word_score(word):
score = 0
for letter in word:
score += VALUES[letter]
return score
if __name__ == '__main__':
print("Example:")
print(worth_of_words(['hi', 'quiz', 'bomb', 'president']))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert worth_of_words(['hi', 'quiz', 'bomb', 'president']) == 'quiz'
assert worth_of_words(['zero', 'one', 'two', 'three', 'four', 'five']) == 'zero'
print("Coding complete? Click 'Check' to earn cool rewards!")