I need to make a function so that I can put in two parameters, an order, and a max, and return a list of all of the lists 'order' long and with each element ranging from 0 to 'max'. I suspect I may need to use recursion, but I am getting lost in this.
so order = 2 max = 3 should return
[[0,0], [0,1], [0,2], [0,3], [1,0], [1,1], ... ,[3,3]]
and order=4, max=5 should return
[[0,0,0,0], [0,0,0,1], [0,0,0,2], ... [3,3,3,3]]
Thanks for the help
Note that in general, @Prune's answer is the weapon of choice, here.
As for recursion: The requested list can be constructed recursively as
1
is the list of all 1
-element lists with elements from the initial set: [1] -> [[1]]
[1, 2] -> [[1], [2]]
[1, 2, 3] -> [[1], [2], [3]]
In Python:
l1 = [[item] for item in range(0, max + 1)]
ln1
of length n + 1
consists of the cartesian product of ln
of length n
with l1
with the elements joined by list concatenation. In Python:
ln1 = [a + b for a in combine(base, n - 1) for b in combine(base, 1)]
def combinations(base, n):
if n == 0:
return []
elif n == 1:
return [[item] for item in base]
else:
return [a + b for a in combine(base, n - 1) for b in combine(base, 1)]
itertools.combinations_with_replacements()
is both faster and more memory efficient. It's also an existing wheel rather than a new one.
You don't need recursion; all you need is the Python itertools package:
import itertools
num_list = [x for x in range(max+1)]
for one_combo in itertools.combinations_with_replacement(num_list, order):
...
Of course, you can combine the two computational lines; it's just easier to see this way.
Here's a function that uses recursion to solve the problem. When you are dealing with recursion, make sure you have a base case and a general case.
def recurseNumbers(order, mx):
if order == 1:
return [[n] for n in range(mx + 1)]
else:
total_array = []
for num in range(mx + 1):
numbers = recurseNumbers(order - 1, mx)
for number in numbers:
total_array.append([num] + number)
return total_array
Also note that Python list addition makes this relatively simple. ["a"] + ["b"] = ["a", "b"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.