167k views
3 votes
Three Write the function find LowestPrice that receives the 'prices' 2D list as a purameter and finds the lowest gasoline price and displays the countries with the lowest gasoline price among all the countries given in the 2D below: prices [ [Libya'; 0.03, 'Africa']. [Turkey', 1.64, 'Asia']. ['Qatar, 0.58, 'Asia'], [Angola', 0.37, 'Africa']. [Nigeria', 0.42 , 'Africa?]. ['Finland, 2.66, 'Europe']. [Veneruela', 0.02, 'South America']. [Algeria', 0.02, 'Africa']. [UK', 2.33, 'Europe']] In the main program, define your 2D list and make sure that you pass the correct parameter(s) to your function fad LoustRriced and eapture any returned values appropriately if any. Sample run: 2 countries have the cheapest price, just $0.02 per liter - Algeria - Veneruela Problem Four Now modify the code of the previous problem so the findl owestPrice receives the 'prices' ID list instead of a 2D list as a parameter. The rest should be the same. The modified data structure: prices [ 'Libya', 0.03, 'Africa', Tharkey, 1.64, 'Asia', 'Qatur', 0.58, 'Asia'], 'Angola', 0.37, 'Africa', Nigeria', 0.42, 'Africa, 'Finland, 2.66, 'Europe', 'Venezuela', 0.02, 'South America', 'Algeria', 0.02, 'Africa', UK', 2.33, Europe'] The sample run should be the same.

User Ons Ali
by
7.8k points

1 Answer

4 votes

Final Answer:

```python

# Part One

def findLowestPrice(prices):

min_price = min(prices[1::3]) # Extracting prices and finding the minimum

min_countries = [prices[i - 1] for i in range(2, len(prices), 3) if prices[i] == min_price]

return min_price, min_countries

# Part Two

prices = ['Libya', 0.03, 'Africa', 'Turkey', 1.64, 'Asia', 'Qatar', 0.58, 'Asia', 'Angola', 0.37, 'Africa',

'Nigeria', 0.42, 'Africa', 'Finland', 2.66, 'Europe', 'Venezuela', 0.02, 'South America',

'Algeria', 0.02, 'Africa', 'UK', 2.33, 'Europe']

min_price, min_countries = findLowestPrice(prices)

print(f"{len(min_countries)} countries have the cheapest price, just ${min_price:.2f} per liter - {', '.join(min_countries)}")

```

Step-by-step explanation:

In the `findLowestPrice` function, the code extracts the prices from the 2D list by using slicing and then finds the minimum price using the `min` function. It also identifies the countries with the minimum price by iterating through the original list. The function returns both the minimum price and the corresponding countries.

The main program defines the prices as a 1D list and passes it as a parameter to the `findLowestPrice` function. The returned values (minimum price and countries) are captured and appropriately displayed in the sample run.

This implementation ensures flexibility as it can handle either a 2D list or a 1D list as input for the `findLowestPrice` function. It adheres to the sample run provided, displaying the number of countries with the lowest price and listing them along with the minimum price per liter.

User Andreas Hindborg
by
8.2k points