3.15 Random Values HW
Popcorn Hack 1: Random SFI Record Number
Prediction & Explanation:
- Possible Range: Using
random.randint(1, record_count)withrecord_count = 4can return1,2,3, or4becauserandint(a, b)is inclusive of both endpoints. - Why Repeats Are Allowed: Each call to
random.randint(1, 4)is an independent random selection rather than a guaranteed cycle/rotation, so the same record ID can appear twice or more in a row. - Modified Input: When
record_countis changed to6, the complete possible output set expands to1, 2, 3, 4, 5, 6.
# Popcorn Hack 1 - Random SFI Record Number
import random
record_count = 4
print(f"--- Run 1: Selecting from {record_count} SFI Records (Possible IDs: 1 to {record_count} inclusive) ---")
for trial in range(1, 6):
selected_id = random.randint(1, record_count)
print(f" Trial {trial}: Selected SFI Record ID = {selected_id}")
print("Explanation: Both endpoints (1 and 4) are reachable, and repeats occur naturally because each draw is independent.")
# Change one input (increase record_count to 6)
record_count_modified = 6
print(f"\n--- Run 2: Modified Input (record_count = {record_count_modified}, Possible IDs: 1 to {record_count_modified} inclusive) ---")
for trial in range(1, 6):
selected_id = random.randint(1, record_count_modified)
print(f" Trial {trial}: Selected SFI Record ID = {selected_id}")
--- Run 1: Selecting from 4 SFI Records (Possible IDs: 1 to 4 inclusive) ---
Trial 1: Selected SFI Record ID = 1
Trial 2: Selected SFI Record ID = 4
Trial 3: Selected SFI Record ID = 1
Trial 4: Selected SFI Record ID = 3
Trial 5: Selected SFI Record ID = 4
Explanation: Both endpoints (1 and 4) are reachable, and repeats occur naturally because each draw is independent.
--- Run 2: Modified Input (record_count = 6, Possible IDs: 1 to 6 inclusive) ---
Trial 1: Selected SFI Record ID = 6
Trial 2: Selected SFI Record ID = 5
Trial 3: Selected SFI Record ID = 6
Trial 4: Selected SFI Record ID = 1
Trial 5: Selected SFI Record ID = 3
Popcorn Hack 2: Random Structured SFI Car Part
Prediction & Explanation:
- Case 1 (
random.choice(parts)): Will select one complete dictionary object from the 3 SFI records (1.1,1.2, or2.1) while keepingproduct_name,category, andspec_numbermatched together. - Case 2 (Modified list with an added Drag Racing part & index selection): Using
random.randint(0, len(parts) - 1)selects a valid 0-based Python index (0to3), preserving the exact relationship between all fields of the chosen dictionary.
# Popcorn Hack 2 - Random SFI Part Record
import random
parts = [
{
"product_name": "Replacement Flywheels and Clutch Assemblies",
"category": "Auto Racing",
"spec_number": "1.1"
},
{
"product_name": "Multiple Disc Clutch Assemblies",
"category": "Drag Racing",
"spec_number": "1.2"
},
{
"product_name": "Racing Flywheel Record",
"category": "Auto Racing",
"spec_number": "2.1"
}
]
print("--- Case 1: Select One Complete Structured Record with random.choice() ---")
selected_record = random.choice(parts)
print("Product Name:", selected_record["product_name"])
print("Category: ", selected_record["category"])
print("Spec Number: ", selected_record["spec_number"])
# Case 2: Modify input by adding a 4th record and selecting via valid random index
parts.append({
"product_name": "Bellhousing Blanket Shield",
"category": "Drag Racing",
"spec_number": "4.1"
})
random_index = random.randint(0, len(parts) - 1)
indexed_record = parts[random_index]
print(f"\n--- Case 2: Modified List (Index {random_index} of 0..{len(parts)-1}) ---")
print("Product Name:", indexed_record["product_name"])
print("Category: ", indexed_record["category"])
print("Spec Number: ", indexed_record["spec_number"])
--- Case 1: Select One Complete Structured Record with random.choice() ---
Product Name: Racing Flywheel Record
Category: Auto Racing
Spec Number: 2.1
--- Case 2: Modified List (Index 3 of 0..3) ---
Product Name: Bellhousing Blanket Shield
Category: Drag Racing
Spec Number: 4.1
Popcorn Hack 3: Random SFI API Test
Prediction & Explanation:
- Predicted Action Outcomes:
- If
selected_action == "GET/search", the script routes to the search branch and prints a lookup message for the chosen part’sspec_number. - If
selected_action == "POST/create", the script routes to the creation branch and validates the chosen part before inserting it.
- If
- Modified Action List: Adding
"DELETE/remove"increases the total possible(part, action)combinations from $3 \times 3 = 9$ outcomes to $3 \times 4 = 12$ possible outcomes.
# Popcorn Hack 3 - Random SFI API Test
import random
parts = [
{"product_name": "Replacement Flywheels", "spec_number": "1.1"},
{"product_name": "Multiple Disc Clutch Assemblies", "spec_number": "1.2"},
{"product_name": "Racing Flywheel Record", "spec_number": "2.1"}
]
actions = [
"GET/search",
"POST/create",
"PUT/update"
]
def run_api_test(part_list, action_list):
chosen_part = random.choice(part_list)
chosen_action = random.choice(action_list)
print(f"Selected Part: {chosen_part['product_name']} (Spec {chosen_part['spec_number']})")
print(f"Selected Action: {chosen_action}")
if chosen_action == "GET/search":
print(f" -> Backend Response: 200 OK - Returning record for Spec {chosen_part['spec_number']}.\n")
elif chosen_action == "POST/create":
print(f" -> Backend Response: 201 Created - Validating and storing '{chosen_part['product_name']}'.\n")
elif chosen_action == "PUT/update":
print(f" -> Backend Response: 200 OK - Updating metadata for Spec {chosen_part['spec_number']}.\n")
else:
print(f" -> Backend Response: 200 OK - Removing Spec {chosen_part['spec_number']} from active records.\n")
print("--- Run 1: Standard 3 Actions (GET, POST, PUT) ---")
run_api_test(parts, actions)
# Change action list to include DELETE/remove and run again
actions_modified = actions + ["DELETE/remove"]
print("--- Run 2: Modified Action List (+ DELETE/remove) ---")
run_api_test(parts, actions_modified)
--- Run 1: Standard 3 Actions (GET, POST, PUT) ---
Selected Part: Multiple Disc Clutch Assemblies (Spec 1.2)
Selected Action: PUT/update
-> Backend Response: 200 OK - Updating metadata for Spec 1.2.
--- Run 2: Modified Action List (+ DELETE/remove) ---
Selected Part: Multiple Disc Clutch Assemblies (Spec 1.2)
Selected Action: DELETE/remove
-> Backend Response: 200 OK - Removing Spec 1.2 from active records.
In-Class MCQ Check & College Board Pseudocode Comparison
MCQ Result Line
MCQ 3.15: 4/4 | answers: C,B,B,B
Section 3 Pseudocode Check
Tracing the College Board pseudocode by hand for LENGTH(parts) = 3:
- Suppose
recordIndex ← RANDOM(1, 3)returns2andactionNumber ← RANDOM(1, 4)returns2. - In 1-based College Board pseudocode,
selectedPart ← parts[2]selects the second record ("Multiple Disc Clutch Assemblies", Spec1.2). - In the nested
IF/ELSEblock,actionNumber = 1isfalse, andactionNumber = 2istrue, so it executesDISPLAY("POST/create"). - Comparison with Python: Python lists are 0-indexed (
parts[0]toparts[2]), sorandom.choice(parts)(orparts[random.randint(0, len(parts) - 1)]) avoids off-by-one index errors while producing the exact same $3 \times 4 = 12$ possible(part, action)combinations.
Homework Hack (Independent): SFI Backend QA Simulator
Simulator Logic & Complete Output Space Explanation:
- Possible Output Set: There are
3structured SFI part records inpartsand4API actions inactions, resulting in $3 \times 4 = 12$ possible(part, action)combinations on any single run. - Endpoints & Repeats: Every part and every action is reachable on each run. Because each iteration makes an independent random selection using
random.choice(), repeated parts or actions across consecutive runs are normal and expected. - Duplicate-Spec Handling: When
"POST/create"is selected, the simulator checks whetherselected_part["spec_number"] in existing_spec_numbers(["1.1", "2.1"]). Specs"1.1"and"2.1"are rejected as duplicates, while Spec"1.2"is accepted as a new spec.
# Homework Hack - SFI Backend QA Simulator
import random
parts = [
{
"product_name": "Replacement Flywheels",
"category": "Auto Racing",
"spec_number": "1.1"
},
{
"product_name": "Multiple Disc Clutch Assemblies",
"category": "Drag Racing",
"spec_number": "1.2"
},
{
"product_name": "Racing Flywheel Record",
"category": "Auto Racing",
"spec_number": "2.1"
}
]
actions = [
"GET/search",
"POST/create",
"PUT/update",
"DELETE/remove"
]
existing_spec_numbers = ["1.1", "2.1"]
test_count = 5
def simulate_sfi_backend_qa(part_records, api_actions, existing_specs, runs):
total_combinations = len(part_records) * len(api_actions)
print(f"=== SFI Backend QA Simulator ({runs} Runs | {total_combinations} Possible Part/Action Pairs) ===\n")
for run_num in range(1, runs + 1):
selected_part = random.choice(part_records)
selected_action = random.choice(api_actions)
name = selected_part["product_name"]
category = selected_part["category"]
spec = selected_part["spec_number"]
is_duplicate = spec in existing_specs
print(f"Run {run_num}:")
print(f" Selected Record -> Name: '{name}' | Category: '{category}' | Spec: '{spec}'")
print(f" Selected Action -> {selected_action}")
if selected_action == "GET/search":
print(f" Backend Result -> 200 OK: Found '{name}' (Spec {spec}) in {category} catalog.\n")
elif selected_action == "POST/create":
if not is_duplicate:
print(f" Backend Result -> 201 CREATED: Spec {spec} is unique. Added '{name}' to backend.\n")
else:
print(f" Backend Result -> 409 CONFLICT (REJECTED): Duplicate Spec {spec} already exists in {existing_specs}.\n")
elif selected_action == "PUT/update":
print(f" Backend Result -> 200 OK: Updated effective metadata for '{name}' (Spec {spec}).\n")
elif selected_action == "DELETE/remove":
print(f" Backend Result -> 200 OK: Archived and removed Spec {spec} ('{name}') from active list.\n")
# Run the simulator for the required test_count (5 runs)
simulate_sfi_backend_qa(parts, actions, existing_spec_numbers, test_count)
=== SFI Backend QA Simulator (5 Runs | 12 Possible Part/Action Pairs) ===
Run 1:
Selected Record -> Name: 'Replacement Flywheels' | Category: 'Auto Racing' | Spec: '1.1'
Selected Action -> PUT/update
Backend Result -> 200 OK: Updated effective metadata for 'Replacement Flywheels' (Spec 1.1).
Run 2:
Selected Record -> Name: 'Racing Flywheel Record' | Category: 'Auto Racing' | Spec: '2.1'
Selected Action -> DELETE/remove
Backend Result -> 200 OK: Archived and removed Spec 2.1 ('Racing Flywheel Record') from active list.
Run 3:
Selected Record -> Name: 'Multiple Disc Clutch Assemblies' | Category: 'Drag Racing' | Spec: '1.2'
Selected Action -> POST/create
Backend Result -> 201 CREATED: Spec 1.2 is unique. Added 'Multiple Disc Clutch Assemblies' to backend.
Run 4:
Selected Record -> Name: 'Multiple Disc Clutch Assemblies' | Category: 'Drag Racing' | Spec: '1.2'
Selected Action -> PUT/update
Backend Result -> 200 OK: Updated effective metadata for 'Multiple Disc Clutch Assemblies' (Spec 1.2).
Run 5:
Selected Record -> Name: 'Racing Flywheel Record' | Category: 'Auto Racing' | Spec: '2.1'
Selected Action -> DELETE/remove
Backend Result -> 200 OK: Archived and removed Spec 2.1 ('Racing Flywheel Record') from active list.