HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Takes in two sorted lists and outputs a sorted list that is their union

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
unionandtwothatoutputslistssortedlisttakestheir

Problem

Write a function that takes in two sorted lists and outputs a sorted
list that is their union

Could anyone help me to improve this code and make it more user-friendly? We are not supposed to use any built-in Python functions, but rather develop our own efficient algorithms.

def answer(list1, list2):

    len1 = len(list1)
    len2 = len(list2)

    final_list = []
    j = 0
    k = 0

    for i in range(len1+len2):

        if k == len1:
            final_list.append(list2[j])
            j += 1
            continue

        if j == len2:
            final_list.append(list1[k])
            k += 1
            continue

        if list1[k] < list2[j]:
            final_list.append(list1[k])
            k += 1

        else:
            final_list.append(list2[j])
            j += 1

    return final_list

print answer([1, 2 , 17, 18, 100], [3, 3, 4, 5, 15, 19, 20, 101])

Solution

I think your solution is ok.

Instead of using continue, consider using if..elif..elif..else:

if k >= len1:
  ...
elif j >= len2:
  ...
elif ...:
  ...
else:
  ...


Also, the test k >= len1 is an example of "defensive programming". It protects against k skipping over len1 when being incremented in the loop. Also, the expression list1[k] doesn't make sense unless k = len1 which is another good reason to use it in the if statement.

If you've learned about xrange() then I would use that instead of range() -- see these SO answers:

https://stackoverflow.com/questions/135041/should-you-always-favor-xrange-over-range

Otherwise it looks good!

Code Snippets

if k >= len1:
  ...
elif j >= len2:
  ...
elif ...:
  ...
else:
  ...

Context

StackExchange Code Review Q#104108, answer score: 4

Revisions (0)

No revisions yet.