Issue
What should I do if I have a variable number of variables and I want the sum of variables? For Eg.
import random
X = random.randint(1, 25)
Y = random.randint(1, 5) + X
for A in range(X, Y):
W = random.randint(1, 10) # you want sum of all W produced
# W = W+W --> will not work
From this very random system, I want to extract the sum of all W.
something like W = W + W won't work, the value of the previous result cannot be stored
I would like you to not edit the previously given part and get the answer because I have tried to reconstruct the code to be smaller. This question is from a bigger code with me having no scope of using W += ...
Solution
You don't even need a for loop for that, simply sum over a generator expression.
import random
X = random.randint(1, 25)
Y = random.randint(1, 5) + X
W = sum(random.randint(1, 10) for _ in range(X, Y))
If all the lines of the code you provided have to stay intact here's what you can do:
import random
X = random.randint(1, 25)
Y = random.randint(1, 5) + X
S = 0
for A in range(X, Y):
W = random.randint(1, 10) # you want sum of all W produced
S += W
Answered By - matszwecja
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.