I get this error:
IndexError: list index out of range
This is my function:
def power(x, y, bound):
list, exp = [], []
z = -1
for i in range (1, bound):
for j in range (1, bound):
if x**i + y**j in range (bound):
if x**i + y**j in list:
break
else:
list.append(x**i + y**j)
z += 1
if z == 0:
exp.append(str(x**i + y**j)+" = " + str(x) + "^" + str(i) + " + " + str(y) + "^" + str(j))
break
if list[z] == max(list):
exp.append(str(x**i + y**j)+" = " + str(x) + "^" + str(i) + " + " + str(y) + "^" + str(j))
else:
for n in range(len(list)):
if (list[z] < list[n+1]) and (list[z] > list[n]):
exp.insert(n, str(x**i + y**j) + " = " + str(x) + "^" + str(i) + " + " + str(y) + "^" + str(j))
else:
break
print("nThe list of values:", sorted(list))
print("nExplaination:n"+"n".join(exp))
Call my function:
print("Input: Two positive integers x and y and the boundnOutput: A list of values x^i + y^j bounded by boundn(i and j are positive integers)n")
x = int(input("Input x: "))
y = int(input("Input y: "))
bound = int(input("Input the bound: "))
power(x, y, bound)
How can I solve this problem?
Advertisement
Answer
Ok, so now you’ve changed your code and my previous answer has been invalidated.
Now your problem is here:
if (list[z] < list[n+1]) and (list[z] > list[n]):
with n+1 because n comes from for n in range(len(list)): and eventually n+1 will fall off the end of list.
You have to ask yourself what: if (list[z] < list[n+1]) and (list[z] > list[n]): actually means.