Reputation: 13
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
Reputation: 9222
Try this lambda:
Triangular = lambda x: (0.5 * ((8 * x + 1) ** 0.5 - 1)).is_integer()
Here's how it works:
n
by 8 and subtract 1You 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
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