1
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

1
  • what are the test cases? Commented Apr 13, 2016 at 3:57

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

As a one liner is_triangular = lambda x: (0.5 * ((8 * x + 1) ** 0.5 - 1)).is_integer()
1

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.

3 Comments

Thanks for your answer.
what is the time complexity for this solution ?
This fails on 1 which technically is triangular.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.