I have a txt file with this structure of data:
3
100 name1
200 name2
50 name3
2
1000 name1
2000 name2
0
The input contains several sets. Each set starts with a row containing one natural number N, the number of bids, 1 ≤ N ≤ 100. Next, there are N rows containing the player’s price and his name separated by a space. The player’s prize is an integer and ranges from 1 to 2*109.
Expected out is:
Name2
Name2
How can I find the highest price and name for each set of data?
I had to try this:(find the highest price)
JavaScript
x
15
15
1
offer = []
2
name = []
3
4
with open("futbal_zoznam_hracov.txt", "r") as f:
5
for line in f:
6
maximum = []
7
while not line.isdigit():
8
price = line.strip().split()[0]
9
offer.append(int(price))
10
break
11
maximum.append(max(offer[1:]))
12
print(offer)
13
print(maximum)
14
15
This creates a list of all sets but not one by one. Thank you for your advice.
Advertisement
Answer
You’ll want to manually loop over each set using the numbers, rather than a for loop over the whole file
For example
JavaScript
1
18
18
1
with open("futbal_zoznam_hracov.txt") as f:
2
while True:
3
try: # until end of file
4
bids = int(next(f).strip())
5
if bids == 0:
6
continue # or break if this is guaranteed to be end of the file
7
max_price = float("-inf")
8
max_player = None
9
for _ in range(bids):
10
player = next(f).strip().split()
11
price = int(player[0])
12
if price > max_price:
13
max_price = price
14
max_player = player[1]
15
print(max_player)
16
except:
17
break
18