Is there any way to fix my python code being stuck? - python

primeNum = []
def isPrime(y):
i = 2
while(i < number):
if number % i == 0:
return False
i = i + 1
return True
def printNum(x):
k = 2
while k <= x:
if isPrime(k):
primeNum.append(k)
k = k + 1
printNum(number)
numOfPrime = len(primeNum)
sum = 0
j= 0
while j < numOfPrime:
sum += primeNum[j]
j = j + 1
print(sum)
When I run the code it just gets stuck on the input. I have tried everything but it doesn't give me an error unless I press CTRL + C then it will tell me Traceback.....

the line k = k + 1 in the function printNum was out of the while loop , making it an infinite loop,same goes for i = i + 1 in isPrime and j = j + 1 in the last loop, so i fixed it for you
additionally, the function isPrime had some bugs
it referred to number instead of y in a few places so I fixed that too
this should do the trick:
primeNum = []
number=10
def isPrime(y):
i = 2
while (i < y):
if y % i == 0:
return False
i = i + 1
return True
def printNum(x):
k = 2
while k <= x:
if isPrime(k):
primeNum.append(k)
k = k + 1
printNum(number)
numOfPrime = len(primeNum)
sum = 0
j = 0
while j < numOfPrime:
sum += primeNum[j]
j = j + 1
print(sum)
print("end")

Related

To generate laundau's prime numbers using python

I want to generate list of primes of the format x2+1 but I am not getting any output.
My code:
def LPrime(n):
for i in range(1,n):
x = i**2+1;
for j in range(2,x):
if x % j != 0:
print(x,i)
Please tell me what am I doing wrong.
The expected output should be something like
2,1
5,2
and so on
Also I am not able to execute it properly, I am using Ubuntu 22.04
There is no output when I try to
If if x % j == 0: you have a divisor. and j will not be 1 or x. So you should mark p as False (there is no prime). else, it is a prime; print it.
def LPrime(n):
for i in range(0, n):
x = i**2+1
p = True
for j in range(2, x):
if x % j == 0:
p = False
if p:
print(f"Prime = {x},\t i = {i}")
Don't forget to call it
>>> LPrime(4)
Prime = 1, i = 0
Prime = 2, i = 1
Prime = 5, i = 2
If you want n primes, use a while loop:
def LPrime(n):
count = 0
i = 0
while count < n:
x = i**2+1
p = True
for j in range(2, x):
if x % j == 0:
p = False
if p:
print(f"Prime = {x},\t i = {i}")
count += 1
i += 1
>>> LPrime(4)
Prime = 1, i = 0
Prime = 2, i = 1
Prime = 5, i = 2
Prime = 17, i = 4

How to find Lagest sum consecutive increasing digits in a number

How can i find the Largest sum consecutive increasing digits and its position in a Number using python ?
Here is my approach :
def findLIS(A, n):
hash = dict()
LIS_size, LIS_index = 1, 0
hash[A[0]] = 1
for i in range(1, n):
if A[i] - 1 not in hash:
hash[A[i] - 1] = 0
hash[A[i]] = hash[A[i] - 1] + 1
if LIS_size < hash[A[i]]:
LIS_size = hash[A[i]]
LIS_index = A[i]
start = LIS_index - LIS_size + 1
while start <= LIS_index:
# print(start, end = " ")
z.insert(i - 1,start)
start += 1
print(z[~0])
print(sum(z))
# Driver Code
if __name__ == "__main__":
num = input()
A = [int(x) for x in str(num)]
n = len(A)
z=[]
findLIS(A, n)
Solution:
n = input()+"0"
max_sum = 0
max_pos = ""
start = 0
sum = int(n[0])
for i in range(1, len(n)):
if n[i-1] >= n[i]:
if max_sum < sum:
max_sum = sum
max_pos = "{}-{}".format(start+1, i)
start = i
sum = int(n[i])
else:
sum += int(n[i])
print("{}:{}".format(max_sum, max_pos))
There is numbers should strictly increase. If sequence 333 also match your condition that you need to change condition: if n[i-1] > n[i]:

python backtracking knapsack

This is the code I have thus far:
def frac_knapsack(n,size, profit,K):
if K <= 0:
return 0
for i in range(0,i):
if profit[i]/size[i]>profit[i-1]/size[i-1]:
profit.append[i] and size.append[i]
s = 0
p = 0
for i in range(n):
if s + size[i] <= K:
p += profit[i]
s += size[i]
else:
p += (K-s) * (profit[i]/size[i])
s = K
break
return p
def Knapsack(i, size):
if i > n or size <= 0:
print(x)
return
if x[j] == 1:
for j in range(0,i-1):
p+=P[j]
if x[j] == 1:
for j in range(0,i-1):
s+=S[j]
if x[i] == 1:
if s+size[i] <= K and (p + profit[i] + B) > MaxProfit:
B = fractional_Knapsack(n-(i+1), size[i+1:], profit[i+1:], T-size[i])
if p+profit[i] > MaxProfit:
MaxProfit=p+profit[i]
x=solution
Knapsack(i+1, T-size[i])
if x[i] == 0:
B = frac_Knapsack(n-(i+1), size[i+1:], profit[i+1:], T)
if (p + B) > MaxProfit:
Knapsack(i+1, T)
I have a problem with sorting in line 4. I have to sort it as weight-efficiency. do i need to use quick sort algorithm?
I want to make input for four things:
n,size,profit and K
do i need to use map? as size and profit is list?
You used
B = fractional_Knapsack(n-(i+1), size[i+1:], profit[i+1:], T)
your method is called
def frac_knapsack(n,size, profit,K):

Turn a function into a generator function with no parameters

I am new to Python and having trouble wrapping my head around converting the following function into a generator function that doesn't take any parameters (without importing itertools). The idea is to generate an infinite look-and-say sequence starting with 2, 12, 1112, 3112...and so on. As it is now, the sequence is working, but I'm not quite sure where I need to change my returns to yields or how to do it without taking a parameter (getting rid of (n)). Any help would be appreciated!
def count_sequence(n):
if (n == 1):
return "2"
if (n == 2):
return "12"
x = "12"
for i in range (3, n + 1):
x += "$"
l = len(x)
count = 1
temp = ""
for y in range(1, l):
if (x[y] != x[y - 1]):
temp += str(count + 0)
temp += x[y - 1]
count = 1
else:
count += 1
x = temp
return x
Start with a wrapper around your function:
def my_generator():
value = 1
while True:
result = count_sequence(value)
yield result
value += 1
then in-line the definition of count_sequence, replacing return with yield and n with value. (In this case, I skip a step and also yield the return value directly, rathe than assigning it to result first then using yield result once at the bottom of the while loop.)
def my_generator():
value = 1
while True:
if value == 1:
yield "2"
elif value == 2:
yield "12"
else:
x = "12"
for i in range(3, value+1):
x += "$"
l = len(x)
count = 1
temp = ""
for y in range(1, l):
if x[y] != x[y-1]:
temp += str(count)
temp += x[y-1]
count = 1
else:
count += 1
x = temp
yield x
value += 1
Then you can simplify it a little, for example pulling the first two yield expression statements out of the loop and getting rid of the if statement.
def my_generator():
yield "2"
yield "12"
value = 3
while True:
x = "12"
for i in range(3, value+1):
x += "$"
l = len(x)
count = 1
temp = ""
for y in range(1, l):
if x[y] != x[y-1]:
temp += str(count)
temp += x[y-1]
count = 1
else:
count += 1
x = temp
yield x
value += 1
I assume your count_sequence() method is called like this:
count_sequence(1)
count_sequence(2)
count_sequence(3)
...
As a generator the function would look like this:
def count_sequence():
yield "2"
yield "12"
x = "12"
n = 2
while True:
n += 1
for i in range (3, n + 1):
x += "$"
l = len(x)
count = 1
temp = ""
for y in range(1, l):
if (x[y] != x[y - 1]):
temp += str(count + 0)
temp += x[y - 1]
count = 1
else:
count += 1
x = temp
yield x
n is a variable now tracked within the generator function.
Call the generator with:
my_generator = count_sequence()
next(my_generator)
next(my_generator)
next(my_generator)
...

Python 3: Optimizing Project Euler Problem #14

I'm trying to solve the Hackerrank Project Euler Problem #14 (Longest Collatz sequence) using Python 3. Following is my implementation.
cache_limit = 5000001
lookup = [0] * cache_limit
lookup[1] = 1
def collatz(num):
if num == 1:
return 1
elif num % 2 == 0:
return num >> 1
else:
return (3 * num) + 1
def compute(start):
global cache_limit
global lookup
cur = start
count = 1
while cur > 1:
count += 1
if cur < cache_limit:
retrieved_count = lookup[cur]
if retrieved_count > 0:
count = count + retrieved_count - 2
break
else:
cur = collatz(cur)
else:
cur = collatz(cur)
if start < cache_limit:
lookup[start] = count
return count
def main(tc):
test_cases = [int(input()) for _ in range(tc)]
bound = max(test_cases)
results = [0] * (bound + 1)
start = 1
maxCount = 1
for i in range(1, bound + 1):
count = compute(i)
if count >= maxCount:
maxCount = count
start = i
results[i] = start
for tc in test_cases:
print(results[tc])
if __name__ == "__main__":
tc = int(input())
main(tc)
There are 12 test cases. The above implementation passes till test case #8 but fails for test cases #9 through #12 with the following reason.
Terminated due to timeout
I'm stuck with this for a while now. Not sure what else can be done here.
What else can be optimized here so that I stop getting timed out?
Any help will be appreciated :)
Note: Using the above implementation, I'm able to solve the actual Project Euler Problem #14. It is giving timeout only for those 4 test cases in hackerrank.
Yes, there are things you can do to your code to optimize it. But I think, more importantly, there is a mathematical observation you need to consider which is at the heart of the problem:
whenever n is odd, then 3 * n + 1 is always even.
Given this, one can always divide (3 * n + 1) by 2. And that saves one a fair bit of time...
Here is an improvement (it takes 1.6 seconds): there is no need to compute the sequence of every number. You can create a dictionary and store the number of the elements of a sequence. If a number that has appeared already comes up, the sequence is computed as dic[original_number] = dic[n] + count - 1. This saves a lot of time.
import time
start = time.time()
def main(n,dic):
'''Counts the elements of the sequence starting at n and finishing at 1'''
count = 1
original_number = n
while True:
if n < original_number:
dic[original_number] = dic[n] + count - 1 #-1 because when n < original_number, n is counted twice otherwise
break
if n == 1:
dic[original_number] = count
break
if (n % 2 == 0):
n = n/2
else:
n = 3*n + 1
count += 1
return dic
limit = 10**6
dic = {n:0 for n in range(1,limit+1)}
if __name__ == '__main__':
n = 1
while n < limit:
dic=main(n,dic)
n += 1
print('Longest chain: ', max(dic.values()))
print('Number that gives the longest chain: ', max(dic, key=dic.get))
end = time.time()
print('Time taken:', end-start)
The trick to solve this question is to compute the answers for only largest input and save the result as lookup for all smaller inputs rather than calculating for extreme upper bound.
Here is my implementation which passes all the Test Cases.(Python3)
MAX = int(5 * 1e6)
ans = [0]
steps = [0]*(MAX+1)
def solve(N):
if N < MAX+1:
if steps[N] != 0:
return steps[N]
if N == 1:
return 0
else:
if N % 2 != 0:
result = 1+ solve(3*N + 1) # This is recursion
else:
result = 1 + solve(N>>1) # This is recursion
if N < MAX+1:
steps[N]=result # This is memoization
return result
inputs = [int(input()) for _ in range(int(input()))]
largest = max(inputs)
mx = 0
collatz=1
for i in range(1,largest+1):
curr_count=solve(i)
if curr_count >= mx:
mx = curr_count
collatz = i
ans.append(collatz)
for _ in inputs:
print(ans[_])
this is my brute force take:
'
#counter
C = 0
N = 0
for i in range(1,1000001):
n = i
c = 0
while n != 1:
if n % 2 == 0:
_next = n/2
else:
_next= 3*n+1
c = c + 1
n = _next
if c > C:
C = c
N = i
print(N,C)
Here's my implementation(for the question specifically on Project Euler website):
num = 1
limit = int(input())
seq_list = []
while num < limit:
sequence_num = 0
n = num
if n == 1:
sequence_num = 1
else:
while n != 1:
if n % 2 == 0:
n = n / 2
sequence_num += 1
else:
n = 3 * n + 1
sequence_num += 1
sequence_num += 1
seq_list.append(sequence_num)
num += 1
k = seq_list.index(max(seq_list))
print(k + 1)

Categories