HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Rendition of Project Euler 26 - reciprocal cycles

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
reciprocalrenditionprojecteulercycles

Problem

This is my solution for problem 26 from Project Euler:

"""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 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 like

if eggs == True:
    # do something


should be replaced by:

if eggs:
    # do something


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 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 True

Code 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 something
if eggs:
    # do something
def isPrime(k):
    for x in xrange(2, int(math.ceil(math.sqrt(k)))):
        if k % x == 0:
        return False
    return True

Context

StackExchange Code Review Q#46759, answer score: 9

Revisions (0)

No revisions yet.