I'm trying to create a recursive function that returns the average of the digits in a number. For example the average of the number 123 is 2. I know how to write a function that sums the digits but without using for I am no able to return the number to divide the function. The print value cannot be change so i can't pass a number of digits or something like that.
def media(x):
if x<1:
return 0
else:
return x%10+media(x//10)
print(media(91234))
for
-loopThere is really no reason not to use a for
-loop for this.
def media(x):
if x == 0:
return 0
else:
digits = []
while x > 0:
digits.append(x % 10)
x = x // 10
return sum(digits) / len(digits)
You can use additional accumulator parameters to store the sum of digits and the number of digits:
def media(x, sumSoFar=0, nDigitsSoFar=0):
if x == 0 and sumSoFar==0:
return 0
elif x == 0:
return sumSoFar / nDigitsSoFar
else:
return media(x // 10, sumSoFar + (x % 10), nDigitsSoFar + 1)
Please note that python is one of the worst languages for recursion, and in particular it doesn't optimize tail-calls.
The builtin function str
will convert an integer to a string of digits. You can use this in conjunction with ord
to get the value of a digit:
def media(x):
s = str(x)
return sum((ord(c) - ord('0')) for c in s) / len(s)
I assume that it is the mean and not the median as it seems like you've written. To find the mean of the digits, you can convert the number into a type str
then extract each digit by iterating over the string with a for... in string
. Next, convert each digit back and find the average of those numbers.
EDIT: It's not recursive, but it doesn't seem meaningful to use recursion for this kind of simple calculation.
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.