+ 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

4th Apr 2022, 4:07 AM
Utsav Singh
Utsav Singh - avatar
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
5th Apr 2022, 10:20 AM
UNKNOWN
+ 1
4th Apr 2022, 6:09 AM
Utsav Singh
Utsav Singh - avatar
+ 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?
4th Apr 2022, 6:12 AM
Utsav Singh
Utsav Singh - avatar
+ 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.
4th Apr 2022, 6:18 AM
Bob_Li
Bob_Li - avatar
+ 1
Bob_Li and also this single line approach is good :D N=int(input()) print(sum(int(x) for x in str(N)))
4th Apr 2022, 6:20 AM
Utsav Singh
Utsav Singh - avatar
+ 1
yes, list comprehension. But that is a secret weapon....😎
4th Apr 2022, 6:23 AM
Bob_Li
Bob_Li - avatar
+ 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))
5th Apr 2022, 7:09 PM
Егор Чугаев
Егор Чугаев - avatar
0
Jay Matthews No,for the first approach using recursion
4th Apr 2022, 4:25 AM
Utsav Singh
Utsav Singh - avatar
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.
4th Apr 2022, 5:50 AM
Bob_Li
Bob_Li - avatar