Eureka moments in Python
mensanator at aol.com
mensanator at aol.com
Tue Mar 13 13:59:03 EDT 2007
On Mar 13, 2:16 am, Steven D'Aprano <s... at REMOVEME.cybersource.com.au>
wrote:
> I'd be interested in hearing people's stories of Eureka moments in Python,
> moments where you suddenly realise that some task which seemed like it
> would be hard work was easy with Python.
>
## I have this problem where, given a list of non-zero
## positive integers (sv), I need to calculate threee constants
## x, y, z where
##
## x is 2 raised to the power of the sum of the elements in sv,
##
## y is 3 raised to the power of the count of the elements in sv,
##
## and
##
## z is 3**a*2**A + 3**b*2**B + ... + 3**m*2**M + 3**n*2**N
##
## where a,b,...m,n are 0,1,...len(sv)-2,len(sv)-1 and
## N is the sum of all elements of sv except the last one,
## M is the sum of all elements of sv except the last two,
## ...
## B is the sum of all elements of sv except the last len(sv)-1,
## A is the sum of all elements of sv except the last len(sv).
##
## This turned out to be one of those things that's
## easier to code than to describe.
##
## And if you saw my original Excel spreadsheet where I
## developed it, you'd say Eureka too.
def calc_xyz(sv):
x = 2**sum(sv)
y = 3**len(sv)
z = 0
for i in xrange(len(sv)):
z += 3**i * 2**sum(sv[:-(i+1)])
return (x,y,z)
sv = [1,2,3,4]
print calc_xyz(sv)
## (1024, 81, 133)
More information about the Python-list
mailing list