0

I'm trying to put the sum of two numbers from list x of which the division by 20 of that sum is not possible into list z. My code does not comply with the rule that only a combination of two numbers from list x can be used. So, for instance, 35 is not valid since it can't be formed by adding two numbers from list x. However, it still occurs in the result of list z.

Also, I'm adding up 'target' by 5 since 5 is the lowest number in list x.

What am I doing wrong?

x = [200, 100, 50, 20, 10, 5]
target = 5
combi=0
max = x[0]+x[1]
z = []
while target <= max:
    for i in x:
        if i < target:
            pair = target - i
            if pair in x:
                combi = 1
    if combi == 1 and target % 20 != 0:
        z.append(target)
    target += 5
print(z)

Given output: [10, 15, 25, 30, 35, 45, 50, 55, 65, 70, 75, 85, 90, 95, 105, 110, 115, 125, 130, 135, 145, 150, 155, 165, 170, 175, 185, 190, 195, 205, 210, 215, 225, 230, 235, 245, 250, 255, 265, 270, 275, 285, 290, 295]

Desired output: [10, 15, 25, 30, 55, 70, 105, 110, 150, 205, 210, 250]

2
  • 3
    You never reset combi to 0. The combi = 0 assignment should be moved inside the while loop Commented Nov 22, 2020 at 10:02
  • 1
    Please read about How to debug small programs. You can also use Python-Tutor which helps to visualize the execution of the code step-by-step. Commented Nov 22, 2020 at 10:21

2 Answers 2

1

The problem is that you never reset the "combi" variable. Here is your fixed code

x = [200, 100, 50, 20, 10, 5]
target = 5
combi=0
max = x[0]+x[1]
z = []
while target <= max:
    for i in x:
        if i < target:
            pair = target - i
            if pair in x:
                combi = 1
    if combi == 1 and target % 20 != 0:
        z.append(target)
    target += 5
    combi = 0
print(z)
Sign up to request clarification or add additional context in comments.

Comments

1

try this code:

x = [200, 100, 50, 20, 10, 5]
z = []
for i in range(0,len(x)):
    for j in range(i+1,len(x)):
        sum=x[i]+x[j]
        if sum%20!=0:
            z.append(sum)
z.reverse()
print(z)

your desired output:

output: [15, 25, 30, 55, 70, 105, 110, 150, 205, 210, 250]

4 Comments

i think 10 is not valid as output
because 10 is not created by adding two numbers
Thanks, but 10 = 5+5.
in list x has only one 5 , so another 5 comes from?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.