I want to use a recursive algorithm for the function, which should print out the sum of all the digits of a given number.
Here is my code. For example, sum_of_digits(343) will return an output of 10.
numbers = [1, 2]
def sum_of_digits(n):
for n in
sum_of_digits(343)
The output I'm trying to achieve: 10
If you have to use recursion, one method would be to get the individual digits by modding n with 10 and adding that to the sum of the remaining digits (computed by sum_of_digits(n // 10):
def sum_of_digits(n):
if n < 10:
return n
return (n % 10) + sum_of_digits(n // 10)
print(sum_of_digits(343))
Output:
10
def sum_of_digits(n):
result = 0
for x in str(n):
result += int(x)
return result
sum_of_digits(343) # 10
How about this simplest solution:
number = 343
sum_of_digits = sum(map(int, str(number)))
print(sum_of_digits)
10
Related
I'm trying to create a function that
The input of it will be a digit.
And the length of the wanted result
The output will be the digit in the length of user input
For example doMul(3,6) will output: 333333.
Now I tried to do this:
def doMul(digit, count=1):
if count == 0:
return 1
return digit + digit * (10 ** doMul(digit, count - 1))
But it doesn't seem to work.
And I can't figure out why.
Worth mentioning I don't want to use any strings.
y ** x is actually y in power of x, not multiplication. You should remove it and return digit rather than 1
def doMul(digit, count=1):
if count == 1:
return digit
return digit + 10 * doMul(digit, count - 1)
def doMul(n, m):
"Return the decimal number that is nnn... m times."
return n * ((10**m)-1) // 9
The reason this works is that M copies of N is simply M copies of 1, multiplied by N. And since (10 ** M) - 1 is the same as doMul(9, m), we can easily generate our base number.
If you absolutely need a recursive solution:
def doMul(n, m):
if m <= 1:
return n
return n + 10 * doMul(n, m-1)
This does essentially the same, compute one digit less than we want, multiply it by 10, then add the digit we want.
Does this work for you?
def doMul(digit, count=1):
if count == 1:
return digit
return str(digit) + str(doMul(digit, count-1))
print(doMul(3, 6))
Trying to figure out how to find the sum of digits between two numbers(including those numbers) using a function in python.
I tried recursion for each individual argument and then subtracted them to compensate for the numbers in between. Then I added these two and got my sum, which is incorrect for every argument unless the digits are below 10. Not sure of the proper way to approach this problem, please help.
def sum_digits(a, b):
"""sum of digits between two numbers"""
sum = 0
ones = a - b
if ones < 0:
ones = ones * -1
if a >= 10 and b >= 10:
sum += ones
while a > 0 and b > 0:
d = a % 10 + b % 10
a = a // 10
b = b // 10
sum += d
return sum
def sum_digits(a, b):
sum = 0
for i in range(a,b+1):
for e in (str(i)):
sum += int(e)
return sum
print(sum_digits(17, 20))
Does this work ?
this works basically by getting the numbers within a range. Now since endrange is usually one less, I manually add a 1 to the endrange
startNumber = 1
endNumber = 5
total = 0;
for i in range(startNumber,endNumber+1):
print(i)
total += i
print total
Thanks
Just sum the digit sum for every number from the first argument to the last. For more ways to do each digit sum, see Sum the digits of a number - python
def sum_digits(a, b):
total = 0
for number in range(a,b+1):
total += sum(int(digit) for digit in str(number))
return total
Here you go:
def sum_digits(a, b):
sum = 0
for i in range(a, b + 1):
number = i
while (number > 0):
sum += number % 10
number = number // 10
return sum
print(sum_digits(17, 20))
My approach:
def sum_of_products(lst, s, f):
result = 0
for i, item in enumerate(range(s, f+1)):
lst[i] = list(map(int, str(item)))
result += sum(lst[i])
return result
lst = [x for x in range(0, 10)]
x = sum_of_products(lst, 14, 20)
print(x)
My 2 cents would to point out that there should be a closed-form formula that doesn't involve looping trough the whole range.
For example, we know that the sum of n numbers is
n*(n-1)/2
and for the sum of digits 0 to 9 it is 45 == 9*10/2
01
02
03
04
05
06
07
08
09
then it becomes a bit more complicated for the next 10 numbers:
10
11
12
13
14
15
16
17
18
19
the sum is 10 times the tens(decades) plus 45.
and then we could have:
for 00..09 we have 0*10+45
for 10..19 we have 1*10+45
for 20..29 we have 2*10+45
...
for d0..d9 we have d*10+45
I am too lazy to derive the good formula myself, therefore I Googled it. And below is what I have found:
The formula is simple if we know before hand the number of digits. For example, as per https://oeis.org/A007953 , if the number of n is less than 100 then the closed-form formula is:
For n < 100 equal to (floor(n/10) + n mod 10)
For an arbitrarily large number there is a sample code here: https://www.geeksforgeeks.org/count-sum-of-digits-in-numbers-from-1-to-n/
dsum(10**d - 1) = dsum(10**(d-1) - 1) * 10 + 45*10**(d-1)
to compute the digit sum of a range just find the difference
dsum(b) - dsum(a)
So I was studying recursion function online. And the one question asks me to write a function to add up a number's digits together. For example (1023) -> 1 + 0 + 2 + 3 = 6. I used % and // get get rid of a digit each time. However, I don't know how to add them up together. The closest I can get is to print out each digit. Can anyone help me solve it or give me a hint please?
def digitalSum(n):
if n < 10:
sum_total = n
print(sum_total)
else:
sum_total = n % 10
digitalSum((n - (n % 10))//10)
print(sum_total)
digitalSum(1213)
Your function should return the current digit plus the sum of the rest of the digits:
def digitalSum(n):
if n < 10: return n
return n % 10 + digitalSum(n // 10)
print digitalSum(1213)
For completeness, you can also handle negative numbers:
def digitalSum(n):
if n < 0: sign = -1
else: sign = 1
n = abs(n)
if n < 10: return n
return sign * (n % 10 + digitalSum(n // 10))
print digitalSum(1213)
A correct version of your function is as follows:
from math import log10
def sum_digits(n, i=None):
if i is None:
i = int(log10(abs(n)))
e = float(10**i)
a, b = (n / e), (abs(n) % e)
if i == 0:
return int(a)
else:
return int(a) + sum_digits(b, (i - 1))
print sum_digits(1234)
print sum_digits(-1234)
Example:
$ python -i foo.py
10
8
>>>
Updated: Updated to properly (IHMO) cope with negative numbers. e.g: -1234 == -1 + 2 + 3 + 4 == 8
NB: Whilst this answer has been accepted (Thank you) I really think that perreal's answer should have been accepted for simplicity and clarity.
Also note: that whilst my solution handles negative numbers and summing their respective digits, perreal clearly points out in our comments that there are ate least three different ways to interpret the summing of digits of a negative number.
I am trying to make a code (in python) where I can input a range and it will find the sum off all the numbers besides the ones that are divisible by x (which i also choose).
For example:
if the range is 0<N<10 and x = 3 then I want the code to sum the numbers
1 + 2 + 4 + 5 + 7 + 8
and output 27.
or if the range is 0<N<5 and x = 2 I want the code to sum the numbers
1 + 3
and output 4
But, the problem is I have no idea how to do it. Can anyone help me?
For your second example: (0<N<5, x=2):
sum(i for i in range(1, 5) if i%2)
def fn(N, x):
total = 0
for i in range(N):
if i%x:
total += i
return total
Read up on loops and ranges in python if you are new.
You could do something like this:
>>> div = 3
>>> n = 10
>>> num_div = filter(lambda x: x%div, range(n))
>>> sum(num_div)
27
or as a function
def func(n,div):
return sum(filter(lambda x: x%div, range(n))
The other answers implicitly assume the range will always start from 0. If you want to be able to set both the start and end points of your range, you could use:
def sumrange(start, stop, n):
return sum(i for i in range(start, stop) if i%n)
I need to write a code that counts the sum of the digits of a number, these is the exact text of the problem:The digital sum of a number n is the sum of its digits. Write a recursive function digitalSum(n) that takes a positive integer n and returns its digital sum. For example, digitalSum(2019) should return 12 because 2+0+1+9=12. These is the code I wrote :
def digitalSum(n):
L=[]
if n < 10:
return n
else:
S=str(n)
for i in S:
L.append(int(i))
return sum(L)
These code works fine, but it's not a recursive function, and I'm not allowed to change any int to str. May you help me?
Try this:
def digitalSum(n):
if n < 10 :
return n
return n % 10 + digitalSum( n // 10 )
Edit: The logic behind this algorithm is that for every call of the recursive function, we chop off the number's last digit and add it to the sum. First we obtain the last digit with n % 10 and then we call the function again, passing the number with the last digit truncated: n // 10. We only stop when we reach a one-digit number. After we stop, the sum of the digits is computed in reverse order, as the recursive calls return.
Example for the number 12345 :
5 + digitalSum( 1234 )
5 + 4 + digitalSum( 123 )
5 + 4 + 3 + digitalSum( 12 )
5 + 4 + 3 + 2 + 1 <- done recursing
5 + 4 + 3 + 3
5 + 4 + 6
5 + 10
15
It's homework, so I'm not writing much code. Recursion can be used in the following way:
get the first (or last) digit
format the rest as a shorter number
add the digit and the digital sum of the shorter number (recursion!)
This is more of a question related to algorithms.
Here is your answer:
def digit_sum(a):
if a == 0:
return 0
return a % 10 + digit_sum(a/10)
Let me know if you don't understand why it works and I'll provide an explanation.
Some hints:
You can define inner functions in Python
You can use the modulus operator (look up its syntax and usage) to good effect, here
There's no need to build up an explicit list representation with a proper recursive solution
EDIT The above is a bit "bad" as a general answer, what if someone else has this problem in a non-homework context? Then Stack Overflow fails ...
So, here's how I would implement it, and you need to decide whether or not you should continue reading. :)
def digitalSum(n):
def process(n, sum):
if n < 10:
return sum + n
return process(n / 10, sum + n % 10)
return process(n, 0)
This might be a bit too much, but even in a learning situation having access to one answer can be instructive.
My solution is more a verbose than some, but it's also more friendly towards a tail call optimizing compiler, which I think is a feature.
def digital_sum(number):
if number < 10:
return number
else:
return number % 10 + digital_sum(number / 10)
def sumofdigits(a):
a = str(a)
a = list(a)
b = []
for i in a:
b.append(int(i))
b = sum(b)
if b > 9:
return sumofdigits(b)
else:
return b
print sumofdigits(5487123456789087654)
For people looking non-recursive ways,
Solution 1:
Using formula,
digits = int(input())
res = (digits * (digits + 1) // 2)
Solution 2:
Using basic syntax
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
total = numbers[0]
print(f'{total}')
for val in numbers[1:]:
print(f'{total} + {val} = {total + val}')
total += val
gives
6
6 + 5 = 11
11 + 3 = 14
14 + 8 = 22
22 + 4 = 26
26 + 2 = 28
28 + 5 = 33
33 + 4 = 37
37 + 11 = 48
Still you can do it in O(log10 n)...cancel out all the digits that adds to 9 then if no numbers left,9 is the answer else sum up all the left out digits...
def rec_sum_Reduce(n) :
ans = 0
for i in map(int,str(n)) :
ans = 1+(ans+i-1)%9
return ans
def drs_f(p):
drs = sum([int (q) for q in str(p)])
while drs >= 10:
drs = sum([int(q) for q in str(drs)])
return drs
def digitalSum(n):
if n < 10:
return n
else:
return ???
The 1st part is from your existing code.
The ??? is the part you need to work out. It could take one digit off n and add it to the digitalSum of the remaining digits.
You don't really need the else, but I left it there so the code structure looks the same