Skip to content

Instantly share code, notes, and snippets.

@xeptore
Created October 29, 2021 20:36
Show Gist options
  • Save xeptore/b19c76a253876a920bd6a4e9d3aefb4c to your computer and use it in GitHub Desktop.
Save xeptore/b19c76a253876a920bd6a4e9d3aefb4c to your computer and use it in GitHub Desktop.
Solution to Codility.com Coding Challenge 2nd Problem
import math
def move_element_at_index_to_last(i, l):
return l[:i] + l[i + 1:] + [l[i]]
BEST = math.inf
def find(l, d):
global BEST
if d >= BEST:
return BEST
total = 0
for i, el in enumerate(l):
if total + el < 0:
candidates = sorted(filter(lambda x: x[1] < 0, enumerate(l[:i + 1])), key=lambda x: x[1])
reses = []
for i, c in candidates:
moved = move_element_at_index_to_last(i, l)
solution_depth = find(moved, d + 1)
if solution_depth < BEST:
BEST = solution_depth
reses.append(solution_depth)
return min(reses)
total += el
return d
def solve(A):
return find(A, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment