+ 1

Python Recursion (task 16.2 python intermediate)

This is the right solution. If anybody can please explain why it is like that and what exactly happens. I tried to understand but i dont get it. What does the „* 10“ do? How exactly does the recursion works in this case? def convert(num): if num==0: return 0 return (num % 2 + 10 * convert(num // 2)) print(convert(int(input())))

3rd Oct 2022, 8:59 PM
Lil Bebi
Lil Bebi - avatar
4 Answers
+ 1
convert(num) is returns either 0 or 1 each time. There 10* convert is used to append next result to previous one. Ex: 5 1+10*( convert (2) ) 1+10*( 0+10*(convert(1))) 1+10*(0+10*(1+10*convert(0))) 1+10*(0+10*(1+10*0)) 1+10*(0+10) 1+100 = 101 Ex: 3 1+10*( 1+10*0) = 1+10=11
3rd Oct 2022, 9:30 PM
Jayakrishna 🇼🇳
+ 1
Okay ty but wouldnt this lead to an infinite recursion since the recursion continues forever. Even if num is 0 convert(num//2) always gives 0 but can continue doesnt it?
4th Oct 2022, 7:04 AM
Lil Bebi
Lil Bebi - avatar
+ 1
Ah yes thank you. Was so deep in the recursion forgot about the if condition
4th Oct 2022, 12:03 PM
Lil Bebi
Lil Bebi - avatar
0
If num==0 : return 0 is the base or stop condition. Without this, it will lead to infinite recursion. It stopping call further recursion. convert(0) returns 0 , does not call again convert(0//2)
4th Oct 2022, 10:39 AM
Jayakrishna 🇼🇳