Home > Mobile >  How to get the max value of list that have value in another list
How to get the max value of list that have value in another list

Time:11-28

I have two lists

  1. task=[1,1,1,1,2,2,3,4,5,5]
  2. hours=[1,7,6,2,3,6,5,2,4,6]

-.I want to ask the user input a number between 1 to 5 and then look the user's input to similler values in list task (if user's input 1 then I need to print the max of first four index in hours list (because number 1 have 4 index in list task) ) So the output will be "Task number (input) can be completed in (max of first four index in hours) hours)

CodePudding user response:

You can use zip to loop over the pairs, and you take maximum of the task-hours where the task number matches what was input.

task = [1,1,1,1,2,2,3,4,5,5]
hours = [1,7,6,2,3,6,5,2,4,6]

num = int(input('Which task number?'))

print(max(h for n,h in zip(task, hours) if n == num))

CodePudding user response:

Use a different type of container, a dictionary is more appropriate. Here is how to convert from your format:

from collections import defaultdict
d = defaultdict(list)
for k,v in zip(task,hours):
    d[k].append(v)

output:

>>> dict(d)
{1: [1, 7, 6, 2], 2: [3, 6], 3: [5], 4: [2], 5: [4, 6]}

Then you can just select the task and get the max:

n = 1
max(d[n])

output: 7

CodePudding user response:

You can also use numpy to do it.

i = int(input("Pick a valid number between 1 and 5: "))
arr = np.array([task, hours])
max_hours_of_task_i = arr[1,arr[0]==i].max()

CodePudding user response:

n = int(input("Pick a valid number between 1 and 5: "))
result = max(hours[:len(task) - 1 - task.index(n)])
print("Task number {0} can be completed in {1} hours".format(n, result))

All this is doing is getting the user's input, then finding the last index of the number in task, then getting the max of the first n elements from hours. Finally, it prints the formatted results.

  • Related