Discuss Stitching two lists together in the Python Programming forum on Dev Shed. Stitching two lists together Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language.
Posts: 17
Time spent in forums: 5 h 17 m 23 sec
Reputation Power: 0
Stitching two lists together
say i have two sorted lists, list1 and list2. i would like to stitch these two lists together to another list, list3. This list would have all items on list1 and list2 sorted in order. How would i go about doing it? I think the way i approached this problem is wrong, below is my trial:
Code:
a, b, result = 0, 0, []
while a != len(list1) or b != len(list2):
if list1[a] <= list2[b]:
result.append(list1[a])
a += 1
else:
result.append(list2[b])
b += 1
I would like to see a correct implementation so I can see which assumption is wrong in my approach
Posts: 3,460
Time spent in forums: 1 Month 2 Weeks 4 Days 6 h 56 m 42 sec
Reputation Power: 403
I'm astounded that my merge function performs almost as well as combining the lists, then using lists's sort method. p.py uses list.sort(), q.py uses merge. Timings and tests are shown.
p.py
Code:
#$ time python /tmp/p.py
#
#real 0m0.532s
#user 0m0.504s
#sys 0m0.020s
import random
N = 100000
def IsSorted(L):
'''
$ python -m doctest p.py
>>> IsSorted(list('acx'))
True
>>> IsSorted(list('cax'))
False
'''
return all(x<=y for (x,y,) in zip(L[:-1],L[1:]))
a = list(random.random() for i in range(N))
b = list(random.random() for i in range(N))
a.sort()
b.sort()
c = a+b
c.sort()
assert IsSorted(c)
q.py
Code:
#$ time python /tmp/q.py
#
#real 0m0.589s
#user 0m0.540s
#sys 0m0.040s
import random
N = 100000
def IsSorted(L):
'''
$ python -m doctest p.py
>>> IsSorted(list('acx'))
True
>>> IsSorted(list('cax'))
False
'''
return all(x<=y for (x,y,) in zip(L[:-1],L[1:]))
a = list(random.random() for i in range(N))
b = list(random.random() for i in range(N))
a.sort()
b.sort()
def merge(a,b):
'''
>>> ''.join(merge(list('Abf'),list('CDEfnp')))
'ACDEbffnp'
'''
c = []
i = j = 0
La = len(a)
Lb = len(b)
while (i < La) and (j < Lb):
if a[i] < b[j]:
c.append(a[i])
i += 1
else:
c.append(b[j])
j += 1
if i < La:
c.extend(a[i:])
elif j < Lb:
c.extend(b[j:])
return c
c = merge(a,b)
c.sort()
assert IsSorted(c)
__________________
[code]Code tags[/code] are essential for python code!