Python while Moon. Here's a simple question

Asked 2 years ago, Updated 2 years ago, 20 views

It may be frustrating because it's such a basic question, but I'm asking this question because I couldn't find a solution.

a=[0,1,2,3]
b=[2,3,4,5]
c=[]

while sum(c) < 3:
    for i in a:
        c.append(b[i])

print(c)

This is the current situation.

What I intended is that if each element is included in the c list and the sum exceeds 3 (of course, it is an example standard) I want to stop making it into the c-list. But that doesn't apply. What should I do? ㅠ<

python

2022-09-22 14:30

2 Answers

The code you gave us is for for a under while without any special conditions. So every time while turns around, you turn the entire a and plug it into c and then you go out. As a result, the entire b is plugged into c.

You can give them a proper termination conditions Check out the demo.

# a = [0,1,2,3] // Actually not needed
b = [0, 1, 1, 1, 4, 5]
c = []

# Only when the sum of the elements of c is not yet greater than 3:
while sum(c) < 3 :
    for i in b :
        # I was going to add an element of b, but if it exceeds 3 this time,
        if (sum(c) + i) > 3 :
            # Quit the for
            break
        # If you don't think you'll get over it,
        else :
            # Put it in
            c.append(i)

print(c)
# [0, 1, 1, 1]


2022-09-22 14:30

Since Yeopto explained everything, I'm writing an extra (for someone searching...).

The function tools module is provided with a function called redundant. The role of this is to add 1 and 2 when there's a list of 1, 2, 3, 4 and then send the result back to the first factor of the function and give the next number to the second factor and keep adding.

This is a function that...((1 + 2) + 3) + 4) does. Because the preceding argument is the total value, you can compare it with it.

from functools import reduce

b = [2, 3, 4, 5, 6, 7]
limitNum = 15 #LimitSize
Reduce (lambdan, m:n + mifn < limitNumelsen, b) # The sum of the results is only 15 or less.

20


2022-09-22 14:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.