+ 1

recursion python question

The given code defines a recursive function convert(), which needs to convert its argument from decimal to binary. However, the code has an error. Fix the code by adding the base case for the recursion, then take a number from user input and call the convert() function, to output the result. Sample Input: 8 Sample Output: 1000 def convert(num): return (num % 2 + 10 * convert(num // 2))

14th Mar 2021, 9:05 AM
pardeep
pardeep - avatar
11 Answers
+ 8
hello pardeep , did you solve the question? if not then here is the code: # you need to provide base case then call the function with an input to allow client interaction def convert(num): if num==1: return 1 else: return (num % 2 + 10 * convert(num // 2)) print(convert(int(input())))
7th Apr 2021, 3:28 AM
Allan 🔥STORMER🔥🔥🔥🔥
Allan 🔥STORMER🔥🔥🔥🔥 - avatar
+ 1
""" you don't provide at least the base code to be fixed, but this one works: """ def convert(n,s=''): if n==0: return s or '0' return convert(n//2,str(n&1)+s) print(convert(int(input())))
14th Mar 2021, 9:37 AM
visph
visph - avatar
+ 1
pardeep Is this the code provided to you, or is it your attempt?
14th Mar 2021, 7:40 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
def convert(num): if num==1: return 1 else: return (num % 2 + 10 * convert(num // 2)) print(convert(int(input())))
10th Nov 2022, 8:30 AM
Pooja Patel
Pooja Patel - avatar
0
Can you attach the code for us to look at
14th Mar 2021, 9:24 AM
Rik Wittkopp
Rik Wittkopp - avatar
0
just provide the base condiation in which the function is evaluated and it is done by using if statements condaition. if the num is zero then the if condiation result return a zero and other wise it will return the (num % 2 + 10 * convert(num // 2)) expression def convert(num): if num == 0: return 0 else: return (num % 2 + 10 * convert(num // 2)) a = int(input()) print(convert(a))
27th May 2021, 5:33 AM
Abhishek Biswas
Abhishek Biswas - avatar
0
recursion python question The given code defines a recursive function convert(), which needs to convert its argument from decimal to binary. However, the code has an error. Fix the code by adding the base case for the recursion, then take a number from user input and call the convert() function, to output the result. Sample Input: 8 Sample Output: 1000 def convert(num): return (num % 2 + 10 * convert(num // 2)) where does this 10 come from?
9th Jun 2022, 10:01 AM
De Zin Htang
De Zin Htang - avatar
0
def convert(num): if num==0: return 0 return (num % 2 + 10 * convert(num // 2)) a=int(input()) print(convert(a))
26th Mar 2023, 9:32 PM
المهندس أحمد
المهندس أحمد - avatar
0
def convert(num): if num == 1.0: return True else: return (num % 2 + 10 * convert(num // 2)) num =int(input()) print(convert(num))
20th Feb 2024, 4:24 PM
Faryda 1990
Faryda 1990 - avatar
- 1
sorry about not posting code,,, now it is updated
14th Mar 2021, 11:55 AM
pardeep
pardeep - avatar
- 1
it is a question provided to me
15th Mar 2021, 10:52 AM
pardeep
pardeep - avatar