Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Python Interview Question Answer

Python Programming question

Sum of Two Numbers:
Factorial of a Number:
Fibonacci Series:
Check Prime Number:
Palindrome Check:
Reverse a String:
Count Vowels and Consonants:
Find Largest Element in a List:
Calculate Area of a Circle:
Swap Two Variables:
Check Leap Year:
Generate Prime Numbers:
Find Common Elements in Lists:
Remove Duplicates from a List:
Count Occurrences of Elements in List:
Sort a List:
Check Anagram Strings:
Calculate LCM and GCD:
Find Missing Number in List:
Identify vowel and constant in python program
pythonloops
pythonvariables
python-functions

  1. Sum of Two Numbers: Calculate and print the sum of two numbers.
num1 = 10
num2 = 20
sum_nums = num1 + num2
print("Sum:", sum_nums)
Enter fullscreen mode Exit fullscreen mode
  1. Factorial of a Number: Calculate and print the factorial of a given number.
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

num = 5
fact = factorial(num)
print(f"Factorial of {num}:", fact)
Enter fullscreen mode Exit fullscreen mode
  1. Fibonacci Series: Generate and print the Fibonacci series up to a certain number of terms.
def fibonacci(n):
    fib_series = [0, 1]
    for i in range(2, n):
        fib_series.append(fib_series[i-1] + fib_series[i-2])
    return fib_series

num_terms = 10
fibonacci_series = fibonacci(num_terms)
print(f"Fibonacci series ({num_terms} terms):", fibonacci_series)
Enter fullscreen mode Exit fullscreen mode
  1. Check Prime Number: Check whether a given number is prime or not.
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

num = 17
if is_prime(num):
    print(f"{num} is a prime number.")
else:
    print(f"{num} is not a prime number.")
Enter fullscreen mode Exit fullscreen mode
  1. Palindrome Check: Check whether a given string is a palindrome or not.
def is_palindrome(s):
    s = s.lower().replace(" ", "")
    return s == s[::-1]

string = "racecar"
if is_palindrome(string):
    print(f"'{string}' is a palindrome.")
else:
    print(f"'{string}' is not a palindrome.")
Enter fullscreen mode Exit fullscreen mode
  1. Reverse a String: Reverse and print a given string.
def reverse_string(s):
    return s[::-1]

string = "Python is fun"
reversed_string = reverse_string(string)
print("Reversed string:", reversed_string)
Enter fullscreen mode Exit fullscreen mode
  1. Count Vowels and Consonants: Count and print the number of vowels and consonants in a string.
def count_vowels_consonants(s):
    vowels = "aeiouAEIOU"
    num_vowels = sum(1 for char in s if char in vowels)
    num_consonants = len(s) - num_vowels
    return num_vowels, num_consonants

string = "Hello, World!"
vowels, consonants = count_vowels_consonants(string)
print("Vowels:", vowels)
print("Consonants:", consonants)
Enter fullscreen mode Exit fullscreen mode
  1. Find Largest Element in a List: Find and print the largest element in a given list.
numbers = [12, 45, 23, 67, 89, 34]
largest = max(numbers)
print("Largest element:", largest)
Enter fullscreen mode Exit fullscreen mode
  1. Calculate Area of a Circle: Calculate and print the area of a circle given its radius.
import math

radius = 5
area = math.pi * radius ** 2
print("Area of the circle:", area)
Enter fullscreen mode Exit fullscreen mode
  1. Swap Two Variables: Swap the values of two variables.
a = 5
b = 10
a, b = b, a
print("a:", a)
print("b:", b)
Enter fullscreen mode Exit fullscreen mode
  1. Check Leap Year: Check whether a given year is a leap year or not.
def is_leap_year(year):
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        return True
    return False

year = 2024
if is_leap_year(year):
    print(f"{year} is a leap year.")
else:
    print(f"{year} is not a leap year.")
Enter fullscreen mode Exit fullscreen mode
  1. Generate Prime Numbers: Generate and print a list of prime numbers within a certain range.
def generate_primes(start, end):
    primes = []
    for num in range(start, end + 1):
        if is_prime(num):
            primes.append(num)
    return primes

start_range = 10
end_range = 50
prime_numbers = generate_primes(start_range, end_range)
print(f"Prime numbers between {start_range} and {end_range}:", prime_numbers)
Enter fullscreen mode Exit fullscreen mode
  1. Find Common Elements in Lists: Find and print the common elements between two lists.
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode
  1. Find Common Elements in Lists (contd): Find and print the common elements between two lists.
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
common_elements = [elem for elem in list1 if elem in list2]
print("Common elements:", common_elements)
Enter fullscreen mode Exit fullscreen mode
  1. Remove Duplicates from a List: Remove duplicates from a list and print the updated list.
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print("List with duplicates:", numbers)
print("List without duplicates:", unique_numbers)
Enter fullscreen mode Exit fullscreen mode
  1. Count Occurrences of Elements in List: Count and print the occurrences of each element in a list.
numbers = [1, 2, 2, 3, 4, 4, 5]
occurrences = {num: numbers.count(num) for num in set(numbers)}
print("Occurrences:", occurrences)
Enter fullscreen mode Exit fullscreen mode
  1. Sort a List: Sort a list in ascending order and print the sorted list.
numbers = [5, 2, 8, 1, 3, 9, 4]
sorted_numbers = sorted(numbers)
print("Sorted list:", sorted_numbers)
Enter fullscreen mode Exit fullscreen mode
  1. Check Anagram Strings: Check whether two given strings are anagrams or not.
def are_anagrams(str1, str2):
    return sorted(str1) == sorted(str2)

string1 = "listen"
string2 = "silent"
if are_anagrams(string1, string2):
    print(f"'{string1}' and '{string2}' are anagrams.")
else:
    print(f"'{string1}' and '{string2}' are not anagrams.")
Enter fullscreen mode Exit fullscreen mode
  1. Calculate LCM and GCD: Calculate and print the least common multiple (LCM) and greatest common divisor (GCD) of two numbers.
num1 = 12
num2 = 18
lcm = abs(num1 * num2) // math.gcd(num1, num2)
gcd = math.gcd(num1, num2)
print("LCM:", lcm)
print("GCD:", gcd)
Enter fullscreen mode Exit fullscreen mode
  1. Find Missing Number in List: Find and print the missing number in a list of consecutive numbers.
numbers = [1, 2, 3, 5, 6, 7, 8]
missing_number = sum(range(1, len(numbers) + 2)) - sum(numbers)
print("Missing number:", missing_number)
Enter fullscreen mode Exit fullscreen mode

These are just some examples of programming questions in Python. Each example covers a specific concept or problem-solving technique. You can use these examples as a starting point to explore different aspects of Python programming.
21.vowels and constonants

def classify_characters(input_string):
    vowels = "aeiouAEIOU"
    vowels_list = []
    consonants_list = []

    for char in input_string:
        if char.isalpha():
            if char in vowels:
                vowels_list.append(char)
            else:
                consonants_list.append(char)

    return vowels_list, consonants_list

input_string = input("Enter a string: ")
vowels, consonants = classify_characters(input_string)

print("Vowels:", vowels)
print("Consonants:", consonants)
Enter fullscreen mode Exit fullscreen mode

Python therotical question Question

What is Python? What are some key features of Python?

What is the difference between Python 2 and Python 3?

Explain the concept of duck typing in Python.

How do you handle exceptions in Python? Provide examples of exception handling code.

What are the differences between lists and tuples in Python?

Explain the concepts of shallow copy and deep copy in Python.

why we use self in python

explain list comprehension

what are namespace in python

Explain difference between args and keyargs

what are literals in python

what are difference between py and pyc in python

What is the difference between set and list

What is the difference between list and tuple

How do you iterate over items in a dictionary in Python?

What is the purpose of the init method in Python classes?

Explain the concept of generators in Python. How are they different from regular functions?

What are decorators in Python? How do you use them?

How does Python handle memory management? Explain the concepts of reference counting and garbage collection.

What are the differences between is and == operators in Python?

Explain the concept of Python's Global Interpreter Lock (GIL).

What are the differences between a module and a package in Python?

How do you handle file input/output operations in Python?

Explain the concept of list comprehensions in Python.

What are the differences between staticmethod and classmethod in Python?

How do you handle multi-threading in Python? What are some libraries or modules available for multi-threading?

Explain the concept of lambda functions in Python. When and how do you use them?

What are some built-in data types in Python?
What is docstring in Python?
What is pass in Python?

expalin difference between set and dictionary Python?

What are different type of function in Python?

Explain the concepts of shallow copy and deep copy in Python.

How do you handle working with dates and times in Python?

Explain the concept of name mangling in Python.

What are some common built-in functions in Python?

How do you handle working with JSON data in Python?

What is Python? What are some key features of Python

Python is a high-level, interpreted programming language known for its simplicity and readability. It was created by Guido van Rossum and first released in 1991. Here are some key features of Python:

Readability: Python emphasizes code readability with its clean and easily understandable syntax. This makes it easier for developers to write and maintain code. For example, the following code snippet prints "Hello, World!" in Python:

print("Hello, World!")
Enter fullscreen mode Exit fullscreen mode

Easy to Learn and Use: Python has a straightforward and beginner-friendly syntax, making it easy for newcomers to learn. Its simplicity allows developers to write code quickly and efficiently. Here's an example of a simple Python function that calculates the sum of two numbers:

def add_numbers(a, b):
    return a + b

result = add_numbers(3, 5)
print(result)  # Output: 8
Enter fullscreen mode Exit fullscreen mode

Large Standard Library: Python comes with a vast standard library that provides a wide range of modules and functions for various tasks. It eliminates the need for writing code from scratch for common functionalities. For example, the math module in Python provides mathematical functions like square root, trigonometric operations, and logarithmic functions.

import math

sqrt_result = math.sqrt(25)
print(sqrt_result)  # Output: 5.0
Enter fullscreen mode Exit fullscreen mode

Multi-paradigm: Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming. Developers can choose the most suitable approach for their specific needs and combine different paradigms as required.

Cross-platform: Python is available and runs on multiple platforms, including Windows, macOS, and various Linux distributions. This allows developers to write code once and run it on different operating systems without major modifications.

Extensive Third-party Libraries: Python has a vibrant and active community that has developed numerous third-party libraries and frameworks. These libraries extend the functionality of Python and provide solutions for various domains, such as data analysis, web development, machine learning, and more. Examples of popular Python libraries include NumPy, pandas, TensorFlow, Django, and Flask.

These are just a few key features that make Python a popular programming language. Its simplicity, readability, extensive standard library, and supportive community contribute to its widespread adoption and versatility across various domains and applications.

What are some common built-in functions in Python?

Python provides a wide range of built-in functions that are readily available for performing various operations. Here are some common built-in functions in Python with step-by-step examples:

print():
The print() function is used to display output to the console.
Example:

print("Hello, World!")
Output: Hello, World!
Enter fullscreen mode Exit fullscreen mode

len():
The len() function returns the length of a sequence (string, list, tuple, etc.).
Example:

text = "Python"
print(len(text))
Enter fullscreen mode Exit fullscreen mode

Output: 6

type():
The type() function returns the type of an object.
Example:

number = 42
print(type(number))
Enter fullscreen mode Exit fullscreen mode

Output:

input():
The input() function allows the user to enter data from the console.
Example:

name = input("Enter your name: ")
print("Hello, " + name + "!")
Enter fullscreen mode Exit fullscreen mode

Output:

Enter your name: John
Hello, John!
Enter fullscreen mode Exit fullscreen mode

range():
The range() function generates a sequence of numbers within a specified range.
Example:

numbers = list(range(1, 6))
print(numbers)
Enter fullscreen mode Exit fullscreen mode

Output: [1, 2, 3, 4, 5]

int(), float(), str():
These functions convert a value to an integer, floating-point number, or string, respectively.
Example:

number = "42"
int_number = int(number)
float_number = float(number)
print(int_number, float_number)
Enter fullscreen mode Exit fullscreen mode

Output: 42 42.0

sum(), min(), max():
These functions calculate the sum, minimum, and maximum of a list of numbers, respectively.
Example:

numbers = [5, 10, 3, 8]
print(sum(numbers), min(numbers), max(numbers))
Enter fullscreen mode Exit fullscreen mode

Output: 26 3 10

sorted():
The sorted() function returns a new sorted list from the elements of an iterable.
Example:

numbers = [5, 10, 3, 8]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
Enter fullscreen mode Exit fullscreen mode

Output: [3, 5, 8, 10]

str.format():
The str.format() method is used for string formatting.
Example:

name = "Alice"
age = 30
message = "My name is {}, and I am {} years old.".format(name, age)
print(message)
Enter fullscreen mode Exit fullscreen mode

Output: My name is Alice, and I am 30 years old.

abs():
The abs() function returns the absolute value of a number.
Example:

num = -5
abs_num = abs(num)
print(abs_num)
Enter fullscreen mode Exit fullscreen mode

Output: 5

These are just a few examples of common built-in functions in Python. Python's extensive standard library provides a wealth of other useful functions for various tasks, and it's essential to explore the official Python documentation to learn more about them.

What are some common built-in functions in Django?

Django provides a variety of built-in functions and utilities that make web development easier and more efficient. Here are some common built-in functions in Django with step-by-step examples:

HttpResponse:
The HttpResponse class is used to send an HTTP response to the client.
Example:

from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello, World!")
Enter fullscreen mode Exit fullscreen mode

In this example, we define a view named hello that returns a simple "Hello, World!" message as an HTTP response.

render:
The render function is used to render an HTML template with context data and return it as an HTTP response.
Example:

from django.shortcuts import render

def greet(request):
    name = 'John'
    context = {'name': name}
    return render(request, 'greet.html', context)
Enter fullscreen mode Exit fullscreen mode

In this example, we define a view named greet that renders the greet.html template with the name variable passed as context data.

redirect:
The redirect function is used to redirect the user to a different URL.
Example:

from django.shortcuts import redirect

def redirect_to_home(request):
    return redirect('home')
Enter fullscreen mode Exit fullscreen mode

In this example, when the redirect_to_home view is called, it redirects the user to the URL with the name 'home' defined in the urls.py file.

get_object_or_404:
The get_object_or_404 function retrieves an object from the database, but if it doesn't exist, it raises a 404 HTTP response.
Example:

from django.shortcuts import get_object_or_404
from .models import Post

def post_detail(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    return render(request, 'post_detail.html', {'post': post})
Enter fullscreen mode Exit fullscreen mode

In this example, we define a view named post_detail that retrieves a Post object with the given post_id. If the object doesn't exist, it raises a 404 response.

reverse:
The reverse function generates a URL for a given view name and arguments.
Example:

from django.urls import reverse
from django.http import HttpResponse

def redirect_to_hello(request):
    url = reverse('hello')
    return HttpResponse(f"Redirecting to: {url}")
Enter fullscreen mode Exit fullscreen mode

In this example, the redirect_to_hello view generates the URL for the view with the name 'hello' and returns it as an HTTP response.

get_list_or_404:
The get_list_or_404 function retrieves a list of objects from the database, but if the list is empty, it raises a 404 HTTP response.
Example:

from django.shortcuts import get_list_or_404
from .models import Post

def all_posts(request):
    posts = get_list_or_404(Post)
    return render(request, 'all_posts.html', {'posts': posts})
Enter fullscreen mode Exit fullscreen mode

In this example, we define a view named all_posts that retrieves all Post objects from the database. If the list is empty, it raises a 404 response.

Python 2 and Python 3 are different versions of the Python

programming language. Python 3 was released as a successor to Python 2 with several significant changes and improvements. The main differences between Python 2 and Python 3 are as follows:

Print Statement:

Python 2: Uses the print statement without parentheses.
Python 3: Uses the print() function with parentheses.
Enter fullscreen mode Exit fullscreen mode

Division Operator:

Python 2: Uses integer division by default when dividing two integers (e.g., 5/2 = 2).
Python 3: Performs true division when dividing two integers (e.g., 5/2 = 2.5). Integer division can be obtained using the // operator.
Enter fullscreen mode Exit fullscreen mode

Unicode Support:

Python 2: Uses ASCII for strings by default and requires the u prefix for Unicode strings (e.g., u'Hello').
Python 3: Uses Unicode for strings by default and allows regular strings to include Unicode characters directly.
Enter fullscreen mode Exit fullscreen mode

Syntax Changes:

Python 3: Requires parentheses for print, removes xrange() in favor of range(), and changes some syntax (e.g., raw_input() is now input()).
Iterating Over Dictionaries:

Python 2: Uses dict.iteritems(), dict.iterkeys(), and dict.itervalues() for iterating over dictionary keys, values, and items, respectively.
Python 3: Uses dict.items(), dict.keys(), and dict.values() for dictionary iteration.
Enter fullscreen mode Exit fullscreen mode

Unicode and str types:

Python 2: Uses str for ASCII strings and unicode for Unicode strings.
Python 3: Unifies both ASCII and Unicode strings into the str type.
Enter fullscreen mode Exit fullscreen mode

Exceptions:

Python 2: Uses except Exception, e for catching exceptions.
Python 3: Uses except Exception as e for catching exceptions.
xrange():

Python 2: Uses xrange() for creating iterators over a range of values.
Python 3: Removes xrange() and renames range() to behave like xrange() (generating an iterator) in Python 2.
Enter fullscreen mode Exit fullscreen mode

Standard Library Changes:

Some modules were renamed or reorganized in Python 3.
Library Support:

Python 2: Some libraries and packages might have better support and more extensive documentation.
Python 3: Many libraries have been updated to support Python 3.
Enter fullscreen mode Exit fullscreen mode

It's essential to note that Python 2 reached its end of life on January 1, 2020, and is no longer actively maintained or updated with new features. New projects should use Python 3, as it offers improved performance, better language features, and ongoing support from the Python community. However, existing projects may still be using Python 2, so it's essential to understand the differences when working with codebases on different Python versions.

These are just a few examples of common built-in functions in Django. There are many other utility functions and classes provided by Django that can greatly simplify web development tasks.

concept of name mangling in Python

In Python, name mangling is a mechanism that alters the name of a class member (attribute or method) to make it unique, primarily to avoid name clashes in subclasses. This process involves adding a prefix to the member's name to prevent unintentional overrides when subclassing.

Name mangling is achieved by prefixing the member name with double underscores (__). The Python interpreter modifies the name to include the class name as a prefix. This makes the member name unique within its class, reducing the risk of accidental overriding in subclasses.

Let's look at an example to better understand name mangling:

class MyClass:
    def __init__(self):
        self.__private_var = 42
        self._protected_var = 99
        self.public_var = 100

    def __private_method(self):
        return "I am a private method"

    def _protected_method(self):
        return "I am a protected method"

    def public_method(self):
        return "I am a public method"
Enter fullscreen mode Exit fullscreen mode
class MySubclass(MyClass):
    def __init__(self):
        super().__init__()

    def access_members(self):
        # Trying to access the private member from the subclass
        print(self.__private_var)  # Will raise an AttributeError

        # Accessing the protected member from the subclass
        print(self._protected_var)  # Will work

        # Accessing the public member from the subclass
        print(self.public_var)  # Will work

        # Trying to access the private method from the subclass
        print(self.__private_method())  # Will raise an AttributeError

        # Accessing the protected method from the subclass
        print(self._protected_method())  # Will work

        # Accessing the public method from the subclass
        print(self.public_method())  # Will work


obj = MySubclass()
obj.access_members()
Enter fullscreen mode Exit fullscreen mode

In this example, we have a base class MyClass with three members: __private_var, _protected_var, and public_var, and three methods: __private_method, _protected_method, and public_method.

When we create a subclass MySubclass that inherits from MyClass, we try to access these members and methods from the subclass using the self keyword.

The attempt to access private_var and __private_method from the subclass raises an AttributeError. This is because the double underscores trigger name mangling, changing the names to _MyClassprivate_var and MyClass_private_method, respectively. Thus, these members are not directly accessible from the subclass.

The _protected_var and _protected_method are accessible from the subclass since they are protected members. Although not enforced by Python's access control, the single underscore prefix indicates that these members are intended to be "protected" and should not be accessed outside the class or its subclasses.

The public_var and public_method are accessible directly from the subclass since they have no name mangling and no underscore prefix.

Name mangling helps maintain encapsulation and prevents accidental overriding of class members, contributing to the robustness and integrity of class hierarchies in Python.

concepts of shallow copy and deep copy in Python

In Python, when you want to create a copy of an object (e.g., a list or a dictionary), there are two methods to do it: shallow copy and deep copy. Both methods create a new object, but they handle nested objects (objects within objects) differently. Let's understand these concepts with coding examples:

Shallow Copy:
A shallow copy creates a new object, but the elements inside the new object still refer to the same objects as the original. Changes made to the nested objects will be reflected in both the original and the shallow copy.
Example of a shallow copy:

# Original list with nested list
original_list = [[1, 2, 3], [4, 5, 6]]

# Shallow copy
shallow_copied_list = copy.copy(original_list)

# Modify the nested list in the shallow copy
shallow_copied_list[0][0] = 10

print("Original List:", original_list)         # Output: Original List: [[10, 2, 3], [4, 5, 6]]
print("Shallow Copied List:", shallow_copied_list)  # Output: Shallow Copied List: [[10, 2, 3], [4, 5, 6]]
Enter fullscreen mode Exit fullscreen mode

In this example, we create a shallow copy of the original_list, and then we modify an element in the nested list of the shallow copy. The same change is reflected in the original_list as well.

Deep Copy:
A deep copy creates a new object and recursively copies all nested objects within it. Changes made to the nested objects in the deep copy will not affect the original.
Example of a deep copy:

# Original list with nested list
original_list = [[1, 2, 3], [4, 5, 6]]

# Deep copy
deep_copied_list = copy.deepcopy(original_list)

# Modify the nested list in the deep copy
deep_copied_list[0][0] = 10

print("Original List:", original_list)        # Output: Original List: [[1, 2, 3], [4, 5, 6]]
print("Deep Copied List:", deep_copied_list)  # Output: Deep Copied List: [[10, 2, 3], [4, 5, 6]]
Enter fullscreen mode Exit fullscreen mode

In this example, we create a deep copy of the original_list, and then we modify an element in the nested list of the deep copy. The change is only seen in the deep copy, and the original_list remains unchanged.

To summarize:

Shallow copy creates a new object but references the same nested objects as the original.
Deep copy creates a new object and recursively copies all nested objects, resulting in a completely independent copy.
Choosing between shallow and deep copy depends on the structure of your data and the level of independence you need between the original and copied objects.

Shallow Copy in Django:
A shallow copy in Django creates a new instance of the model but does not create new copies of related objects. The copied instance and the original instance will still share the same related objects.
Example of a shallow copy in Django:

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

# Original Author instance
original_author = Author.objects.get(pk=1)

# Shallow copy
shallow_copied_author = original_author

# Modify the copied instance
shallow_copied_author.name = "John Doe (Copied)"
shallow_copied_author.pk = None  # Set PK to None to create a new instance in the database
shallow_copied_author.save()

# Both the original and copied instance will have the same books
print(original_author.name)  # Output: John Doe (Copied)
print(original_author.book_set.all())  # Output: Books related to John Doe (Copied)

print(shallow_copied_author.name)  # Output: John Doe (Copied)
print(shallow_copied_author.book_set.all())  # Output: Books related to John Doe (Copied)
In this example, the shallow copy of the Author instance (shallow_copied_author) and the original Author instance (original_author) will still share the same related Book objects.
Enter fullscreen mode Exit fullscreen mode

Deep Copy in Django:
A deep copy in Django creates a new instance of the model and also creates new copies of related objects, ensuring that the copied instance is fully independent of the original.
Example of a deep copy in Django:

# Original Author instance
original_author = Author.objects.get(pk=1)

# Deep copy
deep_copied_author = copy.deepcopy(original_author)

# Modify the copied instance
deep_copied_author.name = "Jane Smith (Deep Copy)"
deep_copied_author.pk = None  # Set PK to None to create a new instance in the database
deep_copied_author.save()

# The copied instance has its own set of books
print(original_author.name)  # Output: John Doe
print(original_author.book_set.all())  # Output: Books related to John Doe

print(deep_copied_author.name)  # Output: Jane Smith (Deep Copy)
print(deep_copied_author.book_set.all())  # Output: No books related to Jane Smi
Enter fullscreen mode Exit fullscreen mode

What are decorators in Python? How do you use them? with examples

In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods without directly changing their code. Decorators allow you to wrap a function inside another function and modify its behavior before or after its execution. They are denoted by the @decorator_function syntax.

To use a decorator, you define a function that takes another function as an argument, and then you return a new function that includes the modifications you want to apply to the original function.

Let's understand decorators with some examples:

Example 1: Creating a Simple Decorator

# Define a decorator function
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()  # Call the original function
        print("Something is happening after the function is called.")
    return wrapper

# Apply the decorator using @ syntax
@my_decorator
def say_hello():
    print("Hello!")

# Call the decorated function
say_hello()
Enter fullscreen mode Exit fullscreen mode

Output:

Something is happening before the function is called.
Hello!
Enter fullscreen mode Exit fullscreen mode

Something is happening after the function is called.
In this example, my_decorator is a simple decorator that wraps the say_hello function. When we call say_hello(), the decorator modifies its behavior by adding additional messages before and after the original function call.

Example 2: Decorator with Arguments

def repeat_n_times(n):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(n):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat_n_times(3)
def greet(name):
    print(f"Hello, {name}!")

greet("John")
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, John!
Hello, John!
Hello, John!
Enter fullscreen mode Exit fullscreen mode

In this example, repeat_n_times is a decorator factory that takes an argument n. It returns a decorator function that repeats the execution of the decorated function n times. The greet function is decorated with @repeat_n_times(3), so it is called three times with the name "John."

Example 3: Decorators with Function Signatures

import functools

def log_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned: {result}")
        return result
    return wrapper

@log_decorator
def add(a, b):
    return a + b

result = add(2, 3)
print(result)
Enter fullscreen mode Exit fullscreen mode

Output:

Calling add with args: (2, 3), kwargs: {}
add returned: 5
5
Enter fullscreen mode Exit fullscreen mode

In this example, we use the functools.wraps decorator from the Python standard library to preserve the original function's name and docstring in the decorated function. This ensures that the decorated function appears with the correct name in documentation or error messages.

Mixed question

Lists and Map:

  1. Create a list of integers and use map() to square each element.
  2. Generate a list of odd numbers from 1 to 20 using range() and filter out even numbers using filter().
  3. Given a list of strings, use map() to convert them to uppercase.
  4. Create a list of floating-point numbers and calculate their integer part using map() and int().
  5. Given a list of words, use map() to find the lengths of each word.
  6. Generate a list of numbers from 1 to 10 and use map() to check if they are prime.
  7. Convert a list of Celsius temperatures to Fahrenheit using map() and a conversion function.
  8. Create a list of strings and use map() to remove whitespace from each string.
  9. Use map() to calculate the factorial of numbers in a list of integers.
  10. Generate a list of integers from 10 to 1 using range() and reverse it using reversed().
    Ranges, Tuples, and Lists:

  11. Create a list of tuples, where each tuple contains a name and age.

  12. Generate a list of tuples representing (year, month) pairs for the last 12 months.

  13. Calculate the sum of elements in a list of tuples, where each tuple contains two numbers.

  14. Use zip() to combine two lists into a list of tuples.

  15. Generate a list of tuples representing (index, value) pairs from a list using enumerate()
    .
    Dictionaries and Map:

  16. Create a dictionary of items and their prices, then apply a discount using map().

  17. Generate a dictionary of numbers and their squares using range() and map().

  18. Given a dictionary of names and scores, use map() to determine pass/fail for each student.

  19. Create a dictionary of words and their lengths, using map() to compute the lengths.

  20. Use map() to capitalize the first letter of each value in a dictionary of words
    .
    Sets and Map:

  21. Create a set of integers and use map() to square each element.

  22. Given a set of strings, use map() to convert them to lowercase.

  23. Generate a set of numbers from 1 to 10 and use map() to check if they are prime.

  24. Create a set of words and use map() to find the lengths of each word.

  25. Use map() to calculate the factorial of elements in a set of integers
    .
    Combination of Structures:

  26. Create a list of dictionaries, where each dictionary contains information about a person.

  27. Generate a list of tuples representing (name, age) pairs using zip() and range().

  28. Create a dictionary where the keys are words and the values are their lengths.

  29. Given a list of dictionaries, use map() to extract the values associated with a specific key.

  30. Create a list of tuples, each containing a name and a set of hobbies
    .
    More Complex Combinations:

  31. Generate a list of numbers from 1 to 100 and use a dictionary to categorize them as even or odd.

  32. Write a function that takes a list of numbers, filters out prime numbers using filter(), and returns a list of tuples with the original number and its square.

  33. Create a dictionary of words and their meanings, then use a list comprehension to find words longer than a certain length.

  34. Generate a list of tuples representing (day, temperature) pairs for a week. Use a dictionary to store the data for each day.

  35. Write a program that calculates the average temperature for each day of the week using a dictionary of lists
    .
    Advanced Mix:

  36. Create a list of tuples containing (word, frequency) pairs, where the frequency is determined by a dictionary.

  37. Write a function that takes a list of tuples containing (name, score) pairs and returns a dictionary with each student's name as the key and their average score as the value.

  38. Generate a list of tuples representing (year, month, day) using zip() and range(), and store them in a dictionary with each date as a key.

  39. Create a dictionary where keys are numbers and values are sets of their divisors. Use a list comprehension to generate the sets.

  40. Write a program that uses dictionaries to track word frequencies in a given text. Use a set to store a list of stop words to exclude from counting
    .
    These questions cover a wide range of scenarios involving combinations of map(), lists, ranges, tuples, dictionaries, and sets. They're designed to challenge your understanding of these data structures and their interactions.

Image description

Image description

Interview question

list
map
dictionary
set
tuple
ranage
sudo code round
sudo round
.

Top comments (0)