[Tutor] Trickier exercise: convert string to complex number
Angus Rodgers
angusr at bigfoot.com
Sat Jul 11 04:15:46 CEST 2009
Wesley Chun, /Core Python Programming/, Ex. 6-13:
"[...] An atoc() was never implemented in the string module, so
that is your task here. atoc() takes a single string as input,
a string representation of a complex number [...] and returns
the equivalent complex number object with the given value [...]"
<http://python.pastebin.com/d6f7c679f> (retention: 1 day)
<http://python.pastebin.com/d2ea157ff> (retention: 1 day)
(helper functions for user input)
The main functions are short enough to post here, I think, but
there are many explanatory and apologetic comments in the first
file above; also, I would welcome (with a grimace!) any comments
as to whether I am developing a cranky or baroque style (as I'm
working very much on my own, apart from whatever feedback I can
get here), and such misdemeanours are more likely to be noticed
in the second (and longer) of the two files above.
from string import whitespace
def no_spaces(str):
return ''.join([ch for ch in str if ch not in whitespace])
def atoc(num):
"""Convert string representation to complex number."""
num = no_spaces(num)
n = len(num)
if not n:
raise ValueError
# Ignore first character
for i, ch in enumerate(num[1:]):
if ch == 'j':
# Must be end of string, else invalid
if i != n - 2:
raise ValueError
return complex(0.0, float(num[:-1]))
if ch in '+-' and num[i] not in 'eE':
return complex(float(num[:i + 1]),
float(num[i + 1:-1]))
return complex(float(num), 0.0)
--
Angus Rodgers
More information about the Tutor
mailing list