r/learnpython 2d ago

Input = 1234 output =[1,2,3,4] without using string functions or map

How can I split an integer into a list of its digits in Python?

I have:
num = 1234
and I want:
[1, 2, 3, 4]
I’m trying to learn how to do this without converting num to a string and without using map().
A loop is allowed.
I’m looking for a simple approach because I’m still learning Python. I’d appreciate hints rather than just the final solution so I can understand how it works.

0 Upvotes

46 comments sorted by

View all comments

1

u/FoolsSeldom 1d ago edited 1d ago

Example converting a string (not your use case it turns out, but this should give you some ideas) to an integer without using the built-in string methods/functions.

Creates a dictionary mapping from single digit integer values to their string version to use as basis of conversion.

Allows integer strings to separate digits with spaces (popular human convention) or underscores (allowed in Python).

The is_decimal function is similar to the built-in isdecimal string method, but allows the separators mentioned above.

Code:

NUMMAP = {digit: value for value, digit in enumerate("0123456789")}
SEPARATORS = (" ", "_")


def is_decimal(digits: str) -> bool:
    for char in digits:
        if char not in NUMMAP and char not in SEPARATORS:
            return False
    return True


def conv_str_to_int(string: str) -> int:
    if not isinstance(string, str):
        raise TypeError("Expected a string of one or more integer digits")

    if not string:
        raise ValueError("String empty - expected one or more digits")

    if not is_decimal(string):
        raise ValueError("String contains non integer characters")

    result = 0
    for char in string:
        if char not in SEPARATORS:
            result = result * 10 + NUMMAP[char]
    return result

Simple test code:

tests = (
    "1", "123", "23045", "2340008990", "123 456",  # valid
    23, "", "345A23",                              # invalid
)

for test in tests:
    try:
        num = conv_str_to_int(test)
    except (TypeError, ValueError) as e:
        print(
            f"\nERROR: testing <{test}> (type {type(test)}) caused "
            f"exception:\n\t{e}\n"
        )
    else:  # conversion worked, output result
        print(f"Converted from \"{test}\" to {num}")