Skip to content

Instantly share code, notes, and snippets.

@milkpuff
Created February 20, 2022 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milkpuff/b813e0a990cf88b39ca5f69cff248f07 to your computer and use it in GitHub Desktop.
Save milkpuff/b813e0a990cf88b39ca5f69cff248f07 to your computer and use it in GitHub Desktop.
平均分一堆重量不同的糖果
import random
n = random.randint(5, 20)
candy = [random.randint(1, 10) for i in range(n)]
# n = 4
# candy = [1, 2, 3, 4]
res_x = []
def calc_half(x, target):
for i, j in enumerate(x):
if j < target:
res = calc_half(x[i + 1:], target - j)
if res:
res_x.insert(0, j)
return True
elif j == target:
res_x.append(j)
return True
else:
return False
return False
print(n, candy, sum(candy))
res = calc_half(candy, target=sum(candy) / 2)
print(res)
print(res_x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment