Here is what I'm supposed to write:
a main function which will count numbers starting at one, and ending when the total digits (for all the numbers) exceeds 1,000,000. So, if you want the total digits for the number 5, you would add:
your program will print both the number and the digit count before it exceeds 1,000,000. This is easiest with a while loop.
I've written the code for the function countDigits, which is:
def countDigits():
value=int(input('Enter Integer: '))
str_num= str(value)
total = 0
for ch in str_num:
total += int(ch)
print(total)
However, I'm stuck as to how to write the main function. Can anyone point me in the right direction?
EDIT
Here is my revised countDigits function:
def countDigits(value):
str_num= str(value)
total = 0
for ch in str_num:
total += int(ch)
print(total)
a one-liner:
factorial_digit_sum = lambda x: sum( sum(map(int, str(a))) for a in range(1,x+1) )
If you EVER write real code like this, Guido will hunt you down. Was kind of a fun brain teaser to golf, though.
For a real answer:
def countDigits(number):
return sum(map(int, str(number)))
def main():
total = 0
count = 1
while total <= 1000000:
total += countDigits(count)
total -= countDigits(count) # you want the number BEFORE it hits 1000000
print("Summing the digits of {}! yields {}".format(count, total))
main()
The problem in your code is that your countDigits
function requests user input. You should change that to accepting the integer as a parameter. It also print
s the result instead of return
ing it.
As @Blorgbeard mentioned in the comments, change countDigits
to accept an integer as input. Also, return the total from it.
In the main function, read input, call countDigits
and add them in a while loop until the total is greater than 1,000,000
def countDigits(value):
str_num= str(value)
total = 0
for ch in str_num:
total += int(ch)
return total
grandTotal = 0
while ( grandTotal < 1000000 ):
value=int(input('Enter Integer: '))
grandTotal += countDigits(value)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.