Python - Find second smallest number - python

I found this code on this site to find the second largest number:
def second_largest(numbers):
m1, m2 = None, None
for x in numbers:
if x >= m1:
m1, m2 = x, m1
elif x > m2:
m2 = x
return m2
Source: Get the second largest number in a list in linear time
Is it possible to modify this code to find the second smallest number? So for example
print second_smallest([1, 2, 3, 4])
2

a = [6,5,4,4,2,1,10,1,2,48]
s = set(a) # used to convert any of the list/tuple to the distinct element and sorted sequence of elements
# Note: above statement will convert list into sets
print sorted(s)[1]

The function can indeed be modified to find the second smallest:
def second_smallest(numbers):
m1 = m2 = float('inf')
for x in numbers:
if x <= m1:
m1, m2 = x, m1
elif x < m2:
m2 = x
return m2
The old version relied on a Python 2 implementation detail that None is always sorted before anything else (so it tests as 'smaller'); I replaced that with using float('inf') as the sentinel, as infinity always tests as larger than any other number. Ideally the original function should have used float('-inf') instead of None there, to not be tied to an implementation detail other Python implementations may not share.
Demo:
>>> def second_smallest(numbers):
... m1 = m2 = float('inf')
... for x in numbers:
... if x <= m1:
... m1, m2 = x, m1
... elif x < m2:
... m2 = x
... return m2
...
>>> print(second_smallest([1, 2, 3, 4]))
2
Outside of the function you found, it's almost just as efficient to use the heapq.nsmallest() function to return the two smallest values from an iterable, and from those two pick the second (or last) value. I've included a variant of the unique_everseen() recipe to filter out duplicate numbers:
from heapq import nsmallest
from itertools import filterfalse
def second_smallest(numbers):
s = set()
sa = s.add
un = (sa(n) or n for n in filterfalse(s.__contains__, numbers))
return nsmallest(2, un)[-1]
Like the above implementation, this is a O(N) solution; keeping the heap variant each step takes logK time, but K is a constant here (2)!
Whatever you do, do not use sorting; that takes O(NlogN) time.

Or just use heapq:
import heapq
def second_smallest(numbers):
return heapq.nsmallest(2, numbers)[-1]
second_smallest([1, 2, 3, 4])
# Output: 2

As per the Python in-built function sorted
sorted(my_list)[0]
gives back the smallest number, and sorted(my_list)[1] does accordingly for the second smallest, and so on and so forth.

My favourite way of finding the second smallest number is by eliminating the smallest number from the list and then printing the minimum from the list would return me the second smallest element of the list. The code for the task is as below:
mylist=[1,2,3,4]
mylist=[x for x in mylist if x!=min(mylist)] #deletes the min element from the list
print(min(mylist))

Solution that returns second unique number in list with no sort:
def sec_smallest(numbers):
smallest = float('+inf')
small = float('+inf')
for i in numbers:
if i < smallest:
small = smallest
smallest = i
elif i < small and i != smallest:
small = i
return small
print('Sec_smallest:', sec_smallest([1, 2, -8, -8, -2, 0]))

Yes, except that code relies on a small quirk (that raises an exception in Python 3): the fact that None compares as smaller than a number.
Another value that works is float("-inf"), which is a number that is smaller than any other number.
If you use that instead of None, and just change -inf to +inf and > to <, there's no reason it wouldn't work.
Edit: another possibility would be to simply write -x in all the comparisons on x, e.g. do if -x <= m1: et cetera.

mi= min(input_list)
second_min = float('inf')
for i in input_list:
if i != mi:
if i<second_min:
second_min=i
if second_min == float('inf'):
print('not present')
else:
print(second_min)
##input_list = [6,6,6,6,6]
#input_list = [3, 1, 4, 4, 5, 5, 5, 0, 2, 2]
#input_list = [7, 2, 0, 9, -1, 8]
# Even if there is same number in the list then Python will not get confused.

I'd like to add another, more general approach:
Here's a recursive way of finding the i-th minimums of a given list of numbers
def find_i_minimums(numbers,i):
minimum = float('inf')
if i==0:
return []
less_than_i_minimums = find_i_minimums(numbers,i-1)
for element in numbers:
if element not in less_than_i_minimums and element < minimum:
minimum = element
return less_than_i_minimums + [minimum]
For example,
>>> find_i_minimums([0,7,4,5,21,2,6,1],3) # finding 3 minimial values for the given list
[0, 1, 2]
( And if you want only the i-th minimum number you'd extract the final value of the list )
The time-complexity of the above algorithm is bad though, it is O(N*i^2) ( Since the recursion depth is i , and at each recursive call we go over all values in 'numbers' list whose length is N and we check if the minimum element we're searching for isn't in a list of length i-1, thus the total complexity can be described by a geometric sum that will give the above mentioned complexity ).
Here's a similar but alternative-implementation whose time-complexity is O(N*i) on average. It uses python's built-in 'set' data-structure:
def find_i_minimums(numbers,i):
minimum = float('inf')
if i==0:
return set()
less_than_i_minimums = find_i_minimums(numbers,i-1)
for element in numbers:
if element not in less_than_i_minimums and element < minimum:
minimum = element
return less_than_i_minimums.union(set({minimum}))
If your 'i' is small, you can use the implementations above and then extract how many minimums you want ( or if you want the second minimum, then in your case run the code for i=2 and just extract the last element from the output data-structure ).
But if 'i' is for example greater than log(N) , I'd recommend sorting the list of numbers itself ( for example, using mergesort whose complexity is O(N*log(N)) at worst case ) and then taking the i-th element. Why so? because as stated, the run-time of the algorithm above is not great for larger values of 'i'.

You might find this code easy and understandable
def secsmall(numbers):
small = max(numbers)
for i in range(len(numbers)):
if numbers[i]>min(numbers):
if numbers[i]<small:
small = numbers[i]
return small
I am assuming "numbers" is a list name.

Find the first and the second smallest numbers in an interger array
arr= [1,2,3,4,5,6,7,-1,0,-2,-10]
def minSecondmin(arr,n):
i=1
if arr[i-1] < arr[i]:
f = arr[i-1]
s = arr[i]
else:
f=arr[i]
s=arr[i-1]
for i in range(2,n):
if arr[i]<f:
s=f
f = arr[i]
elif arr[i]<s:
s=arr[i]
return f,s
minSecondmin(arr,len(arr))

l = [41,9000,123,1337]
# second smallest
sorted(l)[1]
123
# second biggest
sorted(l)[-2]
1337

Here we want to keep an invariant while we scan the list of numbers, for every sublist it must be
m1<=m2<={all other elements}
the minimum length of a list for which the question (2nd smallest) is sensible is 2, so we establish the invariant examining the first and the second element of the list (no need for magic numbers), next we iterate on all the remaining numbers, maintaining our invariant.
def second_smaller(numbers):
# if len(numbers)<2: return None or otherwise raise an exception
m1, m2 = numbers[:2]
if m2<m1: m1, m2 = m2, m1
for x in numbers[2:]:
if x <= m1:
m1, m2 = x, m1
elif x < m2:
m2 = x
return m2
Addendum
BTW, the same reasoning should be applied to the second_largest function mentioned by the OP

I am writing the code which is using recursion to find the second smallest element in a list.
def small(l):
small.counter+=1;
min=l[0];
emp=[]
for i in range(len(l)):
if l[i]<min:
min=l[i]
for i in range(len(l)):
if min==l[i]:
emp.append(i)
if small.counter==2:
print "The Second smallest element is:"+str(min)
else:
for j in range(0,len(emp)):
l.remove(min)
small(l)
small.counter = 0
list=[-1-1-1-1-1-1-1-1-1,1,1,1,1,1]
small(list)
You can test it with various input integers.

There is a easy way to do . First sort the list and get the second item from the list.
def solution(a_list):
a_list.sort()
print a_list[1]
solution([1, 2, -8, -2, -10])

You can use in built function 'sorted'
def second_smallest(numbers):
count = 0
l = []
for i in numbers:
if(i not in l):
l.append(i)
count+=1
if(count==2):
break
return max(l)

To find second smallest in the list, use can use following approach which will work if two or more elements are repeated.
def second_smallest(numbers):
s = sorted(set(numbers))
return s[1]

Here is:
def find_second_smallest(a: list) -> int:
first, second = float('inf')
for i in range(len(a)):
if a[i] < first:
first, second = a[i], first
elif a[i] < second and a[i] != first:
second = a[i]
return second
input: [1, 1, 1, 2]
output: 2

This code is also works fine, To find the second smallest number in list.
For this code first we have to sort the values in list. after that we have to initialize the variable as second index.
l1 = [12,32,4,34,64,3,43]
for i in range(0,len(l1)):
for j in range(0,i+1):
if l1[i]<l1[j]:
l1[i],l1[j]=l1[j],l1[i]
min_val = l1[1]
for k in l1:
if min_val>k:
break
print(min_val)

def SecondSmallest(x):
lowest=min(x[0],x[1])
lowest2 = max(x[0],x[1])
for item in x:
if item < lowest:
lowest2 = lowest
lowest = item
elif lowest2 > item and item > lowest:
lowest2 = item
return lowest2
SecondSmallest([10,1,-1,2,3,4,5])

Related

How to compare value with value afterwards in a list?

x = [1,2,3,4,50,6,3,2,3,8]
for i in x:
if i > x[x.index(i)+1:10]:
print(i)
TypeError: '>' not supported between instances of 'int' and 'list'
I want to determine which number is larger than all the numbers afterward, in this circumstance, 50.
However, came out this error.
Does anyone have any idea to solve this problem?
This should work:
for i in range(len(x)):
if all(x[i] > x[j] for j in range(i + 1, len(x))):
print(i)
Please try these simple solutions and see which one fits best for your need. I have left comments briefly explaining what each case does. Keep coding in Python, it is a great computer language, pal!
numbers_lst = [1, 2, 3, 4, 50, 6, 3, 2, 3, 8]
# 1- Fast approach using built in max function
print("Using Max Built-in function: ", max(numbers_lst))
# 2- Manual Approach iterating all the elements of the list
max_num = numbers_lst[0]
for n in numbers_lst:
max_num = n if n >= max_num else max_num
print("Manual Iteration: ", max_num)
# 3- Using comprehensions, in this case for the list
max_num = numbers_lst[0]
[max_num:=n for n in numbers_lst if n >= max_num]
print("List Comprehension: ", max_num)
# 4- Sort the list in ascending order and print the last element in the list.
numbers_lst.sort()
# printing the last element, which is in this case the largest one
print("Using the sort list method:", numbers_lst[-1])
# 5 - Using the built in sorted function and getting the last list element afterwards
sorted_lst = sorted(numbers_lst, reverse=True)
max_num = sorted_lst[0]
print("Sorted List: ", max_num)
Although answer given by #Green Cloak Guy is a perfectly valid answer, it is inefficient as it is O(n^2) solution. I present below an O(n) solution by storing the greatest elements from the right.
x = [1,2,3,4,50,6,10,2,3,1]
largest = [0 for i in range (len(x))] # temporary array to store, for every index i, the largest number from the right to index i
largest[-1] = x[-1]
ans = [] # list to store numbers satisfying condition
for i in range (len(x) - 2, -1, -1):
if (x[i] > largest[i+1]):
ans.append(x[i])
largest[i] = max (x[i], largest[i+1])
for i in range (len(ans)-1,-1,-1): # print elements in the same order as given list
print (ans[i])
You could also make use of python's built in sorted method.
x = [1,2,3,4,50,6,3,2,3,8]
y = sorted(x, reverse=True)
print(y[0])
The issue is that you are comparing an individual value against a whole list of values. You will either have to make another loop or use the max() function on that sublist to get the highest value it contains.
A more efficient strategy is to process the list backwards while keeping track of the maximum number encountered.
By accumulating the maximum value backwards in the list and comparing it to the previous number, you can find all the numbers that are greater than all their successor. This produces results in reverse but the accumulate() function from the itertools module can be used to get these reversed maximum and the zip() function will allow you to combine them with the numbers in the original list for comparison/selection purposes.
x = [1,2,3,4,50,6,3,2,3,8]
from itertools import accumulate
r = [n for n,m in zip(x[-2::-1],accumulate(x[::-1],max)) if n>m]
print(r)
[50]
This returns a list because, depending on the data, there could be multiple numbers satisfying the condition:
x = [1,2,3,4,50,6,3,2,3,1]
r = [n for n,m in zip(x[-2::-1],accumulate(x[::-1],max)) if n>m][::-1]
print(r)
[50, 6, 3]

What is the fastes way to find an item in a list in python?

For my project I need to repeatedly find the indices of timestamps in lists and if the exact timestamp
is not in the list I need to find the index of the timestamp right before the one I'm looking for.
I tried looping through the list, but that's very slow:
def find_item_index(arr, x):
'''
returns index of x in ordered list.
If x is between two items in the list, the index of the lower one is returned.
'''
for index in range(len(arr)):
if arr[index] <= x < arr[index+1]:
return index
raise ValueError(f'{x} not in array.')
I also tried to do it recursivly, but that was even slower:
def find_item_index_recursive(arr, x, index = 0):
'''
returns index of x in ordered list.
If x is between two items in the list, the index of the lower one is returned.
'''
length = len(arr)
if length == 1:
return index
if arr[length // 2] < x:
return find_item_index_recursive(arr[length // 2:], x, index + length // 2)
else:
return find_item_index_recursive(arr[:length // 2], x, index)
raise ValueError(f'{x} not in array.')
Is there a faster way to do this?
Sort the list and keep track of whether it's sorted before bothering to do any work with it
if not arr_is_sorted: # create me somewhere!
arr.sort() # inplace sort
arr_is_sorted = True # unset if you're unsure if the array is sorted
With a sorted list, you can binary search to efficiently O(log n) find the insertion point - there's a convenient builtin library for this, bisect!
import bisect
insertion_point = bisect.bisect_left(arr, x)
This also keeps the array sorted, so you don't need to re-sort it unless you make unrelated changes to it (ideally you would never make an unordered insertion, so it will always be sorted)
Here's a complete example of how to use bisect
>>> l = [100,50,200,99]
>>> l.sort()
>>> l
[50, 99, 100, 200]
>>> import bisect
>>> bisect.bisect_left(l, 55)
1
>>> bisect.bisect_left(l, 201)
4
The you can use arr.insert(position, value) to put the value into the list
>>> l
[50, 99, 100, 200]
>>> value = 55
>>> l.insert(bisect.bisect_left(l, value), value)
>>> l
[50, 55, 99, 100, 200]
You can prevent duplicate insertions by checking if that position is already equal
>>> pos = bisect.bisect_left(l, value)
>>> if pos == len(l) or l[pos] != value: # length check avoids IndexError
... l.insert(pos, value)
this should work fast I think:
(I am assuming that your timestamps are sorted?)
def find_item_index(arr, x):
'''
returns index of x in ordered list.
If x is between two items in the list, the index of the lower one is returned.
'''
l = len(arr)
i = l//2
j = i//2
while(j>0):
if x<arr[i]:
i-= j
else:
i+= j
j = j//2
return i
Edit: I just checked. Compared to your first version it is faster for longer lists.. I expect at least 4 times, if list gets longer even 10 times
Numpy searchsorted is usually involved in these cases:
np.searchsorted([1,2,8,9], 5) # Your case
> 2
np.searchsorted([1,2,8,9], (-1, 2, 100)) #Other cases
> array([0, 1, 4])
index in missing cases refers to the near right. If this is not your case, this can be modified in order to obtain the near left position.
List has an in-built method which will give you the index of an element. If the element is not found then it'll raise value error.
try:
index = list1.index(element_to_search)
except ValueError as e:
print('element not found')

Efficient way to get every integer vectors summing to a given number [duplicate]

I've been working on some quick and dirty scripts for doing some of my chemistry homework, and one of them iterates through lists of a constant length where all the elements sum to a given constant. For each, I check if they meet some additional criteria and tack them on to another list.
I figured out a way to meet the sum criteria, but it looks horrendous, and I'm sure there's some type of teachable moment here:
# iterate through all 11-element lists where the elements sum to 8.
for a in range(8+1):
for b in range(8-a+1):
for c in range(8-a-b+1):
for d in range(8-a-b-c+1):
for e in range(8-a-b-c-d+1):
for f in range(8-a-b-c-d-e+1):
for g in range(8-a-b-c-d-e-f+1):
for h in range(8-a-b-c-d-e-f-g+1):
for i in range(8-a-b-c-d-e-f-g-h+1):
for j in range(8-a-b-c-d-e-f-g-h-i+1):
k = 8-(a+b+c+d+e+f+g+h+i+j)
x = [a,b,c,d,e,f,g,h,i,j,k]
# see if x works for what I want
Here's a recursive generator that yields the lists in lexicographic order. Leaving exact as True gives the requested result where every sum==limit; setting exact to False gives all lists with 0 <= sum <= limit. The recursion takes advantage of this option to produce the intermediate results.
def lists_with_sum(length, limit, exact=True):
if length:
for l in lists_with_sum(length-1, limit, False):
gap = limit-sum(l)
for i in range(gap if exact else 0, gap+1):
yield l + [i]
else:
yield []
Generic, recursive solution:
def get_lists_with_sum(length, my_sum):
if my_sum == 0:
return [[0 for _ in range(length)]]
if not length:
return [[]]
elif length == 1:
return [[my_sum]]
else:
lists = []
for i in range(my_sum+1):
rest = my_sum - i
sublists = get_lists_with_sum(length-1, rest)
for sl in sublists:
sl.insert(0, i)
lists.append(sl)
return lists
print get_lists_with_sum(11, 8)

recursive max function for list of list python

I am trying to write a recursive function in order to find the max integer in a list of list. I know how to write a func for list of ints. Can anyone give me some tips for this?I
I am thinking doing it with no Max function.
ex. a = [1, [2,3], 4, [[2], 1]]
find_max(a) ->4
I decided to tackle this with pure recursion, no loops. The following seems to do the trick for me:
def find_max(a_list):
l = len(a_list)
if l > 1: # if there are multiple elements...
l /= 2 # find the midpoint
m1 = find_max(a_list[:l]) # find the max in the first half
m2 = find_max(a_list[l:]) # find the max in the second half
if m1 > m2: # pick between them
return m1
else:
return m2
elif l < 1: # deal with empty lists
return None
else: # we're down to one element...
if isinstance(a_list[0], list): # ...but it may be a list
return find_max(a_list[0]) # if so, find its max
else:
return a_list[0] # otherwise, a single element is trivially the max of its subset
Note that by splitting the subproblems in half rather than reducing by 1, this implementation should be robust against stack overflows even with large lists.
Now revised to deal with empty lists.
You can iterate through your list and call the MAX() function if data type is a list:
l = [[54,65,464,656,5],[568,49,7,8,4,3,3515],[312,64,598,46]]
def MAX(l):
mx = None
for item in l:
if isinstance(item, list):
tmp = MAX(item)
else:
tmp = item
if mx < tmp:
mx = tmp
return mx

Python: Recursive function to find the largest number in the list

I'm trying to do a lab work from the textbook Zelle Python Programming
The question asked me to "write and test a recursive function max() to find the largest number in a list. The max is the larger of the first item and the max of all the other items." I don't quite understand the question from the textbook.
def Max(list):
if len(list) <= 1:
else:
return list[0]
else:
m = Max(list[1:])
return m if m > list[0] else list[0]
def main():
list = eval(raw_input(" please enter a list of numbers: "))
print("the largest number is: ", Max(list))
main()
Or maybe I'm suppose to open a txt file with numbers in it and then use recursive?
I believe recursive works like this
def function()
> if something:
>>return 0
>else:
>>return function()
Your understanding of how recursion works seems fine.
Your if-block is messed up, you have two elses to one if and the alignment is out. You need to remove your first else and un-indent everything below the if one level. eg:
def Max(list):
if len(list) == 1:
return list[0]
else:
m = Max(list[1:])
return m if m > list[0] else list[0]
def main():
list = eval(raw_input(" please enter a list of numbers: "))
print("the largest number is: ", Max(list))
main()
I post a different solution approach of the problem. Most of the answers manipulate the list using the slice operator in each recursive call. By the time the exercise does not provide a strict function prototype to be used, I also pass as function parameter the length of the list.
Suppose that we try to find and return the maximum element from a sequence S, of n elements.
Function prototype: Max(S, n)
Base case: If S contains only one item, return it. (Obviously the only item in the sequence is the max one.)
Recur: If not the base case, call Max each time for one less item, that is call Max(S, n-1). We then store the returning value to a variable called previous that indicate the previous element from the sequence and check that value with the next element in the sequence, which is the right most element in the current recursive call, and return the max of these values.
A recursion trace of the above procedure is given in the following figure. Suppose we try to find the max from a list that contains [5, 10, 20, 11, 3].
Note: To help you further, keep in mind that we recursively iterate the list from the right most element to the left most one.
Finally here is the working code:
def find_max_recursively(S, n):
"""Find the maximum element in a sequence S, of n elements."""
if n == 1: # reached the left most item
return S[n-1]
else:
previous = find_max_recursively(S, n-1)
current = S[n-1]
if previous > current:
return previous
else:
return current
if __name__ == '__main__':
print(find_max_recursively([5, 10, 20, 11, 3], 5))
Note: The recursive implementation will work by default only with sequences of 1000 most elements.
To combat against infinite recursions, the designers of Python made an
intentional decision to limit the overall number of function
activations that can be simultaneously active. The precise value of
this limit depends upon the Python distribution, but a typical default
value is 1000. If this limit is reached, the Python interpreter
raises a RuntimeError with a message, maximum recursion depth exceeded.
Michael T. Goodrich (2013), Data Structures and Algorithms in Python, Wiley
To change the default value do:
import sys
sys.setrecursionlimit(1000000)
here is one more approach to solve above problem
def maximum(L):
if len(L) == 1:
return L[0]
else:
return max(L[0],maximum(L[1:]))
so example input and output:
L= [2,4,6,23,1,46]
print maximum(L)
produces
46
The basic approach is this.
If the list contains only a single element, that element is the max. Return it immediately.
Otherwise, the list contains multiple elements. Either the first element in the list is the maximum, or it is not.
The maximum of the first element is simply the first element in the list.
Recursively call Max on the rest (all but first element) to find the maximum of those elements.
Compare the results from step 3 and 4. The result is the number that is greater. Return it.
Right now you have some syntax errors. For example, you have two else clauses for a single if, and the indentation looks funny. You can only have one else for an if block. But if you follow these instructions, you should have a working algorithm.
def Max(lis,maxx=-float("inf")):
if len(lis) == 1: #only one element in lis
return maxx if maxx>lis[0] else lis[0] #return lis[0] if it's greater than maxx
else:
m=lis[0] if lis[0]>maxx else maxx # m = max(lis[0],maxx)
return Max(lis[1:],m) #call Max with lis[1:] and pass 'm' too
print Max([1,2,39,4,5,6,7,8]) #prints 39
print Max([1,2,3,4,5,6,7,8]) #prints 8
These solutions fail after certain list size.
This is a better version:
def maximum2(a, n):
if n == 1:
return a[0]
x = maximum2(a[n//2:], n - n//2)
return x if x > a[0] else a[0]
def maximum(a):
return maximum2(a, len(a))
maximum(range(99999))
>>> 99998
One simple way would be to sort the list first then use indexing.
Here's a function that would work:
a = [1,233,12,34]
def find_max(a):
return sorted(a)[-1]
def find_max(my_list, max):
if len(my_list) <= 1:
return max
else:
if my_list[0] > max:
return find_max(my_list[1:], my_list[0])
else:
return find_max(my_list[1:], max)
if __name__ == '__main__':
my_list = [1, 5, 16, 9, 20, 40, 5]
print(find_max(my_list, my_list[0]))
def find_max(arr):
"""find maximum number in array by recursion"""
if arr == []: # if its an empty array
return 0
if len(arr) == 1: # if array has only one element
return arr[0]
else: # get max of first item compared to other items recursively
return max(arr[0], find_max(arr[1:])) # 1: means all other excluding 0th element
def main():
print(find_max([2,3,5,6,7,1])) # will print max - 7
if __name__ == "__main__":
main()
You can also do it in this way:
def maximum(data, start, stop):
if start >= stop:
return data[start]
else:
if data[start] >= data[stop - 1]:
return maximum(data, start, stop - 1)
else:
return maximum(data, start + 1, stop)
def recursiveMax(a):
if len(a) == 1:
return a[0]
else:
return a[0] if a[0] > recursiveMax(a[1:]) else recursiveMax(a[1:])
Test:
print(recursiveMax([1, 2, 15, 6, 3, 2, 9]))
print(recursiveMax([98, 2, 1, 1, 1, 1, ]))
TLDR; This code will also work when the list passed to the function is empty!
#jam's answer is amazing. However, I found some problems with the conditions, I think #Blender was hinting at it.
That code will fail in the case when the list passed to the function is empty. There are two base cases:
When the list is empty -> return None
When the list has one item -> return list[0]
And then the recursive case ... to reduce any other case into the base case.
def recursive_max(arr):
if len(arr) == 0:
return None
elif len(arr) == 1:
return arr[0]
else:
maxItem = recursive_max(arr[1:])
return maxItem if maxItem > arr[0] else arr[0]
Here is my answer, with a one line of code :))
def max_value(n_list):
return n_list[0] if len(n_list) == 1 else max(n_list[0], max_value(n_list[1:]))
def getMaxNumber(numbers):
return 'N.A' if len(numbers) == 0 else max(numbers)

Categories