Home > Blockchain >  What piece of code am I missing in this python code? Adding digits together
What piece of code am I missing in this python code? Adding digits together

Time:09-23

I have this code with input for example of 34, 56 and supposed output of 28,46. However, what I am getting as output is: 24, 4, 40,6 (24 4 = 28 and 40 6 = 46). Question is, what line of code am I missing?

def decode(code):
    decimals = []
    code = code.split(" ")
    for number in code:
        length = len(number)
        for digit in number:
            decimal = int(digit) * (8**(length - 1))
            decimals.append(decimal)
            length -= 1
    print(decimals)

CodePudding user response:

You forget that you must add the numbers back again. A solution for it:

def decode(code):
        decimals = []
        code = code.split(" ")
        for number in code:
            length = len(number)
            decimal = 0
            for digit in number:
                decimal  = int(digit) * (8**(length - 1))
                length -= 1
            decimals.append(decimal)
        print(decimals)

Edit: When you want, to print it as "28 46", then change the code, above to:

def decode(code):
    decimals = ''
    code = code.split(" ")
    for number in code:
        length = len(number)
        decimal = 0
        for digit in number:
            decimal  = int(digit) * (8 ** (length - 1))
            length -= 1
        decimals  = " " str(decimal)
    print(decimals)

CodePudding user response:

You are missing the concept that each number in the result needs to be the sum of its digits. I would add another list:

def decode(code):
    results = []
    code = code.split(" ")
    for number in code:
        length = len(number)
        decimals = []
        for digit in number:
            decimal = int(digit) * (8**(length - 1))
            decimals.append(decimal)
            length -= 1
        results.append(str(sum(decimals)))
    print(results)
    return ' '.join(results)
  • Related