import random
import time
import sys

def printf(format, *args):
    sys.stdout.write(format % args)

aPGElist = []

# a list, in this file, is printed
#  only if it contains less than printlim values
printlim = 20

# --------------------------------------------------
# inserting INSIDE an array/list is
#    -- convenient and comfortable,
#    -- sometimes completely unnecessary,
#    -- dangerously slow.

# --------------------------------------------------
# inserting AT THE BEGINNING of an the array/list is
#    -- highly convenient and comfortable,
#    -- quite natural in many situations,
#    -- the slowest of all possible insert operations.

# --------------------------------------------------
# Manipulate the list size n to see varying results.
n = 10**6
n = 50000
n = 50000
n = 10

printf( "List length = %d \n\n", n )

# --------------------------------------------------
# Switch on/off appropriate parts of the demonstration 
# by setting if True: / if False:

if True:
    # insert close to the END -- FAST
    print("Insert close to the END")
    aPGElist = []
    t1 = time.time()
    for i in range( n ):
        if i < 10:
            aPGElist.insert(-1, i) # ins last elem
        else:
            aPGElist.insert(-10, i) # ins close to the end
        if n < printlim: print(aPGElist)
    t2 = time.time()
    printf("        time %f\n\n", t2-t1 )

if True:
    # insert at the END -- FAST
    print("Insert at the END")
    aPGElist = []
    t1 = time.time()
    for i in range( n ):
        aPGElist.insert(-1, i) # ins last elem
        if n < printlim: print(aPGElist)
    t2 = time.time()
    printf("        time %f\n\n", t2-t1  )


if True:
    # insert at the BEGINNING -- SLOW
    print("Insert at the BEGINNING")
    aPGElist = []
    t1 = time.time()
    for i in range( n ):
        aPGElist.insert(0, i) # ins first elem
        if n < printlim: print(aPGElist)
    t2 = time.time()
    printf("        time %f\n\n", t2-t1  )

if True:
    # insert SOMEWHERE INSIDE -- EXTREMELY SLOW, LINEAR COMPLEXITY
    print("Insert at RANDOM POSITION")
    aPGElist = [0]
    t1 = time.time()
    for i in range( n ):
        aPGElist.insert(random.randint(0, len(aPGElist)), i) # ins at rnd pos
        if n < printlim: print(aPGElist)
    t2 = time.time()
    printf("        time %f\n\n", t2-t1  )

if True:
    # insert in the middle -- SLOW OR FAST??
    print("Insert in the MIDDLE")
    aPGElist = [0]
    t1 = time.time()
    for i in range( n ):
        aPGElist.insert(len(aPGElist) // 2, i) # ins in the mid
        if n < printlim: print(aPGElist)
    t2 = time.time()
    printf("        time %f\n\n", t2-t1  )

