问题
I'm trying to make a simple recursive function that will generate a list of nested lists in Python. The end result will represent a single elimination tournament bracket. I'm hoping that creating a list like this will make it easy for me to generate what I need. This will later be used to create models for tournament matches.
So if there is a tournament of 4 participants:
[[1,4],[2,3]]
Tournament of 7 participants:
[[1,[4,5]],[[2,7],[3,6]]]
Or a tournament of 8 participants:
[[[1,8],[4,5]],[[2,7],[3,6]]]
I haven't had an algorithms class yet (I'm hoping the class will end up helping with things like this) so I'm not completely sure how to approach this problem. Below is my attempt so far.
def decide_rounds(list_to_fill, player_nums):
if len(player_nums) < 3:
for num in player_nums:
list_to_fill.append(num)
return
left = []
decide_rounds(left, ??????) #Tried passing various things to these with no avail.
list_to_fill.append(left)
right = []
decide_rounds(right, ???????)
list_to_fill.append(right)
Any help or explanation on how to approach this would be greatly appreciated!
Edit: Currently I am calling the function like this:
rounds = []
decide_rounds(rounds, range(1, size +1))
print rounds
回答1:
Try this:
def divide(arr, depth, m):
if len(complements) <= depth:
complements.append(2 ** (depth + 2) + 1)
complement = complements[depth]
for i in range(2):
if complement - arr[i] <= m:
arr[i] = [arr[i], complement - arr[i]]
divide(arr[i], depth + 1, m)
m = int(raw_input())
arr = [1, 2]
complements = []
divide(arr, 0, m)
print arr
We notice that for a bracket with 2^n players, the sum of every pair is the same number. For every pair, the right term is determined by the left element and the depth of the recursion, so we can just proceed by generating the array depth first. We memoize the complements to improve runtime just a bit. It works for any m > 1
as it stops recursing once the complement is too large.
See it in action: http://ideone.com/26G1fB
来源:https://stackoverflow.com/questions/13792213/algorithm-for-generating-a-bracket-model-list-in-python