You need to place a gear on each peg (otherwise the gears will collide with unoccupied pegs). The engineers have plenty of gears in all different sizes stocked up, so you can choose gears of any size, from a radius of 1 on up. Your goal is to build a system where the last gear rotates at twice the rate (in revolutions per minute, or rpm) of the first gear, no matter the direction. Each gear (except the last) touches and turns the gear on the next peg to the right.

Given a list of distinct positive integers named pegs representing the location of each peg along the support beam, write a function answer(pegs) which, if there is a solution, returns a list of two positive integers a and b representing the numerator and denominator of the first gear's radius in its simplest form in order to achieve the goal above, such that radius = a/b. The ratio a/b should be greater than or equal to 1. Not all support configurations will necessarily be capable of creating the proper rotation ratio, so if the task is impossible, the function answer(pegs) should return the list [-1, -1].

For example, if the pegs are placed at [4, 30, 50], then the first gear could have a radius of 12, the second gear could have a radius of 14, and the last one a radius of 6. Thus, the last gear would rotate twice as fast as the first one. In this case, pegs would be [4, 30, 50] and answer(pegs) should return [12, 1].

The list pegs will be given sorted in ascending order and will contain at least 2 and no more than 20 distinct positive integers, all between 1 and 10000 inclusive.

# Swapnil Patel

from fractions import Fraction
def answer(pegs):

    plen = len(pegs)
    n = 1 if (plen % 2 == 0) else 0
    if not pegs or plen==1:
        return [-1,-1]

    rlast = 0
    for i in range(plen):
        if i == 0 or i == plen-1:
            rlast += ((-1)**(i+1))*pegs[i]
            rlast += ((-1)**(i+1))*2*pegs[i]

    if n==1:
        rfirst = Fraction(2*(float(rlast)/3)).limit_denominator()
        rfirst = Fraction(2*rlast).limit_denominator()

    current_r = rfirst
    for i in range(plen-2):
        dist_b = pegs[i+1]-pegs[i]
        next_r = dist_b - current_r

        if current_r < 1 or next_r < 1:
            return [-1,-1]
            current_r = next_r
    return [rfirst.numerator,rfirst.denominator]