Xèo
Xèo

Reputation: 13

What wrong with my Python code to check the triangular number?

def Triangular(n):
    arr = []
    for i in range(n):
        T = i*(i+1)/2
        arr.append(T)
    if n == any(arr):
        return True
    else:
        return False

All test cases are in False. Please show me what I was wrong

Upvotes: 1

Views: 5792

Answers (2)

Richie Bendall
Richie Bendall

Reputation: 9222

Try this lambda:

Triangular = lambda x: (0.5 * ((8 * x + 1) ** 0.5 - 1)).is_integer()

Here's how it works:

  1. Multiply n by 8 and subtract 1
  2. Find the square root of that number
  3. Subtract it by 1 and divide it by 2
  4. Remove the decimal part of the number
  5. If the resulting number is greater than 0, it is triangular

You can also use this lambda from this answer to check if the number is Triangular:

Triangular = lambda n:(8*n+1)**.5%1>0

Upvotes: 2

smead
smead

Reputation: 1808

any() returns a boolean, True or False. you are comparing it to n, an integer. Change the line to

if n in arr:

Or even better yet you can just delete the whole if..else statement and replace it with simply:

return n in arr

edit: you can even avoid creating an array in the first place like this:

def Triangular(n):
    arr = []
    for i in range(n):
        if i*(i+1)/2 == n:
            return True
    return False

This immediately returns True when it finds that n is triangular. If it gets to the end of the list and doesn't find any, it returns false.

Upvotes: 1

Related Questions