Home > Mobile >  Function returns the same value many times I Python
Function returns the same value many times I Python

Time:04-03

I need to write a function that will convert the number A to base N. In this case, the number 19 is binary. All I have to do is rewrite the resulting number backwards and return from the function. I looked into debug mode and didn't understood a thing honestly, it's just looping over line 15 because of... reasons I guess.

def translate(a, n=2):
    r1 = []
    r2 = ()
    r3 = ()

    b = int(a/n)
    c = a%n
    
    if b >= 1:
        r1.append(str(c))
        r1.append(str(translate(b,n)))
    else:
        r1.append(str(c))
    
    return r1

print(translate(19,2))

I didn’t manage to come up with much, after all, I’m not a programmer at all, but I need to do this so that I don’t get expelled.

CodePudding user response:

You don't really need a recursive approach for this. Here's a technique that will work for where 2 <= base <= 10 and a >= 0

def translate(a, base=2):
    r = ''
    while a > 0:
        r  = str(a % base)
        a //= base
    return r[::-1] if r else '0'

CodePudding user response:

The problem was that every time you call the function, it would append to the list and also, the list would be initialized every time it was called. Hence using a global variable and instead of appending the returned value in the if block just running the function again worked. Code:

r1 = []
def translate(a, n=2):
    global r1
    r2 = ()
    r3 = ()

    b = int(a/n)
    c = a%n
    
    if b >= 1:
        r1.append(str(c))
        # print(r1)
        translate(b,n)
        # print(r1)
    else:
        r1.append(str(c))
    
    # return r1
translate(2,2)
print(''.join(r1)[::-1])# Join and reverse
  • Related