1

Based on Paul's answer, I've tried to run the following bubble sort algorithm, which uses slice and __setitem__ methods; I'm positive that there'd be something simple that I'm not doing right, not sure what that might be?

Code

def bubblesort(l):
    [l.__setitem__(slice(i, i + 2), (l[i:i + 2] if l[i] < l[i + 1] else l[i +  1:i - 1:-1])) for j in range(0, len(l)) for i in range(0, len(l) - 1)]
    return l

l = [1,5,-5,0,10,100]
bubblesort(l)
print(l)

Desired Output

[-5, 0, 1, 5, 10, 100]
Emma
  • 27,428
  • 11
  • 44
  • 69

1 Answers1

0

When i == 0, l[i + 1:i - 1:-1] evaluates to [] so you end up shortening your list mid iteration.

hilberts_drinking_problem
  • 11,322
  • 3
  • 22
  • 51
  • 1
    It could be replaced with `[l[i+1], l[i]]` to achieve the same effect without the accidental index wraparound; you only needed two elements after all. Alternatively, you could use `l[i:i+2][::-1]`, which has symmetry with the other use (you just add the canonical reversing slice after, `[::-1]`). – ShadowRanger Aug 07 '19 at 23:42