I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?
Append the first element of the list to a reversed sublist:
mylist = [1, 2, 3, 4, 5]
backwards = lambda l: (backwards (l[1:]) + l[:1] if l else [])
print backwards (mylist)
A bit more explicit:
def rev(l):
if len(l) == 0: return []
return [l[-1]] + rev(l[:-1])
This turns into:
def rev(l):
if not l: return []
return [l[-1]] + rev(l[:-1])
Which turns into:
def rev(l):
return [l[-1]] + rev(l[:-1]) if l else []
Which is the same as another answer.
Tail recursive / CPS style (which python doesn't optimize for anyway):
def rev(l, k):
if len(l) == 0: return k([])
def b(res):
return k([l[-1]] + res)
return rev(l[:-1],b)
>>> rev([1, 2, 3, 4, 5], lambda x: x)
[5, 4, 3, 2, 1]
I know it's not a helpful answer (though this question has been already answered), but in any real code, please don't do that. Python cannot optimize tail-calls, has slow function calls and has a fixed recursion depth, so there are at least 3 reasons why to do it iteratively instead.
The trick is to join after recursing:
def backwards(l):
if not l:
return
x, y = l[0], l[1:]
return backwards(y) + [x]
Use the Divide & conquer strategy. D&C algorithms are recursive algorithms.
To solve this problem using D&C, there are two steps:
Figure out the base case. This should be the simplest possible case.
Divide or decrease your problem until it becomes the base case.
Step 1: Figure out the base case. What’s the simplest list you could
get? If you get an list with 0 or 1 element, that’s pretty easy to sum up.
if len(l) == 0: #base case
return []
Step 2: You need to move closer to an empty list with every recursive
call
recursive(l) #recursion case
for example
l = [1,2,4,6]
def recursive(l):
if len(l) == 0:
return [] # base case
else:
return [l.pop()] + recursive(l) # recusrive case
print recursive(l)
>[6,4,2,1]
Source : Grokking Algorithms
This one reverses in place. (Of course an iterative version would be better, but it has to be recursive, hasn't it?)
def reverse(l, first=0, last=-1):
if first >= len(l)/2: return
l[first], l[last] = l[last], l[first]
reverse(l, first+1, last-1)
mylist = [1,2,3,4,5]
print mylist
reverse(mylist)
print mylist
def revList(alist):
if len(alist) == 1:
return alist #base case
else:
return revList(alist[1:]) + [alist[0]]
print revList([1,2,3,4])
#prints [4,3,2,1]
A recursive function to reverse a list.
def reverseList(lst):
#your code here
if not lst:
return []
return [lst[-1]] + reverseList(lst[:-1])
print(reverseList([1, 2, 3, 4, 5]))
def reverse(q):
if len(q) != 0:
temp = q.pop(0)
reverse(q)
q.append(temp)
return q
looks simpler:
def reverse (n):
if not n: return []
return [n.pop()]+reverse(n)
Take the first element, reverse the rest of the list recursively, and append the first element at the end of the list.
def reverseList(listName,newList = None):
if newList == None:
newList = []
if len(listName)>0:
newList.append((listName.pop()))
return reverseList(listName, newList)
else:
return newList
print reverseList([1,2,3,4])
[4,3,2,1]
Using Mutable default argument and recursion :
def hello(x,d=[]):
d.append(x[-1])
if len(x)<=1:
s="".join(d)
print(s)
else:
return hello(x[:-1])
hello("word")
additional info
x[-1] # last item in the array
x[-2:] # last two items in the array
x[:-2] # everything except the last two items
Recursion part is hello(x[:-1]) where its calling hello function again after x[:-1]
This will reverse a nested lists also!
A = [1, 2, [31, 32], 4, [51, [521, [12, 25, [4, 78, 45], 456, [444, 111]],522], 53], 6]
def reverseList(L):
# Empty list
if len(L) == 0:
return
# List with one element
if len(L) == 1:
# Check if that's a list
if isinstance(L[0], list):
return [reverseList(L[0])]
else:
return L
# List has more elements
else:
# Get the reversed version of first list as well as the first element
return reverseList(L[1:]) + reverseList(L[:1])
print A
print reverseList(A)
Padmal's BLOG
You can reduce the recursion depth by half by swapping the first and last elements at once and calling rev recursively on the middle of the list:
lks=[2,7,3,1,9,6,5]
def rev(lks):
if len(lks)<2:
return lks
return [lks[-1]]+rev(lks[1:-1])+[lks[0]]
print(rev(lks))
The answer you're looking for is inside the function. The rest of the stuff is just to see (or if you want to compare) the time taken by the different algorithms.
import time
import sys
sys.setrecursionlimit(10**6)
def reverse(ls1):
if len(ls1) <= 1:
return ls1
else:
ls1[0], ls1[-1] = ls1[-1], ls1[0]
return [ls1[0]] + reverse(ls1[1:-1]) + [ls1[-1]]
ls = [*range(2000)]
start_time = time.time()
print(reverse(ls))
stop_time = time.time()
print(f"Total time taken: {(stop_time - start_time) * 1000} msec.")
Why not:
a = [1,2,3,4,5]
a = [a[i] for i in xrange(len(a)-1, -1, -1)] # now a is reversed!
if it is a list of numbers easiest way to reverse it would be. This would also work for strings but not recommended.
l1=[1,2,3,4]
l1 = np.array(l1)
assert l1[::-1]==[4,3,2,1]
if you do not want to keep it as a numpy array then you can pass it into a list as
l1 = [*l1]
again I do not recommend it for list of strings but you could if you really wanted to.
def reverse_array(arr, index):
if index == len(arr):
return
if type(arr[index]) == type([]):
reverse_array(arr[index], 0)
current = arr[index]
reverse_array(arr, index + 1)
arr[len(arr) - 1 - index] = current
return arr
if __name__ == '__main__':
print(reverse_array([[4, 5, 6, [4, 4, [5, 6, 7], 8], 8, 7]], 0))
def disp_array_reverse(inp, idx=0):
if idx >= len(inp):
return
disp_array_reverse(inp, idx+1)
print(inp[idx])
Related
after I reverse my list list elements are changing not reversing properly
here is my first code
def reverse_fib_series(num):
x = []
for i in range(num):
if i == 0:
x.append(0)
elif i == 1:
x.append(1)
else:
x.append(sum(reverse_fib_series(i)[-2:]))
return x
print(reverse_fib_series(11))
it returns [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
if I want to reverse it
def reverse_fib_series(num):
x = []
for i in range(num):
if i == 0:
x.append(0)
elif i == 1:
x.append(1)
else:
x.append(sum(reverse_fib_series(i)[-2:]))
return x[::-1]
print(reverse_fib_series(11))
it returns [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]. I do not know why?
i am trying to solve the following exercise:
"In Fibonacci Numbers, each number progresses as the sum of the two preceding numbers, such as 0,1,1,2,3,5,8, ... In this question you are given a number (0 <N <20). Accordingly, write the program that prints all Fibonacci numbers backwards from the Nth Fibonacci number."
This is happening because you reverse the list in each recursive call, rather than only reversing it once at the end -- so instead of summing the last two elements of the series to get the next element, you're summing the first two elements, which are always 0 and 1. That's why every element of the series after the first two becomes 1. (The list isn't changing when you reverse it at the end, the computation of the series is broken because you're reversing it each time.)
You could write the function so that it builds the series in-place from back to front, or you could fix this by simplifying the loop body to eliminate the unnecessary recursion, but this is a good opportunity to learn the concept of composing two simple things to produce one more complicated thing. :) Rather than trying to do it all at once, take the working (if sub-optimal) function you already have to produce the Fibonacci series, and then reverse it afterwards:
def fib_series(num):
x = []
for i in range(num):
if i == 0:
x.append(0)
elif i == 1:
x.append(1)
else:
x.append(sum(fib_series(i)[-2:]))
return x
def reverse_fib_series(num):
return fib_series(num)[::-1]
Note that your fib_series function can be a little simpler than what you wrote; you don't need to recursively call fib_series to get the last two numbers, because you already have them stored in x:
def fib_series(num):
x = []
for i in range(num):
if i == 0:
x.append(0)
elif i == 1:
x.append(1)
else:
x.append(sum(x[-2:]))
return x
or you could make it a little shorter by writing it as a generator:
def fib_series(num):
x = [0, 1]
x.extend(sum(x[-2::]) for _ in range(num - 2))
return x[:num]
try this code:
def reverse_fib_series(num):
x = []
for i in range(num):
if i == 0:
x.append(0)
elif i == 1:
x.append(1)
else:
x.append(sum(reverse_fib_series(i)[-2:]))
return x
print(reverse_fib_series(11)[::-1])
reverse the return value because you use recursion in the function
Because you are reversing array inside of a recursive function. It adds one number and reverse. And it keeps repeating the process.
This code will hel
def reverse_fib_series(num):
x = []
for i in range(num):
if i == 0:
x.append(0)
elif i == 1:
x.append(1)
else:
x.append(sum(reverse_fib_series(i)[-2:]))
return x
reversed = reverse_fib_series(11)[::-1]
print(reversed)
Just another ways, using [].insert(0, sum())
def reverse_fib_loop(n: int):
lx = []
for i in range(n):
if i > 1:
lx.insert(0, sum(lx[:2]))
else:
lx.insert(0, i)
return lx
def reverse_fib_recursion(size: int):
def wrapped(lx: list, sn: int, n: int):
if n > 0:
lx.insert(0, sn)
sn = sum(lx[:2]) if len(lx) >= 2 else 1
return wrapped(lx, sn, n-1)
return lx
return wrapped([], 0, size)
if __name__ == '__main__':
N = int(input('N='))
print(reverse_fib_loop(N))
print(reverse_fib_recursion(N))
I need to write a function that given an input list, all adjacent elements in the list are swapped with each other. If the length of the list is odd, then the last element just stays put. I wrote the function iteratively, like so:
>>>def swap(nums):
for i in range(0,len(nums),2):
try:
nums[i],nums[i+1] = nums[i+1], nums[i]
except:
pass
return nums
>>>swap([1,2,3,4,5])
[2, 1, 4, 3, 5]
I used the exact same logic as before for the recursive version:
def swap(nums, c=0):
try:
nums[c], nums[c+1] = nums[c+1], nums[c]
return swap(nums, c+2)
except:
return nums
Although both work, I feel like I'm cheating a bit with these try/except blocks, and I won't become a better programmer by using them all the time. Can anybody give me suggestions on how to approach these problems without relying on try/except blocks?
For the iterative version, you can use range(0, len(nums)-1, 2) to keep looping till the item before last as the following:
def swap(nums):
for i in range(0, len(nums) - 1, 2):
nums[i], nums[i + 1] = nums[i + 1], nums[i]
return nums
And in the recursive version, you can check if c >= len(nums) - 1 to check if you have reached last item:
def swap(nums, c=0):
if c >= len(nums) - 1:
return nums
nums[c], nums[c+1] = nums[c+1], nums[c]
return swap(nums, c+2)
this way you can avoid try/except because you will not raise index out of range exception. And for reference, if you want to use try/except it is better to use except IndexError: instead of general except:.
Input:
print(swap([1, 2, 3, 4, 5, 6]))
print(swap([1, 2, 3, 4, 5]))
Output:
[2, 1, 4, 3, 6, 5]
[2, 1, 4, 3, 5]
EDIT:
As #agtoever mentioned, you can modify the recursive version to be:
def swap(nums):
if len(nums) < 2:
return nums
return [nums[1], nums[0]] + swap(nums[2:])
Iteratively:
for i in range(0, len(nums) - (len(nums) % 2), 2): #Skips the last element in an odd length list
nums[c], nums[c+1] = nums[c + 1], nums[c]
Recursively:
import math
def swap(nums):
if len(nums) == 2:
return [nums[1], nums[0]]
if len(nums) == 1:
return nums[0]
half = int(math.ceil(len(nums) / 2.0))
return swap(nums[:half]) + swap(nums[half:])
def swap(li):
if len(li) < 2:
return li
else:
return [li[1], li[0]] + swap(li[2:])
or
def swap(li):
def swap_iter(inlist, out):
if len(inlist) < 2:
return out + inlist
else:
return swap_iter(inlist[2:], out + [inlist[1], inlist[0]])
return swap_iter(li, [])
I want to test if a list contains consecutive integers and no repetition of numbers.
For example, if I have
l = [1, 3, 5, 2, 4, 6]
It should return True.
How should I check if the list contains up to n consecutive numbers without modifying the original list?
I thought about copying the list and removing each number that appears in the original list and if the list is empty then it will return True.
Is there a better way to do this?
For the whole list, it should just be as simple as
sorted(l) == list(range(min(l), max(l)+1))
This preserves the original list, but making a copy (and then sorting) may be expensive if your list is particularly long.
Note that in Python 2 you could simply use the below because range returned a list object. In 3.x and higher the function has been changed to return a range object, so an explicit conversion to list is needed before comparing to sorted(l)
sorted(l) == range(min(l), max(l)+1))
To check if n entries are consecutive and non-repeating, it gets a little more complicated:
def check(n, l):
subs = [l[i:i+n] for i in range(len(l)) if len(l[i:i+n]) == n]
return any([(sorted(sub) in range(min(l), max(l)+1)) for sub in subs])
The first code removes duplicates but keeps order:
from itertools import groupby, count
l = [1,2,4,5,2,1,5,6,5,3,5,5]
def remove_duplicates(values):
output = []
seen = set()
for value in values:
if value not in seen:
output.append(value)
seen.add(value)
return output
l = remove_duplicates(l) # output = [1, 2, 4, 5, 6, 3]
The next set is to identify which ones are in order, taken from here:
def as_range(iterable):
l = list(iterable)
if len(l) > 1:
return '{0}-{1}'.format(l[0], l[-1])
else:
return '{0}'.format(l[0])
l = ','.join(as_range(g) for _, g in groupby(l, key=lambda n, c=count(): n-next(c)))
l outputs as: 1-2,4-6,3
You can customize the functions depending on your output.
We can use known mathematics formula for checking consecutiveness,
Assuming min number always start from 1
sum of consecutive n numbers 1...n = n * (n+1) /2
def check_is_consecutive(l):
maximum = max(l)
if sum(l) == maximum * (maximum+1) /2 :
return True
return False
Once you verify that the list has no duplicates, just compute the sum of the integers between min(l) and max(l):
def check(l):
total = 0
minimum = float('+inf')
maximum = float('-inf')
seen = set()
for n in l:
if n in seen:
return False
seen.add(n)
if n < minimum:
minimum = n
if n > maximum:
maximum = n
total += n
if 2 * total != maximum * (maximum + 1) - minimum * (minimum - 1):
return False
return True
import numpy as np
import pandas as pd
(sum(np.diff(sorted(l)) == 1) >= n) & (all(pd.Series(l).value_counts() == 1))
We test both conditions, first by finding the iterative difference of the sorted list np.diff(sorted(l)) we can test if there are n consecutive integers. Lastly, we test if the value_counts() are all 1, indicating no repeats.
I split your query into two parts part A "list contains up to n consecutive numbers" this is the first line if len(l) != len(set(l)):
And part b, splits the list into possible shorter lists and checks if they are consecutive.
def example (l, n):
if len(l) != len(set(l)): # part a
return False
for i in range(0, len(l)-n+1): # part b
if l[i:i+3] == sorted(l[i:i+3]):
return True
return False
l = [1, 3, 5, 2, 4, 6]
print example(l, 3)
def solution(A):
counter = [0]*len(A)
limit = len(A)
for element in A:
if not 1 <= element <= limit:
return False
else:
if counter[element-1] != 0:
return False
else:
counter[element-1] = 1
return True
The input to this function is your list.This function returns False if the numbers are repeated.
The below code works even if the list does not start with 1.
def check_is_consecutive(l):
"""
sorts the list and
checks if the elements in the list are consecutive
This function does not handle any exceptions.
returns true if the list contains consecutive numbers, else False
"""
l = list(filter(None,l))
l = sorted(l)
if len(l) > 1:
maximum = l[-1]
minimum = l[0] - 1
if minimum == 0:
if sum(l) == (maximum * (maximum+1) /2):
return True
else:
return False
else:
if sum(l) == (maximum * (maximum+1) /2) - (minimum * (minimum+1) /2) :
return True
else:
return False
else:
return True
1.
l.sort()
2.
for i in range(0,len(l)-1)))
print(all((l[i+1]-l[i]==1)
list must be sorted!
lst = [9,10,11,12,13,14,15,16]
final = True if len( [ True for x in lst[:-1] for y in lst[1:] if x + 1 == y ] ) == len(lst[1:]) else False
i don't know how efficient this is but it should do the trick.
With sorting
In Python 3, I use this simple solution:
def check(lst):
lst = sorted(lst)
if lst:
return lst == list(range(lst[0], lst[-1] + 1))
else:
return True
Note that, after sorting the list, its minimum and maximum come for free as the first (lst[0]) and the last (lst[-1]) elements.
I'm returning True in case the argument is empty, but this decision is arbitrary. Choose whatever fits best your use case.
In this solution, we first sort the argument and then compare it with another list that we know that is consecutive and has no repetitions.
Without sorting
In one of the answers, the OP commented asking if it would be possible to do the same without sorting the list. This is interesting, and this is my solution:
def check(lst):
if lst:
r = range(min(lst), max(lst) + 1) # *r* is our reference
return (
len(lst) == len(r)
and all(map(lst.__contains__, r))
# alternative: all(x in lst for x in r)
# test if every element of the reference *r* is in *lst*
)
else:
return True
In this solution, we build a reference range r that is a consecutive (and thus non-repeating) sequence of ints. With this, our test is simple: first we check that lst has the correct number of elements (not more, which would indicate repetitions, nor less, which indicates gaps) by comparing it with the reference. Then we check that every element in our reference is also in lst (this is what all(map(lst.__contains__, r)) is doing: it iterates over r and tests if all of its elements are in lts).
l = [1, 3, 5, 2, 4, 6]
from itertools import chain
def check_if_consecutive_and_no_duplicates(my_list=None):
return all(
list(
chain.from_iterable(
[
[a + 1 in sorted(my_list) for a in sorted(my_list)[:-1]],
[sorted(my_list)[-2] + 1 in my_list],
[len(my_list) == len(set(my_list))],
]
)
)
)
Add 1 to any number in the list except for the last number(6) and check if the result is in the list. For the last number (6) which is the greatest one, pick the number before it(5) and add 1 and check if the result(6) is in the list.
Here is a really short easy solution without having to use any imports:
range = range(10)
L = [1,3,5,2,4,6]
L = sorted(L, key = lambda L:L)
range[(L[0]):(len(L)+L[0])] == L
>>True
This works for numerical lists of any length and detects duplicates.
Basically, you are creating a range your list could potentially be in, editing that range to match your list's criteria (length, starting value) and making a snapshot comparison. I came up with this for a card game I am coding where I need to detect straights/runs in a hand and it seems to work pretty well.
I want to find a sequence of n consecutive integers within a sorted list and return that sequence. This is the best I can figure out (for n = 4), and it doesn't allow the user to specify an n.
my_list = [2,3,4,5,7,9]
for i in range(len(my_list)):
if my_list[i+1] == my_list[i]+1 and my_list[i+2] == my_list[i]+2 and my_list[i+3] == my_list[i]+3:
my_sequence = list(range(my_list[i],my_list[i]+4))
my_sequence = [2,3,4,5]
I just realized this code doesn't work and returns an "index out of range" error, so I'll have to mess with the range of the for loop.
Here's a straight-forward solution. It's not as efficient as it might be, but it will be fine unless you have very long lists:
myarray = [2,5,1,7,3,8,1,2,3,4,5,7,4,9,1,2,3,5]
for idx, a in enumerate(myarray):
if myarray[idx:idx+4] == [a,a+1,a+2,a+3]:
print([a, a+1,a+2,a+3])
break
Create a nested master result list, then go through my_sorted_list and add each item to either the last list in the master (if discontinuous) or to a new list in the master (if continuous):
>>> my_sorted_list = [0,2,5,7,8,9]
>>> my_sequences = []
>>> for idx,item in enumerate(my_sorted_list):
... if not idx or item-1 != my_sequences[-1][-1]:
... my_sequences.append([item])
... else:
... my_sequences[-1].append(item)
...
>>> max(my_sequences, key=len)
[7, 8, 9]
A short and concise way is to fill an array with numbers every time you find the next integer is the current integer plus 1 (until you already have N consecutive numbers in array), and for anything else, we can empty the array:
arr = [4,3,1,2,3,4,5,7,5,3,2,4]
N = 4
newarr = []
for i in range(len(arr)-1):
if(arr[i]+1 == arr[i+1]):
newarr += [arr[i]]
if(len(newarr) == N):
break
else:
newarr = []
When the code is run, newarr will be:
[1, 2, 3, 4]
#size = length of sequence
#span = the span of neighbour integers
#the time complexity is O(n)
def extractSeq(lst,size,span=1):
lst_size = len(lst)
if lst_size < size:
return []
for i in range(lst_size - size + 1):
for j in range(size - 1):
if lst[i + j] + span == lst[i + j + 1]:
continue
else:
i += j
break
else:
return lst[i:i+size]
return []
mylist = [2,3,4,5,7,9]
for j in range(len(mylist)):
m=mylist[j]
idx=j
c=j
for i in range(j,len(mylist)):
if mylist[i]<m:
m=mylist[i]
idx=c
c+=1
tmp=mylist[j]
mylist[j]=m
mylist[idx]=tmp
print(mylist)
I want to define a recursive function can sort any list of ints:
def sort_l(l):
if l==[]:
return []
else:
if len(l)==1:
return [l[-1]]
elif l[0]<l[1]:
return [l[0]]+sort_l(l[1:])
else:
return sort_l(l[1:])+[l[0]]
Calling this function on a list [3, 1, 2,4,7,5,6,9,8] should give me:
[1,2,3,4,5,6,7,8,9]
But I get:
print(sort_l([3, 1, 2,4,7,5,6,9,8]))--> [1, 2, 4, 5, 6, 8, 9, 7, 3]
Please help me to fix the problem, actual code would be appreciated. Thanks!
The quick sort is recursive and easy to implement in Python:
def quick_sort(l):
if len(l) <= 1:
return l
else:
return quick_sort([e for e in l[1:] if e <= l[0]]) + [l[0]] +\
quick_sort([e for e in l[1:] if e > l[0]])
will give:
>>> quick_sort([3, 1, 2, 4, 7, 5, 6, 9, 8])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
For this you would want to use merge sort. Essentially in a merge sort you recursively split the list in half until you have single elements and than build it back up in the correct order. merge sort on has a complexity of O(n log(n)) and is an extremely stable sorting method.
Here are some good in depth explanations and visuals for merge sorting:
https://www.youtube.com/watch?v=vxENKlcs2Tw
http://www.princeton.edu/~achaney/tmve/wiki100k/docs/Merge_sort.html
def maximum(lis):
if len(lis) == 1:
return lis[0]
return maximum(lis[1:]) if lis[0] < lis[1] else maximum(lis[:1] + lis[2:])
def sorter(lis):
if len(lis) == 1:
return lis
x = maximum(lis)
lis.remove(x)
return sorter(lis) + [x]
with functional programming:
sor = lambda lis: lis if len(lis) == 1 else [lis.pop(lis.index(reduce(lambda x, y: x if x > y else y, lis)))] + sor(lis)
def quicksort(lst):
"Quicksort over a list-like sequence"
if len(lst) == 0:
return lst
pivot = lst[0]
pivots = [x for x in lst if x == pivot]
small = quicksort([x for x in lst if x < pivot])
large = quicksort([x for x in lst if x > pivot])
return small + pivots + large
Above is a more readable recursive implementation of Quick Sort Algorithm. Above piece of code is from book Functional programing in python by O'REILLY.
Above function will produce.
list=[9,8,7,6,5,4]
quicksort(list)
>>[4,5,6,7,8,9]
def sort(array, index = 0, bigNumber = 0):
if len(array) == index:
return array
elif bigNumber > array[index]:
array[index - 1] = array[index]
array[index] = bigNumber
bigNumber = array[0]
index = 0
else:
bigNumber = array[index]
return sort(array, (index + 1), bigNumber)
#sort an int list using recursion
global array
array=[5,3,8,4,2,6,1]
def sort1(array:[])->[]:
if len(array)==1:
return
temp=array[-1]
array.pop()
sort1(array)
sort2(array,temp)
def sort2(array:[],temp):
if len(array)==0 or temp>=array[-1]:
array.append(temp)
return
a=array[-1]
array.pop()
sort2(array,temp)
array.append(a)
sort1(array)
print(array)
Here i am explaining recursive approach to sort a list. we can follow "Induction Base-condition Hypothesis" recursion approach. so basically we consider our hypothesis here sort_l(nums) function which sorts for given list and Base condition will be found when we have singly number list available which is already sorted. Now in induction step, we insert the temp element (last element of list) in the correct position of given list.
example-
sort_l([1,5,0,2]) will make below recursively call
sort_l([1]) <-- 5 (here you need to insert 5 in correct position)
sort_l([1,5]) <-- 0 (here you need to insert 0 in correct position)
sort_l([0,1,5]) <-- 2 (here you need to insert 2 in correct position)
sort_l([0,1,5,2]) Finally it will be in sorted list.
====== Below is working code=======
def insert_element(nums, temp):
if len(nums) == 1:
if nums[0] > temp:
nums.insert(0, temp)
elif nums[0] < temp:
nums.append(temp)
else:
for i in range(len(nums)):
if nums[i] > temp:
nums.insert(i, temp)
break
if nums[-1] < temp:
nums.append(temp)
def sort_l(nums): ## hypothesis
if len(nums)==1: ## base condition
return nums
temp = nums[-1]
nums.pop()
sort_l(nums)
insert_element(nums, temp) ## induction
return nums
This is a complementary answer since both quicksort and complexity are already covered in previous answers. Although, I believe an easy-to-get sort function that covers Python's identity is missing*.
def sort(xs: list) -> list:
if not xs:
return xs
else:
xs.remove(num := min(xs))
return [num] + sort(xs)
[*] Python is a (slow) interpreted language, but it has become famous because of its readability and easiness to learn. It doesn't really "reward" its developers for using immutable objects nor it is a language that should be used for computation intensive applications
This is a recursive solution. For an explanation, refer to this video:
arr = [3,1,2,4,7,5,6,9,8]
def insert_fn(arr, temp): # Hypothesis
if len(arr) == 0 or arr[-1] <= temp: # Base - condition
arr.append(temp)
return arr
# Induction
val = arr[-1]
arr.pop()
insert_fn(arr, temp) # Call function on a smaller input.
arr.append(val) # Induction step
return arr
def sort_fn(arr): # Hypothesis
if len(arr) == 1: # Base - condition
return arr
# Induction
val = arr[-1]
arr.pop()
sort_fn(arr) # Call function on a smaller input.
insert_fn(arr, val) # Induction step
return arr
print(sort_fn(arr))