+ 1
Can someone please tell how this approach will work?
I have checked with the two approach using recursion and second approach is working fine. Please help with the first one. User input:-12345 Output:-15 Problem:-Sum of n digits https://code.sololearn.com/cy2EEWNq0mAt/?ref=app
9 Respostas
+ 2
#first approach
def Sum(n):
s=0
if n==0 or n==1:
return n
else:
m=str(n)
for j in m:
s=s+int(j)
return s
n=int(input())
print(Sum(n))
This is working
+ 1
Jay Matthews thanks
+ 1
Bob_Li yes I know but I am revising thats why I solved some question on recursion. And by the way according to you which approach is best to any problem?
+ 1
US22
There is no single best approach, but using the language's built in methods is usually the most efficient way.
Like in your example, I would probably use split() to separate the input string to a list of strings, map() to convert to int, then use sum() to get the sum.
Also, with user input, you have to deal with invalid inputs, so it is not as straightforward as you might imagine.
+ 1
Bob_Li and also this single line approach is good :D
N=int(input())
print(sum(int(x) for x in str(N)))
+ 1
yes, list comprehension. But that is a secret weapon....😎
+ 1
# It is no need to cast int from input at the first step
def Sum(n):
sum = 0
for ch in n:
sum += int(ch)
return sum
n=input()
print(Sum(n))
0
Jay Matthews No,for the first approach using recursion
0
why recursion? it is not a good approach for this simple problem.
Also, I keep noticing a lot of post about recursion from different users on different problems. I avoid recursion whenever I can. It is problematic.