Created
October 29, 2021 20:36
-
-
Save xeptore/b19c76a253876a920bd6a4e9d3aefb4c to your computer and use it in GitHub Desktop.
Solution to Codility.com Coding Challenge 2nd Problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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