I try to run this program but it has the following error:
Traceback (most recent call last):
File "C:/Users/Αλέξανδρος/Desktop/1.py", line 12, in <module>
k=k+C[s]
IndexError: list index out of range
The code is below
a=0
b=0
s=0
k=0
A = [0 for a in range(1000)]
B = [0 for b in range(1000)]
C = [0 for s in range(1000000)]
while a<=1000:
C[s]=(A[a]**2+B[b]**2)**0.5
a=a+1
s=s+1
k=k+C[s]
if a==1000:
b=b+1
a=0
if a==1000 and b==1000:
print (k/1000000)
I know that this question is probably duplicated, but I don't know how to solve it, because in the beggining I thought that the error is because C[-1] doesn't exist. But I don't think that is the problem.
Thank you in advance
Because of a<=1000 you code executes 1,000,001 iterations, but there are only 1,000,000 elements in the list. You made a classical "off by 1" mistake. Change <= to <.
Indeed, you should be using numpy for problems like this.
You are acessing past the array range, but just changing <= to < won't fix it as it will still execute
s=s+1
k=k+C[s]
in the iteration where s=999999 and it breaks when trying to access C[1000000].
You can easily debug the values on the iteration where it breaks by adding a print:
#!/usr/bin/python3
a=0
b=0
s=0
k=0
A = [0 for a in range(1000)]
B = [0 for b in range(1000)]
C = [0 for s in range(1000000)]
while a<=1000:
print("a={:d} b={:d} s={:d}".format(a,b,s))
C[s]=(A[a]**2+B[b]**2)**0.5
a=a+1
s=s+1
k=k+C[s]
if a==1000:
b=b+1
a=0
if a==1000 and b==1000:
print (k/1000000)
And you will get your culprit:
(...)
a=997 b=999 s=999997
a=998 b=999 s=999998
a=999 b=999 s=999999
Traceback (most recent call last):
File "./off.py", line 15, in <module>
k=k+C[s]
IndexError: list index out of range
Regarding your algorithm, the s=s+1 / k=k+C[s] lines should probably be reversed (you want to accumulate in k the latest C[s] computed, C[s+1] is always 0 as it will only be computed by the next iteration.
Related
I am working on a problem from code wars. It is "Delete occurrences of an element if it occurs more than n times".
The instructions are Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering.
For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3].
Example: delete_nth ([1,1,1,1],2) # return [1,1] delete_nth ([20,37,20,21],1) # return [20,37,21]
The issue is that when I run this in code wars it comes back with the error.
Traceback (most recent call last):
File "tests.py", line 30, in <module>
do_test()
File "tests.py", line 9, in do_test
test.assert_equals(delete_nth([], 5), [], "From list [],5 you get")
File "/workspace/default/solution.py", line 6, in delete_nth
if o.count(o[x]) > max_e:
IndexError: list index out of range
But everything is fine and I get zero errors when I run it in VSC. I know what the error is telling me but I just can't understand or see how that is.
def delete_nth(order,max_e):
o = order[::-1]
x = 0
while x != len(o)+1:
if o.count(o[x]) > max_e:
o.remove(o[x])
x += 1
if x >= len(o):
return(o[::-1])
return(o[::-1])
Try putting
if order == []:
return []
before the while loop (of course at the same indentation level with while).
The error happens when you put [] as the first parameter, as the error message indicates. In that chase o in your code is an empty list, so in the while loop o[x] cannot be evaluated. The if above will deal with this pathological case.
I am trying to generate the Fibonacci value of a number efficiently, but my code returns this error:
"Traceback (most recent call last):
File "fibonacci_number.py", line 22, in <module>
print(fibonacci_number(input_n))
File "fibonacci_number.py", line 16, in fibonacci_number
next_num = fib_list[n-2] + fib_list[n-1]
IndexError: list index out of range"
Here is the full code:
def fibonacci_number(n):
assert 0 <= n <= 45
fib_list = [0, 1]
for i in range(2, n):
next_num = fib_list[n-2] + fib_list[n-1]
fib_list.append(next_num)
return fib_list[n]
if __name__ == '__main__':
input_n = int(input())
print(fibonacci_number(input_n))
I don't want to call fibonacci_number() recursively, as it will make me recalculate fib_list[n-2] and fib_list[n-1] over and over, which takes up time.
I found other people with similar issues, but using ".append()" seemed to resolve their issue of adding something new to a Python list.
Some things I've tried:
fib_list = fib_list.append(next_num)
fib_list.append(fib_list[n-2] + fib_list[n-1])
declaring next_num separately and setting it equal to 0 before later updating its value
The error is in this line:
next_num = fib_list[n-2] + fib_list[n-1]
You are always setting next_num using "n", which would mean you're calculating the final number in your list. You want to replace this line with
next_num = fib_list[i-2] + fib_list[i-1]
You should also change to
return fib_list[n-1]
BTW, if you want to calculate the n-th fibonacci number SUPER efficiently, I would recommend using another method from this article.
Can you please tell me what I did wrong in this code?
for r in range(10):
for c in range(5):
print(L[r][c], end=" ")
print()
Why am I getting this error?
1 2 Traceback (most recent call last):
File "<pyshell#111>", line 3, in <module>
print(L[r][c], end=" ")
IndexError: list index out of range
Apparently your L array or each sub-array of it doesn't have the dimensions you're supposing they have. This should solve your problem:
for r in range(len(L)):
for c in range(len(L[r])):
print(L[r][c], end=" ")
print()
You could do more intuitive and better code, as follow
L = [[1,2,3], [4,5,6], [7,8,9]]
for row in L:
for column in row:
print(column)
'''
Your iteration depths are mismatch with your (supposed) nested list. Show us your list L.
This is a question of nested loop where I have to find the names of students in alphabetical order with 2nd lowest marks.
I am getting following error:
Traceback (most recent call last):
File "solution.py", line 12, in <module>
if (l[i][0]==l[0][0]):
IndexError: list index out of range
Following is my complete code.
l=list()
p=list()
q=list()
for i in range (int(raw_input())):
p=[raw_input(),int(raw_input())]
p.reverse()
l.append(p)
l.sort()
print len(l)
for i in range(0,len(l)):
print "i= ",i
if (l[i][0]==l[0][0]):
l.remove(l[i])
print l
for i in range(0,len(l)):
if (l[i][0]==l[0][0]):
q.append(l[i][1])
q.sort()
for i in range(0,len(q)):
print q[i]
I have even printed the index which shows the values are in range. Please run the function to find the following output:
4
i= 0
i= 1
i= 2
i= 3
I will happy if I get any better method from my the community ,But my main concern is the error I am getting "Index Out of Range" .It doesn't seem right here
The problem is that you are removing items from a loop. The thumb rule is that you shall never remove items from a list while iterating over it.
I don't really understand your code right now, but you can just change the way you are doing the first loop and apply the same logic for the next ones, at least you will have what you want.
The idea here is that with the while statement, after each iteration, you will have another verification of the size of the list. Meanwhile with the for loop, only at the first time, since range will return a list and the for loop will just iterate over the list which was already created.
l=list()
p=list()
q=list()
for i in range (int(raw_input())):
p=[raw_input(),int(raw_input())]
p.reverse()
l.append(p)
l.sort()
print len(l)
i = 0
while i < len(l):
print "i= ",i
if (l[i][0]==l[0][0]):
l.remove(l[i])
i += 1
print l
You are using remove, because of that l, in some moment, have less elements than you expect.
How do I go about doing something like this?
Say I have an array x = np.array([1,2,3,4,5]) of length 5,
for i,j in range(len(x)):
I want i and j to increment together.
This is throwing me an error message:
TypeError Traceback (most recent call last)
<ipython-input-4-37d0ddc3decf> in <module>()
----> 1 for i,j in range(len(x)):
2 print i,j
3
TypeError: only length-1 arrays can be converted to Python scalars
The reason I need this is because I have to use it in a condition inside the for loop. Like say, y[i][j] and I want this to be 0,0 then 1,1 and so on.
Why do you need j in the first place? If j is always equal to i, just use i. No need for a second variable.
Edited answer
OP says
The reason I need this is because I have to use it in a condition inside the for loop. Like say, y[i][j] and I want this to be 0,0 then 1,1 and so on.
In that case, you could simply use:
y[i][i]
Original answer
I'm not really sure why you would want to do that, you could just set it in the first line of the for loop:
for i in range(len(x)):
j = i
... #rest of the code follows
You could also use enumerate, as pointed in comments by #Julien, like below (but IMO, the earlier method is better):
>>> for i, j in enumerate(xrange(len(x))):
... print i, j
...
0 0
1 1
2 2
You could try this:
for i, j in zip(range(len(x)), range(len(x))):
print i, j
So the question is about how to iterate two variables, not why ;-)