Skip to content

Instantly share code, notes, and snippets.

@marklap
Last active May 6, 2018 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marklap/6a8b46450281ab696f64e3dd7a134bd1 to your computer and use it in GitHub Desktop.
Save marklap/6a8b46450281ab696f64e3dd7a134bd1 to your computer and use it in GitHub Desktop.
Implementation of atoi
''' atoi package '''
''' atoi converts string representations of integers and floats to their numeric type
'''
from decimal import Decimal
ORD_0 = ord('0')
def atoi_int(s):
''' atoi_int converts a string representation of an integer into an integer
Args:
s (str): string representing an integer
Returns:
int: integer equivalent of `s`
'''
sum = 0
s_len = len(s)
for i in range(s_len):
sum += (ord(s[s_len-(i+1)]) - ORD_0) * (10 ** i)
return sum
def atoi_float(s):
''' atoi_float converts a string representation of a float to a float
Note: uses the `decimal` package because the floating point byte conversion produce results
that are unexpected. Example: 3.14159 == 3.14159000000000002
Args:
s (str): string representing a floating point number
Return:
float: floating point equivalent
'''
if '.' in s:
d, f = s.split('.', 1)
else:
d = s
f = '0'
sum = Decimal(0)
f_len = len(f)
for i in range(f_len):
sum += Decimal(ord(f[i]) - ORD_0) / (10 ** (i+1))
return float(atoi_int(d) + sum)
''' test_atoi includes nosetests for atoi functions
to run:
`# nosetests -v`
'''
from .atoi import atoi_int, atoi_float
def test_int():
cases = (
('1234', 1234),
('42', 42),
('8675309', 8675309),
('5150', 5150),
)
for s, want in cases:
got = atoi_int(s)
assert want == got, 'integer mismatch - want: {0}, got: {1}'.format(want, got)
def test_float():
cases = (
('1234.5678', 1234.5678),
('3.14159', 3.14159),
('1.6180', 1.618),
('0', 0.0),
('21', 21.0),
('0.739085', 0.739085),
)
for s, want in cases:
got = atoi_float(s)
assert want == got, 'float mismatch - want: {0}, got: {1}'.format(want, got)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment