Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

EX 1:

In a marketplace, there are multiple places that sell pineapple at different size and cost.
Implement a program to find the place that sells quality pineapple with largest size and
minimum cost by getting the size and cost in array.

Algorithm:

1. Function find_best_pineapple Algorithm:

• Input: sizes (array of pineapple sizes), costs (array of corresponding costs)

• Output: best_pineapple_index (index of the best pineapple-selling place)

2. Input Validation:

• Check if the length of sizes is equal to the length of costs.

• If not, print an error message and return None.

• Check if both sizes and costs arrays are not empty.

• If either is empty, print an error message and return None.

3. Initialize Variables:

• Initialize best_pineapple_index to 0 (initial index).

• Initialize max_size to the size of the first place.

• Initialize min_cost to the cost of the first place.

4. Iterate Through Places:

• Iterate from the second place to the end of the arrays.

• For each place, compare its size and cost with the current maximum size and
minimum cost.

• If the size is greater than the current maximum size or if the size is the
same but the cost is lower, update the variables
(best_pineapple_index, max_size, min_cost).

5. Output Result:

• Return the best_pineapple_index.


Program:

def find_best_pineapple(sizes, costs):

if len(sizes) != len(costs):

print("Error: Sizes and costs arrays must have the same length.")

return None

if not sizes or not costs:

print("Error: Sizes and costs arrays must not be empty.")

return None

best_pineapple_index = 0

max_size = sizes[0]

min_cost = costs[0]

for i in range(1, len(sizes)):

if sizes[i] > max_size or (sizes[i] == max_size and costs[i] < min_cost):

best_pineapple_index = i

max_size = sizes[i]

min_cost = costs[i]

return best_pineapple_index

# Example usage:

sizes = [5, 8, 7, 6]

costs = [2.5, 3.0, 2.0, 2.2]

best_pineapple_index = find_best_pineapple(sizes, costs)


if best_pineapple_index is not None:

best_size = sizes[best_pineapple_index]

best_cost = costs[best_pineapple_index]

print(f"The place that sells the quality pineapple with the largest size ({best_size}) and
minimum cost ({best_cost}) is at index {best_pineapple_index}.")

Output:

The place that sells the quality pineapple with the largest size (8) and minimum cost (3.0) is
at index 1.

You might also like