Sorting and comparing lists with a nested for loop

67 Views Asked by At

Im Trying to sort and compare lists with a for loop, but I keep getting the error:

sorted(lista[str(y+1)])
KeyError: '14454'

Here's my code:

l = 0
k = 0
u = 0
lista = {}


sys.stdout = open("1.txt", "w")
for i in range(1,28):
    for j in range(1,28):
        for k in range(1,28):
          a = float(i)
          b = float(j)
          c = float(k)
          q = (a*b*c) / ((a+b+c)*(a+b+c)*(a+b+c))
          if q > (1 / 81) and q < 1:
            if a != b and b != c and c != a:
              lista[str(l)] = [a,b,c]
              l = l + 1

for x in range(l):
    for y in range(l):
        sorted(lista[str(x)])
        sorted(lista[str(y+1)])

        if lista[str(x)] == [str(y+1)]:
            u = u + 1
    
sys.stdout.close()
1

There are 1 best solutions below

1
On

The Error (Explained)

KeyError: "14454"

means that that the key is non-existent. For example, if my dict is {"hi": "hi", "hello": "hello"}, and I try calling myDict["hiya"], it will return KeyError: "hiya".

What should you do?

Well, debug it. By placing print(lista) before the loop (to avoid the console being overflowed), you can see the keys of lista and find your code solution from there!