Home > database >  How do I print the digits of a number from left to right in Python without using string index or lis
How do I print the digits of a number from left to right in Python without using string index or lis

Time:02-26

num = int(input("Enter a number: "))

while num > 0:
    num2 = num
    dig = 0

    while num2 > 0:
        num2 = num2 //10
        dig = dig   1

    x = num // 10**(dig-1)
    if dig == 1:
        print (x, end = " ")
    else:
        print (x, end = ", ")
    num = num % 10**(dig-1)

I wrote this code which outputs the number from left to right unless there is a zero at the middle or at the last of the number

For example: If input = 12345; output = 1, 2, 3, 4, 5

However, if input = 120 OR 102; output = 1, 2, OR 1, 2

Is there any workaround for this? I have been told not to use string indexing or lists to solve this.

CodePudding user response:

We can recursively iterate from right to left and then return the value we saw:

def get_digits(a: int):
    if a == 0:
        return ""
    if a > 9:
        return get_digits(a//10)   f", {a}" 
    return f"{a}"


    
print("100:", get_digits(100))
print("12345:", get_digits(12345))
print("120:", get_digits(120))
print("102:", get_digits(102))

The output will be:

100: 1, 0, 0
12345: 1, 2, 3, 4, 5
120: 1, 2, 0
102: 1, 0, 2

CodePudding user response:

Assuming strings are not strictly forbidden, here are some possible alternative solutions.

def get_digits(num):
    return [int(i) for i in str(num)]

Another solution [1]:

import math

def get_digits(num):
    return [(num//(10**i)) for i in range(math.ceil(math.log(num, 10))-1, -1, -1)]

This would be optimal if you just needed to print the digits directly.

print(", ".join([i for i in str(num)]))

If you're in a beginning Python class, your professor likely only wants to see something like this which doesn't use lists or string indexes:

num = 1203

for i, n in enumerate(str(num)):
    if i == 0:
        print(n, end="")
    else:
        print(', '   n, end='')

[Out]: 1, 2, 0, 3
  • Related