## Linear merging for lists in Python

merge two sorted lists python

python program to merge two lists and sort it

merge two lists recursively python

python combine two list one by one

merge two sorted linked lists python

merge sort python

python merge sort lists

I'm working through Google's Python class exercises. One of the exercises is this:

Given two lists sorted in increasing order, create and return a merged list of all the elements in sorted order. You may modify the passed in lists. Ideally, the solution should work in "linear" time, making a single pass of both lists.

The solution I came up with was:

def linear_merge(list1, list2): list1.extend(list2) return sorted(list1)

It passed the the test function, but the solution given is this:

def linear_merge(list1, list2): result = [] # Look at the two lists so long as both are non-empty. # Take whichever element [0] is smaller. while len(list1) and len(list2): if list1[0] < list2[0]: result.append(list1.pop(0)) else: result.append(list2.pop(0)) # Now tack on what's left result.extend(list1) result.extend(list2) return result

Included as part of the solution was this:

Note: the solution above is kind of cute, but unfortunately list.pop(0) is not constant time with the standard python list implementation, so the above is not strictly linear time. An alternate approach uses pop(-1) to remove the endmost elements from each list, building a solution list which is backwards. Then use reversed() to put the result back in the correct order. That solution works in linear time, but is more ugly.

Why are these two solutions so different? Am I missing something, or are they being unnecessarily complicated?

They're encouraging you to think about the actual method (algorithm) of merging two sorted lists. Suppose you had two stacks of paper with names on them, each in alphabetical order, and you wanted to make one sorted stack from them. You wouldn't just lump them together and then sort that from scratch; that would be too much work. You'd make use of the fact that each pile is already sorted, so you can just take the one that comes first off of one pile or the other, and put them into a new stack.

**Python,** Correctness. First of all, your merging code is not correct. If you have list1 = [1, 2, 3] and list2 = [4, 5, 6] , the result would be [6, 5, 4, 1, 2, 3] . Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square

As you noted, your solution works perfectly. So why the complexity? Well, for a start

Ideally, the solution should work in "linear" time, making a single pass of both lists.

Well, you're not explicitly passing through any lists, but you are calling `sorted()`

. So how many times will `sorted()`

pass over the lists?

Well, I don't actually know. Normally, a sorting algorithm would operate in something like `O(n*log(n))`

time, though look at this quote from the Python docs:

The Timsort algorithm used in Python does multiple sorts efficiently because it can take advantage of any ordering already present in a dataset.

Maybe someone who knows timsort better can figure it out.

But what they're doing in the solution, is using the fact that they *know* they have 2 sorted lists. So rather than starting from "scratch" with `sorted`

, they're picking off elements 1 by 1.

**Merging Two Sorted Lists in Python In Linear Time,** Suppose we have two sorted lists A and B. We have to merge them and form only one sorted list C. The size of lists may different.For an� 14.2. The linear search algorithm. We’d like to know the index where a specific item occurs within in a list of items. Specifically, we’ll return the index of the item if it is found, or we’ll return -1 if the item doesn’t occur in the list.

I like the @Abhijit approach the most. Here is a slightly more pythonic/readable version of his code snippet:

def linear_merge(list1, list2): result = [] while list1 and list2: result.append((list1 if list1[-1] > list2[-1] else list2).pop(-1)) return (result + list1 + list2)[-1::-1]

With the help of the built-in python features, we:

- don't need to explicitly check if the lists are empty with the
**len**function. - can merge/append empty lists and the result will remain unchanged, so no need for explicit checking.
- we can combine multiple statements (if the readability allows), which sometimes makes the code more compact.

**Merge algorithm,** Fromg Google's Python Class: E. Given two lists sorted in increasing order, create and return a merged list of all the elements in sorted order. Merging two Lists in Python: We can simply merge two lists using + operator like below. list1 = [10, 20, 30] list2 = [40, 50, 60] merged_list = list1 + list2 print("Merged List: ", merged_list) #It is also equivalent to above code using += list1 += list2 print("Merged List using +=: ", list1)

Your solution is O(n log n), which means that if your lists were 10 times as long, the program would take (roughly) 30 times as much time. Their solution would only take 10 times as long.

**Merge Two Sorted Lists in Python,** Step 2- merge sorted lists. Given two sorted lists we should be able to “merge” them into a single list in a linear operation. def merge_sorted_lists(� Merging Lists in Python. Top 25 Questions on Python List. An Introduction to the Python Range Function. Welcome to Reddit, the front page of the internet.

Pop off the end of the lists until one is empty. I think this is linear, and also the reverses are linear too. Ugly, but a solution.

def linear_merge(list1, list2): # NOT return sorted (list1 + list2), as this is not linear list3 = [] rem = [] empty = False while not empty: # Get last items from each list, if they exist if len (list1) > 0: a = list1[-1] else: rem = list2[:] empty = True if len (list2) > 0: b = list2[-1] else: rem = list1[:] empty = True # Pop the one that's largest onto the new list if not empty: if a > b: list3.append (a) list1.pop () else: list3.append (b) list2.pop () # add the (reversed) remainder to the list rem.reverse () list3 += rem # reverse the entire list list3.reverse () return list3

**My implementation of merging two sorted lists in linear time,** Given two lists sorted in increasing order, create and return a merged # list of all the elements in sorted order. You may modify the passed in� Python | Merge two lists alternatively. Given two lists, write a Python program to merge the given lists in an alternative fashion, provided that the two lists are of equal length.

**Merge sort walkthrough with code in Python | by Amir Ziai,** The algorithm works in O(n.logn). This is because the list is being split in log(n) calls and the merging process takes linear time in each call. There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the +operator.

**python list linear merge,** There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator. Example. Join two list: list1 =� Python Find in List Using a Linear Search A linear search is a simple searching algorithm that finds an item in a list. A linear search starts at one end of a list and compares a value with every element in the list. If that value is in the list, a linear search returns the position of the item.

**Merge sort in Python,**

##### Comments

- OK, that makes sense. I guess it just seemed weird that they would expect a n00b to come up with that. Can you give me an example of what result.extend(list1) result.extend(list2) would achieve?
`pop`

removes an item from a list and returns its value, so you're removing items from each list and putting them onto`result`

. The initial loop runs as long as**both**`list1`

and`list2`

contain anything. When one runs out, you simply take whatever's left in the other and tack it onto`result`

; that's what`extend`

does.- Thanks a lot, I think I get it now.
- Glad I could help. I guess you're new to programming? It's a cool world, have fun!
- They expect you, as 'a n00b', to come up with that because they expect you to think and do problem solving. If you can figure out that
`pop(0)`

doesn't run in constant time with the standard Python implementation, then you certainly aren't lacking in thinking skills. With this sort of thing, try starting out by modelling the problem: grab a deck of cards, shuffle it, cut it in half, sort each half, and then take those two halves and sort them together - and think about what you're doing. - For the given example (sorted sublists) I believe Python's Timsort (like similar mergesorts) is O(n).
- "if your lists were 10 times as long, the program would take (roughly) 30 times as much time." No; the ratio of running-time would approach 10 as the list size increases without limit. The kind of formula you're trying to use really only works with running times of the O(n^k) type.