python code is restarting - python

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

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.

Almost Perfect Kattis (Time Limit Exceeded )

Hope you can help me in this problem :
So the problem is Almost Perfect in Kattis.
https://open.kattis.com/problems/almostperfect
This is my code. the first test is passed but the second no it gives me am message (Time Limit Exceeded)
def isperfect(n):
l=0
for i in range(1,n):
if n%i==0:
l+=i
if l>n+2 :
print(f"{n} not perfect")
break
if(l==n):
print(f"{n} perfect")
elif abs((n-l))<=2:
print(f"{n} almost perfect")
else :
print(f"{n} not perfect")
while True:
try :
n = int(input())
isperfect(n)
except EOFError:
break;
Where is the mistake ? or how can I optimise it ?
Thank you in advance
The issue is that the code is simply too slow. Luckily, there's a simple optimization that can save you.
Note that if d is a divisor of n, then n / d is also a divisor. Furthermore, if d is lesser than sqrt(n), then n / d is greater than sqrt(n) (and vice-versa).
What this effectively means is we only need to check numbers up to sqrt(n) instead of checking all the way to n. And for every divisor d we find, we also make sure to add n / d to the divisor sum, except when d is 1 or exactly sqrt(n).
Here's what that might look like in your code:
l = 1
for i in range(1, int(sqrt(n)) + 1):
if n % i == 0:
l += i
if i < sqrt(n): l += n // i
if l > n + 2: break
Another minor bug is that when l > n + 2 you'll print the message twice, which is easily solved by removing the print before break.
import sys
import math
def almostPerfect(num):
count = 1
for i in range (2,int(math.sqrt(num)) + 1):
if(num % i == 0):
count += i
if(i*i != num):
count += num // i
if(count == num):
return "{} perfect".format(num)
elif (count == (num-2)):
return "{} almost perfect".format(num)
elif (count == (num+2)):
return "{} almost perfect".format(num)
elif (count == (num-1)):
return "{} almost perfect".format(num)
elif (count == (num+1)):
return "{} almost perfect".format(num)
else:
return "{} not perfect".format(num)
for line in sys.stdin.readlines():
line = int(line)
print(almostPerfect(line))
This could be another solution that works for python, and I think we need to take note about (i*i != num), so that we don't start adding the same number.

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)

Python list index out of range but shouldn't be

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.

Basic Loop/Python

I am supposed to write a program that displays numbers from 100 to 200, ten per line, that are divisible by 5 or 6 but NOT both. This is my code so far. I know it's a basic problem so can you tell me the basic code that I'm missing instead of the "shortcut" steps. Any help is appreciated!
def main():
while (num >= 100) and (num <= 200):
for (num % 5 == 0) or (num % 6 == 0)
print (num)
main()
This is how I would go about it. I would recommend using a for loop over a while loop if you know the range you need. You are less likely to get into an endless loop. The reason for the n variable is since you said you needed 10 numbers per line. The n variable will track how many correct numbers you find so that you know when you have ten results and can use a normal print statement which automatically includes a newline. The second print statement will not add a newline.
n = 0
for i in range(100,201):
if (i%5 == 0 or i%6 == 0) and not (i%5 == 0 and i%6 == 0):
n += 1
if n%10 == 0:
print(i)
else:
print(str(i) + ", ", end="")
You should init every variable using in the code
While (condition) will break when the condition false. Since your condition depends on num, but num is never changed in your code, infinity loop will happen. You need to add num = num + 1 at the end of your loop block.
It's supposed to use if not for for each iterator here. And the condition you used for your problem is wrong to.
Should be like this:
def main():
num = 100
while (num >= 100) and (num <= 200):
if ((num % 5 == 0) or (num % 6 == 0)) and (num % 30 != 0):
print (num)
num = num + 1
main()

Categories