Skip to content
Advertisement

generated empty [i] in for loop

I want to create an empty set up to the value n entered by the user and assign the values in the for loop into this set. But for this, it is necessary to create as many for loops as the user inputs, it is not possible to do this. How can I do it?

The code below works correctly, but I manually enter the value n=4. Again I’m creating j indices manually. I want to get this value of n from the user and create j indices as much as this value.

def result():
    for j in combinations(lastList, 4):
        if  j[0] + j[1] + j[2] + j[3] == sum:
            print (j[0] , j[1] , j[2] , j[3])

Advertisement

Answer

You can use the sum() function to add all the elements of a sequence, so you don’t have to write the indexes explicitly.

def result(n, s):
    for j in combinations(lastList, n):
        if sum(j) == s:
            print(*j)

BTW, don’t use sum as a variable name, since it’s the name of a built-in function.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement