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.
>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)