Python Forum
sum of number's caracters
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sum of number's caracters
#8
Assuming (I know that is bad) that you are early in your training and are just familiar with strings and numbers, your approach was to work with the digits as numbers. While possible, would it not be easier to work with the digits as characters, converting just to add? Then take the total and convert back to a string. When the string has a length of 1 you are done (a whole number less than 10 is one character long). Similar to Perfringo's approach, but keeping to the simplest structures
input_string = "135246"
while len(input_string) > 1 :
    total = 0
    for c in input_string :
        total += int(c)
Print the total, convert the total back to be input_string, and you are done.
Reply


Messages In This Thread
sum of number's caracters - by foli - Oct-28-2019, 09:44 AM
RE: sum of number's caracters - by buran - Oct-28-2019, 09:48 AM
RE: sum of number's caracters - by perfringo - Oct-28-2019, 09:48 AM
RE: sum of number's caracters - by foli - Oct-28-2019, 10:36 AM
RE: sum of number's caracters - by foli - Oct-28-2019, 11:53 AM
RE: sum of number's caracters - by perfringo - Oct-28-2019, 12:48 PM
RE: sum of number's caracters - by MckJohan - Nov-02-2019, 06:26 AM
RE: sum of number's caracters - by jefsummers - Nov-02-2019, 11:53 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020