Avatar ·

for _ in range . how does underscore work

📁 Advanced Python Topics, example

matrix = [[[0]*5] for _ in range(5)]

there is such an expression, it creates five elements like 0 0 0 0 0. Can someone explain the mechanics of creation, the simpler the better.

For example

for x in range(5):    print (x)

range(5) - this is 0,1,2,3,4

and for each value starting from the first (0) the action print(x) is executed (prints the current value, in this case 0), after which it takes

Avatar ·

If only natural numbers n are input, you can do this:

n = int(input())sum_of_factorials = 1curr_factorial = 1for i in range(2, n + 1):    curr_factorial *= i    sum_of_factorials += curr_factorialprint(sum_of_factorials)

(You need 1!+2!+3!+...+n!, right? Or did you not make a typo? If not, then just multiply sum_of_factorials by 2 at the end and subtract 1).

This is quite simple dynamic programming. You don't need to recalculate each time from scratch.

Log in to leave an answer

Blogs