patternpythonMinor
Rendition of Project Euler 26 - reciprocal cycles
Viewed 0 times
reciprocalrenditionprojecteulercycles
Problem
This is my solution for problem 26 from Project Euler:
Can it be written in a better way?
"""Find the value of d longest:
longest = [period, x]
else:
fact = primeFact(x)
periods = []
for k in fact:
if k != 2 and k != 5:
if fact.count(k) == 1:
periods.append(periodIfPrime(k))
else:
periods.append((periodIfPrime(k)) * k**(fact.count(k) - 1))
if lcm(periods) > longest[0]:
longest = [lcm(periods), x]
return longest
elapsed_time = timer() - start
elapsed_time /= 100 # milliseconds
print "Found %d in %r ms." % (longestPeriod(1000)[1], elapsed_time)Can it be written in a better way?
Solution
You don't have to define your own
Also, you shouldn't write
should be replaced by:
I realized that youare actually using Python 2 (for some reason, I thought that you were using Python 3). Therefore, You can probably improve the function
gcd function: it already exists in the fractions module of the standard library. And actually, it works with any integer type. Therefore, you can rewrite lcm as:def lcm(numbers):
"""finds lcm of list of #s"""
from fractions import gcd
return reduce(lambda a,b: (a*b)/gcd(a, b), numbers)Also, you shouldn't write
== True in a conditional, a code likeif eggs == True:
# do somethingshould be replaced by:
if eggs:
# do somethingI realized that youare actually using Python 2 (for some reason, I thought that you were using Python 3). Therefore, You can probably improve the function
isPrime. You are currently using range in the function. range creates and returns a list. You should use xrange instead: xrange is a generator; it will generate and yield a new int at each iteration. Since you occasionally return early from your loop, you don"t always need to compute the whole list of integers, and xrange should be a best fit for this job.def isPrime(k):
for x in xrange(2, int(math.ceil(math.sqrt(k)))):
if k % x == 0:
return False
return TrueCode Snippets
def lcm(numbers):
"""finds lcm of list of #s"""
from fractions import gcd
return reduce(lambda a,b: (a*b)/gcd(a, b), numbers)if eggs == True:
# do somethingif eggs:
# do somethingdef isPrime(k):
for x in xrange(2, int(math.ceil(math.sqrt(k)))):
if k % x == 0:
return False
return TrueContext
StackExchange Code Review Q#46759, answer score: 9
Revisions (0)
No revisions yet.