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

Printing Armstrong Numbers from a Range in a For Loop as an Array *Python*

I’m trying to print armstrong values from a specified range in an array style format.
My current code is as below:

def main():


#Low and high set the bounds for the loop
low = 100

high = 499


#start the for loop for num in the range initialized
for num in range(low, high +1):

    #gets the exponent for each number
    ind_num = len(str(num))
   
    #initializes the addition of each number
    add = 0
   
    # sets x equal to num so we can check if the number is armstrong or not
    x = num

    
    #calculates the armstrong
    while x > 0:
        digit = x % 10
       
        add += digit ** ind_num

        x //= 10

    if num ==  add:
       
       print(num)
       





if __name__ == "__main__":
    main()

The output comes out to be:

153
370
371
407

and I want it to be: [153, 370, 371, 407]
I’m probably thinking too hard on how to make the integers that come out of the for loop arrange as an array, but so far changing them to strings and appending them with a separate defined array variable did not work.

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

>Solution :

If you replace print(num) with yield num your function will be a generator of armstrong numbers. Make low and high parameters and you end up with a versatile function:

def armstrong(low, high):
    for num in range(low, high +1):
        ind_num = len(str(num))
        add = 0
        x = num
        while x > 0:
            digit = x % 10       
            add += digit ** ind_num
            x //= 10
        if num == add:
            yield num


result = list(armstrong(100, 499))
print(result)
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