From 66991be9ecf900e38fb99c4500001e7f19cabf79 Mon Sep 17 00:00:00 2001 From: Walter Bender Date: Fri, 12 Feb 2010 13:03:06 +0000 Subject: better? alphanumeric conversion --- (limited to 'talogo.py') diff --git a/talogo.py b/talogo.py index 1210d27..a847d86 100644 --- a/talogo.py +++ b/talogo.py @@ -68,20 +68,51 @@ class logoerror(Exception): Utility functions """ -def char_to_num(x, y): +''' +The strategy for mixing numbers and strings is to first try +converting the string to a float; then if the string is a single +character, try converting it to an ord; finally, just treat it as a +string. Numbers appended to strings are first trreated as ints, then +floats. +''' +def convert(x, fn): try: - xx = float(x) + return fn(x) except ValueError: - xx = x - if type(xx) == str or type(xx) == unicode and len(xx) == 1: - xx = ord(xx[0]) - try: - yy = float(y) - except ValueError: - yy = y - if type(yy) == str or type(yy) == unicode and len(yy) == 1: - yy = ord(yy[0]) - return xx, yy + return x + +def numtype(x): + if type(x) == int: + return True + if type(x) == float: + return True + return False + +def strtype(x): + if type(x) == str: + return True + if type(x) == unicode: + return True + return False + +def str_to_num(x): + xx = convert(x, float) + if type(xx) is float: + return xx + else: + xx, xflag = chr_to_ord(x) + if xflag: + return xx + else: + raise logoerror("#syntaxerror") + +def chr_to_ord(x): + if strtype(x) and len(x) == 1: + try: + return ord(x[0]), True + except ValueError: + return x, False + return x, False def careful_divide(x, y): try: @@ -94,100 +125,96 @@ def careful_divide(x, y): def taequal(x, y): try: return float(x)==float(y) - except: + except TypeError: typex, typey = False, False - if type(x) == str or type(x) == unicode: + if strtype(x): typex = True - if type(y) == str or type(y) == unicode: + if strtype(y): typey = True if typex and typey: return x == y - xx, yy = char_to_num(x, y) - return xx==yy + return str_to_num(x) == str_to_num(y) def taless(x, y): try: return float(x)