Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding Triangle numbers in the list

I need help to find numbers in list if it’s triangle number or not and if it’s triangle number, 1(string format), else 0(also string format).

For Example:

Input: n = [3, 4, 6, 55, 345]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output: "10110"

Another Example:

Input: n = [0, 1, 2, 5]

Output: "1100"

Thanks in advance.

I am using Python 3.12.

Here’s my code:

n = [1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035]
a = int(input())
b = list(map(int,input().split()))
d = ""
for i in b:
    if i in n:
        d += "1"
    else:
        d += "0"
print(d)

But it’s limited by 1035. Is there any way to check it without using list? Maximum number is can be input is 10^8.

>Solution :

A triangular number or triangle number counts objects arranged in an equilateral triangle. Triangular numbers are a type of figurate number, other examples being square numbers and cube numbers. The nth triangular number is the number of dots in the triangular arrangement with n dots on each side, and is equal to the sum of the n natural numbers from 1 to n

https://en.wikipedia.org/wiki/Triangular_number

Top 20000 triangle numbers.. Similarly you can increase the limit depending upon your need.

As @Kelly suggested keep the elements in set

from itertools import accumulate
limit = 20000
a = set(accumulate(range(1, limit+1)))

For your question you can do:

n = [3, 4, 6, 55, 345]

''.join('1' if x in a else '0' for x in n )

#output
'10110'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading