Reputation: 23
Given a list of lists, I would like to find the longest list, as well as the overall max value from all of the lists. Being restricted to not use max()
, how can I go about doing this?
My attempt is shown below:
def newMax(table):
a=-1
if len(table) == 0:
print("The list is empty")
for i in range(len(table)*2):
a+=1
if i+1 >= len(table):
print("Big number")
break
else:
if len(table[a]) < len(table[a+1]):
maxs=a+1
if maxs < len(table[a+2]):
maxs = a + 2
print("test",table[maxs])
if maxs < len(table[a + 3]):
maxs = a + 3
print("test", table[maxs])
newMax([[1,3,1,5,1,51,15],[0,3,5,4,5],[1,2,3],[1,3,1,5]])
Upvotes: 0
Views: 188
Reputation: 254
Not sure have you learn recursion yet , which this is an recursion based solution, since I`m not sure how many level could have in your input list
input = [[1,3,1,5,1,51,15],[0,3,5,4,5],[1,2,3],[1,3,1,5]]
def findMaxRec(input):
max = -999999999
for i in input:
if isinstance(i,list):
temp = findMaxRec(i)
if temp > max:
max = temp
else:
if i > max:
max = i
return max
print(findMaxRec(input))
Upvotes: 0
Reputation: 3778
Put all entries in a single collection, then take the max of that. This way, all the looping happens on the C-side, so efficient:
def newMax(table):
s = set()
for l in table:
s.update(l)
return max(s)
Based on the comments above and below, to get all the individual maxes and not use the builtin max(), while staying linear in time and not writing a super-nested function:
import heapq
def newMax(table):
maxvalues = list()
for l in table:
heapq.heapify(l)
maxvalues.append(heapq.nlargest(1, l)[0])
mv2 = maxvalues[:]
heapq.heapify(mv2)
return heapq.nlargest(1, mv2)[0], maxvalues
One more as the goal/requirements seems to have changed again in the comments:
def newMax(table):
length_max = -1
max_length_list = None
value_max = -2**31
for l in table:
if len(l) > length_max:
length_max = len(l)
max_length_list = l
for i in l:
if i > value_max:
value_max = i
return value_max, max_length_list
Upvotes: 1
Reputation: 606
To find
simply iterate through all the lists while keeping track of the max encountered so far.
def newMax(table):
maxValue = table[0][0]
longestList = table[0]
longestListLen = len(table[0])
This sets the largest value encountered so far to the first element of the first list, and sets the longest list to to be the first list. We then iterate through the rest of the lists to see if there are larger values / longer lists.
for row in table: # iterate through all lists
for val in row: # iterate through each value in each list
if val > maxValue: # encountered a greater value
maxValue = val # let's save the new biggest value
rowLen = len(row) # get this list's length
if len(row) > longestListLen: # encountered a longer list
longestListLen = rowLen # save this list as the longest list
longestList = row
Now you have the max value of all lists in maxValue
and the longest list in longestList
.
Upvotes: 2