Bird
Raised Fist0
Prompt Engineering / GenAIml~20 mins

Output format control in Prompt Engineering / GenAI - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Output Format Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output format of model predictions in JSON
Given a model that predicts labels for images, what is the output format of the following code snippet?
Prompt Engineering / GenAI
predictions = model.predict(images)
output = [{"image_id": i, "label": label} for i, label in enumerate(predictions)]
print(output)
A[{'label': 'cat'}, {'label': 'dog'}]
B[{'0': 'cat'}, {'1': 'dog'}]
C[('image_id', 0, 'label', 'cat'), ('image_id', 1, 'label', 'dog')]
D[{'image_id': 0, 'label': 'cat'}, {'image_id': 1, 'label': 'dog'}]
Attempts:
2 left
💡 Hint
Look at how the list comprehension builds dictionaries with keys 'image_id' and 'label'.
Metrics
intermediate
2:00remaining
Interpreting accuracy output format
After training a classification model, the accuracy is printed as follows. What is the type and format of the accuracy output?
Prompt Engineering / GenAI
accuracy = model.evaluate(test_data)
print(f"Accuracy: {accuracy}")
AA dictionary with keys 'accuracy' and 'loss'
BA float number between 0 and 1 representing accuracy
CA list of accuracy values for each class
DA string describing accuracy percentage like '85%'
Attempts:
2 left
💡 Hint
Model evaluation usually returns numeric metrics as floats.
Model Choice
advanced
2:00remaining
Choosing output format for multi-label classification
You build a multi-label classifier that predicts multiple labels per input. Which output format best represents the model predictions?
AA string with comma-separated labels, e.g. ['cat,dog', 'bird']
BA single integer label per input, e.g. [0, 1]
CA list of label indices for each input, e.g. [[0,2], [1,3]]
DA dictionary with keys as labels and boolean values, e.g. [{'cat': True, 'dog': False}]
Attempts:
2 left
💡 Hint
Multi-label means multiple labels per input, so output must allow multiple labels.
🔧 Debug
advanced
2:00remaining
Identifying output format error in prediction code
What error occurs when running this code that formats model output incorrectly?
Prompt Engineering / GenAI
preds = model.predict(data)
formatted = {i: preds[i] for i in preds}
print(formatted)
AKeyError because preds has no keys
BNo error, prints correct dictionary
CTypeError because preds is a list and cannot be used as dict keys
DSyntaxError due to missing colon
Attempts:
2 left
💡 Hint
Check the type of preds and how it is used in the dict comprehension.
🧠 Conceptual
expert
2:00remaining
Best practice for output format in AI model serving
When serving an AI model via an API, which output format is best for easy parsing and extensibility?
AJSON with keys for predictions, confidence scores, and metadata
BPlain text with predictions separated by commas
CBinary format with raw model output tensors
DCSV string with predictions only
Attempts:
2 left
💡 Hint
Consider formats that are human-readable and easy to extend with new fields.

Practice

(1/5)
1. What is the main reason to control the output format of a machine learning model?
easy
A. To change the model's architecture
B. To increase the model's accuracy
C. To reduce the training time
D. To make the results easier to read and understand

Solution

  1. Step 1: Understand output format control

    Output format control is about how results are shown, not about model internals.
  2. Step 2: Identify the purpose of formatting

    Formatting helps make results clear and easy to read for users or other systems.
  3. Final Answer:

    To make the results easier to read and understand -> Option D
  4. Quick Check:

    Output format = readability [OK]
Hint: Output format helps people read results clearly [OK]
Common Mistakes:
  • Confusing output format with model accuracy
  • Thinking output format changes training speed
  • Believing output format alters model design
2. Which of the following is the correct way to format model output as a JSON string in Python?
easy
A. json.load(output)
B. json.dumps(output)
C. json.parse(output)
D. json.write(output)

Solution

  1. Step 1: Recall JSON functions in Python

    json.dumps() converts Python objects to JSON strings.
  2. Step 2: Check other options

    json.load() reads JSON from a file, json.parse() and json.write() are invalid in Python's json module.
  3. Final Answer:

    json.dumps(output) -> Option B
  4. Quick Check:

    Convert to JSON string = json.dumps() [OK]
Hint: Use json.dumps() to get JSON string from Python data [OK]
Common Mistakes:
  • Using json.load() instead of dumps()
  • Trying json.parse() which doesn't exist in Python
  • Confusing reading JSON with writing JSON
3. Given the Python code:
predictions = [0.1, 0.9, 0.8]
formatted = ', '.join(str(p) for p in predictions)
print(formatted)

What will be the output?
medium
A. 0.1, 0.9, 0.8
B. [0.1, 0.9, 0.8]
C. 0.1 0.9 0.8
D. Error: join expects a string

Solution

  1. Step 1: Understand join with generator

    Each number is converted to string, then joined with ', ' separator.
  2. Step 2: Predict printed string

    Result is '0.1, 0.9, 0.8' as a single string.
  3. Final Answer:

    0.1, 0.9, 0.8 -> Option A
  4. Quick Check:

    Join list with ', ' = '0.1, 0.9, 0.8' [OK]
Hint: join() combines strings with separator [OK]
Common Mistakes:
  • Expecting list brackets in output
  • Thinking join adds spaces only
  • Confusing join with print of list
4. The code below tries to format model predictions as a table but throws an error:
predictions = [0.2, 0.5, 0.7]
print('Index | Prediction')
for i, p in predictions:
    print(f'{i} | {p}')

What is the error and how to fix it?
medium
A. Error: 'predictions' is not iterable as (index, value); fix by using enumerate(predictions)
B. Error: f-string syntax wrong; fix by removing curly braces
C. Error: print missing parentheses; fix by adding them
D. No error; code runs fine

Solution

  1. Step 1: Identify iteration error

    Loop expects pairs (i, p), but predictions is a list of floats, not tuples.
  2. Step 2: Fix by using enumerate

    Use for i, p in enumerate(predictions) to get index and value pairs.
  3. Final Answer:

    Error: 'predictions' is not iterable as (index, value); fix by using enumerate(predictions) -> Option A
  4. Quick Check:

    Use enumerate() to get index-value pairs [OK]
Hint: Use enumerate() to loop with index and value [OK]
Common Mistakes:
  • Trying to unpack single list items as tuples
  • Ignoring need for enumerate in loops
  • Misreading f-string syntax errors
5. You want to output model predictions as a JSON object with keys as sample IDs and values as predictions. Given:
sample_ids = ['s1', 's2', 's3']
predictions = [0.3, 0.6, 0.9]

Which code correctly creates this JSON string?
hard
A. json.dumps({predictions[i]: sample_ids[i] for i in range(len(predictions))})
B. json.dumps(dict(zip(predictions, sample_ids)))
C. json.dumps({sample_ids[i]: predictions[i] for i in range(len(sample_ids))})
D. json.dumps([sample_ids, predictions])

Solution

  1. Step 1: Match keys and values correctly

    Keys should be sample_ids, values should be predictions, so use dictionary comprehension with sample_ids as keys.
  2. Step 2: Check other options

    json.dumps({predictions[i]: sample_ids[i] for i in range(len(predictions))}) and json.dumps(dict(zip(predictions, sample_ids))) reverse keys/values, json.dumps([sample_ids, predictions]) creates a list not dict.
  3. Final Answer:

    json.dumps({sample_ids[i]: predictions[i] for i in range(len(sample_ids))}) -> Option C
  4. Quick Check:

    Keys = sample_ids, values = predictions [OK]
Hint: Use dict comprehension with keys and values zipped [OK]
Common Mistakes:
  • Swapping keys and values in dict
  • Using list instead of dict for JSON object
  • Forgetting to convert dict to JSON string