'complex' function with string argument.

Steven D'Aprano steve at pearwood.info
Tue Mar 18 09:00:29 CET 2014


On Tue, 18 Mar 2014 08:04:44 +0100, Christian Gollwitzer wrote:

> Am 15.03.14 17:26, schrieb Jayanth Koushik:
>> This is regarding the inbuilt 'complex' function. The python docs say:
>> "Note: When converting from a string, the string must not contain
>> whitespace around the central + or - operator. For example,
>> complex('1+2j') is fine, but complex('1 + 2j') raises ValueError."
> 
> It's funny that you ask this question exactly now; because I'm currently
> implementing a compiler for a small language that understands complex
> numbers. As others have explained, the basic issue is the question how
> to parse an expression like
> 
> 	1+2i*3
> 
> is it "complex(1+2i) times 3" 

Putting my mathematician's hat on, I would say *absolutely not*.

> or is it sum of 1 and product of complex 2i and 3? 

This one. Multiplication has higher precedence than addition, so 1+2i*3 
has to be evaluated as 1+(2i*3).


-- 
Steve



More information about the Python-list mailing list