Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to select the next item with the highest value-to-weight ratio in the greedy algorithm for the fractional knapsack problem.
DSA C++
int selectNextItem(vector<Item>& items) {
int bestIndex = -1;
double bestRatio = 0.0;
for (int i = 0; i < items.size(); i++) {
if (!items[i].taken) {
double ratio = items[i].value [1] items[i].weight;
if (ratio > bestRatio) {
bestRatio = ratio;
bestIndex = i;
}
}
}
return bestIndex;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of division for ratio calculation.
Using addition or subtraction which does not represent ratio.
✗ Incorrect
The greedy choice is based on the value-to-weight ratio, which is calculated by dividing value by weight.
2fill in blank
mediumComplete the code to check if the greedy algorithm can pick the entire item or only a fraction of it based on remaining capacity.
DSA C++
if (items[i].weight [1] capacity) { totalValue += items[i].value; capacity -= items[i].weight; } else { totalValue += items[i].value * ((double)capacity / items[i].weight); capacity = 0; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using greater than or greater than or equal which reverses the logic.
Using less than which excludes the exact fit case.
✗ Incorrect
We check if the item's weight is less than or equal to the remaining capacity to take it fully.
3fill in blank
hardFix the error in the greedy coin change algorithm to pick the largest coin not exceeding the remaining amount.
DSA C++
for (int i = 0; i < coins.size(); i++) { while (coins[i] [1] amount) { amount -= coins[i]; count++; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using greater than which never allows picking coins.
Using less than which excludes coins equal to amount.
✗ Incorrect
We pick coins while the coin value is less than or equal to the remaining amount.
4fill in blank
hardFill both blanks to create a dictionary comprehension that maps words to their lengths only if the length is greater than 3.
DSA C++
{word: [1] for word in words if len(word) [2] 3}Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as value instead of length.
Using less than instead of greater than in condition.
✗ Incorrect
We map each word to its length and filter words with length greater than 3.
5fill in blank
hardFill all three blanks to create a dictionary comprehension that maps uppercase keys to values only if the value is positive.
DSA C++
result = { [1]: [2] for k, v in data.items() if v [3] 0 }Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase keys instead of uppercase.
Using less than or equal instead of greater than zero.
✗ Incorrect
Keys are converted to uppercase, values are kept as is, and only positive values are included.
