Armstrong Numbers

lst = []
def is_armstrong_number(number):
    sum_num = 0
    for digit in str(number):
        lst.append(int(digit))
        for i in lst:
            i = pow(i, len(lst))
            sum_num += i
            if sum_num == number:
                return True
            else:
                return False

This code doesn’t work for some numbers. I think the issue lies with the nested loops – they might be preventing the code from completing its calculations properly.

Code Run

self.assertIs(is_armstrong_number(5), True)

Test Failure

AssertionError: False is not True


Code Run

self.assertIs(is_armstrong_number(153), True)

Test Failure

AssertionError: False is not True


Code Run

self.assertIs(is_armstrong_number(9474), True)

Test Failure

AssertionError: False is not True


Code Run

self.assertIs(is_armstrong_number(9926315), True)

Test Failure

AssertionError: False is not True

Could you walk through the code execution when that code is called with the input 10? Which lines execute in which order and what is the value on each variable on the line as the line is executed?

You’re using a different exponent for each digit. The Armstrong algorithm expects you to use the same exponent for each digit.

You’re also returning after the first iteration, instead of iterating over all the digits.

1 Like
lst = []


def is_armstrong_number(number):  #10
    sum_num = 0
    for digit in str(number): # it should be 1 and 0, but in IDE it just ouputs 1
        lst.append(int(digit)) #expected : [1,0] , redult I get : [1]
        for i in lst:
            i = i ** len(lst) # 1 ** 2 = 1  , 0 ** 2 = 0
            sum_num += i # 1 ** 2   + 0 ** 2 = 1 => 1 != 10
        if sum_num == number: 1 != 10
            return True # skipped
        else:
            return False # runs

You can determine the length of the input number before you enter the outer loop. That value is the exponent for each digit.

And consider when you are returning. Are you iterating over every digit?

And consider whether you need an inner loop.

Please look away from your current implementation and read the instructions again, carefully.

1 Like
I think I see the problem: spoiler alert

starting from for i in lst: your indentation is one level too much. And then the if statement also needs one less indentation level

def is_armstrong_number(number):
  for digit in str(number):
    ...
  for i in lst:
    ...
  if z == number:
    ...