Lab

8.4.2. Lab#

  • Use this lab to practice the chapter’s coding skills in runnable Python code.

  • Sign in from the account menu before you start working on the lab.

  • Launch Live Code (the rocket) to write and run code in the coding cells.

  • Multiple submissions are allowed. The highest score is kept.

### Question 1: Clean a messy title
# raw_title has extra whitespace and inconsistent case.
# Build clean_title by collapsing all whitespace to single spaces
# (join raw_title.split() with a single space) and title-casing the
# result.
# Compute word_count as the number of words in clean_title.
# Print exactly these two lines:
# Clean title: The Quick Brown Fox
# Word count: 4
raw_title = "  the Quick BROWN fox   "
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
raw_title = "  the Quick BROWN fox   "

clean_title = " ".join(raw_title.split()).title()
word_count = len(clean_title.split())

print("Clean title:", clean_title)
print("Word count:", word_count)
Clean title: The Quick Brown Fox
Word count: 4
### Question 2: Normalize a ticket code
# ticket_code has stray whitespace, a lowercase prefix, and hyphens.
# Build normalized by stripping whitespace, uppercasing, then
# replacing every "-" with "_".
# Compute is_valid as True when normalized starts with "TS".
# Compute underscore_count as the number of "_" characters in
# normalized.
# Print exactly these three lines:
# Normalized: TS_2024_ALPHA
# Valid ticket: True
# Underscore count: 2
ticket_code = "  ts-2024-Alpha  "
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
ticket_code = "  ts-2024-Alpha  "

normalized = ticket_code.strip().upper().replace("-", "_")
is_valid = normalized.startswith("TS")
underscore_count = normalized.count("_")

print("Normalized:", normalized)
print("Valid ticket:", is_valid)
print("Underscore count:", underscore_count)
Normalized: TS_2024_ALPHA
Valid ticket: True
Underscore count: 2
### Question 3: Sort words case-insensitively
# word_list mixes upper and lower case spellings of the same words.
# Build sorted_words by sorting word_list with key=str.casefold, so
# the sort ignores case.
# Compute unique_count as the number of distinct case-folded words.
# Print exactly these two lines:
# Sorted words: ['Apple', 'apple', 'banana', 'Banana', 'cherry']
# Unique count: 3
word_list = ["banana", "Apple", "cherry", "apple", "Banana"]
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
word_list = ["banana", "Apple", "cherry", "apple", "Banana"]

sorted_words = sorted(word_list, key=str.casefold)
unique_count = len({w.casefold() for w in word_list})

print("Sorted words:", sorted_words)
print("Unique count:", unique_count)
Sorted words: ['Apple', 'apple', 'banana', 'Banana', 'cherry']
Unique count: 3
### Question 4: Extract numbers from a report line
# report is one line of a server log with numbers mixed into text.
# Import re and use re.findall(r"\d+", report) to build numbers, a
# list of the digit sequences found (as strings).
# Compute total as the sum of those numbers converted to int.
# Print exactly these two lines:
# Numbers found: ['1', '42', '2', '108']
# Total: 153
report = "Server room1 handled 42 requests and room2 handled 108 requests"
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
report = "Server room1 handled 42 requests and room2 handled 108 requests"

import re

numbers = re.findall(r"\d+", report)
total = 0
for n in numbers:
    total += int(n)

print("Numbers found:", numbers)
print("Total:", total)
Numbers found: ['1', '42', '2', '108']
Total: 153
### Question 5: Validate and split a user code
# code should match the pattern: one uppercase letter, a hyphen,
# then exactly four digits (for example "A-1234").
# Import re. Compute is_valid as a bool using
# re.fullmatch(r"[A-Z]-\d{4}", code).
# Use re.search(r"([A-Z])-(\d{4})", code) to get a match object, then
# read letter as group(1) and number as group(2).
# Print exactly these three lines:
# Valid code: True
# Letter: A
# Number: 1234
code = "A-1234"
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
code = "A-1234"

import re

is_valid = bool(re.fullmatch(r"[A-Z]-\d{4}", code))
match = re.search(r"([A-Z])-(\d{4})", code)
letter = match.group(1)
number = match.group(2)

print("Valid code:", is_valid)
print("Letter:", letter)
print("Number:", number)
Valid code: True
Letter: A
Number: 1234