'How do I print the digits of a number from left to right in Python without using string index or list?
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.
Solution 1:[1]
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%10}"
return f"{a%10}"
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
Solution 2:[2]
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))%10 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
Solution 3:[3]
Adjusted the code and now it is working for me. For now it gives me my desired results without using func, string indexing, etc.
num = int(input("Enter a number: "))
num2 = num
dig = 0
while num2 > 0:
num2 = num2 //10
dig = dig + 1
while dig > 0:
x = num // 10**(dig - 1)
if dig == 1:
print (x, end = " ")
else:
print (x, end = ", ")
num = num % 10**(dig - 1)
dig = dig - 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | S4eed3sm |
| Solution 2 | |
| Solution 3 | Tasrif Rahman |
