Home > Mobile >  generated empty [i] in for loop
generated empty [i] in for loop

Time:02-01

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])

CodePudding user response:

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.

CodePudding user response:

Not sure if I got the point, but maybe you want to do something like

def result(num: int, sum_: int) -> None:
    for a, b, c, d in combinations(lastList, num):
        if  a   b   c   d == sum_:
            print (a, b, c, d)

CodePudding user response:

this answer is according to my interpretation of the questions might be wrong. but !!works!!

def result():
    expected_sum=int(input("User please enter required sum"))
    n=int(input("User please enter the number"))
    for j in combinations(lastList, n):
        if   sum(j)== expected_sum:
            print (j)

CodePudding user response:

Try to do the following with the input abilities for the sum you want to achieve and the number you have.

def result(number, sum_goal):
     for list_item in combinations(lastList, number):
           if sum(list_item) == sum_goal:
                print('List of item is: ', list_item)

Then on the main program do the following:

if __name__ == "__main__":
   number = int(input("This is the number"))
   sum_goal = int(input("This is the sum"))
   result(number, sum_goal)

enter image description here

enter image description here

  •  Tags:  
  • Related