The "3n+1" Programming Challenge in Pythonallenge - python

I'm a Python beginner. I'm trying to solve the 3n+1 problem on UVa Online Judge. The program worked fine with the input files. However, I submitted several times but still got Runtime error.
import sys
def compute(i, j):
maxCycleLength = 1
if i <= j/2:
k = j/2+1
else:
k = i
for n in range(k, j+1):
num = n
cycleLength = 1
while (num != 1):
if num%2 != 0:
num = 3*num+1
else:
num = num/2
cycleLength += 1
if cycleLength > maxCycleLength:
maxCycleLength = cycleLength
return maxCycleLength
while True:
nums = sorted(int(x) for x in next(sys.stdin).split())
m = compute(nums[0], nums[1])
print("{} {} {}\n".format(nums[0], nums[1], m))

Related

What the missing part for my python stress test Algorithm?

Here's the code, The main problem is to test the algorithm with the naive method and my own method.
def my_solution(numbers):
n = len(numbers)
index_1 = 1
for i in range(0,n):
if numbers[i] > numbers[index_1]:
index_1 = i
if index_1 == 0:
index_2 = 1
else:
index_2 = 0
for i in range(0,n):
if numbers[i] != numbers[index_1] and numbers[i] >= numbers[index_2]:
index_2 = i
sum = numbers[index_1] * numbers[index_2]
return sum
def naive_solution(numbers):
n = len(numbers)
max_product = 0
for first in range(n):
for second in range(first + 1, n):
max_product = max(max_product,
numbers[first] * numbers[second])
return max_product
def testGenerator():
pass
def main():
for i in range(1000):
test = testGenerator()
correct_answer = naive_solution(test)
my_answer = my_solution(test)
assert(my_answer == correct_answer)
Do I need to edit the testGenerator function? Or any other part missing for? I run the code and nothing happen.
You haven't called your functions. Try calling them by using their name followed by parentheses () and any arguments that need to be entered

How do I make the code shorter and more efficent?

import time
start_time = time.time()
a = [2]
inp = 2
while inp < 60000:
div = 2
inp += 1
while div <= (inp / 2 + 1):
prime = inp / div
if prime.is_integer() == True:
break
else:
if div >= (inp / 2):
a.append(str(inp))
break
else:
div += 1
print(a)
print(len(a))
print("Process finished --- %s seconds ---" % (time.time()-start_time))
I wrote my first own program to calculate every prime number between 0 and 60000. I am searching for tips how to format it better or improve it.
import math
n = 60000
primes = []
for k in range(2,n):
if k % 2 == 0 and k > 2:
pass
elif all(k % i for i in range(3, int(math.sqrt(k)) + 1, 2)):
print(k)
EDIT
Since even number are not prime except 2, i have modified the anwer again
import math
primes2 = [2]
for k in range(3,n,2):
if all(k % i for i in range(3, int(math.sqrt(k)) + 1, 2)):
primes2.append(k)
Or Liner (It will helps in perforamce as well)
from math import sqrt # Most efficient way to use external libraries
primes = [k for k in range(3,n+1,2) if all(k % i for i in range(3, int(sqrt(k)) + 1, 2))]
primes.insert(0, 2)
# To print
print(*[k for k in range(3,n+1,2) if all(k % i for i in range(3, int(sqrt(k)) + 1, 2))],sep='\n')
this is how i would have done it
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def printPrime(n):
for i in range(2, n + 1):
if isPrime(i):
print (i, end =" ")
n = 60000 <--- you can change n by any value you want
printPrime(n)

google codejam shows python runtime error

This code is for the Google codejam competition. The below code is compiling correctly on my PC and gives the correct result for the sample code. However it is showing runtime error whenever I try to run it on the google website. I have been messing with it for one hour and still have no idea what's wrong with it.
def reversort(reverList):
global totalScore
length = len(reverList)
score = 0
for i in range(length - 1):
minimum = reverList.index(min(reverList[i: ]))
tempList = reverList[i:minimum + 1]
tempList.reverse()
reverList[i: minimum + 1] = tempList
score += minimum - i + 1
totalScore.append(score)
if __name__ == "__main__":
t = int(input())
totalScore = []
rev = []
for i in range(t):
n = int(input())
apen = []
for j in range(n):
apen.append(int(input()))
reversort(apen)
print("Case #{}: {}".format(i+1,totalScore[i]))
rev.append(apen)
try this
reverse = int(input())
for i in range(1, reverse + 1):
a = int(input())
b = list(map(int, input().split()))
out = 0
for index in range(a-1):
min_index = b.index(min(b[index:a]))
b[index: min_index + 1] = reversed(b[index: min_index + 1])
out += (min_index) - (index) + 1
print("Case #{}: {}".format(i, out))

Syntax error in python code to find Prime-factors. Id appreciate if someone could help me

I have been getting a syntax error with code which does prime-factorization
The is this Code
from sys import argv
from os import system, get_terminal_size
from math import sqrt
number = int(argv[1])
width = get_terminal_size().columns
prime_numbers = []
prime_factors = []
_ = system('clear')
print()
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
if is_prime(number):
print(f"It is a prime number \nIts only factors are 1 and itself \n1, {number}")
exit()
x = len(str(number))
for i in range(2, int(sqrt(number))):
if is_prime(i):
prime_numbers.append(i)
#print(f"found ")
#print(prime_numbers)
i = 0
while True:
if (number % prime_numbers[i] != 0):
i += 1
continue
prime_factors.append(prime_numbers[i])
print("%2d | %3d".center(width) % (prime_numbers[i], number))
print("_________".center(width))
number /= prime_numbers[i]
if number == 1:
break
print("1".center(width))
print("Answer ")
i = len(prime_factors)
j = 1
for k in prime_factors:
if j == i:
print(k)
break
print(f"{k}", end=" X ")
j += 1
This works for small numbers , less than 4 or 5 digits but gives an index error for bigger ones.
If I remove the sqrt function on line 24 it starts taking too long.
The errors look like this
Traceback (most recent call last):
File "prime-factor.py", line 33, in <module>
if (number % prime_numbers[i] != 0):
IndexError: list index out of range
real 0m0.049s
user 0m0.030s
sys 0m0.014s
(base) Souravs-MacBook-Pro-5:Fun-Math-Algorithms aahaans$ time python3 prime-factor.py 145647
I am unable to resolve this issue, Id appreciate it if you could help me.
No need to rebuild what's already available primePy
from primePy import primes
primes.factors(101463649)
output
[7, 23, 73, 89, 97]
There are two basic issues with the code. One with the for loop for prime numbers, you have to check until int(sqrt(number))+1. And, in the while loop after that, you have to break when the number is below sqrt of the original number, for which another variable should be used. The corrected code is:
from sys import argv
from os import system, get_terminal_size
from math import sqrt
number = int(argv[1])
width = get_terminal_size().columns
prime_numbers = []
prime_factors = []
_ = system('clear')
print()
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
if is_prime(number):
print(f"It is a prime number \nIts only factors are 1 and itself \n1, {number}")
exit()
x = len(str(number))
limit = int(sqrt(number))
for i in range(2, limit+1):
if is_prime(i):
prime_numbers.append(i)
i = 0
while True:
if i == len(prime_numbers)-1:
# prime_factors.append(int(number))
break
if (number % prime_numbers[i] != 0):
i += 1
continue
prime_factors.append(prime_numbers[i])
print("%2d | %3d".center(width) % (prime_numbers[i], number))
print("_________".center(width))
number /= prime_numbers[i]
prime_factors.append(int(number))
print("%2d | %3d".center(width) % (number, number))
print("_________".center(width))
print("1".center(width))
print("Answer ")
i = len(prime_factors)
j = 1
for k in prime_factors:
if j == i:
print(k)
break
print(f"{k}", end=" X ")
j += 1
If my explanation wasn't clear, look at the changes in the code.
I wrote a small number factorization engine that can factor numbers.
import math
def LLL(N):
p = 1<<N.bit_length()-1
if N == 2:
return 2
if N == 3:
return 3
s = 4
M = pow(p, 2) - 1
for x in range (1, 100000):
s = (((s * N ) - 2 )) % M
xx = [math.gcd(s, N)] + [math.gcd(s*p+x,N) for x in range(7)] + [math.gcd(s*p-x,N) for x in range(1,7)]
try:
prime = min(list(filter(lambda x: x not in set([1]),xx)))
except:
prime = 1
if prime == 1:
continue
else:
break
#print (s, x, prime, xx)
return prime
Factor:
In [219]: LLL(10142789312725007)
Out[219]: 100711423
from https://stackoverflow.com/questions/4078902/cracking-short-rsa-keys
I also made Alpertons ECM SIQs engine work in python if you want factorization at that (over 60 digits level): https://github.com/oppressionslayer/primalitytest

Getting the 983rd prime number instead of 1000th

I have just started coding, and I don't seem to be getting it quite right. I would like some feedback on my program.
I am getting 7753 instead of 7919
primes = []
sk = [] # list for all None values
def primtal(a):
if ((2 ** a) - 2) % a == 0:
return a
t = 2
while len(primes) < 1001:
kand = primtal(t)
if kand == None:
sk.append(kand)
else:
primt = kand
primes.append(primt)
t = t + 1
print primes[1000]

Categories

Resources