Skip to content
Snippets Groups Projects
Commit 24751052 authored by Dennis Ahrens's avatar Dennis Ahrens
Browse files

Add solutions for islands Elemantary and Home

parents
No related branches found
No related tags found
No related merge requests found
def checkio(number):
number_s = str(number).replace("0", "")
r = int(number_s[0])
for n in number_s[1:]:
r = r * int(n)
return r
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(123405) == 120
assert checkio(999) == 729
assert checkio(1000) == 1
assert checkio(1111) == 1
def checkio(array):
"""
sums even-indexes elements and multiply at the last
"""
if len(array) == 0: return 0
sum = 0
for i in range(len(array)):
if i % 2 == 0:
sum += array[i]
return sum * array[-1]
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)*5=30"
assert checkio([1, 3, 5]) == 30, "(1+5)*5=30"
assert checkio([6]) == 36, "(6)*6=36"
assert checkio([]) == 0, "An empty array = 0"
#Your optional code here
#You can import some modules or create additional functions
def checkio(number):
if number % 5 == 0 and number % 3 == 0:
return 'Fizz Buzz'
elif number % 5 == 0:
return 'Buzz'
elif number % 3 == 0:
return 'Fizz'
else:
return str(number)
#Some hints:
#Convert a number in the string with str(n)
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(15) == "Fizz Buzz", "15 is divisible by 3 and 5"
assert checkio(6) == "Fizz", "6 is divisible by 3"
assert checkio(5) == "Buzz", "5 is divisible by 5"
assert checkio(7) == "7", "7 is not divisible by 3 or 5"
def flatten(dictionary):
stack = [((), dictionary)]
result = {}
while stack:
path, current = stack.pop()
for k, v in current.items():
if isinstance(v, dict):
if len(v.keys()) == 0:
result["/".join((path + (k,)))] = ""
continue
stack.append((path + (k,), v))
else:
result["/".join((path + (k,)))] = v
return result
if __name__ == '__main__':
#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"}
\ No newline at end of file
def index_power(array, n):
"""
Find Nth power of the element with index N.
"""
if n >= len(array):
return -1
g = [array[n]] * n
r = 1
for e in g:
r*=e
return r
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert index_power([1, 2, 3, 4], 2) == 9, "Square"
assert index_power([1, 3, 10, 100], 3) == 1000000, "Cube"
assert index_power([0, 1], 0) == 1, "Zero power"
assert index_power([1, 2], 3) == -1, "IndexError"
import types
def min(*args, **kwargs):
key = kwargs.get("key", None)
if len(args) > 1 \
or not hasattr(args[0], '__iter__'): return sorted(args, key=key)[0]
else: return sorted(args[0], key=key)[0]
def max(*args, **kwargs):
key = kwargs.get("key", None)
i = -1
if key == int:
keyed_args = sorted(map(key, args), reverse=True)
last_v = keyed_args[0]
for k, v in enumerate(keyed_args[1:]):
if v == last_v: i -= 1
if len(args) > 1 \
or not hasattr(args[0], '__iter__'): return sorted(args, key=key)[i]
else: return sorted(args[0], key=key)[-1]
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert max(3, 2) == 3, "Simple case max"
assert min(3, 2) == 2, "Simple case min"
assert max([1, 2, 0, 3, 4]) == 4, "From a list"
assert min("hello") == "e", "From string"
assert min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1]) == [9, 0], "lambda key"
assert max(2.2, 5.6, 5.9, key=int) == 5.6, "Two maximal items"
assert max(range(6)) == 5, "with range"
assert min(abs(i) for i in range(-10, 10)) == 0
assert max([1, 2, 3], [5, 6], [7], [0, 0, 0, 1]) == [7]
def checkio(*args):
return sorted(args)[-1]-sorted(args)[0] if len(args) >= 2 else 0
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
def almost_equal(checked, correct, significant_digits):
precision = 0.1 ** significant_digits
return correct - precision < checked < correct + precision
assert almost_equal(checkio(1, 2, 3), 2, 3), "3-1=2"
assert almost_equal(checkio(5, -5), 10, 3), "5-(-5)=10"
assert almost_equal(checkio(10.2, -2.2, 0, 1.1, 0.5), 12.4, 3), "10.2-(-2.2)=12.4"
assert almost_equal(checkio(), 0, 3), "Empty"
def checkio(data):
out = []
for i in range(len(data)):
if data[i] in data[:i] + data[i+1:]:
out.append(data[i])
return out
if __name__ == "__main__":
#These "asserts" using only for self-checking and not necessary for auto-testing
assert isinstance(checkio([1]), list), "The result must be a list"
assert checkio([1, 2, 3, 1, 3]) == [1, 3, 1, 3], "1st example"
assert checkio([1, 2, 3, 4, 5]) == [], "2nd example"
assert checkio([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5], "3rd example"
assert checkio([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9], "4th example"
class Path:
def __init__(self,nodes, totalCost):
self.nodes = nodes;
self.totalCost = totalCost;
def getNodes(self):
return self.nodes
def getTotalMoveCost(self):
return self.totalCost
class Node:
def __init__(self,location,mCost,lid,parent=None):
self.location = location # where is this node located
self.mCost = mCost # total move cost to reach this node
self.parent = parent # parent node
self.score = 0 # calculated score for this node
self.lid = lid # set the location id - unique for each location in the map
def __eq__(self, n):
if n.lid == self.lid:
return 1
else:
return 0
class AStar:
def __init__(self,maphandler):
self.mh = maphandler
def _getBestOpenNode(self):
bestNode = None
for n in self.on:
if not bestNode:
bestNode = n
else:
if n.score<=bestNode.score:
bestNode = n
return bestNode
def _tracePath(self,n):
nodes = [];
totalCost = n.mCost;
p = n.parent;
nodes.insert(0,n);
while 1:
if p.parent is None:
break
nodes.insert(0,p)
p=p.parent
return Path(nodes,totalCost)
def _handleNode(self,node,end):
i = self.o.index(node.lid)
self.on.pop(i)
self.o.pop(i)
self.c.append(node.lid)
nodes = self.mh.getAdjacentNodes(node,end)
for n in nodes:
if n.location == end:
# reached the destination
return n
elif n.lid in self.c:
# already in close, skip this
continue
elif n.lid in self.o:
# already in open, check if better score
i = self.o.index(n.lid)
on = self.on[i];
if n.mCost<on.mCost:
self.on.pop(i);
self.o.pop(i);
self.on.append(n);
self.o.append(n.lid);
else:
# new node, append to open list
self.on.append(n);
self.o.append(n.lid);
return None
def findPath(self,fromlocation, tolocation):
self.o = []
self.on = []
self.c = []
end = tolocation
fnode = self.mh.getNode(fromlocation)
self.on.append(fnode)
self.o.append(fnode.lid)
nextNode = fnode
while nextNode is not None:
finish = self._handleNode(nextNode,end)
if finish:
return self._tracePath(finish)
nextNode=self._getBestOpenNode()
return None
class SQ_Location:
"""A simple Square Map Location implementation"""
def __init__(self,x,y):
self.x = x
self.y = y
def __eq__(self, l):
"""MUST BE IMPLEMENTED"""
if l.x == self.x and l.y == self.y:
return 1
else:
return 0
def cardinal_direction(self, location):
print('sx: %i, sy: %i, lx: %i, ly: %i' % (self.x, self.y, location.x, location.y))
if self.x > location.x: return 'S'
if self.x < location.x: return 'N'
if self.y > location.y: return 'E'
if self.y < location.y: return 'W'
class SQ_MapHandler:
"""A simple Square Map implementation"""
def __init__(self,mapdata,width,height):
self.m = mapdata
self.w = width
self.h = height
def getNode(self, location):
"""MUST BE IMPLEMENTED"""
x = location.x
y = location.y
if x<0 or x>=self.w or y<0 or y>=self.h:
return None
d = self.m[(y*self.w)+x]
if d == 1:
return None
return Node(location,d,((y*self.w)+x))
def getAdjacentNodes(self, curnode, dest):
"""MUST BE IMPLEMENTED"""
result = []
cl = curnode.location
dl = dest
n = self._handleNode(cl.x+1,cl.y,curnode,dl.x,dl.y)
if n: result.append(n)
n = self._handleNode(cl.x-1,cl.y,curnode,dl.x,dl.y)
if n: result.append(n)
n = self._handleNode(cl.x,cl.y+1,curnode,dl.x,dl.y)
if n: result.append(n)
n = self._handleNode(cl.x,cl.y-1,curnode,dl.x,dl.y)
if n: result.append(n)
return result
def _handleNode(self,x,y,fromnode,destx,desty):
n = self.getNode(SQ_Location(x,y))
if n is not None:
dx = max(x,destx) - min(x,destx)
dy = max(y,desty) - min(y,desty)
emCost = dx+dy
n.mCost += fromnode.mCost
n.score = n.mCost+emCost
n.parent=fromnode
return n
return None
def checkio(maze_map):
astar = AStar(SQ_MapHandler([item for sublist in maze_map for item in sublist],12,12))
start = SQ_Location(1,1)
end = SQ_Location(10,10)
route = ''
for node in astar.findPath(start,end).getNodes():
route += start.cardinal_direction(node.location)
start = node.location
print('x: %i y: %i' % (node.location.x, node.location.y))
print(route)
return route
if __name__ == '__main__':
#This code using only for self-checking and not necessary for auto-testing
def check_route(func, labyrinth):
MOVE = {"S": (1, 0), "N": (-1, 0), "W": (0, -1), "E": (0, 1)}
#copy maze
route = func([row[:] for row in labyrinth])
pos = (1, 1)
goal = (10, 10)
for i, d in enumerate(route):
move = MOVE.get(d, None)
if not move:
print("Wrong symbol in route")
return False
pos = pos[0] + move[0], pos[1] + move[1]
if pos == goal:
return True
if labyrinth[pos[0]][pos[1]] == 1:
print("Player in the pit")
return False
print("Player did not reach exit")
return False
# These assert are using only for self-testing as examples.
assert check_route(checkio, [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1],
[1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1],
[1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1],
[1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "First maze"
assert check_route(checkio, [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Empty maze"
assert check_route(checkio, [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Up and down maze"
assert check_route(checkio, [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 1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 1],
[1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
[1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "The big dead end."
print("The local tests are done.")
\ No newline at end of file
LITERALS = 'abcdefgh'
def get_guarding(field):
'''Returns all field names that may guard this field.'''
literal = field[0]
number = int(field[1])
if number == 0:
return [] # can not be guarded by a pawn
number_string = str(number - 1)
literal_index = LITERALS.index(literal)
if literal_index == 0: return [LITERALS[literal_index + 1] + number_string]
elif literal_index == 7: return [LITERALS[literal_index - 1] + number_string]
else: return [LITERALS[literal_index - 1] + number_string, LITERALS[literal_index + 1] + number_string]
def is_guarded(pawn, pawns):
'''Checks wether or not one of the given pawns stays on a field that protects the given pawn.'''
for can_guard in get_guarding(pawn):
if can_guard in pawns:
return True
return False
def safe_pawns(pawns):
'''Counts the pawns that are safe.'''
result = 0
for pawn in pawns:
if is_guarded(pawn, pawns.copy()):
result += 1
return result
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) == 6
assert safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}) == 1
def left_join(phrases):
return ','.join(phrases).replace("right", "left")
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert left_join(("left", "right", "left", "stop")) == "left,left,left,stop", "All to left"
assert left_join(("bright aright", "ok")) == "bleft aleft,ok", "Bright Left"
assert left_join(("brightness wright",)) == "bleftness wleft", "One phrase"
assert left_join(("enough", "jokes")) == "enough,jokes", "Nothing to replace"
ROMAN_MAP = (('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
('V', 5),
('IV', 4),
('I', 1))
def checkio(data):
result = ""
for literal, integer in ROMAN_MAP:
while data >= integer:
result += literal
data -= integer
return result
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio(6) == 'VI', '6'
assert checkio(76) == 'LXXVI', '76'
assert checkio(499) == 'CDXCIX', '499'
assert checkio(3888) == 'MMMDCCCLXXXVIII', '3888'
\ No newline at end of file
def find_message(text):
"""joins together all letters that are in upper case."""
return ''.join(map(lambda letter: letter if letter.isupper() else '',text))
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert find_message("How are you? Eh, ok. Low or Lower? Ohhh.") == "HELLO", "hello"
assert find_message("hello world!") == "", "Nothing"
assert find_message("HELLO WORLD!!!") == "HELLOWORLD", "Capitals"
def checkio(words):
counts = 0
for word in words.split(" "):
counts = 0 if word.isdigit() else counts + 1
if counts == 3: return True
return False
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio("Hello World hello") == True, "Hello"
assert checkio("He is 123 man") == False, "123 man"
assert checkio("1 2 3 4") == False, "Digits"
assert checkio("bla bla bla bla") == True, "Bla Bla"
assert checkio("Hi") == False, "Hi"
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment