Continuing our journey into the world of Python interview questions, we bring you Part 2 of our series.

In case you've missed Part 1 here is a link:

As Python remains one of the most popular languages in technical interviews, being well-prepared with common problem-solving techniques is crucial for success.

Hi everyone, CyCoderX here! Today, we'll delve into four more Python coding examples that interviewers love to throw your way. Before we jump in, I highly recommend giving these problems a shot yourself first! Spend 20–30 minutes wrestling with the solution — that struggle is where the real learning happens. Then, come back here and compare your approach to mine. Remember, there's often more than one way to solve a coding challenge. In this series, I'll be providing just one solution, but feel free to explore alternative approaches and share them in the comments! Let's sharpen those Python skills and get interview-ready!

In is Part 2 of our series, and we'll cover the following examples:

  1. Write a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd.
  2. Write a Python function that accepts a string and calculates the number of uppercase letters and lowercase letters.
  3. Write a program that accepts input in this form: s3t1z5 and returns a string where the character is repeated for the corresponding number of times.
  4. Take a sentence as input and print only the words that start with "t" in the sentence.

Let's dive in and start with the first example!

Did you know that you can clap up to 50 times per article? Well now you do! Please consider helping me out by smashing that clap button and following me! 😊

Interested in SQL and Python content? Don't worry I got you covered! Feel free to explore some of my lists on medium! Dedicated for every tech enthusiast!

Example 1: Lesser of Two Evens or Greater if Odd

Problem Description

Write a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd. This problem helps in understanding conditional logic and basic comparison operations in Python.

Explanation of the Approach

As mentioned in Part 1, when you face a coding question, it's best to come up with a plan and write some pseudocode. This will break down your approach into smaller, easier-to-follow steps. For example:

  1. Check if both numbers are even.
  2. If both numbers are even, return the lesser of the two numbers.
  3. If one or both numbers are odd, return the greater of the two numbers.

Python Code

# Function to return the lesser of two evens or greater if odd
def lesser_or_greater(a, b):
    # Check if both numbers are even
    if a % 2 == 0 and b % 2 == 0:
        # Return the lesser of the two numbers
        return min(a, b)
    else:
        # Return the greater of the two numbers
        return max(a, b)

# Example usage
num1 = 4
num2 = 10
result = lesser_or_greater(num1, num2)
print(f"The result for ({num1}, {num2}) is: {result}")

num1 = 5
num2 = 8
result = lesser_or_greater(num1, num2)
print(f"The result for ({num1}, {num2}) is: {result}")

Quick note there are many ways to solve a problem and this is just my solution to the problem.

Detailed Explanation of the Code

  1. Function Definition: We define a function lesser_or_greater that takes two parameters a and b.
  2. Check for Even Numbers: We use the modulus operator % to check if both numbers are even. If a % 2 == 0 and b % 2 == 0 are both true, the numbers are even.
  3. Return Lesser Number: If both numbers are even, we use the min() function to return the lesser of the two numbers.
  4. Return Greater Number: If one or both numbers are odd, we use the max() function to return the greater of the two numbers.
  5. Example Usage: We provide example inputs to demonstrate how the function works, printing the results for different pairs of numbers.

Example 2: Count Uppercase and Lowercase Letters in a String

Problem Description

Write a Python function that accepts a string and calculates the number of uppercase letters and lowercase letters. This problem tests your ability to work with strings and character classifications.

Explanation of the Approach

To solve this problem, we can follow these steps:

  1. Initialize two counters: one for uppercase letters and one for lowercase letters.
  2. Iterate through each character in the string.
  3. Check if the character is uppercase or lowercase.
  4. Update the counters accordingly.
  5. Return or print the final counts.

Python Code

# Function to count uppercase and lowercase letters in a string
def count_upper_lower(input_string):
    # Initialize counters
    upper_count = 0
    lower_count = 0
    
    # Iterate through each character in the string
    for char in input_string:
        # Check if the character is uppercase
        if char.isupper():
            upper_count += 1
        # Check if the character is lowercase
        elif char.islower():
            lower_count += 1
            
    # Return the counts
    return upper_count, lower_count

# Input string from the user
input_string = input("Enter a string: ")

# Get the counts of uppercase and lowercase letters
upper, lower = count_upper_lower(input_string)

# Print the results
print(f"Number of uppercase letters: {upper}")
print(f"Number of lowercase letters: {lower}")

Detailed Explanation of the Code

  1. Function Definition: We define a function count_upper_lower that takes an input string as its parameter.
  2. Initialize Counters: We initialize two counters, upper_count and lower_count, to zero.
  3. Iterate through Characters: We use a for loop to iterate through each character in the input string.
  4. Check for Uppercase Letters: If the character is uppercase (using char.isupper()), we increment upper_count.
  5. Check for Lowercase Letters: If the character is lowercase (using char.islower()), we increment lower_count.
  6. Return Counts: The function returns the counts of uppercase and lowercase letters.
  7. User Input: We take the input string from the user using input().
  8. Get Counts: We call the function with the input string and store the results in upper and lower.
  9. Print Results: Finally, we print the counts of uppercase and lowercase letters.

Example 3: Expand Characters Based on Following Number

Problem Description

Write a program that accepts input in this form: s3t1z5. Here, any character is followed by a number. The program should return a string where the character is repeated for the corresponding number of times. This problem tests your ability to manipulate strings and work with loops.

Explanation of the Approach

To solve this problem, we can follow these steps:

  1. Initialize an empty result string.
  2. Iterate through the input string, checking each character and the number that follows.
  3. For each character, repeat it according to the following number and append it to the result string.
  4. Return or print the final result string.

Python Code

# Function to expand characters based on following number
def expand_string(input_string):
    # Initialize the result string
    result = ""
    
    # Iterate through the input string
    i = 0
    while i < len(input_string):
        # Current character
        char = input_string[i]
        i += 1
        
        # Initialize a variable to store the number
        num = 0
        # Read the following digits to form the number
        while i < len(input_string) and input_string[i].isdigit():
            num = num * 10 + int(input_string[i])
            i += 1
        
        # Append the character repeated 'num' times to the result string
        result += char * num
    
    return result

# Input string from the user
input_string = input("Enter a string in the form of 's3t1z5': ")

# Get the expanded string
expanded_string = expand_string(input_string)

# Print the result
print(f"Expanded string: {expanded_string}")

Detailed Explanation of the Code

  1. Function Definition: We define a function expand_string that takes an input string as its parameter.
  2. Initialize Result String: We initialize an empty string result to store the final expanded string.
  3. Iterate through Input String: We use a while loop to iterate through each character in the input string. We use an index i to keep track of our current position in the string.
  4. Extract Character and Number: For each character, we move to the next index to read the following digits, which represent the number. We use another while loop to read consecutive digits and convert them to an integer num.
  5. Repeat and Append Character: We use the * operator to repeat the character num times and append it to the result string.
  6. Return Result: The function returns the final expanded string.
  7. User Input: We take the input string from the user using input().
  8. Get Expanded String: We call the function with the input string and store the result in expanded_string.
  9. Print Result: Finally, we print the expanded string.

Example 4: Print Words Starting with 't' in a Sentence

Problem Description

Write a program that takes a sentence as input and prints only the words that start with the letter "t". This problem tests your ability to work with strings and lists in Python.

Explanation of the Approach

To solve this problem, we can follow these steps:

  1. Split the input sentence into words.
  2. Initialize an empty list to store the words that start with 't'.
  3. Iterate through the list of words.
  4. Check if each word starts with 't' (case-insensitive).
  5. Append the word to the list if it starts with 't'.
  6. Print the words that start with 't'.

Python Code

# Function to print words starting with 't'
def print_words_starting_with_t(sentence):
    # Split the sentence into words
    words = sentence.split()
    
    # Initialize an empty list to store the result
    t_words = []
    
    # Iterate through the words
    for word in words:
        # Check if the word starts with 't' or 'T'
        if word.lower().startswith('t'):
            t_words.append(word)
    
    # Print the words that start with 't'
    print("Words starting with 't':")
    for word in t_words:
        print(word)

# Input sentence from the user
sentence = input("Enter a sentence: ")

# Print words starting with 't'
print_words_starting_with_t(sentence)

Detailed Explanation of the Code

  1. Function Definition: We define a function print_words_starting_with_t that takes a sentence as its parameter.
  2. Split Sentence into Words: We use the split() method to split the input sentence into a list of words.
  3. Initialize Result List: We initialize an empty list t_words to store the words that start with 't'.
  4. Iterate through Words: We use a for loop to iterate through each word in the list.
  5. Check for Words Starting with 't': We use the startswith() method with word.lower() to check if the word starts with 't' (case-insensitive). If it does, we append the word to t_words.
  6. Print Result: We print the words that start with 't' by iterating through the t_words list.
  7. User Input: We take the input sentence from the user using input().
  8. Call Function: We call the function with the input sentence to print the words that start with 't'.

Master data manipulation with my comprehensive guide to Data Science, featuring popular tools like Pandas and NumPy!

Conclusion

In this article, we have explored four more common Python interview problems and their solutions. These examples are not just questions that might appear in interviews but are also excellent practice to enhance your problem-solving skills and Python programming knowledge.

  1. Lesser of Two Evens or Greater if Odd: This problem helps you understand conditional logic and basic comparison operations.
  2. Count Uppercase and Lowercase Letters in a String: This example introduces you to string manipulation and character classification.
  3. Expand Characters Based on Following Number: This problem tests your ability to manipulate strings and work with loops.
  4. Print Words Starting with 't' in a Sentence: This basic yet fundamental problem demonstrates string splitting and list operations.

Each of these problems requires a clear understanding of Python basics, and solving them will prepare you for more complex coding challenges. Stay tuned for Part 3, where we will cover more interesting and commonly asked Python interview questions.

Keep practicing and happy coding!

None
Photo by Afif Ramdhasuma on Unsplash

Final Words:

Thank you for taking the time to read my article.

This article was first published on medium by CyCoderX.

Hey There! I'm CyCoderX, a data engineer who loves crafting end-to-end solutions. I write articles about Python, SQL, AI, Data Engineering, and more!

Join me as we explore the exciting world of tech, data and beyond!

For similar articles and updates, feel free to explore my Medium profile:

If you enjoyed this article, consider following for future updates.

Interested in Python content and tips? Click here to check out my list on Medium.

Interested in more SQL, Databases and Data Engineering content? Click here to find out more!

What did you think about this article? Let me know in the comments below … or above, depending on your device! 🙃

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go: