Finishing 13 elements

This commit is contained in:
Clement Desmidt 2020-01-02 17:30:27 +01:00
parent a615255dfa
commit f81e9d7ae3
13 changed files with 436 additions and 0 deletions

34
Alice/humpty-dumpty.py Normal file
View File

@ -0,0 +1,34 @@
import math
def checkio(height, width):
return [round(calculate_volume(height, width), 2), round(calculate_area(height, width), 2)]
def calculate_area(height, width):
r_width = width / 2
r_height = height / 2
if r_width == r_height:
return 4 * math.pi * math.pow(r_width, 2)
return calculate_area_c_less_than_a(r_width, r_height) if height <= width else calculate_area_c_more_than_a(r_width, r_height)
def calculate_area_c_less_than_a(r_width, r_height):
e = math.sqrt(1 - (math.pow(r_height, 2) / math.pow(r_width, 2)))
return 2 * math.pi * math.pow(r_width, 2) + math.pi * (math.pow(r_height, 2) / e) * math.log((1 + e) / (1 - e))
def calculate_area_c_more_than_a(r_width, r_height):
e = math.sqrt(1 - (math.pow(r_width, 2) / math.pow(r_height, 2)))
return 2 * math.pi * math.pow(r_width, 2) * (1+(r_height/(r_width*e))*math.asin(e))
def calculate_volume(height, width):
return (4 * math.pi / 3) * math.pow(width / 2, 2) * (height / 2)
# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(4, 2) == [8.38, 21.48], "Prolate spheroid"
assert checkio(2, 2) == [4.19, 12.57], "Sphere"
assert checkio(2, 4) == [16.76, 34.69], "Oblate spheroid"

View File

@ -0,0 +1,28 @@
def checkio(expression):
OPENING_BRACKETS = ["(", "[", "{"]
CLOSING_BRACKETS = [")", "]", "}"]
current_bracket = []
for letter in expression:
if letter in CLOSING_BRACKETS:
if len(current_bracket) == 0:
return False
else:
last_bracket = current_bracket[-1:][0]
if OPENING_BRACKETS.index(last_bracket) == CLOSING_BRACKETS.index(letter):
current_bracket.pop()
else:
return False
if letter in OPENING_BRACKETS:
current_bracket.append(letter)
return len(current_bracket) == 0
# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio("((5+3)*2+1)") == True, "Simple"
assert checkio("{[(3+1)+2]+}") == True, "Different types"
assert checkio("(3+{1-1)}") == False, ") is alone inside {}"
assert checkio("[1+1]+(2*2)-{3/3}") == True, "Different operators"
assert checkio("(({[(((1)-2)+3)-3]/3}-3)") == False, "One is redundant"
assert checkio("2+3") == True, "No brackets, no problem"
assert checkio("(((([[[{{{3}}}]]]]))))") == False, "No brackets, no problem"

View File

@ -0,0 +1,26 @@
def count_consecutive_summers(num):
index = num
number_of_consecutive_summers = 1
while index > 0:
index -= 1
sums = index
count = 1
while sums <= num and index - count >= 0:
if sums == num:
number_of_consecutive_summers += 1
break
sums += index - count
count += 1
return number_of_consecutive_summers
if __name__ == '__main__':
print("Example:")
print(count_consecutive_summers(42))
# These "asserts" are used for self-checking and not for an auto-testing
assert count_consecutive_summers(42) == 4
assert count_consecutive_summers(99) == 6
assert count_consecutive_summers(1) == 1
assert count_consecutive_summers(15) == 4
print("Coding complete? Click 'Check' to earn cool rewards!")

View File

@ -0,0 +1,35 @@
def date_time(time: str) -> str:
[date, time] = time.split(" ")
return "{} {}".format(parse_date(date), parse_time(time))
def parse_date(date: str) -> str:
MONTHS = [
"", "January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"
]
[day, month, year] = date.split(".")
day = int(day)
return "{} {} {} year".format(int(day), MONTHS[int(month)], year)
def parse_time(time: str) -> str:
[hours, minutes] = time.split(":")
return "{} hour{} {} minute{}".format(
int(hours),
"s" if int(hours) != 1 else "",
int(minutes),
"s" if int(minutes) != 1 else ""
)
if __name__ == '__main__':
print("Example:")
print(date_time('01.01.2000 00:00'))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert date_time("01.01.2000 00:00") == "1 January 2000 year 0 hours 0 minutes", "Millenium"
assert date_time("09.05.1945 06:30") == "9 May 1945 year 6 hours 30 minutes", "Victory"
assert date_time("20.11.1990 03:55") == "20 November 1990 year 3 hours 55 minutes", "Somebody was born"
print("Coding complete? Click 'Check' to earn cool rewards!")

View File

@ -0,0 +1,33 @@
def largest_histogram(histogram):
stack = list()
max_area = 0
index = 0
while index < len(histogram):
if (not stack) or (histogram[stack[-1]] <= histogram[index]):
stack.append(index)
index += 1
else:
top_of_stack = stack.pop()
area = (histogram[top_of_stack] *
((index - stack[-1] - 1)
if stack else index))
max_area = max(max_area, area)
while stack:
top_of_stack = stack.pop()
area = (histogram[top_of_stack] *
((index - stack[-1] - 1)
if stack else index))
max_area = max(max_area, area)
return max_area
if __name__ == "__main__":
# These "asserts" using only for self-checking and not necessary for auto-testing
assert largest_histogram([5]) == 5, "one is always the biggest"
assert largest_histogram([5, 3]) == 6, "two are smallest X 2"
assert largest_histogram([1, 1, 4, 1]) == 4, "vertical"
assert largest_histogram([1, 1, 3, 1]) == 4, "horizontal"
assert largest_histogram([2, 1, 4, 5, 1, 3, 3]) == 8, "complex"
print("Done! Go check it!")

View File

@ -0,0 +1,43 @@
import abc
class State(object, metaclass=abc.ABCMeta):
def __init__(self):
self.color_index = 0
@abc.abstractmethod
def light(self):
COLORS = ["Green", "Red", "Blue", "Yellow"]
state_color = COLORS[self.color_index]
self.color_index += 1
if self.color_index == len(COLORS):
self.color_index = 0
return state_color
class Lamp(State):
def __init__(self):
super().__init__()
self.color = None
def light(self):
self.color = super().light()
return self.color
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
lamp_1 = Lamp()
lamp_2 = Lamp()
lamp_1.light() # Green
lamp_1.light() # Red
lamp_2.light() # Green
assert lamp_1.light() == "Blue"
assert lamp_1.light() == "Yellow"
assert lamp_1.light() == "Green"
assert lamp_2.light() == "Red"
assert lamp_2.light() == "Blue"
print("Coding complete? Let's try tests!")

View File

@ -0,0 +1,36 @@
def checkio(data):
result = 0
data_length = len(data)
if data_length > 0:
result += data[0]
if data_length > 1:
result += data[1]
if data_length > 2:
result += data[2]
if data_length > 3:
result += data[3]
if data_length > 4:
result += data[4]
if data_length > 5:
result += data[5]
if data_length > 6:
result += data[6]
if data_length > 7:
result += data[7]
if data_length > 8:
result += data[8]
if data_length > 9:
result += data[9]
if data_length > 10:
result += data[10]
if data_length > 11:
result += data[11]
if data_length > 12:
result += data[12]
if data_length > 13:
result += data[13]
return result
assert checkio([43, -10, 68, 84, 91, 71, -10, -80, 38]) == 295
assert checkio([1, 37, -64, 57, -78, 57, 64, -38, -91, 61, 53, -89, 41]) == 295

View File

@ -0,0 +1,71 @@
def reverse_roman(roman_string):
mille = ['', 'M', 'MM', 'MMM']
centaine = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']
dixaine = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']
unite = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']
number = 0
roman_string_length = len(roman_string)
index = 0
while True:
letter = roman_string[index]
current_number = letter
is_multiple = False
if current_number in mille:
while current_number in mille and index < roman_string_length - 1:
index += 1
current_number += roman_string[index]
if current_number not in mille:
is_multiple = True
current_number = current_number[0:-1]
number += (mille.index(current_number) * 1000)
elif current_number in centaine:
while current_number in centaine and index < roman_string_length - 1:
index += 1
current_number += roman_string[index]
if current_number not in centaine:
is_multiple = True
current_number = current_number[0:-1]
number += 100 * (centaine.index(current_number))
elif current_number in dixaine:
while current_number in dixaine and index < roman_string_length - 1:
index += 1
current_number += roman_string[index]
if current_number not in dixaine:
is_multiple = True
current_number = current_number[0:-1]
number += 10 * (dixaine.index(current_number))
elif current_number in unite:
while current_number in unite and index < roman_string_length - 1:
index += 1
current_number += roman_string[index]
if current_number not in unite:
is_multiple = True
current_number = current_number[0:-1]
number += unite.index(current_number)
if index == roman_string_length - 1:
if is_multiple:
letter = roman_string[index]
if letter in mille:
number += (mille.index(letter)) * 1000
elif letter in centaine:
number += 100 * (centaine.index(letter))
elif letter in dixaine:
number += 10 * (dixaine.index(letter))
elif letter in unite:
number += unite.index(letter)
break
return number
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert reverse_roman('VI') == 6, '6'
assert reverse_roman('LXXVI') == 76, '76'
assert reverse_roman('CDXCIX') == 499, '499'
assert reverse_roman('MMMDCCCLXXXVIII') == 3888, '3888'
assert reverse_roman("I") == 1, '1'
assert reverse_roman("X") == 10, '10'
assert reverse_roman("MMMDCCCX") == 3810, '3810'
print('Great! It is time to Check your code!')

View File

@ -0,0 +1,26 @@
def time_converter(time):
[time, apm] = time.split(" ")
time_int = int(time.replace(':', ''))
if apm == "a.m.":
if time_int < 1200:
return time.rjust(5, "0")
else:
[hours, minutes] = time.split(":")
return "00:{}".format(minutes)
else:
if time_int < 1200:
[hours, minutes] = time.split(":")
return "{}:{}".format(int(hours) + 12, minutes)
else:
return time
if __name__ == '__main__':
print("Example:")
print(time_converter('12:30 p.m.'))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert time_converter('12:30 p.m.') == '12:30'
assert time_converter('9:00 a.m.') == '09:00'
assert time_converter('11:15 p.m.') == '23:15'
print("Coding complete? Click 'Check' to earn cool rewards!")

View File

@ -0,0 +1,25 @@
def count_inversion(sequence):
"""
Count inversions in a sequence of numbers
"""
sequence = list(sequence)
ordered_sequence = sorted(sequence)
inversions = 0
for index, number in enumerate(ordered_sequence):
if sequence.index(number) == index:
continue
inversions += sequence.index(number) - index
sequence.insert(index, sequence.pop(sequence.index(number)))
return inversions
if __name__ == '__main__':
print("Example:")
print(count_inversion([1, 2, 5, 3, 4, 7, 6]))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert count_inversion((1, 2, 5, 3, 4, 7, 6)) == 3, "Example"
assert count_inversion((0, 1, 2, 3)) == 0, "Sorted"
assert count_inversion((5, 3, 2, 1, 0)) == 10, "Reversed"
assert count_inversion((99, -99)) == 1, "Two numbers"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

20
IceBase/cut-sentence.py Normal file
View File

@ -0,0 +1,20 @@
def cut_sentence(line, length):
"""
Cut a given sentence, so it becomes shorter than or equal to a given length.
"""
if length >= len(line):
return line
if line[length] == " ":
return line[:length]+"..."
line = line[:length].split(" ")
line.pop()
return " ".join(line)+"..."
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert cut_sentence("Hi my name is Alex", 4) == "Hi...", "First"
assert cut_sentence("Hi my name is Alex", 8) == "Hi my...", "Second"
assert cut_sentence("Hi my name is Alex", 18) == "Hi my name is Alex", "Third"
assert cut_sentence("Hi my name is Alex", 20) == "Hi my name is Alex", "Fourth"
print('Done! Do you like it? Go Check it!')

View File

@ -0,0 +1,38 @@
def steps_to_convert(line1, line2):
len_line1 = len(line1)
len_line2 = len(line2)
if line1 == "" or line2 == "":
return len_line1 if len_line1 != 0 else len_line2
similarities = has_similar(line1, line2)
if len(similarities) > 0:
return abs(max(len_line1, len_line2) - len(similarities))
else:
if len_line1 < len_line2:
if line1 in line2:
return len_line2 - len_line1
else:
if line2 in line1:
return len_line1 - len_line2
return 0
def has_similar(line1, line2):
similarities = []
for index, letter in enumerate(line1):
if letter == line2[index]:
similarities.append(index)
return similarities
if __name__ == "__main__":
# These "asserts" using only for self-checking and not necessary for auto-testing
assert steps_to_convert('line1', 'line1') == 0, "eq"
assert steps_to_convert('line1', 'line2') == 1, "2"
assert steps_to_convert('line', 'line2') == 1, "none to 2"
assert steps_to_convert('ine', 'line2') == 2, "need two more"
assert steps_to_convert('line1', '1enil') == 4, "everything is opposite"
assert steps_to_convert('', '') == 0, "two empty"
assert steps_to_convert('l', '') == 1, "one side"
assert steps_to_convert('', 'l') == 1, "another side"
print("You are good to go!")

View File

@ -0,0 +1,21 @@
def double_substring(line):
"""
length of the longest substring that non-overlapping repeats more than once.
"""
result = []
for i in range(len(line) - 1):
for j in range(i + 1, len(line) + 1):
if line[i:j] in line[j:]:
result.append(len(line[i:j]))
if len(result) > 0:
return max(result)
else:
return 0
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert double_substring('aaaa') == 2, "First"
assert double_substring('abc') == 0, "Second"
assert double_substring('aghtfghkofgh') == 3, "Third"