Digit_Sum 4/15


#1

Hi, I’m trying to figure out what I"m missing on this code. What I’ve tried is below:

def digit_sum(n):
  from math import floor
  total = 0
  x = n										# x = n == 1234
  while x > 0:								# x > 0
    i = x % 10								# i = x % 10 == 4
    total += i								# total += i == 0 + 4
    x = floor(n/10)							# x = floor(n/10) == 123
											# repeat until x == floor(1/10) == 0
  return total
  print total
  
  
number=(int(raw_input('gimme dat num: ')))
digit_sum(number)

It isn’t throwing an error when I run the code, it just times out eventually, so I’m guessing I’ve missed something with resolving the loop conditions? Using their sample number, I feel like the code should be working just fine…


#2

Usually we see the floor division operator in this type of expression.

x = n // 10

Should that be n or x over 10?

x //= 10

#3

Yep, that did it! Thank you very much!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.