0

How to write a program to write binary number using divmod function in python

Python divmod

2nd Jul 2020, 9:33 AM
Chandrakant Bellary
Chandrakant Bellary - avatar
6 Réponses
+ 7
I have put it together: (1) added a condition to stop recursion if n gets 0 (2) using a list + insert() for generating the output, as values are coming in reverse sequence (3) using return binar() instead of just binar() lst = [] def binar(n): if n == 0: # condition to stop recursion return 0 a,b=divmod(n,2) lst.insert(0,str(b)) return binar(a) n = b binar(200) print(''.join(lst))
2nd Jul 2020, 3:29 PM
Lothar
Lothar - avatar
+ 5
There is an infinite loop in the binar() function. So the maximum recursion level will be reached. This is due to a missing condition to stop recursion.
2nd Jul 2020, 3:10 PM
Lothar
Lothar - avatar
+ 3
Please do a try by yourself before you ask for help. Put your code in playground and link it here. Thanks!
2nd Jul 2020, 10:38 AM
Lothar
Lothar - avatar
+ 1
Thanks a lot!!
2nd Jul 2020, 3:55 PM
Chandrakant Bellary
Chandrakant Bellary - avatar
0
https://code.sololearn.com/ckvrt80p0J9y/?ref=app I'd tried this.. Not quite sure why it's not working
2nd Jul 2020, 2:26 PM
Chandrakant Bellary
Chandrakant Bellary - avatar
0
Oh...ok...thanks...I tried using if n>1 condn in the beginning however now the output is coming as 00 Anything else also wrong?
2nd Jul 2020, 3:18 PM
Chandrakant Bellary
Chandrakant Bellary - avatar