Question

str(reduce(lambda x, y: x * y, range(1, 11))) -> this returns 10! or '3628800'

Without creating a for loop, how can I map this function to another function as a list of one-digit integers: e.g. reduce(lambda x, y: x+ y, [3, 6, 2, 8, 8, 0, 0])

Clarification:

reduce(lambda x, y: x + y, [str(reduce(lambda x, y: x * y, range(1, 11)))])

How do I turn everything inside the [ ] into a list of one-digit integers so that the first function can evaluate it? Of course I need to transform it inside the [ ].

Was it helpful?

Solution 2

You can use a list comprehension:

[int(x) for x in str(reduce(lambda x, y: x * y, range(1, 11)))]

The final product:

reduce(lambda x, y: x + y, [int(x) for x in str(reduce(lambda x, y: x * y, range(1, 11)))])

OTHER TIPS

I think you're simply looking for map(int, s) where s is the string you want to get integer digits from. For example:

>>> import math
>>> math.factorial(10)
3628800
>>> str(math.factorial(10))
'3628800'
>>> map(int,str(math.factorial(10)))
[3, 6, 2, 8, 8, 0, 0]
>>> sum(map(int,str(math.factorial(10))))
27
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top