├── README.md ├── codility-boat-alignment.py ├── codility-brackets.py ├── codility-cannonballs.py ├── codility-closest-ascenders.py ├── codility-count-bounded-slices.py ├── codility-dominator.py ├── codility-equileader.py ├── codility-fish.py ├── codility-frog-jump.py ├── codility-frog-river-one.py ├── codility-gnemonic-range-query.py ├── codility-island-waterlevels.py ├── codility-longest-ascending-walk.py ├── codility-max-counters.py ├── codility-max-double-slice-sum.py ├── codility-max-product-three.py ├── codility-max-profit.py ├── codility-max-slice-sum.py ├── codility-max_distance_monotonic.py ├── codility-min-avg-two-slice.py ├── codility-min-perimeter-rectangle.py ├── codility-nesting.py ├── codility-num-disc-intersects.py ├── codility-passing-cars.py ├── codility-perm-check.py ├── codility-perm-missing-elm.py ├── codility-shortest-adjacent-sequence.py ├── codility-stone-wall.py ├── codility-tape-equilibrium.py ├── codility-triangular-triplet.py └── codility-visit-maximal-children.py /README.md: -------------------------------------------------------------------------------- 1 | A number of Gold (100%) solutions to codility problems written in Python. -------------------------------------------------------------------------------- /codility-boat-alignment.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(R, X, M): 3 | top, solution, space_available = None, 0, 0 4 | if len(R) * (2*X) > M: return -1 5 | 6 | for boat_position in R: 7 | boat, move_right = boat_position, 0 8 | 9 | if not top: 10 | index = max(boat, X) 11 | top = {'left':index - X, 'right': index + X, 'previous':top, 'max':0, 'min':boat - index} 12 | space_available = index - X 13 | solution = abs(boat - index) 14 | continue 15 | 16 | boat = max(X, min(M - X, boat)) 17 | overlap = (top['right']) - (boat - X) 18 | midpoint = ceil(overlap/2.0) 19 | 20 | if overlap > 0: 21 | space_right = M - (boat+X) 22 | move_right = space_right if space_right < midpoint else midpoint 23 | space_right -= move_right 24 | overlap -= move_right 25 | boat += move_right 26 | 27 | while overlap and space_available: 28 | gap = top['left'] - (top['previous']['right'] if top['previous'] else 0) 29 | diff = ceil((top['max'] + overlap + move_right) / 2) 30 | adjust_right = min(space_right, diff - move_right) if space_right and diff - move_right > 0 else 0 31 | boat += adjust_right 32 | move_right += adjust_right 33 | space_right -= adjust_right 34 | move_left = min(gap, overlap) - adjust_right 35 | overlap -= adjust_right + move_left 36 | space_available -= move_left 37 | top['max'] += move_left 38 | top['right'] -= move_left 39 | top['left'] -= move_left 40 | 41 | if move_left == gap and top['previous']: 42 | top, rightboats = top['previous'], top 43 | top['right'],top['max'] = rightboats['right'], max(top['max'], rightboats['max']) 44 | 45 | boat += overlap 46 | 47 | if not (boat - X) - top['right']: 48 | top['right'], top['min'] = boat + X, max(top['min'], boat - boat_position) 49 | else: 50 | top, space_available = {'left':boat - X, 'right': boat + X, 'previous':top, 'max':0, 'min':0}, space_available + (boat - X) - top['right'] 51 | 52 | solution = max(solution, max(top['max'], abs(top['min']))) 53 | 54 | return int(solution) 55 | -------------------------------------------------------------------------------- /codility-brackets.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(S): 3 | open_brackets, closed_brackets, stack = {'{':1,'[':2,'(':3}, {'}':1,']':2,')':3}, [] 4 | for char in S: 5 | if char in open_brackets: 6 | stack.append(open_brackets[char]) 7 | elif not len(stack) or closed_brackets[char] != stack.pop(): 8 | return 0 9 | return 1 if not len(stack) else 0 10 | 11 | 12 | solution("()(()()(((()())(()()))") #0 -------------------------------------------------------------------------------- /codility-cannonballs.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A, B): 3 | heighest = 0 4 | heights = [] 5 | for height in A: 6 | heighest, old = max(height, heighest), heighest 7 | heights.append(heighest) 8 | 9 | current = 0 10 | points = [0] * (max(heights) + 1) 11 | for index, height in enumerate(heights): 12 | if current != height: 13 | for i in xrange(current + 1, height + 1 , 1): 14 | points[i] = index 15 | current = height 16 | 17 | for ball in B: 18 | index = (points[ball] if len(points) > ball else 0) - 1 19 | if index == -1: 20 | continue 21 | A[index] += 1 22 | dropped_height = A[index] 23 | 24 | if points[dropped_height] > index: 25 | points[dropped_height] = index 26 | return A 27 | 28 | -------------------------------------------------------------------------------- /codility-closest-ascenders.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | ret = [] 4 | for left,right in zip(get_closest_ascenders(A) ,list(reversed(get_closest_ascenders(list(reversed(A)))))): 5 | value = min(left, right) 6 | ret.append(0 if value == float('inf') else value) 7 | return ret 8 | 9 | def get_closest_ascenders(A): 10 | stack = [0] * len(A) 11 | ascenders = [0] * len(A) 12 | stack_index = -1 13 | for index, a in enumerate(A): 14 | while stack_index > -1 and A[stack[stack_index]] <= a: 15 | stack_index -= 1 16 | if stack_index == -1: 17 | ascenders[index] = float('inf') 18 | else: 19 | ascenders[index] = index - stack[stack_index] 20 | stack_index += 1 21 | stack[stack_index] = index 22 | return ascenders 23 | 24 | 25 | print solution([4, 3, 1, 4, -1, 2, 1, 5, 7]) -------------------------------------------------------------------------------- /codility-count-bounded-slices.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(K, A): 3 | lindex, left = 0, A[0] 4 | maxi, mini = -float('inf'), float('inf') 5 | ranges,maxes,mins,overlaps = [],[],[],[] 6 | max_index = min_index = 0 7 | 8 | for rindex, right in enumerate(A): 9 | 10 | maxi, mini, prev_max, prev_min = max(maxi, right), min(mini, right), None, None 11 | 12 | while(len(maxes) > max_index and maxes[-1][0] < right): prev_max = maxes.pop() 13 | while(len(mins) > min_index and mins[-1][0] > right): prev_min = mins.pop() 14 | 15 | maxes.append((right, prev_max[1] if prev_max and prev_max[0] < right else rindex)) 16 | mins.append((right, prev_min[1] if prev_min and prev_min[0] > right else rindex)) 17 | 18 | if abs(maxi - mini) > K: 19 | 20 | ranges.append(rindex - lindex) 21 | 22 | if not maxi == right: 23 | while max_index < len(maxes) and maxes[max_index][0] > mini + K: max_index += 1 24 | next_point = maxes[max_index] 25 | maxi, lindex = next_point 26 | else: 27 | while min_index < len(mins) and mins[min_index][0] < maxi - K: min_index += 1 28 | next_point = mins[min_index] 29 | mini, lindex = next_point 30 | 31 | overlaps.append(rindex - lindex) 32 | 33 | ranges.append(rindex - lindex + 1) 34 | 35 | return min( 36 | reduce(lambda total, a: total - (a * (a+1))/2, overlaps, 37 | reduce(lambda total, a: total + (a * (a+1))/2, ranges, 0)), 38 | 1000000000) 39 | 40 | #print solution(6, [2, 2, 3, 3, 9, 8, 5, 1, 7, 4, 6, 10]) #40 41 | #print solution(4, [1, 3, -3, -2, -1, 2, 3, 1, 4]) #23 42 | #print solution(2, [3, 5, 7, 6, 3]) #9 43 | #print solution(5, [2, 3, 2, 9, 8, 3, 10, 6, 7, 1, 10, 9]) #21 44 | #print solution(3, [10, 1, 7, 2, 2, 9, 3, 6, 2, 7, 3, 3]) # 15 45 | #print solution(5, [10, 7, 10, 4, 9, 3, 5, 8, 2, 7, 7, 3]) #25 46 | #print solution(6, [4, 5, 8, 5, 1, 4, 6, 8, 7, 2, 2, 5]) # 44 -------------------------------------------------------------------------------- /codility-dominator.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | stack = [] 4 | for a in A: 5 | stack.append(a) 6 | while len(stack) > 1 and stack[-1] != stack[-2]: 7 | stack.pop(),stack.pop() 8 | if stack: 9 | candidate, total = stack[0], 0 10 | for index, a in enumerate(A): 11 | total += 1 if a == candidate else 0 12 | if total > len(A)/2: 13 | return index 14 | return -1 15 | -------------------------------------------------------------------------------- /codility-equileader.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | def get_leader(A): 4 | from collections import defaultdict 5 | stack, leaders = [], [] 6 | counts = defaultdict(int) 7 | for index, a in enumerate(A): 8 | counts[a] += 1 9 | stack.append(a) 10 | while len(stack) > 1 and stack[-1] != stack[-2]: 11 | stack.pop(),stack.pop() 12 | leaders.append(stack[-1] if( stack and counts[stack[-1]] > (index + 1)/2.) else -1) 13 | return leaders 14 | return len(filter(lambda x: x[0] == x[1] and x[0] != -1, zip(get_leader(A), list(reversed(get_leader(reversed(A))))[1:]))) 15 | 16 | print solution([1, 2, 3, 4, 5]) -------------------------------------------------------------------------------- /codility-fish.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A, B): 3 | stack, alive = [], len(A) 4 | for fish in zip(A, B): 5 | size, up = fish 6 | if not up: 7 | while stack and stack[-1] < size: 8 | alive -= 1 9 | stack.pop() 10 | alive -= 1 if stack else 0 11 | else: 12 | stack.append(size) 13 | 14 | return alive 15 | 16 | 17 | 18 | print solution([4, 3, 2, 1, 5], [0, 1, 0, 0, 0]) #2 -------------------------------------------------------------------------------- /codility-frog-jump.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(X, Y, D): 3 | import math 4 | return int(math.ceil((Y - X)/float(D))) 5 | -------------------------------------------------------------------------------- /codility-frog-river-one.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(X, A): 3 | # write your code in Python 2.6 4 | frog, leaves = 0, [False] * (X) 5 | for minute, leaf in enumerate(A): 6 | if leaf <= X: 7 | leaves[leaf - 1] = True 8 | while leaves[frog]: 9 | frog += 1 10 | if frog == X: return minute 11 | return -1 12 | 13 | 14 | #print solution(5, [1, 3, 9, 4, 2, 3, 5, 4]) -------------------------------------------------------------------------------- /codility-gnemonic-range-query.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(S, P, Q): 3 | table, charmap = {1:[0], 2:[0], 3:[0], 4:[0]}, {'A':1, 'C':2, 'G':3, 'T':4} 4 | for char in S: 5 | for charvalue, prefixsums in table.items(): 6 | prefixsums.append( prefixsums[-1] + charvalue if charvalue == charmap[char] else prefixsums[-1]) 7 | results = [] 8 | for left, right in zip(P, Q): 9 | for i in range(4): 10 | if(table[i + 1][left] - table[i + 1][right + 1]): 11 | results.append(i + 1) 12 | break 13 | 14 | return results 15 | 16 | 17 | print solution('GACACCATA', [0, 0, 4, 7], [8, 2, 5, 7]) -------------------------------------------------------------------------------- /codility-island-waterlevels.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A, B): 3 | water_levels, current_peak, total_peaks = [1] + [0] * max(max(A),max(B)), None, 0 4 | 5 | for previous_water_level, water_level in zip(A[:-1], A[1:]): 6 | 7 | if water_level < previous_water_level: 8 | current_peak = [water_level, current_peak[1]] if current_peak else [water_level, previous_water_level] 9 | 10 | elif water_level > previous_water_level and current_peak != None: 11 | water_levels[current_peak[0]] += 1 12 | water_levels[current_peak[1]] -= 1 13 | current_peak = None 14 | 15 | water_levels[current_peak[1] if current_peak else water_level] -= 1 16 | 17 | for i, l in enumerate(water_levels): water_levels[i] = total_peaks = total_peaks + l 18 | 19 | return [water_levels[day] for day in B] 20 | -------------------------------------------------------------------------------- /codility-longest-ascending-walk.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(N, A, B, C): 3 | tokens = [[[0,-float('inf')]] for n in xrange(N)] 4 | C = sorted([(item, index) for index, item in enumerate(C)]) 5 | 6 | maxlength = 0 7 | to_remove = [] 8 | for attractiveness, index in C: 9 | frm, to = A[index], B[index] 10 | left_token, right_token = None, None 11 | 12 | if frm == to: 13 | best_token = None 14 | 15 | to_remove = [] 16 | for token in tokens[frm]: 17 | if token[1] < attractiveness: 18 | if best_token: 19 | if best_token[0] < token[0]: 20 | best_token = token 21 | else: 22 | best_token = token 23 | 24 | if best_token: 25 | left_token = best_token 26 | maxlength = max(maxlength, best_token[0] + 1) 27 | 28 | else: 29 | to_remove = [] 30 | best_token = None 31 | for token in tokens[frm]: 32 | if token[1] < attractiveness: 33 | if best_token: 34 | if best_token[0] < token[0]: 35 | best_token = token 36 | else: 37 | best_token = token 38 | 39 | if best_token: 40 | left_token = best_token 41 | maxlength = max(maxlength, best_token[0] + 1) 42 | 43 | best_token = None 44 | for token in tokens[to]: 45 | if token[1] < attractiveness: 46 | if best_token: 47 | if best_token[0] < token[0]: 48 | best_token = token 49 | else: 50 | best_token = token 51 | 52 | if best_token: 53 | right_token = best_token 54 | maxlength = max(maxlength, best_token[0] + 1) 55 | 56 | if left_token: 57 | tokens[to].append([left_token[0] + 1, attractiveness]) 58 | tokens[frm] = filter(lambda x: x[1] >= attractiveness or x == left_token, tokens[frm]) 59 | if right_token: 60 | tokens[to] = filter(lambda x: x[1] >= attractiveness or x == right_token, tokens[to]) 61 | tokens[frm].append([right_token[0] + 1, attractiveness]) 62 | 63 | return maxlength 64 | -------------------------------------------------------------------------------- /codility-max-counters.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(N, A): 3 | counters = [0] * N 4 | max_value, threshold = 0, 0 5 | for a in A: 6 | index = a - 1 7 | if index == N: 8 | threshold = max_value 9 | else: 10 | counters[index] = max(threshold + 1, counters[index] + 1) 11 | max_value = max(max_value, counters[index]) 12 | for index, counter in enumerate(counters): 13 | counters[index] = max(threshold, counter) 14 | return counters 15 | 16 | 17 | print solution(5, [3, 4, 4, 6, 1, 4, 4]) -------------------------------------------------------------------------------- /codility-max-double-slice-sum.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | N, starts, ends = len(A), [0] * N, [0] * N 4 | for i in range(1,N-1): 5 | left, right = i, N-i-1 6 | starts[left] = max(starts[left - 1] + A[left], 0) 7 | ends[right] = max(ends[right + 1] + A[right], 0) 8 | return max((starts[i-1] + ends[i+1] for i in range(1, N-1))) 9 | -------------------------------------------------------------------------------- /codility-max-product-three.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | index_pairs = list(sorted(((a, index) for index,a in enumerate(A)))) 4 | return max(index_pairs[-1][0] * index_pairs[-2][0] * index_pairs[-3][0],index_pairs[-1][0] * index_pairs[0][0] * index_pairs[1][0]) 5 | -------------------------------------------------------------------------------- /codility-max-profit.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | minimum, maxprofit = float('inf'), 0 4 | for value in A: 5 | minimum = min(value, minimum) 6 | maxprofit = max(value - minimum, maxprofit) 7 | return maxprofit 8 | 9 | print solution([4,5,6,9,1,10]) -------------------------------------------------------------------------------- /codility-max-slice-sum.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | 4 | maxslice, ending = -float('inf'), None 5 | for value in A: 6 | ending = value if ending == None else max(value, ending + value) 7 | maxslice = max(ending, maxslice) 8 | return maxslice 9 | 10 | 11 | print solution([3, 6, 64, -33, -60, 2, 94, -11, 12]) #97 12 | -------------------------------------------------------------------------------- /codility-max_distance_monotonic.py: -------------------------------------------------------------------------------- 1 | def solution(A): 2 | current = None 3 | left, right = A[0], A[-1] 4 | ltor, rtol = [(left, 0)],[(right, len(A) - 1)] 5 | 6 | for index in xrange(len(A)): 7 | rindex = len(A) - index - 1 8 | if left > A[index]: 9 | left = A[index] 10 | ltor.append((left, index)) 11 | if right < A[rindex]: 12 | right = A[rindex] 13 | rtol.append((right, rindex)) 14 | 15 | ltor_index, rng, maxrange = len(ltor) - 1, 0,0 16 | 17 | for rtol_group in rtol: 18 | right, rindex = rtol_group 19 | left, lindex = ltor[ltor_index] 20 | 21 | while left <= right: 22 | if ltor_index == -1: break 23 | rng = rindex - ltor[ltor_index][1] 24 | maxrange = max(maxrange, rng) 25 | ltor_index -= 1 26 | left, lindex = ltor[ltor_index] 27 | if ltor_index == -1: break 28 | while ltor[ltor_index][1] >= rindex: 29 | ltor_index -= 1 30 | if ltor_index == -1: break 31 | 32 | 33 | 34 | return maxrange 35 | 36 | 37 | print solution([7, 10, 3, 9, 4, 10, 3, 1])#5 38 | print solution([5, 3, 6, 3, 4, 2])#3 39 | -------------------------------------------------------------------------------- /codility-min-avg-two-slice.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | total, length, left_index = A[0], 1, 0 4 | min_average, min_index = float('inf'), float('inf') 5 | 6 | for index, (left, right) in enumerate(zip(A[:-1],A[1:])): 7 | total, length = total + right, length + 1 8 | average = total / float(length) 9 | if (left + right)/ 2.0 <= average: 10 | total, length = (left + right), 2 11 | average = total / float(length) 12 | left_index = index 13 | 14 | if average < min_average: 15 | min_average, min_index = average, left_index 16 | return min_index 17 | 18 | 19 | print solution([10, 10, -1, 2, 4, -1, 2, -1]) #5 -------------------------------------------------------------------------------- /codility-min-perimeter-rectangle.py: -------------------------------------------------------------------------------- 1 | # 2 | # Author: Wouter Coppieters 3 | # 4 | # 1. MinPerimeterRectangle 5 | # 6 | # An integer N is given, representing the area of some rectangle. 7 | # The area of a rectangle whose sides are of length A and B is A * B, and the perimeter is 2 * (A + B). 8 | # The goal is to find the minimal perimeter of any rectangle whose area equals N. The sides of this rectangle should be only integers. 9 | # For example, given integer N = 30, rectangles of area 30 are: 10 | # (1, 30), with a perimeter of 62, 11 | # (2, 15), with a perimeter of 34, 12 | # (3, 10), with a perimeter of 26, 13 | # (5, 6), with a perimeter of 22. 14 | # Write a function: 15 | # def solution(N) 16 | # that, given an integer N, returns the minimal perimeter of any rectangle whose area is exactly equal to N. 17 | # For example, given an integer N = 30, the function should return 22, as explained above. 18 | # Assume that: 19 | # N is an integer within the range [1..1,000,000,000]. 20 | # Complexity: 21 | # expected worst-case time complexity is O(sqrt(N)); 22 | # expected worst-case space complexity is O(1).def solution(N): 23 | import math 24 | 25 | div = int(math.ceil(math.sqrt(N))) 26 | while N % div != 0: 27 | div -= 1 28 | 29 | return ((N/div*2) + div + div) -------------------------------------------------------------------------------- /codility-nesting.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(S): 3 | open_brackets, closed_brackets, stack = {'{':1,'[':2,'(':3}, {'}':1,']':2,')':3}, [] 4 | for char in S: 5 | if char in open_brackets: 6 | stack.append(open_brackets[char]) 7 | elif not len(stack) or closed_brackets[char] != stack.pop(): 8 | return 0 9 | return 1 if not len(stack) else 0 10 | -------------------------------------------------------------------------------- /codility-num-disc-intersects.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | from collections import defaultdict 4 | starts, ends, discs, intersects = [0] * len(A), [0] * len(A), 0, 0 5 | if not len(A): 6 | return 0 7 | for index, radius in enumerate(A): 8 | left, right = index - radius, index + radius 9 | starts[max(0,left)] += 1 10 | ends[min(len(A) - 1,right)] += 1 11 | 12 | for i in range(len(A)): 13 | if starts[i] > 0: 14 | intersects += discs * starts[i] + (starts[i] * (starts[i] - 1)/2) 15 | discs += starts[i] 16 | discs -= ends[i] 17 | 18 | return intersects if intersects <= 10000000 else -1 19 | 20 | 21 | print solution([1, 5, 8, 7, 8, 4, 8, 5, 0, 5]) -------------------------------------------------------------------------------- /codility-passing-cars.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | right,total = 0,0 4 | for left in A: 5 | right, total = (right + 1, total) if not left else (right, total + right) 6 | return total if total < 1000000000 else -1 7 | 8 | -------------------------------------------------------------------------------- /codility-perm-check.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | present = [False] * len(A) 4 | for a in A: 5 | if a > len(present): 6 | return 0 7 | present[a - 1] = True 8 | for is_valid in present: 9 | if not is_valid: 10 | return 0 11 | return 1 12 | 13 | print solution([4, 1, 3]) -------------------------------------------------------------------------------- /codility-perm-missing-elm.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | expected = (len(A)+2) * (len(A) + 1)/2 4 | for a in A: 5 | expected -= a 6 | return expected -------------------------------------------------------------------------------- /codility-shortest-adjacent-sequence.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | from collections import defaultdict 4 | from Queue import Queue 5 | nodes = defaultdict(dict) 6 | left = None 7 | first = None 8 | for right in A: 9 | if left != None: 10 | nodes[left][right] = nodes[right] 11 | nodes[right][left] = nodes[left] 12 | else: 13 | first = right 14 | left = right 15 | if left == first: 16 | return 1 17 | stack = Queue() 18 | stack.put((nodes[first], 1)) 19 | while stack.qsize(): 20 | evaluate, depth = stack.get() 21 | if 'visited' in evaluate: 22 | continue 23 | for index, item in evaluate.items(): 24 | if index == left: 25 | return depth + 1 26 | stack.put((item, depth + 1)) 27 | evaluate['visited'] = True 28 | return 1 29 | 30 | 31 | -------------------------------------------------------------------------------- /codility-stone-wall.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(H): 3 | blocks, previous, stack = 0, 0, [] 4 | for current in H: 5 | if current > previous: 6 | blocks += 1 7 | elif current < previous: 8 | existing = previous 9 | while len(stack) and stack[-1] >= current: 10 | existing = stack.pop() 11 | blocks += 1 if existing != current else 0 12 | previous = current 13 | stack.append(previous) 14 | return blocks 15 | 16 | 17 | 18 | 19 | 20 | print solution([8, 8, 5, 7, 9, 8, 7, 4, 8]) #7 -------------------------------------------------------------------------------- /codility-tape-equilibrium.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | total, minimum, left = sum(A), float('inf'), 0 4 | for a in A[:-1]: 5 | left += a 6 | minimum = min(abs(total - left - left), minimum) 7 | return minimum 8 | 9 | print solution([3, 1, 2, 4, 3]) -------------------------------------------------------------------------------- /codility-triangular-triplet.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(A): 3 | A = sorted(A) 4 | for left, mid, right in zip(A[:-2], A[1:-1], A[2:]): 5 | if left + mid > right and left + right > mid: 6 | return 1 7 | return 0 8 | 9 | print solution([10, 2, 5, 1, 8, 20]) -------------------------------------------------------------------------------- /codility-visit-maximal-children.py: -------------------------------------------------------------------------------- 1 | # Author: Wouter Coppieters 2 | def solution(K, T): 3 | answer, end_points, visited = [], [], [0] * len(T) 4 | Tree = [{} for i in range(len(T))] 5 | 6 | for index, value in enumerate(T): Tree[index][value], Tree[value][index] = True, True 7 | 8 | root = {'index':K, 'next':None, 'skip':False, 'neighbors':0} 9 | children = Tree[root['index']].keys() 10 | stack = [{'index':child, 'next':root, 'skip':False, 'neighbors':0} for child in children] + [None] * len(T) 11 | visited[K] = True 12 | for child in children: 13 | visited[child] = True 14 | 15 | stack_index, stack_end = 0, len(children) 16 | 17 | while(stack_index < stack_end): 18 | node, stack_index = stack[stack_index], stack_index + 1 19 | 20 | for child in filter(lambda child: (not visited[child]) and child != node['index'], Tree[node['index']].keys()): 21 | visited[child], node['neighbors'] = True, node['neighbors'] + 1 22 | stack[stack_end], stack_end = {'index':child, 'next':node, 'skip':False, 'neighbors':0}, stack_end + 1 23 | 24 | end_points.append(node) if not node['neighbors'] else None 25 | 26 | next_round = sorted(end_points, key=lambda s: -s['index']) 27 | 28 | while len(end_points): 29 | next_round, end_points = [], next_round 30 | for point in end_points: 31 | if point['index'] == K: continue 32 | elif point['next'] == None or point['next']['index'] == K or (point['next'] and point['next']['neighbors'] > 1): 33 | answer.append(point['index']) 34 | if point['next']: point['next']['neighbors'] -= 1 35 | elif point['index'] != K: 36 | point['next'] = point['next']['next'] 37 | next_round.append(point) 38 | 39 | return list(reversed(answer + [K])) 40 | 41 | print solution(16, [10, 8, 3, 12, 6, 9, 10, 11, 4, 1, 16, 6, 9, 14, 10, 1, 16]) 42 | --------------------------------------------------------------------------------