This python code converts integers to strings and strings to ints without the inbuilt functions "int()" and "str()" It is my solution from a challange from edabit.com named &quot;Drunken Python&quot;. Thats the task:
You need to create two functions to substitute str() and int(). A function called int_to_str() that converts integers into strings and a function called str_to_int() that converts strings into integers.
I hope you can tell me things I could do better and if the algorithms I used (e.g. to calculate the length of an int) are optimal.
# A function called int_to_str() that converts integers into strings and a function called str_to_int() that
# converts strings into integers without using the in built functions &quot;int()&quot; and str().


def str_to_int(num_str):
    dec_places = {11: 10000000000, 10: 1000000000, 9: 100000000, 8: 10000000, 7: 1000000, 6: 100000, 5: 10000, 4: 1000,
                  3: 100, 2: 10, 1: 1}
    char_digit = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    num = 0
    length = len(num_str)
    for i in range(length):
        x = char_digit[num_str[0 - (i + 1)]] * dec_places[i + 1]
        num = num + x
    return num


def calculate_length(num):
    div = 10
    i = 1
    while num / div &gt;= 1:
        div = div * 10
        i = i + 1
    return i


def int_to_str(num_int):
    word = &quot;&quot;
    div = 10
    char_digit = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}
    length = calculate_length(num_int)
    for i in range(length):
        x = (num_int % div) // (div // 10)
        word = char_digit[x] + word
        num_int = num_int - x
        div = div * 10
    return word
```
Keep it simple
Your functions are way too complicated. First, you can convert a single digit from integer to character by using ord() and the fact that the ordinals of the characters '0' to '9' are consecutive. Furthermore, you don't need to calculate the length of an integer if you reverse the way you build up the string. Here are example implementations that are simpler:
def str_to_int(num_str):
    num = 0

    for char in num_str:
        num *= 10
        num += ord(char) - ord('0')

    return num

def int_to_str(num_int):
    word = &quot;&quot;

    while num_int:
        word = chr(ord('0') + num_int % 10) + word
        num_int //= 10

    return word or &quot;0&quot;

Integers can be negative
Your code (and my example simplification above) does not handle negative integers.