3

I usually do my incrementation this way:

n=0
n=n+1 # and never do n+=1

Now there is code that I am trying to comprehend and I'm struggling to understand it.

sum=0
temp = num
while temp > 0:
    digit = temp % 10
    # below is the line I do not understand
    sum += digit ** power # what is happening here?. with power= len(str(num))
    temp //= 10

if num == sum:
   print num    

This snippet is a piece to list the armstrong numbers.

5
  • 4
    In your case (and most cases), the line sum += digit ** power is equivalent to sum = sum + digit ** power. Commented May 30, 2018 at 13:25
  • Please provide the complete code. Also, num is not defined, please explain what num is. Commented May 30, 2018 at 13:32
  • @Flaming_Dorito the OP isn't asking to debug code, they're asking for someone to explain what n ** x means. Thus, an MCVe isn't necessary. Commented May 30, 2018 at 13:34
  • 1
    Possible duplicate of What does the ** maths operator do in Python? Commented May 30, 2018 at 13:35
  • @ResetACK OP might have been asking why we do that calculation and what it means in the calculation of the final answer. It wasn't clear. Commented May 30, 2018 at 13:47

3 Answers 3

4

In python ** is the sign for exponent, so x ** 2 is x^2 (or x squared).

x += g is the same as x = x + g

sum += digit ** power == sum = sum + (digit ** power)

Sign up to request clarification or add additional context in comments.

1 Comment

As for being reluctant to use n += 1, it's up to you but that method is far easier to understand in my opinion than n = n + 1
2
while temp > 0:
    digit = temp % 10 
    sum += digit ** power
    temp //= 10
  1. Take the last digit of temp

  2. Add to sum the digit to the power of power

  3. Delete the last digit of temp

Comments

0

suppose num = 34, then power becomes 2, so, for first iteration:

digit = 4
sum = 0 + 4 ** 2 # which is 0 + 16 = 16. Then adding to sum

so, digit ** power is digit to the power of 2

similarly, for second iteration:

digit = 3
sum = 16 + 3 ** 2 # which is  16 + 9 = 25

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.