Skip to content

Instantly share code, notes, and snippets.

@greenmoss
Created November 2, 2021 02:45
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 greenmoss/7dc2e82b774c1d3b57f0bcf81dcd2f9e to your computer and use it in GitHub Desktop.
Save greenmoss/7dc2e82b774c1d3b57f0bcf81dcd2f9e to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
def add_digits(the_digits, sum_log10_inversed = False):
total = 0
digit_count = len(the_digits)
if(sum_log10_inversed):
the_digits.reverse()
# count down, from the last digit to the first
for position_index in range(digit_count):
total = add_int_with_log10( total, the_digits[position_index], position_index)
return(total)
def add_int_with_log10(old_int, new_int, new_log10):
return( old_int + (int(new_int) * (10 ** new_log10)) )
def is_digit(the_char):
ordinal_value = ord(the_char)
# it's an ascii integer
if (ordinal_value >= 48) and (ordinal_value <= 57):
return(True)
# it's not an ascii integer
return(False)
def is_first(index):
return(index == 0)
def is_dot(the_char):
return(the_char == '.')
def is_dash(the_char):
return(the_char == '-')
def parse_str(the_str):
print(f'== {the_str}')
is_negative = False
before_fractional = True
whole_digits = []
fractional_digits = []
for index in range(len(the_str)):
the_char = the_str[index]
if is_first(index):
if is_dash(the_char):
is_negative = True
continue
if is_dot(the_char):
print("error: first character is ., which is invalid")
return(None) # give up! invalid
if is_digit(the_char):
whole_digits.append(int(the_char))
continue
# anything below here is 2nd character or later
if is_digit(the_char):
if before_fractional:
whole_digits.append(int(the_char))
else:
fractional_digits.append(int(the_char))
# handling non-digits
if is_dot(the_char):
if before_fractional:
before_fractional = False
else:
print("error: specified more than one ., which is invalid")
return(None) # give up! invalid
if is_dash(the_char):
print("error: contains more than one -, which is invalid")
return(None) # give up! invalid
if(len(whole_digits) == 0):
print("error: no whole digits give, which is invalid")
return(None)
whole_number = add_digits(whole_digits, True)
fractional_number = add_digits(fractional_digits)
print(f'is it negative? {is_negative}')
print(f'part before the dot: {whole_number}, from {whole_digits}')
print(f'part after the dot: {fractional_number}, from {fractional_digits}')
for my_str in ['0.5000', '-1', '-0.5', '0.5', '312.237', '00005000', '-.5', '-a', 'a1', '0a', '.3', '--1', '05..3']:
parse_str(my_str)
@greenmoss
Copy link
Author

Fractional part is broken!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment