-1

I want to implement bubblesort using python list comprehension but it displays blank. Tried using assignment operators to swap (l[j]=l[j+1]) but it throws an error as list comprehension does not support assignment

l = [8, 1, 3, 5, 4, 6, 7, 2]
newlist= [ [(l[j],l[j+1]),(l[j+1],l[j])] for i in range(1,len(l)-1) for j in range(0,len(l)-1) if l[j]>l[j+1] ]

Expected output is: 1, 2, 3, 4, 5, 6, 7, 8

But I am getting the output as [].

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Tas
  • 11
  • 2
    When running your exact code the output is not `[]`.... Also, note that what you are getting in `newlist` is a list of lists of 2 tuples of 2 elements. – Tomerikoo Jul 02 '19 at 18:03
  • 5
    Why are you trying to do this in a list comprehension? I can't imagine a world where that's the best approach. – Adam Smith Jul 02 '19 at 18:05
  • 4
    The only reasonable approach to use bubblesort in a list comprehension is to write your bubblesort function separately, then call `sorted_list = [el for el in bubblesort(lst)]` – Adam Smith Jul 02 '19 at 18:07
  • You can't use assignments in list comprehension. Read [here](https://stackoverflow.com/questions/10291997/how-can-i-do-assignments-in-a-list-comprehension). The `if` in list comprehension is used for filtering, so you can't decide which pair to use: `(a,b)` or `(b,a)`. Try different approach. – Omri Attiya Jul 02 '19 at 18:08
  • 1
    Bubble sort is an *inplace* algorithm, whereas a list comprehension creates a *new* list. The two are fundamentally different approaches to handling data. – MisterMiyagi Jul 02 '19 at 18:21

1 Answers1

1

This fails from a conceptual problem, which is that every filtered result must produce a value to include in the list. Your list comprehension has no capability to store intermediate results -- it's doomed to failure. You have to determine whether to emit a value, and which value to emit, given only the original list, i, and j. That information does not exist with bubble-sort logic.

For instance, consider the first nested iteration. You have this information at hand:

l = [8,1,3,5,4,6,7,2]
i = 1
j = 0

Given this, you must decide right now whether or not to put information into y our final list -- if so, which information to put there. You cannot defer this to a second pass, because you have no temporary storage within the comprehension.

See the problem?

Prune
  • 76,765
  • 14
  • 60
  • 81