[Tutor] Trickier exercise: convert string to complex number

Rich Lovely roadierich at googlemail.com
Sat Jul 11 06:19:33 CEST 2009


On 11 Jul 2009, at 03:15, Angus Rodgers <angusr at bigfoot.com> wrote:

> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

This would probably be considered cheating, but there _is_ actually a  
atoc() (of sorts) in the 2.6 stdlib. It's called ast.literal_eval().   
It will take a string representing ANY python literal, and SAFELY  
return it's value.

Why has no one here spoted this before?

---
Rich "RoadieRich" Lovely
There are 10 types of people in the world: those who know binary,  
those who do not, and those who are off by one.

(Sent from my iPod - please allow me a few typos: it's a very small  
keyboard)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090711/9bb4b8ce/attachment.htm>


More information about the Tutor mailing list