Skip to content

Instantly share code, notes, and snippets.

@ftfarias
Created August 28, 2019 18:48
Show Gist options
  • Save ftfarias/f82b01a7f769b70e63f5d88563756ac2 to your computer and use it in GitHub Desktop.
Save ftfarias/f82b01a7f769b70e63f5d88563756ac2 to your computer and use it in GitHub Desktop.
import copy
def verify_partial_valid_solution(A,w):
if len(w[0]) > 2:
return False
w1 = sum(w[1])
w2 = sum(w[2])
w3 = sum(w[3])
a = sum(A)
if a + w1 < w2: return False
if a + w1 < w3: return False
if a + w2 < w1: return False
if a + w2 < w3: return False
if a + w3 < w1: return False
if a + w3 < w2: return False
return True
def try_solution(a, w):
#print('---')
#print(a)
#print(w)
if len(a) == 0:
#print('test solution')
# check result
w1 = sum(w[1])
w2 = sum(w[2])
w3 = sum(w[3])
return len(w[0]) == 2 and w1 == w2 and w2 == w3
if not verify_partial_valid_solution(a,w):
#print('parcial rejected')
return False
head = a[0]
tail = a[1:]
#print('head ',head)
#print('tail ',tail)
if len(w[0]) <2:
wt = copy.deepcopy(w)
wt[0].append(head)
if try_solution(tail[:], wt[:]):
return True
wt = copy.deepcopy(w)
wt[1].append(head)
if try_solution(tail, wt):
return True
wt = copy.deepcopy(w)
wt[2].append(head)
if try_solution(tail, wt):
return True
wt = copy.deepcopy(w)
wt[3].append(head)
if try_solution(tail, wt):
return True
return False
def solution(A):
w = [[],[],[],[]]
return try_solution(A,w)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment