-2

trying to write a Python function: def compare_lengths(x, y, z)

which takes as arguments three arrays and checks their lengths and returns them as a triple in order of length.

For example, if the function takes [1,2,3], [10,20,30,40] and [65,32,7] as input, want it to return either ([1,2,3], [65,32,7], [10,20,30,40]) or ([65,32,7], [1,2,3], [10,20,30,40])

it can take it as either:

Array = [1,2,3],[10,20,30,40],[65,32,7]

or:

x = [1,2,3]
y = [10,20,30,40]
z = [65,32,7]

but it needs to be sorted as either:

([1,2,3], [65,32,7], [10,20,30,40])

or:

([65,32,7], [1,2,3], [10,20,30,40])

using bubble sort

ER404
  • 9
  • 1

2 Answers2

3

You can do this, the only difference being the condition used is the length of the array instead of an individual value.

n = len(arr)
for i in range(n):
    for j in range(n-i-1):
        if len(arr[j]) > len(arr[j+1]):
            arr[j], arr[j+1] = arr[j+1], arr[j]

vnk
  • 1,060
  • 1
  • 6
  • 18
  • Thanks for letting me know. I've updated the code. The earlier one was a careless mistake on my part, I checked it out with a couple of other cases and surprisingly they all worked. – vnk Oct 04 '21 at 13:20
  • 3
    Yeah, it really does work, though non-obviously so. I actually made it a [question](https://stackoverflow.com/q/69437526/16759116). Unfortunately many people dismissed it based on wrong thinking about what it does, but by now it looks like someone will get it right. – no comment Oct 04 '21 at 15:18
1

You needn't invent your own sorting algorithm or use bubble sort. It can be done with Python's built-in sorting mechanism and specifying the sorting criteria as a lambda:

arrays = [[1, 2, 3], [10, 20, 30, 40], [65, 32, 7], [3, 3]]
result = sorted(arrays, key=lambda arr: len(arr))
print(result)

Or as an inplace sort:

arrays = [[1, 2, 3], [10, 20, 30, 40], [65, 32, 7], [3, 3]]
arrays.sort(key=lambda arr: len(arr))
print(arrays)

If you understand the concept of function pointers, you may even do it shorter:

arrays = [[1, 2, 3], [10, 20, 30, 40], [65, 32, 7], [3, 3]]
result = sorted(arrays, key=len)
print(result)
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222