HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonMinor

Convert a numeric string to number but without python's built in function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
builtwithoutnumbernumericconvertbutfunctionpythonstring

Problem

I'd like to get a code review and some insights of whether I chose a good way to do this. What would other, clever ways look like.

"""
Convert numeric string to number withoutusing python's built in functions.
"""
dec_places = {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}

def str2int(num_str):
    iter = len(num_str)
    number = 0
    for char in num_str:
        number += (char_digit[char] * dec_places[iter])
        iter -= 1
    return number

print(str2int('623297'))

Solution

Doctstrings

The docstring:

"""
Convert numeric string to number withoutusing python's built in functions.
"""


Should be at the top of the inside of the function.

(Also withoutusing should be without using.)

Global Variables

Global variables are typically a bad design practice. Move these:

dec_places = {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}


Inside the function.

Function naming

str2int should be renamed to str_to_int.

Better algorithm

dec_places is unneeded and limits your algorithm significantly.

I would enumerate over the reversed of your string:

for ind, char in enumerate(reversed(num_str)):
    number += char_digit[char] * 10**(ind + 1)


enumerate takes an iterable and creates tuples of (0, el1), (1, el2) ....

We reverse the string and then multiply each character by the appropriate power of 10. This allows you to go beyond the 6th power.

Alternatively, you can keep an iter value that counts up from 1. I'll leave this as an exercise. It might be faster than using reversed. You should not need a dictionary though.

Code Snippets

"""
Convert numeric string to number withoutusing python's built in functions.
"""
dec_places = {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}
for ind, char in enumerate(reversed(num_str)):
    number += char_digit[char] * 10**(ind + 1)

Context

StackExchange Code Review Q#151003, answer score: 4

Revisions (0)

No revisions yet.