Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python Digit into number

voldyy

Coder
Hi, how can i change this code to work for two-digit numbers or three-digit number?

For now only work for single digit numbers, tried to change algorthm but didnt work.

Python:
def to_number(digits):
    result=digits[0]
    for el in digits[1:]:
        result=result*10
        result=result + el
    return result

Now the ouput is 2221 - i think is because of this line result=result + el
It has to output this:
input: [ 21, 12, 1]
output: 21121
 
I could be wrong but I think you are trying to get 23221 not 21121
Python:
def to_number(digits):
    result=digits[0]
    for el in digits:
        result=result*10
        result=result + el
    return result
  
x = to_number([21,12,1])
print(x)

#21 * 10 = 210 + 21 = 231
#231 * 10 = 2310 + 12 = 2322
#2322 * 10 = 23220 + 1 = 23221

The way you have it there its:


Python:
def to_number(digits):
    result=digits[0]
    for el in digits[1:]:
        print("our digit is {}".format(el))
        print("result is {}".format(result))
        result=result*10
        result=result + el
    return result
  
x = to_number([21,12,1])
print(x)

#21 * 10 = 210 + 12 = 222
#222 * 10 = 2220 + 1 = 2221

Output:
our digit is 12
result is 21
our digit is 1
result is 222
2221
 
Perhaps:
Python:
def to_number(digits):
    result = ''
    for el in digits:
        result = result + str(el)
    return int(result)
  
x = to_number([21,34,7])
print(x)
 
Last edited:
Python:
def to_number(digits):
     result = [str(digit) for digit in digits]
     result = ''.join(result)
     return int(result)

myinput = [21,12,1]
print(to_number(myinput))
 

New Threads

Buy us a coffee!

Back
Top Bottom