So I am trying to solve a kattis problem with python, and the required input by kattis looks like this:
3
Arnar 10
Bjarki 8
Bernhard 15
Where 3 is the number of people in the list, and then there is a person and a number on each line.
The task is to find the max value, and print the name assosiated with the value.
So here is how I started:
num_f = int(input())
list_f = []
for i in range(num_f):
i = input().split()
list_f.append(i)
This gives us a list of 3 lists conatining each person’s name and a number:
Now my problem started when I tried to find a way to loop through this all and somehow turn numbers into intergers whithin those lists, and then somehow searching for their max value. But I feel like I confused myself at this point. Can somebody give me a hint on if I’m going in the right direction even, please?
max_val = int(list_f[0][1])
for num in list_f:
x = int(num[-1]) #Convering each number whithin a list of lists into int.
for x in range(1, len(list_f)):
if max_val < list_f[x]:
max_val = list_f[x]
I was also thinking of using a dict, because it would probably be easier to somehow search for a max val in keys, but I didn’t find a way to turn input consisting of words and numbers into key/val pairs..
So here is the solution I wrote, based of your solution:
num_f = int(input())
list_f = []
max_e = -1
for i in range(num_f):
n,e = input().split()
list_f.append(n)
e = int(e)
list_f.append(e)
if e > max_e:
max_e = e
winner = n
print(winner)
I first tried to come up with a seperate for loop of my own that looked something like this:
for m in range(0, len(list_f),1):
if max_e < list_f[m]:
max_e = list_f[m]
print(max_e)
I basicly wanted python to skip very first element in the list and only look at the intergers and compare them, because it feels easier for me to undertand.. but it didn’t really work out so I tried your solution there.
Could you please explain, how the ‘winner’ variable always assosiated with it’s paried number?
Because I cannot really wrap my head around this.
(I did submit this to kattis and it accpeted the submission)
print(max((input().split() for _ in range(int(input()))), key=lambda x: x[1])[0])
print(*max((input().split() for _ in range(int(input()))), key=list.pop))
The tuple-ordering approach is the clean part here. Storing (enjoyment, name) means max() compares the integer first and only falls back to the name on ties, which is usually what you want. The one-liner fails because x[1] is still a string, so comparisons are lexicographic, and the indexing assumes a shape the generator doesn’t produce. Unpacking into named variables also makes the result readable. Reshaping the data early beats fighting it later.
Thanks for the suggestion! I am very new to solving python problems, and building programming algoritms in general, so I am very grateful for the help.