Working in Python.
Take k and n positive integers.
I have a function F with input a list L of positive integers where len(L) = k, max(L) < n 1. F returns an integer.
I want to return sum([F(L) for L a list of positive integers with len(L) = k, max(L)<n 1])
The naive approach is to have k nested for loops.
value = 0
for jj1 in range(1,n 1):
for jj2 in range(1,n 1):
...
for jjk in range(1,n 1)
value = value F([jj1,jj2,...,jjk])
return value
This is not satisfactory because I want to take this sum in a loop over various values of k (so sometimes k =1, sometimes k=10).
I'm hoping there is some standard trick to do this?
CodePudding user response:
You want itertools.product
.
>>> from itertools import product
>>> n, k = 4, 3
>>> list(product(range(1, n 1), repeat=k))
[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 3, 1), (1, 3, 2), (1, 3, 3), (1, 3, 4), (1, 4, 1), (1, 4, 2), (1, 4, 3), (1, 4, 4), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 1, 4), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 2, 4), (2, 3, 1), (2, 3, 2), (2, 3, 3), (2, 3, 4), (2, 4, 1), (2, 4, 2), (2, 4, 3), (2, 4, 4), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 1, 4), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 2, 4), (3, 3, 1), (3, 3, 2), (3, 3, 3), (3, 3, 4), (3, 4, 1), (3, 4, 2), (3, 4, 3), (3, 4, 4), (4, 1, 1), (4, 1, 2), (4, 1, 3), (4, 1, 4), (4, 2, 1), (4, 2, 2), (4, 2, 3), (4, 2, 4), (4, 3, 1), (4, 3, 2), (4, 3, 3), (4, 3, 4), (4, 4, 1), (4, 4, 2), (4, 4, 3), (4, 4, 4)]
Given F
, n
, and k
, you can therefore do:
sum(F(list(L)) for L in product(range(1, n 1), repeat=k))
(or leave off the list
call if it's fine for L
to be a tuple instead of a list)