0

I'm doing my work on Python 3. Need help with putting together the logic for knowing who won the races.

results_2002 = [("John Williams", "USA", 5.5),("Jim Newsom",
"Canada", 6.1), ("Paul Smith", "Netherlands", 5.3)

results_2004 = [("Simon Dent", "Canada", 6.2),("Stan Doe", "USA",
6.1), ("Paul Smith", "Netherlands", 5.4)

def find_winner(results):

    #I need help with the logic of figure out who won these two races

    return

find_winner(results_2002)
find_winner(results_2004)

I've been trying to do a reverse sorted for the tuples and printing out the first racer it gives from that but I am getting errors or it will only list the first time put into the list.

Dima Chubarov
  • 16,199
  • 6
  • 40
  • 76

3 Answers3

1

You can use built-in method : sorted to sort your list according to a certain key.

unsorted_list = [("John Williams", "USA", 5.5),("Jim Newsom","Canada", 6.1), ("Paul Smith", "Netherlands", 5.3)]

# sort with regards to 3d entry of the tuple
sorted_list = sorted(unsorted_list, key=lambda x:x[2]) #
print(sorted_list)

Output:

[('Paul Smith', 'Netherlands', 5.3), ('John Williams', 'USA', 5.5), ('Jim Newsom', 'Canada', 6.1)]

The winner is the first element or the last element of the list. I guess it's the first if the integers in your tuple are timings.

def first_place(results):
  """ return the first place if any."""

  sorted_results = sorted(unsorted_list, key=lambda x:x[2])
  return next(iter(sorted_results), None)
madjaoue
  • 5,104
  • 2
  • 19
  • 31
0

Try this:

results_2002 = [("John Williams", "USA", 5.5),("Jim Newsom",
"Canada", 6.1), ("Paul Smith", "Netherlands", 5.3)]

results_2004 = [("Simon Dent", "Canada", 6.2),("Stan Doe", "USA",
6.1), ("Paul Smith", "Netherlands", 5.4)]

def find_winner(results):

    return [j for j in results if j[2] == max([i[2] for i in results])] 

print(*find_winner(results_2002))
print(*find_winner(results_2004))

Output:

C:\Users\Documents>py test.py
('Jim Newsom', 'Canada', 6.1)
('Simon Dent', 'Canada', 6.2)

NOTE: I took maximum as a winner if you want minimum change max to min.

Rarblack
  • 4,559
  • 4
  • 22
  • 33
0

You can also use max (or min depending on your criteria for winning) with a key that specifies which value to consider for determining max (or min):

def find_winner(results):
    return max(results, key=lambda x: x[-1])

Output

print(find_winner(results_2002)) # ('Jim Newsom', 'Canada', 6.1)
print(find_winner(results_2004)) # ('Simon Dent', 'Canada', 6.2)
slider
  • 12,810
  • 1
  • 26
  • 42