HI WELCOME TO KANSIRIS

Coding/Practical Python Interview Questions

Leave a Comment

  

1. Reverse a string without using slicing.

 

To reverse a string without using slicing ([::-1]), you can use a loop or built-in functions like reversed() and join(). Here's a simple example using a loop:

Using a for loop:

Python

def reverse_string(s):

    result = ""

    for char in s:

        result = char + result

    return result

 

print(reverse_string("Python"))  # Output: nohtyP

 

Using reversed() and join():

Python

def reverse_string(s):

    return ''.join(reversed(s))

 

print(reverse_string("Python"))  # Output: nohtyP

 

Both methods avoid slicing and give you the reversed string. Would you like to see how to reverse a string recursively or using a stack?

 

 

2. Find the first non-repeating character in a string.

 To find the first non-repeating character in a string in Python, you can use a dictionary to count character occurrences and then iterate through the string to find the first character with a count of 1.

Example Code:

Python

def first_non_repeating_char(s):

    char_count = {}

 

    # Count occurrences of each character

    for char in s:

        char_count[char] = char_count.get(char, 0) + 1

 

    # Find the first character with count 1

    for char in s:

        if char_count[char] == 1:

            return char

 

    return None  # If no non-repeating character found

 

# Example usage

print(first_non_repeating_char("aabbcdeff"))  # Output: c

 

Show more lines

🔸 How It Works:

  1. First loop: Builds a frequency dictionary.

  2. Second loop: Checks the original order to find the first character with a count of 1.

Would you like a version that ignores case or whitespace, or one that works with Unicode characters?

 

 

3. Flatten a nested list (without using libraries).

 To flatten a nested list in Python without using any external libraries, you can use recursion to handle arbitrary levels of nesting.

Example: Recursive Function

Python

def flatten_list(nested):

    flat = []

    for item in nested:

        if isinstance(item, list):

            flat.extend(flatten_list(item))  # Recursively flatten

        else:

            flat.append(item)

    return flat

 

# Example usage

nested = [1, [2, [3, 4], 5], 6]

print(flatten_list(nested))  # Output: [1, 2, 3, 4, 5, 6]

 

🔸 How It Works

  • The function checks if each item is a list.

  • If it is, it recursively flattens it.

  • If not, it adds the item to the result list.

Would you like a version that handles other iterable types (like tuples or sets) or avoids recursion using a stack?

 

 

4. Write a function to check if two strings are anagrams.

 To check if two strings are anagrams in Python, you can compare the sorted characters or use a frequency count. Here's a simple and efficient way using a dictionary:

Function to Check Anagrams

Python

def are_anagrams(s1, s2):

    # Early exit if lengths differ

    if len(s1) != len(s2):

        return False

 

    # Count characters in both strings

    count = {}

 

    for char in s1:

        count[char] = count.get(char, 0) + 1

 

    for char in s2:

        if char not in count:

            return False

        count[char] -= 1

        if count[char] < 0:

            return False

 

    return True

 

Show more lines

🔸 Example Usage

Python

print(are_anagrams("listen", "silent"))  # True

print(are_anagrams("hello", "world"))    # False

 

🔹 Alternate Method: Using sorted()

Python

def are_anagrams(s1, s2):

    return sorted(s1) == sorted(s2)

 

This is simpler but less efficient for large strings due to sorting overhead.

Would you like a version that ignores case and whitespace or handles Unicode characters?

 

 

5. Find the longest palindrome substring in a string.

 To find the longest palindromic substring in a given string, you can use the expand-around-center approach, which is efficient and easy to implement.

Python Function: Longest Palindromic Substring

Python

def longest_palindrome(s):

    if not s:

        return ""

 

    start, end = 0, 0

 

    for i in range(len(s)):

        # Odd-length palindrome

        len1 = expand_from_center(s, i, i)

        # Even-length palindrome

        len2 = expand_from_center(s, i, i + 1)

        max_len = max(len1, len2)

 

        if max_len > (end - start):

            start = i - (max_len - 1) // 2

            end = i + max_len // 2

 

    return s[start:end + 1]

 

def expand_from_center(s, left, right):

    while left >= 0 and right < len(s) and s[left] == s[right]:

        left -= 1

        right += 1

    return right - left - 1

 

Show more lines

 

🔸 Example Usage

Python

print(longest_palindrome("babad"))  # Output: "bab" or "aba"

print(longest_palindrome("cbbd"))   # Output: "bb"

 

🔹 How It Works

  • It checks for palindromes centered at each character (odd and even).

  • Expands outward while characters match.

  • Keeps track of the longest one found.

Would you like a version that returns all longest palindromic substrings or visualizes the expansion process?

 

 

6. Implement a custom context manager using classes.

 You can implement a custom context manager in Python using a class by defining the special methods __enter__() and __exit__(). Here's a simple example that demonstrates how to create one:

 

Example: Custom Context Manager Using a Class

Python

class FileManager:

    def __init__(self, filename, mode):

        self.filename = filename

        self.mode = mode

        self.file = None

 

    def __enter__(self):

        print("Opening file...")

        self.file = open(self.filename, self.mode)

        return self.file

 

    def __exit__(self, exc_type, exc_value, traceback):

        print("Closing file...")

        if self.file:

            self.file.close()

        # Optionally handle exceptions

        if exc_type:

            print(f"An error occurred: {exc_value}")

        return True  # Suppress exception if needed

 

# Usage

with FileManager("example.txt", "w") as f:

    f.write("Hello, world!")

 

Show more lines

🔸 How It Works

  • __enter__() is called when the with block starts.

  • __exit__() is called when the block ends, even if an exception occurs.

  • You can use exc_type, exc_value, and traceback to handle errors gracefully.

Would you like to see a version tha

 

 

7. Write a decorator that logs function execution time.

 Here’s a Python decorator that logs the execution time of any function it wraps:

Execution Time Logging Decorator

Python

import time

import functools

 

def log_execution_time(func):

    @functools.wraps(func)

    def wrapper(*args, **kwargs):

        start_time = time.time()

        result = func(*args, **kwargs)

        end_time = time.time()

        print(f"Function '{func.__name__}' executed in {end_time - start_time:.4f} seconds")

        return result

    return wrapper

 

🔸 Example Usage

Python

@log_execution_time

def slow_function():

    time.sleep(2)

    return "Done"

 

print(slow_function())

 

Output:

Function 'slow_function' executed in 2.0001 seconds

Done

🔹 Features

  • Uses functools.wraps to preserve the original function’s metadata.

  • Measures time using time.time() (you can also use time.perf_counter() for higher precision).

  • Works with any function, including those with arguments.

Would you like to log execution time to a file or include timestamps and function arguments in the log?

 

 

8. Remove duplicates from a list while preserving order.

 To remove duplicates from a list while preserving order, you can use a set to track seen items and a loop to build the result:

Example Function

Python

def remove_duplicates(lst):

    seen = set()

    result = []

    for item in lst:

        if item not in seen:

            seen.add(item)

            result.append(item)

    return result

 

# Example usage

data = [1, 2, 2, 3, 1, 4, 3]

print(remove_duplicates(data))  # Output: [1, 2, 3, 4]

 

🔸 How It Works

  • seen keeps track of items already added.

  • result builds the final list in original order.

  • Works for hashable types (like numbers, strings, tuples).

 

 

9. Implement Fibonacci using recursion and generators.

 Here’s how you can implement the Fibonacci sequence using both recursion and generators in Python:

1. Using Recursion

Python

def fibonacci_recursive(n):

    if n <= 0:

        return 0

    elif n == 1:

        return 1

    else:

        return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)

 

# Example: Print first 10 Fibonacci numbers

for i in range(10):

    print(fibonacci_recursive(i), end=" ")

 

⚠️ Note: Recursive Fibonacci is not efficient for large n due to repeated calculations. You can optimize it using memoization.

2. Using a Generator

Python

def fibonacci_generator():

    a, b = 0, 1

    while True:

        yield a

        a, b = b, a + b

 

# Example: Print first 10 Fibonacci numbers

gen = fibonacci_generator()

for _ in range(10):

    print(next(gen), end=" ")

 

Generators are memory-efficient and great for producing sequences on demand.

Would you like to see a memoized recursive version or a visual plot of the Fibonacci sequence?

 

 

10. Count frequency of words in a text file.

 

To count the occurrences of each word in a text file using Python, you can employ the following method:

Python

from collections import Counter
 import re

 

 def count_word_occurrences(file_path):

     """

    Counts the occurrences of each word in a given text file.

 

    Args:

        file_path (str): The path to the text file.

 

    Returns:

        dict: A dictionary where keys are words and values are their counts.

    """
     word_counts = Counter()

     try:

         with open(file_path, 'r', encoding='utf-8') as file:

             for line in file:

                
# Convert to lowercase and split into words, removing non-alphanumeric characters
                 words = re.findall(r'\b\w+\b', line.lower())

                 word_counts.update(words)

     except FileNotFoundError:

         print(f"Error: The file '{file_path}' was not found.")

         return {}

     except Exception as e:

         print(f"An error occurred: {e}")

 
        return {}
     return dict(word_counts)

 

 
# Example usage:
 file_name = "sample.txt"

 
# Create a dummy file for demonstration
 with open(file_name, 'w') as f:

     f.write("This is a sample text file.\n")

     f.write("This file contains sample words.\n")

     f.write("A sample word is 'sample'.")

 

 occurrences = count_word_occurrences(file_name)

 

 if occurrences:

     print(f"Word occurrences in '{file_name}':")

     for word, count in occurrences.items():

         print(f"'{word}': {count}")

This code snippet defines a function count_word_occurrences that takes a file path as input. It utilizes the collections.Counter class for efficient word counting. The re.findall(r'\b\w+\b', line.lower()) part extracts words from each line, converting them to lowercase and ensuring only whole words are counted by using regular expressions to find word boundaries. The function includes error handling for FileNotFoundError and other potential exceptions during file processing. Finally, it demonstrates how to use the function and print the resulting word counts.

 

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.