Home > Net >  Getting lenght of the list
Getting lenght of the list

Time:11-14

My current program prints all the different sums that are generated with the given integers. Instead of the program printing the content of the list, I would want to print only the lenght of the list.

def sums(items):
    if len(items) == 1:
        return items

    else:
        new_list = []
        for i in items:
            new_list.append(i)

        for x in sums(items[1:]):
            new_list.append(x)
            new_list.append(x   items[0])
            new_list = list(set(new_list))

        return new_list

                
if __name__ == "__main__":
    print(sums([1, 2, 3]))                  # should print 6
    print(sums([2, 2, 3]))                  # should print 5

Just editing the sums function, instead of return new_list I tried to return len(new_list) this gives me an error of TypeError: 'int' object is not iterable. I'm just trying to return the lenght of the list, so I don't really understand the error.

CodePudding user response:

Do not change the function, you are getting the error because it is recursive (returning value is important), change this section instead

if __name__ == "__main__":
    print(len(sums([1, 2, 3])))              
    print(len(sums([2, 2, 3])))

CodePudding user response:

Use len()

if __name__ == "__main__":
    print(len(sums([1, 2, 3])))            
    print(len(sums([2, 2, 3])))     
  • Related