Codepath

Count Even Strings

TIP102 Unit 1 Session 2 Standard (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 10 mins
  • 🛠️ Topics: String Length, List Operations

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • The function count_evens() should take a list of strings lst and return the count of strings with even lengths.
HAPPY CASE
Input: lst = ["na", "nana", "nanana", "batman", "!"]
Expected Output: 4

Input: lst = ["you", "either", "die", "a", "hero", "or", "you", "live", "long", "enough", "to", "see", "yourself", "become", "the", "villain"]
Expected Output: 9

EDGE CASE
Input: lst = []
Expected Output: 0

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Iterate through the list of strings, check the length of each string, and count those with even lengths.

1. Define the function `count_evens(lst)`.
2. Initialize a counter variable `count` to 0.
3. Loop through each string in `lst`.
   - If the length of the string is even, increment the `count` by 1.
4. Return the `count`

⚠️ Common Mistakes

  • Forgetting to check the length correctly or initializing the count variable.

I-mplement

Implement the code to solve the algorithm.

def count_evens(lst):
    count = 0
    for string in lst:
        if len(string) % 2 == 0:
            count += 1
    return count
Fork me on GitHub