user3678321
user3678321

Reputation: 31

Generate triangular numbers

This function is supposed to take an integer, generate the list of triangular numbers within range of that integer, check that list for the longest list of numbers whose sum == number and return them in a list, otherwise if there is no such list within that range of triangular numbers, return an empty list. I thought I had it somewhat, and it runs on python tutor.com, but when I run it in IDLE, nothing happens.

def checkio(number):
    x = 4
    lst = [1, 3, 6]
    new = []
    if number == 0:
        return []
    elif number == 1:
        return [1]
    elif number == 3:
        return []
    elif number == 6:
        return []
    elif number == 4:
        return [1, 3]
    elif number == 7:
        return [1, 6]
    elif number == 10:
        return [1, 3, 6]
    elif number > 10:
        while number > lst[-1]: # Generates a list of all the triangular numbers up to number 
            for item in range(lst[-1]):
                lst.append(x + lst[-1]) 
                x += 1
        go = []
        start = 0
        end = 0
        count = 0 
        while count < len(lst) * 2:
            if sum(lst[start:end+1]) < number:
                end += 1
                count += 1 
            elif sum(lst[start:end+1]) > number:
                start += 1
                count += 1 
            elif sum(lst[start:end+1]) == number:
                go.append(lst[start:end+1])
                break
                return go   
        if count >= len(lst) * 2:
            return [] 

Upvotes: 0

Views: 436

Answers (2)

llrs
llrs

Reputation: 3397

As Bakuriu commented: If you want to get a result change the order of this lines:

        elif sum(lst[start:end+1]) == number:
            go.append(lst[start:end+1])
            break
            return go   

To :

        elif sum(lst[start:end+1]) == number:
            go.append(lst[start:end+1])
            return go   
            break

This will return a value before escaping the while loop. As noted in the comments (thanks Andrea Corbellini) you can also remove the break statement and it will work well. Because after the return statement by definition escapes the function.

Also to run in idle once defined (you copied the code and pressed return), call it as Christian says. This way you will check if works.
Note that you don't check in the ifelse clauses for the numbers 2, 5, 8 and 9. If you call this function with checkio(5), like suggested by Crhistian, it will not return anything because it doesn't have anything to return!

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34166

In the code you post you are just declaring a function. In order to run it, you have to make a call to that function. In your case, it receives one argument, so you have to pass it inside the parentheses ():

number = 5 # for example
checkio(number) # this is the function call

Upvotes: 2

Related Questions