Reputation: 31
I'm trying to write a Python program that will return an Armstrong number and the resulting outputs do not meet my expectations. An Armstrong number in a given number base is a number that is the sum of its own digits each raised to the power of the number of digits.
for i in range(0,len(lst)):
lst[i] = int(lst[i])
sum2= 0
for i in range(0,len(lst)):
sum1 = lst[i]*lst[i]*lst[i]
sum2 += sum1
if sum2 == n :
print("Armstrong number")
else:
print("Not an Armstrong number")
Why is this code returning incorrect results?
Upvotes: 0
Views: 176
Reputation: 11
You need to cast n as answered above!
Also Armstrong number is not just power of 3
The power is equal to number of digits present in the number.
For Eg :
153 has 3 digits 1 5 and 3 so 1^3 + 5^3 + 3^3 = 153
But if number is 4 digit Number then :
Input : 1634
Output : 1634 is an Armstrong Number
1^4 + 6^4 + 3^4 + 4^4 = 1634
and so on!
So basically the power is no. of digits present in the given no.
Here is my simple piece of code for it :
def Armstrong(num):
exp = len(num)
res = 0
for i in num:
res += pow(int(i),exp)
if res == int(num):
print(num + " is an Armstrong Number")
else:
print(num + " is not an Armstrong Number")
num=input("Enter a number : ")
Armstrong(num)
Upvotes: 1
Reputation: 2747
You are very, very close. The only problem is that n
is a string, not an int, so when you compare it to sum2
it will never be equivalent. Cast n
to an int and problem solved:
if sum2 == int(n):
If you want to see a more streamlined way to get the same result, here is an example:
value_string = input("Enter an integer value: ")
starting_value = int(value_string)
digits = [int(char) for char in value_string]
cubed_sum = sum([
one_digit ** 3
for one_digit in digits
])
if cubed_sum == starting_value:
print(f"{starting_value} is an Armstrong number.")
else:
print(f"{starting_value} is not an Armstrong number.")
Upvotes: 0