'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.
Solution 1:[1]
This is as simple as adding the items to a list and then printing the list.
At the start of your main()
function add in a variable output = []
. Then in your if
statement if num == add:
, instead of calling print
do output.append(num)
. Then at the end of your main()
function print the list, print(output)
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nathan Roberts |