1

I just want to calculate the product of certain elements (whose index value + 1 is in N) of a string.

This works fine:

start = 1
end = 1000000
N = (1, 10, 100, 1000, 10000, 100000, 1000000) 
product = 1

concatenated_numbers_str = ''.join([str(x) for x in range(1, end + 1)])

for n in N:
    product *= int(concatenated_numbers_str[n - 1])
print(product)

But what is a better way to do this?

Thank you

luffe
  • 1,588
  • 3
  • 21
  • 32
  • http://stackoverflow.com/questions/7948291/python-product-in-built-function – Pavel May 15 '12 at 15:27
  • @Pavel Could you please elaborate how you are going to use the `reduce()` to do the product? The numbers to be multiplied together are not available together in a separate list. How would you extract the required integers from `concatenated_numbers_str` list and multiply them together using `reduce()`? – Susam Pal May 15 '12 at 15:37
  • `[int(concatenated_numbers_str[n]) for n in N]` – Pavel May 15 '12 at 15:45

1 Answers1

0

I like Pavel's answer, but it should be n-1 instead of n:

import operator
end = 1000000
N = (1, 10, 100, 1000, 10000, 100000, 1000000)
concatenated_numbers_str = ''.join([str(x) for x in range(1, end + 1)])
print reduce(operator.mul, [int(concatenated_numbers_str[n-1]) for n in N], 1)
opiethehokie
  • 1,862
  • 11
  • 14