Python list index out of range but shouldn't be - python

startDate, stopDate, startTime, stopTime, startBehavior, and stopBehavior are all lists with the same length. I'm getting a list index out of range in line 5 (if startDate[i] != stopDate[j]) and I'm not sure why. It was working before and now it's not. I'm trying to print the specific behaviors based on the conditions in the if/elif statements.
i = 0
while (i < len(startDate)):
j = 0
while (j < len(stopDate)):
if startDate[i] != stopDate[j]:
j += 1
elif startDate[i] == stopDate[j]:
if stopTime[j] < startTime[i]:
j += 1
elif stopTime[j] > startTime[i]:
if startBehavior[i] != stopBehavior[j]:
j += 1
elif startBehavior[i] == stopBehavior[j]:
print(startBehavior[i])
print(stopBehavior[j])
print('')
i += 1
any help would be appreciated! thank you in advanced!

If you run the following snippet, it will run forever, even though i is clearly greater than 100.
i = 0
while i < 100:
while True:
i += 1
print(i)
Your code is doing something similar -- in the case that i == len(startDate) - 1; startDate[i] == stopDate[j]; stopTime[j] > startTime[i]; and startBehavior[i] == stopBehavior[j], your code will increment i so that i == len(startDate), and then, since j < len(stopDate) is still True, you will not have exited your second while loop. When you try to access startDate[i], you will get an IndexError.
This is somewhat data-dependent so it is possible that it worked before without ever having this issue.

Related

Python Beginner Question “Prime Number Count”

def prime_count(a, b):
for i in range(a,b):
if i % 2 != 0:
return sum(i)
else:
return 0 "
I am a beginner programmer, I have been practicing on some challenges on Edabit, small problems but that require some thinking (for me).
I am trying to count how many prime numbers are on a and b, they are already integers and there is no user input.
I am not very good at loops yet and thought this was going to be a good challenge to practice, what am I doing wrong? I keep getting int object is not iterable
If reference need, here is the link for the challenge.
Link : https://edabit.com/challenge/6QYwhZstMuHYtZRbT
it is an interesting problem that you are solving. You will have to run two-loops here. One to iterate from a to b and the inner loop to check if each element in a -->b is prime or not (the inner loop should run from 2 to j in [a,b).
def primecheck(a,b):
printlist=[]
if a > 1:
for i in range(a,b+1):
for j in range(2,i):
if i % j == 0:
break
else:
printlist.append(i)
if len(printlist) == 0:
return 0
else:
return len(printlist), printlist
Try this out.
As people say in the comment section, calling sum() is what's causing an error.
But, even if you somehow got that part right, you wouldn't quite get what you want. Maybe you were just trying a simple for loop to check if numbers are odd...?
Anyway, I normally like using Sieve of Eratosthenes to generate prime numbers because it's simple.
def sieve_of_eratosthenes(start, end):
if start > end:
raise AssertionError
# end = end + 1 # If end is inclusive, then uncomment this line.
if end < 2:
return 0
sieve = [i for i in range(2, end)] # Initialize an array of number from 2 to end.
size = len(sieve)
p = 2 # Initial prime.
count = 0
# This block implements Sieve of Eratosthenes.
while count < size:
for i in range(count, size):
num = sieve[i]
if num != p and num % p == 0:
sieve[i] = 0
if count == size-1:
break
count += 1
while sieve[count] == 0:
count += 1
if count == size-1:
break
p = sieve[count] # Update the next prime.
# This block calculates the numbers of primes between start and end.
num_of_primes = 0
for p in sieve:
if p == 0 or p < start:
continue
num_of_primes += 1
print(sieve)
return num_of_primes
sieve_of_eratosthenes(1, 100) # This should return 25.

the problem statement but I don't know what exactly is indented

Increment the variable num by 1 post checking the above condition. (note that this increment will be outside the if statement, take care of the indentation in order to avoid a scenario of infinite loop)
this is the problem statement but I don't know what exactly is indented
I don't know if its correct or not
num = 1
factors=[ ]
while num <= 100:
if (num % 10) == 0 :
factors.append(num)
num += 1
print(factors)
I think this is the answer to your question
num = 1
factors = []
while num <= 100:
if (num % 10) == 0:
factors.append(num)
num += 1
print (factors)
Python uses indentation to indicate nested blocks of code, in this example you have a block of code within your while loop, indicated by the 4 space indentation. You then have an if statement when then also needs it's content indented by another 4 spaces. This would give you the following result:
num = 1
factors = []
while num <= 100:
if (num % 10) == 0:
factors.append(num)
num += 1
print(factors)

Using conditional statements in while loop

I was under the impression that adding the following if statement in my while loop makes python pick only the odd values of i that are smaller than 7 and sums them. However, this is not the case.
Here's my code:
i = 0
sum = 0
while i < 7:
if (i % 2) == 1:
sum += i
i += 1
I expect sum to be 9 but an infinite loop occurs, causing the sum to be infinite.
I can't seem to understand how. Any help is appreciated. Thanks in advance!
You only increment i inside the if, so if the condition is not meant, i stays the same forever
i = 0
sum = 0
while i < 7:
if (i % 2) == 1:
sum += i
i += 1
print(sum)
Output:
9
As you keep conditioning i % 2, but if it doesn't go through, the i never changes, it will always exit the if statement, to solve it:
i = 0
sum = 0
while i < 7:
if (i % 2) == 1:
sum += i
i += 1
print(sum)
You have to unindent by 4 spaces your i += 1 line.
For similar cases it is better to use for loop than while loop. Especially if you have long loops. link
sum = 0
for i in range(7):
if (i % 2) == 1:
sum += i

Working with recursion but not with for loop

I have written a code using recursion, but later realized that the depth is too high and does not work for higher level input values. It works completely fine without any issue.
def checkCount(first_window, index=0,reference_list=None):
reference_list = []
count = 0
while index<=len(first_window)-2:
if first_window[index] < first_window[index+1]:
index += 1
count += 1
else: break
if count != 0:
reference_list.append(int((count*(count+1))/2))
count = 0
while index <= len(first_window)-2:
if first_window[index] > first_window[index+1]:
index += 1
count += 1
else: break
if count != 0:
reference_list.append(-int((count*(count+1))/2))
if index > len(first_window)-2: return reference_list
elif first_window[index] == first_window[index+1] and index<len(first_window)-2: index += 1
reference_list = reference_list + checkCount(first_window, index, reference_list)
return reference_list
import random
import time
start = time.clock()
input_array = list(map(int,"188930 194123 201345 154243 154243".split(" ")))
input_array = random.sample(range(1,100),10)
def main():
N = len(input_array)
K = 8
if K == 1: return None
print("Input array: ",input_array)
print("First Window",input_array[:K])
print("Real Output", checkCount(input_array[:K]))
if __name__ == "__main__":main()
Now no matter how I try without recursion, it ends with an infinite loop. I have tried different ways but no progress.
One way I have tried is taking out the recursion statement and returning the referencelist + index:
def checkCount(..):
....
....
return referencelist,index
while index <= K-2:
print("While",index)
reference_list, index = checkCount(new_input, index=0, reference_list=[])
referencelist += reference_list
The application is similar to the here. But we have to deal with tons of data where recursion cannot help. Assume that the input array is greater than 100,000. I am really struck here, I do not understand what logic am I missing. Any help will be grateful.
The first_window variable is only read, and the index variable is only incremented. There is no need for recursion, a simple loop can work.
def check_count(first_window):
reference_list = []
index = 0
while index < len(first_window) - 2:
count = 0
while index <= len(first_window) - 2:
if first_window[index] < first_window[index + 1]:
index += 1
count += 1
else:
break
if count != 0:
reference_list.append(int((count * (count + 1)) / 2))
count = 0
while index <= len(first_window) - 2:
if first_window[index] > first_window[index + 1]:
index += 1
count += 1
else:
break
if count != 0:
reference_list.append(-int((count * (count + 1)) / 2))
if index < len(first_window) - 2 and first_window[index] == first_window[index + 1]:
index += 1
return reference_list
Of course, this algorithm can be optimised, for instance, we can avoid repetitions like: len(first_window) - 2.

python code is restarting

as I'm proceeding slowly with project Euler I started learning python.
although its a great and simple language i got a bit stuck.
every code that i wrote and tried to run is automatically restarting.
i think its because of the very very long loop (for example, finding the 10001 prime number), but i cant find out how to fix this issue.
can anyone help me, give me a guide line or a tip?
oh, if its matters im using python 2.7
thank you!
the code as an example:
count = 0
num = 0
i = 1
def prime(num):
if num <= 1:
return False
if num == 2:
return True
else:
for i in range(3, num):
if (num % i) == 0:
return False
break
else:
return True
while (count < 10001):
if prime(i) == True:
num == i
count == count + 1
i = i + 1
print num
You just need to change the == to = (twice) in your while loop:
while (count < 10001):
if prime(i) == True:
num = i
count = count + 1
i = i + 1
Then the code runs fine, and prints num as 104729

Categories