+ 1

Decimal to binary using recursion

I want to complete this coding challenge, I am given a recursive function and I need to add a base case and fix the code. This is the function that is given to me: def convert(num): return (num % 2 + 10 * convert(num // 2)) This is what I have tried: def convert(num): If num == 0: return return (num % 2 * convert(num // 2)) print(convert(input()) I get this an error: not all numbers converted during string formatting. I tried watching video on converting decimal to binary but I don't have idea, how to put what's on the video to code.

20th Sep 2021, 8:15 PM
Thandolwenkosi Ndzimande
Thandolwenkosi Ndzimande - avatar
6 Réponses
+ 2
Description for this expression: num % 2 + 10 * convert(num // 2) Decimal numeral system have 10 different digits. In binary numeral system we have only 2 digits(0,1). To convert decimal to binary, We divide the decimal number by 2, and write the remainder. Then divide the quotient by 2, and write the remainder on the left of previous number. And so on until the quotient is zero. In the code above, multiplying by 10 is used to go to the left of the previous digit. see it this way: 10 * convert(num//2) + num % 2 This code can help you understand the story: def dec2bin(x): b = '' while x != 0: b = str(x % 2) + b x = x // 2 return b https://code.sololearn.com/c2Xc52f529Yq/?ref=app
20th Sep 2021, 10:27 PM
Arsalan [Inactive]
Arsalan [Inactive] - avatar
+ 1
So add a base case: if num == 0 return 0
20th Sep 2021, 8:24 PM
Arsalan [Inactive]
Arsalan [Inactive] - avatar
+ 1
1.You have to change the type of the input() to int: int(input()) 2. return "10" to where it was: num % 2 + 10 * .....
20th Sep 2021, 8:39 PM
Arsalan [Inactive]
Arsalan [Inactive] - avatar
+ 1
Thank you Arsalan, I managed to complete the coding challenge.
21st Sep 2021, 9:11 AM
Thandolwenkosi Ndzimande
Thandolwenkosi Ndzimande - avatar
0
I did that Arsalan my code is not working and I I don't understand the code that is given to me , so that I can be able to identify where it needs fixing
20th Sep 2021, 8:31 PM
Thandolwenkosi Ndzimande
Thandolwenkosi Ndzimande - avatar
0
Unfortunately, I don't understand this practice. could you guys please explain more?! Thank you
16th Aug 2022, 4:38 PM
Masoud MahmoudKelayeh
Masoud MahmoudKelayeh - avatar