Skip to content

Week 7 - Iteration & Search

Objective:

  • Explore techniques for looping, searching, and applying counting operations on strings and files in Python.
  • Practice solving exercises to solidify understanding.

Loops and Strings

  • For Loop Basics:
    • Review for loops, particularly range for numerical iteration.
    • Example: Loop to display numbers 0 to 2 in one line.
      1
      2
      for i in range(3):
          print(i, end=' ')
      
  • Character Iteration in Strings:
    • Looping through characters in a string.
    • New Code Example: Using a loop to print only vowels in a word.
      1
      2
      3
      4
      word = "Gadsby"
      for letter in word:
          if letter.lower() in 'aeiou':
              print(letter, end=' ')
      
  • Checking for Specific Characters:
    • Demonstrate a function has_letter(word, char) that checks for any character in a word.
      1
      2
      3
      4
      5
      def has_letter(word, char):
          for letter in word:
              if letter.lower() == char.lower():
                  return True
          return False
      
    • Test has_letter("Gadsby", "a") and has_letter("Gadsby", "e").

Reading Files and Word Lists

  • Using the open Function:
    • How to open, read, and loop through each line in a file.
  • Example Code: Count lines in words.txt.
    1
    2
    3
    4
    file_path = 'words.txt'
    with open(file_path, 'r') as file:
        line_count = sum(1 for _ in file)
    print("Number of lines:", line_count)
    
  • Using strip() for Clean Data:
    • Show how strip() removes whitespace, including newlines.
  • Practice Exercise: Write a function count_words(file_path) that reads each line, strips whitespace, and counts the total words.

Variable Updating

  • Basic Assignments vs. Updates:
    • Difference between initializing, updating, and incrementing variables.
  • Example: Cumulative word length calculator for words with an “e”.
    1
    2
    3
    4
    5
    6
    7
    8
    def cumulative_length_e_words(file_path):
        total_length = 0
        with open(file_path, 'r') as file:
            for line in file:
                word = line.strip()
                if 'e' in word:
                    total_length += len(word)
        return total_length
    
    • Test this function with a small word list.

Looping and Counting Patterns

  • Counter Variables:
    • Using counters to count specific conditions within loops.
  • Code Example: Count words containing at least one vowel.
    1
    2
    3
    4
    5
    6
    7
    8
    def count_vowel_words(file_path):
        count = 0
        with open(file_path, 'r') as file:
            for line in file:
                word = line.strip()
                if any(vowel in word for vowel in 'aeiou'):
                    count += 1
        return count
    

Using the in Operator

  • Simplify Checks:
    • Rewrite has_letter using in.
      1
      2
      def has_letter(word, char):
          return char.lower() in word.lower()
      
  • Practice Excercise: Refactor a function that checks if a word contains any vowels using in.
  • Definition and Practicality:
    • Introduce linear search as a pattern that sequentially checks elements.
  • Example: General function contains_any(word, letters) using in.
    1
    2
    def contains_any(word, letters):
        return any(letter in word for letter in letters.lower())
    
  • Practice Exercise: Write a function to return all positions of a specified letter in a word.

Doctest and Testing Functions

  • Introduction to Doctests:
    • How doctests verify function correctness by embedding test cases in the docstring.
  • Example Code: Writing a doctest for the contains_any function.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    def contains_any(word, letters):
        """Checks if a word uses any letters in a given set.
    
        >>> contains_any('banana', 'aeiou')
        True
        >>> contains_any('banana', 'xyz')
        False
        """
        return any(letter in word for letter in letters.lower())
    
  • Practice Exercise: Write doctests for has_letter and run them.

Exercises

Exercise 1: Detect Palindromic Words

  • Write a function is_palindromic(word) that returns True if a word reads the same backward.

Exercise 2: Counting Words by Length

  • Write count_by_length(file_path, n) that counts the number of words with exactly n letters.

Exercise 3: Find Words with Specific Letter Patterns

  • Write find_words_with_pattern(file_path, pattern) to count words with a particular letter pattern.