DEV Community

Discussion on: Daily Challenge #13 - Twice Linear

Collapse
 
edh_developer profile image
edh_developer

For n = 100,000 , on an ok laptop, it runs in roughly 45 seconds

import time

n = 100000

print "n = %d" % n

def insert(l,val):
    index = len(l) - 1
    done = False

    while not done and index >= 0:
        if l[index] == val:
            done = True
        elif l[index] < val:
            l.insert(index + 1,val)
            done = True
        else:
            index -= 1

    if not done:
        l.insert(0,val)


list = [1]
index = 0

start = time.time()

while index < n:
    x = list[0]
    y = (2 * x) + 1
    z = (3 * x) + 1

    insert(list,y)
    insert(list,z)

    # Remove unnecessary entries from the list, which otherwise
    # grows to unreasonable size for large values of n.
    list.remove(x)
    while (index + len(list)) > n :
        list.pop()

    index += 1

end = time.time()

print "result = %d" % list[0]
print "elapsed time (seconds) = %3.6f" % (end - start)