user3349164
user3349164

Reputation: 31

Python List Index Error

Here is my version of the code right now and I keep getting list index error.

n = 0
y = len(list1)-1
while n < y:
    for k in list1:
        if list1[n]+ k == g:
            print("The 2 prime numbers that add up to ",g,"are ", list1[n]," and ",k,".")
            break
        else:
            n = n+1

Upvotes: 0

Views: 175

Answers (2)

Josh
Josh

Reputation: 1

You left a few bits of information out, but I gather that you are trying to find 2 primes that match a target. In order to access a list in this manner, you need to enumerate it.

y = len(list1) - 1
while n < y:
    for n, k in enumerate(list1):
        if list1[n]+ k == g :
            print("The 2 prime numbers that add up to ",g,"are ", list1[n]," and ",k,".")
            break

However, you don't really need the index, two for loops would accomplish the same thing.

target = 8
primes = [2, 3, 5, 7, 11, 13, 17, 19]
message = 'The 2 prime numbers that add up to {target} are {value1} and {value2}'
for index1, value1 in enumerate(primes):
    for value2 in primes[index1 + 1:]:
        if value1 + value2 == target:
            print(message.format(target=target, value1=value1, value2=value2))

Upvotes: 0

isedev
isedev

Reputation: 19641

You are incrementing n in the for loop but testing its contraint in the outer while loop.

Perhaps this is what you wanted:

n = 0
y = len(list1)-1
found = 0
while n < y:
    for k in list1:
        if list1[n]+ k == g:
            print("The 2 prime numbers that add up to ",g,"are ", list1[n]," and ",k,".")
            found = 1
            break # for loop
    if found:
       break # while loop
    n = n + 1

A much better way to do it is using itertools.combinations_with_replacement:

import itertools
for (v1,v2) in itertools.combinations_with_replacement(list1, 2):
    if v1 + v2 == g:
        print("blah blah blah")
        break

combinations_with_replacement(list1,2) will return all the unordered combinations of two elements of list1. For instance, combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC

Upvotes: 2

Related Questions