python minmax using only recursion - python

I am trying to build a function that takes in a list and returns a tuple of (min, max).
For example,
[2,1,4,9,4.5]
would return
(1, 9)
I am trying to use only recursion and want to perform this task without using other things that would make this very easy (such as min(),max(),sort(),sorted(),loop..etc)
So far, I have been able to create function that find maximum
def findmax(alist):
if len(alist) <= 1:
return tuple(alist)
elif len(alist) == 2:
if alist[0] >= alist[1]:
return findmax([alist[0]])
elif alist[0] <= alist[1]:
return findmax([alist[1]])
elif len(alist) > 2:
if alist[0] >= alist[1]:
return findmax([alist[0]] + alist[2:])
elif alist[0] <= alist[1]:
return findmax(alist[1:])
which
findmax([2,1,4,9,4.5])
returns
(9,)
and a function that find minimum (which is not too different)
def findmin(alist):
if len(alist) <= 1:
return tuple(alist)
elif len(alist) == 2:
if alist[0] >= alist[1]:
return findmin([alist[1]])
elif alist[0] <= alist[1]:
return findmin([alist[0]])
elif len(alist) > 2:
if alist[0] >= alist[1]:
return findmin(alist[1:])
elif alist[0] <= alist[1]:
return findmin([alist[0]] + alist[2:])
which
findmin([2,1,4,9,4.5])
returns
(1,)
Is there a way to put this two separate functions into one using only recursion so that it would return a desired result of
(1, 9)
Any help would really be appreciated.

I find that these sorts of problems tend to be simpler than you expect. Let the recursion do the work:
def find_min_max(a_list):
if a_list:
head, *tail = a_list
if tail:
minimum, maximum = find_min_max(tail)
return [head, minimum][minimum < head], [head, maximum][maximum > head]
return head, head
return a_list
USAGE
>>> find_min_max([2, 1, 4, 9, 4.5])
(1, 9)
>>> find_min_max('elephant')
('a', 't')
>>>
This solution is Python 3 specific but can be easily modified for Python 2 & 3 compatibility.

Below, minmax is expressed using continuation-passing style. In this style, it's as if our state variables are pulled out of the aether. For additional examples of other programs written using this style, please see this answer.
from math import inf
def first (xs):
return xs[0]
def rest (xs):
return xs[1:]
def tuple2 (a, b):
return (a, b)
def minmax (xs = [], then = tuple2):
if not xs: # base case: no `x`
return then (inf, -inf)
else: # inductive case: at least one `x`
return minmax \
( rest(xs)
, lambda a, b:
then \
( min (a, first (xs))
, max (b, first (xs))
)
)
print (minmax ([ 2, 1, 4, 9, 4.5 ]))
# (1, 9)
print (minmax ([]))
# (inf, -inf)
min and max are defined as
def min (a, b)
if a < b:
return a
else:
return b
def max (a, b)
if a > b:
return a
else:
return b

To find either max or min separately is easy. What is difficult is to find both max and min through recursive calls. Tail recursion is exactly for this (maintain and update status of variables through recursive calls) and is usually straightforward to write:
def findminmax(L):
def inner(L1, min, max):
if L1 == []:
return (min, max)
elif L1[0] > max:
return inner(L1[1:], min, L1[0])
elif L1[0] < min:
return inner(L1[1:], L1[0], max)
else:
return inner(L1[1:], min, max)
return inner(L[1:], L[0], L[0])
findminmax([2,1,4,9,4.5])
# => (1, 9)
No need for assignment and fancy list indexing. Only the most basic list operation is needed. The recursion structure is clear and very standard (obviously see base case, reduction and function recursive call) and the code is also very readable as plain English.
Update
A little modification to handle the string input and empty list or string input:
def findminmax(LS):
def inner(LS1, min, max):
if not LS1:
return (min, max)
elif LS1[0] > max:
return inner(LS1[1:], min, LS1[0])
elif LS1[0] < min:
return inner(LS1[1:], LS1[0], max)
else:
return inner(LS1[1:], min, max)
try:
return inner(LS[1:], LS[0], LS[0])
except IndexError:
print("Oops! That was no valid input. Try again...")
findminmax([2,1,4,9,4.5])
# => (1, 9)
findminmax([2])
# => (2, 2)
findminmax('txwwadga')
# => ('a', 'x')
findminmax('t')
# => ('t', 't')
findminmax([]) # empty list
# => Oops! That was no valid input. Try again...
findminmax('') # empty string
# => Oops! That was no valid input. Try again...

You can add another def (read comments):
def f(l):
return findmin(l)+findmax(l) # Also you can do: `(findmin(l)[0],findmax(l)[0])`
Now to call it, do:
print(f([2,1,4,9,4.5]))
Output would be:
(1, 9)

You're definitely over-complicating the recursive function. Both minimum and maximum can be returned in a tuple with the following recursive code.
my_list = [2,1,4,9,4.5]
def recursive_min_max(list_a, pos, biggest, smallest):
if pos != len(list_a) - 1:
biggest_new = list_a[pos] if biggest == None else list_a[pos] if list_a[pos] > biggest else biggest
smallest_new = list_a[pos] if smallest == None else list_a[pos] if list_a[pos] < smallest else smallest
return recursive_min_max(list_a, pos + 1, biggest_new, smallest_new)
return (biggest,smallest)
print(recursive_min_max(my_list, 0, None, None))
At each step, the current list item is being compared to the current biggest and smallest elements. If they are bigger/smaller, the current value replaces them.

Related

Returning smallest positive int that does not occur in given list

Write a function that given an array of A of N int, returns the smallest positive(greater than 0) that does not occur in A.
I decided to approach this problem by iterating through the list after sorting it.
The value of the current element would be compared to the value of the next element. Because the list is sorted, the list should follow sequentially until the end.
However, if there is a skipped number this indicates the smallest number that does not occur in the list.
And if it follows through until the end, then you should just add one to the value of the last element.
def test():
arr = [23,26,25,24,28]
arr.sort()
l = len(arr)
if arr[-1] <= 0:
return 1
for i in range(0,l):
for j in range(1,l):
cur_val = arr[i]
next_val = arr[j]
num = cur_val + 1
if num != next_val:
return num
if num == next_val: //if completes the list with no skips
return arr[j] + 1
print(test())
I suggest that you convert to a set, and you can then efficiently test whether numbers are members of it:
def first_int_not_in_list(lst, starting_value=1):
s = set(lst)
i = starting_value
while i in s:
i += 1
return i
arr = [23,26,25,24,28]
print(first_int_not_in_list(arr)) # prints 1
You can do the following:
def minint(arr):
s=set(range(min(arr),max(arr)))-set(arr)
if len(s)>0:
return min(set(range(min(arr),max(arr)))-set(arr)) #the common case
elif 1 in arr:
return max(arr)+1 #arr is a complete range with no blanks
else:
return 1 #arr is negative numbers only
You can make use of sets to achieve your goal.
set.difference() method is same as relative complement denoted by A – B, is the set of all elements in A that are not in B.
Example:
Let A = {1, 3, 5} and B = {1, 2, 3, 4, 5, 6}. Then A - B = {2, 4, 6}.
Using isNeg() method is used to check whether given set contains any negative integer.
Using min() method on A - B returns the minimum value from set difference.
Here's the code snippet
def retMin(arrList):
min_val = min(arrList) if isNeg(arrList) else 1
seqList=list(range((min_val),abs(max(arrList))+2))
return min(list(set(seqList).difference(arrList)))
def isNeg(arr):
return(all (x > 0 for x in arr))
Input:
print(retMin([1,3,6,4,1,2]))
Output:
5
Input:
print(retMin([-2,-6,-7]))
Output:
1
Input:
print(retMin([23,25,26,28,30]))
Output:
24
Try with the following code and you should be able to solve your problem:
def test():
arr = [3,-1,23,26,25,24,28]
min_val = min(val for val in arr if val > 0)
arr.sort()
l = len(arr)
if arr[-1] <= 0:
return 1
for i in range(0,l):
if arr[i] > 0 and arr[i] <= min_val:
min_val = arr[i] + 1
return min_val
print(test())
EDIT
It seems you're searching for the the value grater than the minimum positive integer in tha array not sequentially.
The code it's just the same as before I only change min_val = 1 to:
min_val = min(val for val in arr if val > 0), so I'm using a lambda expression to get all the positive value of the array and after getting them, using the min function, I'll get the minimum of those.
You can test it here if you want

python3 binary search not working [duplicate]

I am trying to implement the binary search in python and have written it as follows. However, I can't make it stop whenever needle_element is larger than the largest element in the array.
Can you help? Thanks.
def binary_search(array, needle_element):
mid = (len(array)) / 2
if not len(array):
raise "Error"
if needle_element == array[mid]:
return mid
elif needle_element > array[mid]:
return mid + binary_search(array[mid:],needle_element)
elif needle_element < array[mid]:
return binary_search(array[:mid],needle_element)
else:
raise "Error"
It would be much better to work with a lower and upper indexes as Lasse V. Karlsen was suggesting in a comment to the question.
This would be the code:
def binary_search(array, target):
lower = 0
upper = len(array)
while lower < upper: # use < instead of <=
x = lower + (upper - lower) // 2
val = array[x]
if target == val:
return x
elif target > val:
if lower == x: # these two are the actual lines
break # you're looking for
lower = x
elif target < val:
upper = x
lower < upper will stop once you have reached the smaller number (from the left side)
if lower == x: break will stop once you've reached the higher number (from the right side)
Example:
>>> binary_search([1,5,8,10], 5) # return 1
1
>>> binary_search([1,5,8,10], 0) # return None
>>> binary_search([1,5,8,10], 15) # return None
Why not use the bisect module? It should do the job you need---less code for you to maintain and test.
array[mid:] creates a new sub-copy everytime you call it = slow. Also you use recursion, which in Python is slow, too.
Try this:
def binarysearch(sequence, value):
lo, hi = 0, len(sequence) - 1
while lo <= hi:
mid = (lo + hi) // 2
if sequence[mid] < value:
lo = mid + 1
elif value < sequence[mid]:
hi = mid - 1
else:
return mid
return None
In the case that needle_element > array[mid], you currently pass array[mid:] to the recursive call. But you know that array[mid] is too small, so you can pass array[mid+1:] instead (and adjust the returned index accordingly).
If the needle is larger than all the elements in the array, doing it this way will eventually give you an empty array, and an error will be raised as expected.
Note: Creating a sub-array each time will result in bad performance for large arrays. It's better to pass in the bounds of the array instead.
You can improve your algorithm as the others suggested, but let's first look at why it doesn't work:
You're getting stuck in a loop because if needle_element > array[mid], you're including element mid in the bisected array you search next. So if needle is not in the array, you'll eventually be searching an array of length one forever. Pass array[mid+1:] instead (it's legal even if mid+1 is not a valid index), and you'll eventually call your function with an array of length zero. So len(array) == 0 means "not found", not an error. Handle it appropriately.
This is a tail recursive solution, I think this is cleaner than copying partial arrays and then keeping track of the indexes for returning:
def binarySearch(elem, arr):
# return the index at which elem lies, or return false
# if elem is not found
# pre: array must be sorted
return binarySearchHelper(elem, arr, 0, len(arr) - 1)
def binarySearchHelper(elem, arr, start, end):
if start > end:
return False
mid = (start + end)//2
if arr[mid] == elem:
return mid
elif arr[mid] > elem:
# recurse to the left of mid
return binarySearchHelper(elem, arr, start, mid - 1)
else:
# recurse to the right of mid
return binarySearchHelper(elem, arr, mid + 1, end)
def binary_search(array, target):
low = 0
mid = len(array) / 2
upper = len(array)
if len(array) == 1:
if array[0] == target:
print target
return array[0]
else:
return False
if target == array[mid]:
print array[mid]
return mid
else:
if mid > low:
arrayl = array[0:mid]
binary_search(arrayl, target)
if upper > mid:
arrayu = array[mid:len(array)]
binary_search(arrayu, target)
if __name__ == "__main__":
a = [3,2,9,8,4,1,9,6,5,9,7]
binary_search(a,9)
Using Recursion:
def binarySearch(arr,item):
c = len(arr)//2
if item > arr[c]:
ans = binarySearch(arr[c+1:],item)
if ans:
return binarySearch(arr[c+1],item)+c+1
elif item < arr[c]:
return binarySearch(arr[:c],item)
else:
return c
binarySearch([1,5,8,10,20,50,60],10)
All the answers above are true , but I think it would help to share my code
def binary_search(number):
numbers_list = range(20, 100)
i = 0
j = len(numbers_list)
while i < j:
middle = int((i + j) / 2)
if number > numbers_list[middle]:
i = middle + 1
else:
j = middle
return 'the index is '+str(i)
If you're doing a binary search, I'm guessing the array is sorted. If that is true you should be able to compare the last element in the array to the needle_element. As octopus says, this can be done before the search begins.
You can just check to see that needle_element is in the bounds of the array before starting at all. This will make it more efficient also, since you won't have to do several steps to get to the end.
if needle_element < array[0] or needle_element > array[-1]:
# do something, raise error perhaps?
It returns the index of key in array by using recursive.
round() is a function convert float to integer and make code fast and goes to expected case[O(logn)].
A=[1,2,3,4,5,6,7,8,9,10]
low = 0
hi = len(A)
v=3
def BS(A,low,hi,v):
mid = round((hi+low)/2.0)
if v == mid:
print ("You have found dude!" + " " + "Index of v is ", A.index(v))
elif v < mid:
print ("Item is smaller than mid")
hi = mid-1
BS(A,low,hi,v)
else :
print ("Item is greater than mid")
low = mid + 1
BS(A,low,hi,v)
BS(A,low,hi,v)
Without the lower/upper indexes this should also do:
def exists_element(element, array):
if not array:
yield False
mid = len(array) // 2
if element == array[mid]:
yield True
elif element < array[mid]:
yield from exists_element(element, array[:mid])
else:
yield from exists_element(element, array[mid + 1:])
Returning a boolean if the value is in the list.
Capture the first and last index of the list, loop and divide the list capturing the mid value.
In each loop will do the same, then compare if value input is equal to mid value.
def binarySearch(array, value):
array = sorted(array)
first = 0
last = len(array) - 1
while first <= last:
midIndex = (first + last) // 2
midValue = array[midIndex]
if value == midValue:
return True
if value < midValue:
last = midIndex - 1
if value > midValue:
first = midIndex + 1
return False

Python Pure recursion - Divisor - One input

What is the recursive call (or inductive steps) for a function that returns the number of integers from 1 to N, which evenly divide N. The idea is to concieve a pure recursive code in python for this function. No 'for' or 'while' loops, neither modules can be used. The function num_of_divisors(42) returns 8, representing 1, 2, 3, 6, 7, 14, 21, and 42 as divisors of 42.
def num_of_divisors(n):
return sum(1 if n % i==0 else 0 for i in range(((n+1)**0.5)//1)
Good luck explaining it to your teacher!
If you really can't use for loops (?????????) then this is impossible without simulating one.
def stupid_num_of_divisors_assigned_by_shortsighted_teacher(n, loop_num=1):
"""I had to copy this from Stack Overflow because it's such an
inane restriction it's actually harmful to learning the language
"""
if loop_num <= (n+1) ** 0.5:
if n % loop_num == 0:
return 2 + \
stupid_num_of_divisors_assigned_by_shortsighted_teacher(n, loop_num+1)
else:
return stupid_num_of_divisors_assigned_by_shortsighted_teacher(n, loop_num+1)
else:
if n % loop_num == 0:
return 1
Bonus points: explain why you're adding 2 in the first conditional, but only 1 in the second conditional!
Here you go buddy your teacher'll be happy.
def _num_of_divisors(n, k):
if (k == 0):
return 0
return _num_of_divisors(n, k-1) + (n % k == 0)
def num_of_divisors(n):
return _num_of_divisors(n, n)
It's easier than you think to convert such a simple problem from a loop to a recursive function.
Start with a loop implementation:
n = 42
result = []
for i in range(n+1):
if n % i == 0:
result.append(i)
then write a function
def num_of_divisors_helper(i, n, result):
if <condition when a number should be added to result>:
result.append(n)
# Termination condition
if <when should it stop>:
return
# Recursion
num_of_divisors_helper(i+1, n, result)
Then you define a wrapper function num_of_divisors that calls num_of_divisors_helper. You should be able to fill the gaps in the recursive function and write the wrapper function yourself.
It's a simple, inefficient solution, but it matches your terms.
Without using %
def is_divisible(n, i, k):
if k > n:
return False
if n - i*k == 0:
return True
else:
return is_divisible(n, i, k+1)
def num_of_divisors(n, i=1):
if i > n/2:
return 1
if is_divisible(n, i, 1):
return 1 + num_of_divisors(n, i+1)
else:
return num_of_divisors(n, i+1)
num_of_divisors(42) -> 8
def n_divisors(n,t=1):
return (not n%t)+(n_divisors(n,t+1) if t < n else 0)
good luck on the test later ... better hit those books for real, go to class and take notes...
with just one input i guess
t=0
def n_divisors(n):
global t
t += 1
return (not n%t)+(n_divisors(n) if t < n else 0)

Does the sum exist in the given list [duplicate]

I am trying to write a function that will not only determine whether the sum of a subset of a set adds to a desired target number, but also to print the subset that is the solution.
Here is my code for finding whether a subset exists:
def subsetsum(array,num):
if num == 0 or num < 1:
return False
elif len(array) == 0:
return False
else:
if array[0] == num:
return True
else:
return subsetsum(array[1:],(num - array[0])) or subsetsum(array[1:],num)
How can I modify this to record the subset itself so that I can print it? Thanks in advance!
Based on your solution:
def subsetsum(array,num):
if num == 0 or num < 1:
return None
elif len(array) == 0:
return None
else:
if array[0] == num:
return [array[0]]
else:
with_v = subsetsum(array[1:],(num - array[0]))
if with_v:
return [array[0]] + with_v
else:
return subsetsum(array[1:],num)
Modification to also detect duplicates and further solutions when a match happened
def subset(array, num):
result = []
def find(arr, num, path=()):
if not arr:
return
if arr[0] == num:
result.append(path + (arr[0],))
else:
find(arr[1:], num - arr[0], path + (arr[0],))
find(arr[1:], num, path)
find(array, num)
return result
You could change your approach to do that more easily, something like:
def subsetsum(array, num):
if sum(array) == num:
return array
if len(array) > 1:
for subset in (array[:-1], array[1:]):
result = subsetsum(subset, num)
if result is not None:
return result
This will return either a valid subset or None.
Thought I'll throw another solution into the mix.
We can map each selection of a subset of the list to a (0-padded) binary number, where a 0 means not taking the member in the corresponsing position in the list, and 1 means taking it.
So masking [1, 2, 3, 4] with 0101 creates the sub-list [2, 4].
So, by generating all 0-padded binary numbers in the range between 0 and 2^LENGTH_OF_LIST, we can iterate all selections. If we use these sub-list selections as masks and sum the selection - we can know the answer.
This is how it's done:
#!/usr/bin/env python
# use a binary number (represented as string) as a mask
def mask(lst, m):
# pad number to create a valid selection mask
# according to definition in the solution laid out
m = m.zfill(len(lst))
return map(lambda x: x[0], filter(lambda x: x[1] != '0', zip(lst, m)))
def subset_sum(lst, target):
# there are 2^n binary numbers with length of the original list
for i in xrange(2**len(lst)):
# create the pick corresponsing to current number
pick = mask(lst, bin(i)[2:])
if sum(pick) == target:
return pick
return False
print subset_sum([1,2,3,4,5], 7)
Output:
[3, 4]
To return all possibilities we can use a generator instead (the only changes are in subset_sum, using yield instead of return and removing return False guard):
#!/usr/bin/env python
# use a binary number (represented as string) as a mask
def mask(lst, m):
# pad number to create a valid selection mask
# according to definition in the solution laid out
m = m.zfill(len(lst))
return map(lambda x: x[0], filter(lambda x: x[1] != '0', zip(lst, m)))
def subset_sum(lst, target):
# there are 2^n binary numbers with length of the original list
for i in xrange(2**len(lst)):
# create the pick corresponsing to current number
pick = mask(lst, bin(i)[2:])
if sum(pick) == target:
yield pick
# use 'list' to unpack the generator
print list(subset_sum([1,2,3,4,5], 7))
Output:
[[3, 4], [2, 5], [1, 2, 4]]
Note: While not padding the mask with zeros may work as well, as it will simply select members of the original list in a reverse order - I haven't checked it and didn't use it.
I didn't use it since it's less obvious (to me) what's going on with such trenary-like mask (1, 0 or nothing) and I rather have everything well defined.
Slightly updated the below code to return all possible combinations for this problem. Snippet in the thread above will not print all possible combinations when the input is given as subset([4,3,1],4)
def subset(array, num):
result = []
def find(arr, num, path=()):
if not arr:
return
if arr[0] == num:
result.append(path + (arr[0],))
else:
find(arr[1:], num - arr[0], path + (arr[0],))
find(arr[1:], num, path)
find(array, num)
return result
A bit different approach to print all subset through Recursion.
def subsetSumToK(arr,k):
if len(arr)==0:
if k == 0:
return [[]]
else:
return []
output=[]
if arr[0]<=k:
temp2=subsetSumToK(arr[1:],k-arr[0]) #Including the current element
if len(temp2)>0:
for i in range(len(temp2)):
temp2[i].insert(0,arr[0])
output.append(temp2[i])
temp1=subsetSumToK(arr[1:],k) #Excluding the current element
if len(temp1)>0:
for i in range(len(temp1)):
output.append(temp1[i])
return output
arr=[int(i) for i in input().split()]
k=int(input())
sub=subsetSumToK(arr,k)
for i in sub:
for j in range(len(i)):
if j==len(i)-1:
print(i[j])
else:
print(i[j],end=" ")
Rather than using recursion, you could use the iterative approach.
def desiredSum(array, sum):
numberOfItems = len(array)
storage = [[0 for x in range(sum + 1)] for x in range(numberOfItems + 1)]
for i in range(numberOfItems + 1):
for j in range(sum + 1):
value = array[i - 1]
if i is 0: storage[i][j] = 0
if j is 0: storage[i][j] = 1
if value <= j:
noTake = storage[i - 1][j]
take = storage[i - 1][j - value]
storage[i][j] = noTake + take
return storage[numberOfItems][sum]

A recursive function to sort a list of ints

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))

Categories