Integrated Problem-solving in Python

Chapter 5 - Lists, Strings & Algorithms

Table of Contents

Explore the key topics in this chapter

Basic Concepts

Learn about lists, indexing, and string fundamentals

Algorithm Theory

Master essential list algorithms and operations

Practical Applications

Apply concepts to real-world problem solving

Interactive Quiz

Test your understanding with 12 questions

Flashcards

Review key terms and concepts

Past Exam Questions

Practice with DSE-style questions

Basic Concepts

Fundamental building blocks of Python programming

Lists (列表)

A list in Python is a collection of items stored in a single variable. Lists are similar to 1-dimensional arrays and can hold multiple values of different data types.

# Creating a list
marks = [87, 85, 79, 100, 50]

# Initialization with default values
time = [0] * 4  # Creates [0, 0, 0, 0]

# Mixed data types
student = ["Alice", 16, 95.5, True]

List Indexing (列表索引)

List indices start from 0. The first element is at index 0, the second at index 1, and so on. This is because indices represent memory offsets from the base address.

# Accessing list items
fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Output: apple
print(fruits[2])  # Output: cherry

# Negative indexing (from the end)
print(fruits[-1])  # Output: cherry

Why start from 0? In memory, the index represents the offset from the base address. Index 0 means 0 offset (the starting position).

List Operations (列表操作)

Lists are mutable, meaning you can modify, add, or remove elements after creation.

# Updating items
marks[0] = 90

# Outputting lists
print(marks)  # Entire list
for mark in marks:
    print(mark)  # Each item

# Copying lists
original = [1, 2, 3]
copy = original[:]  # Creates a new list

Strings (字串)

Strings in Python are sequences of characters. They can be treated like lists of characters, with similar indexing and operations.

# String basics
text = "Hello World"
print(len(text))  # Length: 11
print(text[0])    # First character: H
print(text[6:11]) # Substring: World

# String operations
upper_text = text.upper()
lower_text = text.lower()
split_text = text.split()  # ["Hello", "World"]

Algorithm Theory

Essential algorithms for list and string processing

Finding Sum & Average (求和與平均值)

Calculate the total sum and average of numeric values in a list using a loop accumulator.

# Example: Calculate average time
time = [14.9, 15.5, 16.1, 15.8]
N = len(time)

total = 0
for i in range(N):
    total = total + time[i]

average = total / N

print(f"Total: {total}")      # 62.3
print(f"Average: {average}")  # 15.575

Linear Search (線性搜尋)

Search for a target value in a list by checking each element sequentially. Use a flag variable to track if the item is found.

# Search for a character in a string
the_string = "Work Hard!"
target = "r"

found = False
index = -1
i = 0
N = len(the_string)

while i < N and found == False:
    if the_string[i] == target:
        index = i
        found = True
    i = i + 1

if found:
    print(f"Found at index: {index}")  # 2
else:
    print("Not found")

Counting (計數)

Count how many elements in a list meet specific conditions.

# Count passing marks (>= 50)
marks = [87, 85, 79, 100, 50, 35, 90, 100, 60, 80]
count = 0

for mark in marks:
    if mark >= 50:
        count = count + 1

print(f"Passing students: {count}")  # 9

Finding Max/Min (求最大/最小值)

Find the largest or smallest value in a list by comparing each element with a temporary variable.

# Find highest mark
mark = [87, 85, 79, 100, 50, 35, 90, 100, 60, 80]
highest_mark = mark[0]

for i in range(1, len(mark)):
    if mark[i] > highest_mark:
        highest_mark = mark[i]

print(f"Highest mark: {highest_mark}")  # 100

# Find all students with highest mark
for i in range(len(mark)):
    if mark[i] == highest_mark:
        print(f"Student {i+1} has highest mark")

Checking Order (檢查排序)

Verify if a list is sorted in ascending or descending order using a Boolean flag.

# Check if list is in ascending order
numbers = [1, 3, 5, 7, 9]
is_sorted = True

for i in range(len(numbers) - 1):
    if numbers[i] > numbers[i + 1]:
        is_sorted = False
        break

if is_sorted:
    print("List is sorted in ascending order")
else:
    print("List is not sorted")

Add/Delete/Move Items (新增/刪除/移動項目)

Modify list contents by adding, removing, or shifting elements.

# Delete item at position P and shift remaining
def delete_at_position(lst, P):
    N = len(lst)
    for i in range(P, N - 1):
        lst[i] = lst[i + 1]
    lst.pop()  # Remove last item
    return lst

# Add item at position P
def insert_at_position(lst, P, value):
    lst.append(0)  # Add space
    for i in range(len(lst) - 1, P, -1):
        lst[i] = lst[i - 1]
    lst[P] = value
    return lst

# Example usage
data = [10, 20, 30, 40, 50]
delete_at_position(data, 2)  # [10, 20, 40, 50]
insert_at_position(data, 1, 15)  # [10, 15, 20, 40, 50]

Practical Applications

Real-world problem solving with Python

String Processing - Finding Characters

Search for specific characters in strings, extract substrings, and analyze character types using ASCII values.

# Find first occurrence of character
def find_char(text, target):
    for i in range(len(text)):
        if text[i] == target:
            return i
    return -1

# Extract substring
sentence = "Hello World"
word = sentence[0:5]  # "Hello"

# Check character type using ASCII
def is_uppercase(char):
    return ord(char) >= 65 and ord(char) <= 90

def is_digit(char):
    return ord(char) >= 48 and ord(char) <= 57

print(is_uppercase("A"))  # True
print(is_digit("5"))      # True

Password Validation

Validate passwords by checking length, presence of spaces, and character type requirements.

def validate_password(password):
    # Check length
    if len(password) < 8:
        return False, "Password too short"
    
    # Check for spaces
    if " " in password:
        return False, "Password contains spaces"
    
    # Check for uppercase, lowercase, and digit
    has_upper = False
    has_lower = False
    has_digit = False
    
    for char in password:
        if ord(char) >= 65 and ord(char) <= 90:
            has_upper = True
        elif ord(char) >= 97 and ord(char) <= 122:
            has_lower = True
        elif ord(char) >= 48 and ord(char) <= 57:
            has_digit = True
    
    if has_upper and has_lower and has_digit:
        return True, "Valid password"
    else:
        return False, "Password must contain uppercase, lowercase, and digit"

# Test
result, message = validate_password("Pass123")
print(message)

Department Store Robot Navigation

Help users navigate a multi-floor department store by searching for shop locations and calculating floor differences.

# 7-floor department store
shop = ["Electronics", "Clothing", "Books", "Toys", 
        "Furniture", "Sports", "Food Court"]

def find_shop(shop_name):
    for i in range(len(shop)):
        if shop[i] == shop_name:
            return i
    return -1

# Get user input
current = input("Current location: ")
destination = input("Destination: ")

current_floor = find_shop(current)
dest_floor = find_shop(destination)

if current_floor == -1 or dest_floor == -1:
    print("No such shop")
else:
    diff = dest_floor - current_floor
    if diff > 0:
        print(f"You should go up {diff} level(s)")
    elif diff < 0:
        print(f"You should go down {-diff} level(s)")
    else:
        print("You are already there")

Interactive Quiz

Test your understanding with 12 questions

1. Which statement correctly creates a list of 5 zeros in Python?

2. Given the list fruits = ["apple", "banana", "cherry"], what is fruits[1]?

3. What is the output of the following code?
nums = [1, 2, 3]
for i in range(len(nums)):
    nums[i] = nums[i] * 2
print(nums)

4. In linear search, what is the purpose of the "found" flag variable?

5. To find the average of values in a list, you must first:

6. Which code correctly counts how many numbers in a list are greater than 50?

7. To find the maximum value in a list, you should initialize the temporary variable to:

8. Which condition checks if a list is sorted in ascending order?

9. After deleting an item at position P from a list, what must you do?

10. What does len("Hello") return?

11. Given text = "Python", what is text[2:5]?

12. The ASCII value of 'A' is 65. What is the ASCII value of 'B'?

Flashcards

Click cards to flip and review key concepts

List / 列表

A collection of items stored in a single variable, similar to a 1-dimensional array. Example: marks = [87, 85, 79]

Index / 索引

A number representing the position of an element in a list or string. In Python, indices start from 0.

Initialization / 初始化

Setting initial values for a list. Example: nums = [0] * 5 creates [0, 0, 0, 0, 0]

Linear Search / 線性搜尋

A search algorithm that checks each element in sequence until the target is found or the list ends.

Flag / 旗標

A Boolean variable used to track a condition. Example: found = False, then set to True when item is found.

len() function

Returns the number of items in a list or characters in a string. Example: len("Hello") returns 5

Substring / 子字串

A portion of a string extracted using slicing. Example: "Hello"[0:3] gives "Hel"

ASCII

American Standard Code for Information Interchange - a character encoding standard. 'A' = 65, 'a' = 97, '0' = 48

append() method

Adds an item to the end of a list. Example: nums.append(10) adds 10 to the end of nums

Pointer / 指針

A variable that stores the memory address of another variable or data structure.

Base Address / 起始地址

The memory address of the first element in a list. Indices represent offsets from this base address.

Dynamic vs Static / 動態 vs 靜態

Dynamic: size can change during runtime (Python lists). Static: fixed size (arrays in C/Java).

Boolean / 布林值

A data type with only two values: True or False. Used for flags and conditions.

for loop / for 迴圈

Iterates over a sequence a fixed number of times. Example: for i in range(5): print(i)

while loop / while 迴圈

Repeats as long as a condition is True. Example: while i < 10: i += 1

range() function

Generates a sequence of numbers. range(5) gives 0,1,2,3,4. range(2,7) gives 2,3,4,5,6.

Concatenation / 串接

Joining strings or lists together. Example: "Hello" + " " + "World" = "Hello World"

ord() function

Returns the ASCII value of a character. Example: ord('A') returns 65

Palindrome / 對稱字

A word or phrase that reads the same forwards and backwards. Example: "radar", "level"

Sentinel Value / 哨兵值

A special value used to signal the end of input or data. Example: using -1 to exit a loop

Past Exam Questions

Practice with DSE-style programming questions

Question 1: Sum of List Elements Basic

Write a Python program that receives a list of N integers from the user and calculates the sum of all elements in the list. Display the total sum.

Reference Answer
# Get number of elements
N = int(input("Enter number of elements: "))

# Initialize list
numbers = []

# Input elements
for i in range(N):
    num = int(input(f"Enter element {i+1}: "))
    numbers.append(num)

# Calculate sum
total = 0
for num in numbers:
    total = total + num

# Display result
print(f"Sum of all elements: {total}")

Explanation: This program uses an accumulator pattern. We initialize total to 0, then add each element in the list to total using a for loop. This is the standard approach for finding the sum of list elements.

Question 2: Linear Search Basic

Write a Python program that searches for a target value in a list and outputs its index position. If the value is not found, display "Not found".

Reference Answer
# Sample list
numbers = [10, 25, 30, 45, 50, 60, 75]

# Get target value
target = int(input("Enter value to search: "))

# Linear search with flag
found = False
index = -1

for i in range(len(numbers)):
    if numbers[i] == target:
        index = i
        found = True
        break  # Exit loop once found

# Display result
if found:
    print(f"Value found at index: {index}")
else:
    print("Not found")

Explanation: Linear search checks each element sequentially. We use a Boolean flag (found) to track whether the target is found. The index variable stores the position. We can use break to exit the loop early once the target is found for better efficiency.

Question 3: Second Largest Value Intermediate

Write a Python program that finds the second largest value in a list of integers. Assume the list has at least 2 elements and all values are unique.

Reference Answer
# Sample list
numbers = [45, 88, 23, 67, 92, 55, 71]

# Initialize largest and second largest
if numbers[0] > numbers[1]:
    largest = numbers[0]
    second_largest = numbers[1]
else:
    largest = numbers[1]
    second_largest = numbers[0]

# Find largest and second largest
for i in range(2, len(numbers)):
    if numbers[i] > largest:
        second_largest = largest
        largest = numbers[i]
    elif numbers[i] > second_largest:
        second_largest = numbers[i]

print(f"Second largest value: {second_largest}")

Explanation: We maintain two variables: largest and second_largest. When we find a value larger than largest, we update both (second_largest becomes the old largest). When we find a value between largest and second_largest, we only update second_largest. We initialize both variables using the first two elements.

Question 4: Delete and Shift Intermediate

Write a Python program that deletes an item at position P from a list and shifts all remaining items to fill the gap. Display the modified list.

Reference Answer
# Sample list
items = [10, 20, 30, 40, 50, 60, 70]
print(f"Original list: {items}")

# Get position to delete
P = int(input("Enter position to delete (0-indexed): "))

# Validate position
if P < 0 or P >= len(items):
    print("Invalid position")
else:
    # Shift elements left
    for i in range(P, len(items) - 1):
        items[i] = items[i + 1]
    
    # Remove last element (now duplicate)
    items.pop()
    
    print(f"Modified list: {items}")

Explanation: To delete an item at position P, we shift all elements after P one position to the left. This overwrites the item at P. After shifting, the last element is a duplicate, so we use pop() to remove it. The time complexity is O(n) where n is the number of elements after position P.

Question 5: Second Word Length Advanced

Write a Python program that receives a sentence from the user and outputs the length of the second word in the sentence. Assume words are separated by single spaces and the sentence has at least 2 words.

Reference Answer
# Get sentence from user
sentence = input("Enter a sentence: ")

# Method 1: Using split()
words = sentence.split()
if len(words) >= 2:
    second_word = words[1]
    print(f"Length of second word: {len(second_word)}")
else:
    print("Sentence must have at least 2 words")

# Method 2: Manual parsing (without split)
space_count = 0
start_index = -1
end_index = -1

# Find start of second word
for i in range(len(sentence)):
    if sentence[i] == " ":
        space_count += 1
        if space_count == 1:
            start_index = i + 1
    elif space_count == 1 and sentence[i] != " ":
        if end_index == -1:
            continue
    elif space_count == 2:
        end_index = i
        break

# Handle case where second word is last word
if end_index == -1:
    end_index = len(sentence)

# Calculate length
if start_index != -1:
    second_word_length = end_index - start_index
    print(f"Length of second word (manual): {second_word_length}")

Explanation: Method 1 uses the built-in split() function to divide the sentence into words, then accesses the second word directly. Method 2 manually parses the string by counting spaces to locate the start and end positions of the second word, demonstrating string traversal and index manipulation. The manual method is more complex but shows fundamental string processing skills.

made with