7
votes

I'm trying to implement add2strings, sub2strings, mult2strings functions in Python. They're all very easy if you just do int(string), but I want to do them without that and without importing another cheating thing like Decimal. My current idea is to use bytes.

Is there another way to do this?

3
I am very curious to know why you want to do this. - Ignacio Vazquez-Abrams
You could split string to get chars and then you can compare char with "0" to get digit 0, etc. - furas
Coding practice. And I'm liking Python a lot more than C/C++ ATM. - Eugene K
@furas ah interesting idea! I suppose that would work. - Eugene K
This would be much better on CodeGolf.StackExchange.com - user764357

3 Answers

12
votes

Refer to a basic atoi in C:

int myAtoi(char *str)
{
    int res = 0; // Initialize result

    // Iterate through all characters of input string and update result
    for (int i = 0; str[i] != '\0'; ++i)
        res = res*10 + str[i] - '0';

    // return result.
    return res;
}

Which translates into the Python:

def atoi(s):
    rtr=0
    for c in s:
        rtr=rtr*10 + ord(c) - ord('0')

    return rtr

Test it:

>>> atoi('123456789')
123456789   

If you want to accommodate an optional sign and whitespace the way that int does:

def atoi(s):
    rtr, sign=0, 1
    s=s.strip()
    if s[0] in '+-':
        sc, s=s[0], s[1:]
        if sc=='-':
            sign=-1

    for c in s:
        rtr=rtr*10 + ord(c) - ord('0')

    return sign*rtr

Now add exceptions and you are there!

2
votes

This is really inefficient but:

>>> zero = ord("0")
>>> s = "1234"
>>> sum([x * 10**i for i, x in enumerate(map(lambda x: x - zero, map(ord, s))[::-1])])
1234

This is slightly better:

>>>> sum([x * 10**i for i, x in enumerate([ord(x) - zero for x in s[::-1]])])
1234

>>> atoi = lambda s: sum([x * 10**i for i, x in enumerate([ord(x) - zero for x in s[::-1]])])
>>> atoi("1234")
1234
1
votes

What about just iterating through all the integers, converting them to strings and comparing strings?

import exceptions
MAX_INT  = 1000
MIN_INT = -1000

def str2int(s):
  for i in range(MIN_INT,MAX_INT):
    if s == str(i):
      return i
  raise exceptions.OverflowError

def add2strings(s,t):
  return str(str2int(s)+str2int(t))

print add2strings("170","-300")
print add2strings("170","-1001")

This gives:

"-170"
Traceback (most recent call last):
  Line 15, in <module>
    print add2strings("170","-1001")
  Line 12, in add2strings
    return str(str2int(s)+str2int(t))
  Line 9, in str2int
    raise exceptions.OverflowError
OverflowError