-6

Why isn't this working? It says int is not subscriptable when I run speedtest.

This is the error:

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    speedtest()
  File "\\internal.sloughgrammar.berks.sch.uk\students$\Home\2014\14KHANDELWALA\MyDocs\Year8\Computing\Raspberry Pi\test_sort.py", line 14, in speedtest
    insertion(a)
  File "\\internal.sloughgrammar.berks.sch.uk\students$\Home\2014\14KHANDELWALA\MyDocs\Year8\Computing\Raspberry Pi\test_sort.py", line 41, in insertion
    val, j = 0[i], i-1
TypeError: 'int' object is not subscriptable

This is my code:

# test_sort.py
from random import *
from time import *

def speedtest():
    print("*** Bubble Sort vs. Insertion Sort ***")
    for y in [2000, 4000, 8000]:
        print("\nArray of {} random numbers from 0 to 999:".format(y))
        a = [randint(1,999) for x in range(y)]
        b = a[:]
        tic = time()
        insertion(a)
        toc = time()
        print("Insertion Sort: {} seconds.".format(str(round(toc-tic,1)).rjust(5)))
        tic = time()
        bubble(a)
        toc = time()
        print("Bubble Sort: {} seconds.".format(str(round(toc-tic,1)).rjust(5))) 

def bubble(a):
    """Takes a list and sorts it."""
    j = len(a)
    while True:
        swap = False
        j -= 1
        for k in range(j):
            if a[k] > a[k+1]:
                a[k], a[k+1] = a[k+1], a[k]
                swap = True
    if not swap:
        return 

# insertion_sort.py
def insertion(a):
    a = [randint(1,999) for x in range(y)]
    """Takes a list and sorts it using insertion sort."""
    for i in range(1, len(a)):
        val, j = 0[i], i-1
        while j >= 0 and a[j] > val:
            a[j+1] = a[j]
            j -= 1
        a[j+1] = val 
khelwood
  • 46,621
  • 12
  • 59
  • 83

1 Answers1

1
val, j = 0[i], i-1

Edit this line and try this instead -

val, j = a[i], i-1
Sahil Agarwal
  • 470
  • 2
  • 12