Python Help ...

Bill Campbell linux-sxs
Thu Mar 29 09:11:57 PDT 2007


On Thu, Mar 29, 2007, Matthew Carpenter wrote:
>On Wednesday 28 March 2007 16:18, Bill Campbell wrote:
>> On Wed, Mar 28, 2007, Ben Duncan wrote:
>> >But, I need to be able to manipulate the array with values
>> >latter on. Since strings are immutable, I do not think I can
>> >do this.
>>
>> This is really fairly easy, and probably more efficient than
>> having to deal with the subscripting
>
>While I agree it's easier, it is certainly not more efficient.  Every time you 
>subscript a string like that, it's the equivalent of 2 or 3 strncpys.  It may 
>save some memory, but you'll pay in processor cycles.
>
>Also, you should be able to do your method without the s variable:
>
>table[j] = table[j][:i] + c + tables[j][i+1:]

I could, but find it easier, probably more efficient, and less
prone to gypotraphical errors to set an intermediate variable
rather than subscript into an array multiple times.

The amount of memory taken for an intermediate variable is
generally less than the amount taken for code multiply
referencing into an array or a dictionary.

An extreme example of this was a FORTRAN program I worked on
about forty years ago where a scientist (who wasn't a programmer
and proud of it) was working with hyperbolic functions and
calculsting things like this repeatedly


	tanh = (exp(x) - exp(-x))/(exp(x) + exp(-x))

Granted modern compilers could well optimize this to avoid
multiple calculations of the exp() functions, but I found it much
easier and clearer to do it with a couple of intermediate
variables.  It not only cuts the number of calls to the exp
functions in half, it means I have to hit the shift key and find
the parenthesis keys 8 times instead of 12.

	epx = exp(x)
	emx = exp(-x)
	tanh = (epx - emx)/(exp + emx)

So as a general rule, I think it's better coding style to use
intermediate variables in most cases as it reduces typing errors
and is probably more efficient in terms of memory and CPU use.
The reduction in typing time and errors is the major factor.

Bill
--
INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

The most serious doubt that has been thrown on the authenticity of the
biblical miracles is the fact that most of the witnesses in regard to
them were fishermen.
		-- Arthur Binstead



More information about the Linux-users mailing list