For example, say I have
a = [1, 3, 9]
b = [1, 2, 4, 5]
and I want to return a new list(n) in sequential order:
n = [1,1,2,3,4,5,9] by using recursion.
I have tried doing this using a standard recursion method but my issue is that whenever I create a new list inside the recursive function, its value is always set to [] again during the recursive call. Is there any way to have n not go back to being empty?
def recur(a,b):
if a[0] <= b[0]:
n.append(a[0])
return (merge(a[1:], b))
One way (off the top of my head, may have mistakes):
def merge_sorted(a, b):
if not a:
return b
if not b
return a
if a[0] < b[0]:
return [a[0]] + merge_sorted(a[1:], b)
return [b[0]] + merge_sorted(a, b[1:])
I suggest implementing a few versions, and try finding some yourself, if learning recursion is your goal. One version could be similar to what you started - returning the result in a 3d list (so you would need a 3d argument. The other option is a global which i don't like personally). The recipe for me is always the same:
merge_sorted
returns a proper merger of the lists.This is very similar to proof by induction (identical?).
You can do this:
def recur(array):
ret = []
if len(array) <= 1:
return array;
half = int(len(array) / 2)
lower = recur(array[:half])
upper = recur(array[half:])
lower_len = len(lower)
upper_len = len(upper)
i = 0
j = 0
while i != lower_len or j != upper_len:
if( i != lower_len and (j == upper_len or lower[i] < upper[j])):
ret.append(lower[i])
i += 1
else:
ret.append(upper[j])
j += 1
return ret
a = [1, 3, 9]
b = [1, 2, 4, 5]
print(a+b) #[1, 3, 9, 1, 2, 4, 5]
print(recur(a+b)) #[1, 1, 2, 3, 4, 5, 9]
a = [1, 3, 9]
b = [1, 2, 4, 5]
c=[]
def recurse(a,b,c):
if len(a)==0 and len(b)==0:
pass
elif len(a)==0 and len(b)!=0:
c.extend(b)
elif len(a)!=0 and len(b)==0:
c.extend(a)
elif a[0]<b[0]:
c.append(a[0])
del a[0]
recurse(a,b,c)
else:
c.append(b[0])
del b[0]
recurse(a,b,c)
recurse(a,b,c)
Explanation:
1.Create an empty list c
2.1st If: if both 'a' & 'b' are empty, your recursion is complete
3.1st elif:If only 'a' is empty, extend() all value of 'b' to 'c' & recursion complete
4.2nd elif: similar to 1st elif but vice versa
5.If both are non-empty, check for 1st element of 'a' & 'b'. Whichever is lower, append to 'c' & delete, recursively call 'recurse'
Though it considers both 'a' & 'b' are sorted as in the example above
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.