From ecb12b0d573bb2e444aa145bd053747a9e1916c3 Mon Sep 17 00:00:00 2001 From: Ajay-Dhangar Date: Fri, 30 Aug 2024 20:47:40 +0530 Subject: [PATCH] Update codes --- docs/python/Interview ques/Advance.md | 667 ----------------- docs/python/Interview ques/Basic.md | 661 ----------------- docs/python/Interview ques/Intermediate.md | 800 --------------------- docs/python/Interview ques/_category_.json | 8 - docusaurus.config.js | 2 +- 5 files changed, 1 insertion(+), 2137 deletions(-) delete mode 100644 docs/python/Interview ques/Advance.md delete mode 100644 docs/python/Interview ques/Basic.md delete mode 100644 docs/python/Interview ques/Intermediate.md delete mode 100644 docs/python/Interview ques/_category_.json diff --git a/docs/python/Interview ques/Advance.md b/docs/python/Interview ques/Advance.md deleted file mode 100644 index 51217294c..000000000 --- a/docs/python/Interview ques/Advance.md +++ /dev/null @@ -1,667 +0,0 @@ ---- -id: advance-level -title: Advance Level Interview Question -sidebar_label: Advance Level -sidebar_position: 3 -tags: [python,Advance level,Interview Question] -description: In this tutorial, you'll be focusing on advance-level interview questions. ---- - -1. **Explain the Global Interpreter Lock (GIL) in Python. What are its implications on concurrency and multi-threading?** - - **Answer:** The GIL is a mutex that protects access to Python objects, ensuring only one thread executes Python bytecode at a time. This limits multi-threaded performance for CPU-bound tasks but allows efficient I/O-bound tasks and simplifies memory management. - -2. **Discuss Python's memory management mechanism, including reference counting and garbage collection. How does it impact performance and memory usage?** - - **Answer:** Python uses reference counting to manage object lifetimes and garbage collection (cyclic GC) to detect and clean up unused objects. While efficient for most cases, cyclic GC can introduce overhead and occasional delays due to periodic collection runs. - -3. **Explain the use of Python's `asyncio` module for asynchronous programming. How does it differ from threads and multiprocessing?** - - **Answer:** `asyncio` enables concurrent I/O-bound operations using coroutines (`async` and `await`), managed by an event loop. Unlike threads and multiprocessing, `asyncio` is single-threaded but supports thousands of tasks due to cooperative multitasking, suitable for scalable network applications. - -4. **What are Python decorators, and how can they be used for metaprogramming? Provide examples of their application in modifying function behavior.** - - **Answer:** Decorators are functions that modify the behavior of other functions or methods. They are powerful for metaprogramming tasks like logging, authentication, and caching. - ```python - def my_decorator(func): - def wrapper(*args, **kwargs): - print('Before function execution') - result = func(*args, **kwargs) - print('After function execution') - return result - return wrapper - - @my_decorator - def say_hello(): - print('Hello!') - - say_hello() # Output: Before function execution, Hello!, After function execution - ``` - -5. **Discuss the use of metaclasses in Python. Provide an example of how they can be used to customize class creation behavior.** - - **Answer:** Metaclasses allow customization of class creation by overriding the default `__new__` and `__init__` methods of `type`. They are useful for enforcing class constraints, adding class-level methods, or modifying attribute handling during class instantiation. - ```python - class MyMeta(type): - def __new__(cls, name, bases, dct): - dct['attr'] = 100 - return super().__new__(cls, name, bases, dct) - - class MyClass(metaclass=MyMeta): - pass - - print(MyClass.attr) # Output: 100 - ``` - -6. **Explain the concept of Python descriptors. Provide examples of how they can be used to control attribute access and modification.** - - **Answer:** Descriptors are objects that define how attribute access is handled by defining `__get__`, `__set__`, or `__delete__` methods. They are used for implementing managed attributes with custom behavior. - ```python - class Temperature: - def __init__(self, celsius=0): - self._celsius = celsius - - def to_fahrenheit(self): - return (self._celsius * 9/5) + 32 - - def get_temperature(self): - print("Getting value") - return self._celsius - - def set_temperature(self, value): - if value < -273.15: - raise ValueError("Temperature below -273.15 is not possible") - print("Setting value") - self._celsius = value - - temperature = property(get_temperature, set_temperature) - - # Usage - t = Temperature() - t.temperature = 30 # Setting value - print(t.temperature) # Getting value, Output: 30 - ``` - -7. **Discuss the usage and benefits of Python's `collections` module. Provide examples of commonly used data structures from this module.** - - **Answer:** The `collections` module provides specialized data structures beyond built-in types like lists and dictionaries, optimized for specific use cases. - - Examples include `namedtuple` for memory-efficient data containers, `defaultdict` for default values in dictionaries, `Counter` for counting hashable objects, and `deque` for double-ended queues. - -8. **Explain the purpose and usage of Python's `multiprocessing` module for parallel processing. How does it differ from threading?** - - **Answer:** The `multiprocessing` module allows parallel execution using separate processes, leveraging multiple CPU cores. Unlike threading, each process has its own memory space, avoiding the GIL limitation and making it suitable for CPU-bound tasks. - -9. **Discuss Python's support for functional programming features like `map`, `filter`, and `reduce`. Provide examples of their usage.** - - **Answer:** Functional programming features in Python facilitate concise and expressive code by operating on iterables without modifying them. - ```python - # Example of map - numbers = [1, 2, 3, 4, 5] - squared = list(map(lambda x: x**2, numbers)) - print(squared) # Output: [1, 4, 9, 16, 25] - - # Example of filter - even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) - print(even_numbers) # Output: [2, 4] - - # Example of reduce (requires importing functools) - from functools import reduce - product = reduce(lambda x, y: x * y, numbers) - print(product) # Output: 120 - ``` - -10. **Explain the concept of Python's `contextlib` module. How can it be used to create context managers?** - - **Answer:** The `contextlib` module simplifies the creation of context managers using the `contextmanager` decorator, allowing resources to be managed using the `with` statement. - ```python - from contextlib import contextmanager - - @contextmanager - def file_opener(filename, mode): - try: - f = open(filename, mode) - yield f - finally: - f.close() - - with file_opener('example.txt', 'r') as f: - print(f.read()) - ``` - -11. **Discuss Python's `itertools` module. Provide examples of commonly used functions and their applications.** - - **Answer:** The `itertools` module provides functions for creating iterators for efficient looping and data manipulation. - ```python - import itertools - - # Example of itertools.cycle() - numbers = [1, 2, 3] - cycle_iter = itertools.cycle(numbers) - for _ in range(5): - print(next(cycle_iter)) # Output: 1, 2, 3, 1, 2 - - # Example of itertools.chain() - list1 = [1, 2, 3] - list2 = ['a', 'b', 'c'] - combined = itertools.chain(list1, list2) - print(list(combined)) # Output: [1, 2, 3, 'a', 'b', 'c'] - ``` - -12. **Explain Python's `functools` module. Provide examples of its usage, including `functools.partial` and `functools.lru_cache`.** - - **Answer:** The `functools` module provides higher-order functions for functional programming tasks. - ```python - from functools import partial, lru_cache - - # Example of functools.partial() - def power(base, exponent): - return base ** exponent - - square = partial(power, exponent=2) - print(square(5)) # Output: 25 - - # Example of functools.lru_cache() - @lru_cache(maxsize=None) - def fib(n): - if n < 2: - return n - return fib(n-1) + fib(n-2) - - print(fib(10)) # Output: 55 - ``` - -13. **Discuss Python's `logging` module for structured logging. How does it help in debugging and error tracking?** - - **Answer:** The `logging` module provides a flexible framework for emitting log messages from Python programs. It supports multiple log levels, configurable output destinations, and formatting options, making it essential for debugging and error tracking in complex applications. - ```python - import logging - - # Configure logging - logging.basicConfig(level=logging.DEBUG, - format='%(asctime)s - %(levelname)s - %(message)s') - - # Example usage - def divide(x, y): - try: - result = x / y - except ZeroDivisionError: - logging.error('Tried to divide by zero') - else: - logging.info(f'Division result: {result}') - return result - - divide(10, 0) - ``` - -14. **Explain the use of Python's `pdb` module for debugging. How can it be used to set breakpoints and step through code?** - - **Answer:** The `pdb` module is Python's built-in debugger, allowing interactive debugging of Python programs. - ```python - import pdb - - def calculate(x, y): - result = x + y - pdb.set_trace() # Set breakpoint - result *= 2 - return result - - calculate(10, 5) - ``` - When executed, this code will pause at the `pdb.set_trace()` line, allowing inspection of variables (`x`, `y`, `result`) and stepping through code execution. - -15. **Explain the concept of Python decorators with parameters. Provide examples of how decorators can accept arguments and modify function behavior accordingly.** - - **Answer:** Decorators with parameters are implemented using nested functions. They allow customization of decorator behavior based on arguments passed. - ```python - def repeat(num_times): - def decorator_repeat(func): - def wrapper(*args, **kwargs): - for _ in range(num_times): - result = func(*args, **kwargs) - return result - return wrapper - return decorator_repeat - - @repeat(num_times=3) - def greet(name): - print(f'Hello, {name}') - - greet('Alice') - # Output: - # Hello, Alice - # Hello, Alice - # Hello, Alice - ``` - -16. **Discuss Python's `argparse` module for command-line argument parsing. How does it handle argument parsing and validation?** - - **Answer:** The `argparse` module simplifies parsing command-line arguments and options in Python scripts, providing built-in support for argument types, default values, help messages, and validation. - ```python - import argparse - - parser = argparse.ArgumentParser(description='Process some integers.') - parser.add_argument('integers', metavar='N', type=int, nargs='+', - help='an integer for the accumulator') - parser.add_argument('--sum', dest='accumulate', action='store_const', - const=sum, default=max, - help='sum the integers (default: find the max)') - - args = parser.parse_args() - print(args.accumulate(args.integers)) - ``` - -17. **Explain Python's `collections.defaultdict`. Provide an example of its usage and advantages over standard dictionaries.** - - **Answer:** `defaultdict` is a subclass of `dict` from the `collections` module that provides a default value for missing keys. - ```python - from collections import defaultdict - - # Example usage - d = defaultdict(int) - d['a'] = 1 - print(d['a']) # Output: 1 - print(d['b']) # Output: 0 (default value for int) - ``` - -18. **Discuss Python's `async` and `await` keywords for asynchronous programming. How do they facilitate concurrent execution of tasks?** - - **Answer:** `async` defines an asynchronous function (coroutine), while `await` pauses execution until the awaited coroutine completes, allowing non-blocking concurrent execution of multiple tasks. - ```python - import asyncio - - async def async_task(): - print('Task 1') - await asyncio.sleep(1) - print('Task 2') - - asyncio.run(async_task()) - # Output: - # Task 1 - # (1 second delay) - # Task 2 - ``` - -19. **Discuss Python's support for functional programming with `lambda` functions. Provide examples of their usage and limitations.** - - **Answer:** `lambda` functions are anonymous functions defined using the `lambda` keyword, typically used for short, one-line functions. - ```python - # Example usage - square = lambda x: x ** 2 - print(square(5)) # Output: 25 - - # Limitations: Limited to single expressions, cannot contain statements or multiple lines of code. - ``` - -20. **Explain Python's `concurrent.futures` module. How does it simplify concurrent programming with threads and processes?** - - **Answer:** The `concurrent.futures` module provides a high-level interface for asynchronously executing callable objects (`ThreadPoolExecutor` for threads, `ProcessPoolExecutor` for processes), managing futures, and handling results asynchronously. - ```python - from concurrent.futures import ThreadPoolExecutor - - def square(n): - return n ** 2 - - with ThreadPoolExecutor() as executor: - futures = [executor.submit(square, i) for i in range(10)] - results = [future.result() for future in futures] - print(results) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] - ``` - -21. **Discuss Python's `contextlib` module. How can it be used to create context managers? Provide examples of its usage.** - - **Answer:** The `contextlib` module simplifies the creation of context managers using the `contextmanager` decorator, allowing resources to be managed using the `with` statement. - ```python - from contextlib import contextmanager - - @contextmanager - def file_opener(filename, mode): - try: - f = open(filename, mode) - yield f - finally: - f.close() - - with file_opener('example.txt', 'r') as f: - print(f.read()) - ``` - -22. **Explain Python's `threading` module. How does it facilitate concurrent programming? Discuss its limitations compared to `multiprocessing`.** - - **Answer:** The `threading` module in Python provides a way to create and manage threads for concurrent execution within a single process. It allows sharing of memory between threads but is limited by the Global Interpreter Lock (GIL), restricting CPU-bound performance compared to `multiprocessing`. - -23. **Discuss Python's `unittest` framework for unit testing. How does it facilitate test-driven development (TDD)?** - - **Answer:** The `unittest` module provides a framework for writing and running tests in Python, supporting test discovery, fixtures, assertions, and test suites. It promotes TDD by encouraging developers to write tests before code implementation to ensure functionality and maintainability. - -24. **Explain Python's support for metaprogramming with `__getattr__`, `__setattr__`, and `__delattr__` methods. Provide examples of their usage.** - - **Answer:** Metaprogramming in Python allows modification of class attributes and behavior dynamically. - ```python - class DynamicAttributes: - def __init__(self): - self._attrs = {} - - def __getattr__(self, name): - if name in self._attrs: - return self._attrs[name] - else: - raise AttributeError(f'{self.__class__.__name__} object has no attribute {name}') - - def __setattr__(self, name, value): - self._attrs[name] = value - - def __delattr__(self, name): - del self._attrs[name] - - obj = DynamicAttributes() - obj.name = 'Alice' - print(obj.name) # Output: Alice - del obj.name - ``` - -25. **Discuss Python's `sys` module. How can it be used for system-level operations and interaction with the interpreter?** - - **Answer:** The `sys` module provides access to system-specific parameters and functions, such as command-line arguments (`sys.argv`), Python interpreter details (`sys.version`), and standard input/output (`sys.stdin`, `sys.stdout`, `sys.stderr`). - -26. **Explain Python's support for database access using modules like `sqlite3` or ORM frameworks like `SQLAlchemy`. Provide examples of their usage.** - - **Answer:** Python supports database access through modules like `sqlite3` for SQLite databases and ORM frameworks like `SQLAlchemy` for relational databases. - ```python - import sqlite3 - - # Example using sqlite3 - conn = sqlite3.connect('example.db') - cursor = conn.cursor() - cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)') - cursor.execute('INSERT INTO users (name) VALUES (?)', ('Alice',)) - conn.commit() - - # Example using SQLAlchemy (ORM) - from sqlalchemy import create_engine, Column, Integer, String - from sqlalchemy.ext.declarative import declarative_base - from sqlalchemy.orm import sessionmaker - - engine = create_engine('sqlite:///example.db', echo=True) - Base = declarative_base() - - class User(Base): - __tablename__ = 'users' - id = Column(Integer, primary_key=True) - name = Column(String) - - Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) - session = Session() - user = User(name='Bob') - session.add(user) - session.commit() - ``` - -27. **Explain the purpose and usage of Python's `async` generators. How do they combine asynchronous programming with generator functions?** - - **Answer:** `async` generators allow asynchronous iteration over a sequence of values, combining the capabilities of asynchronous programming (`async` and `await` keywords) with generator functions (`yield` statement), enabling efficient handling of asynchronous data streams. - ```python - async def async_data_stream(): - for i in range(5): - yield i - await asyncio.sleep(1) - - async def main(): - async for value in async_data_stream(): - print(value) - - asyncio.run(main()) - ``` - -28. **Discuss Python's support for web development with frameworks like Django and Flask. How do they differ in their approach and usage?** - - **Answer:** Django and Flask are popular Python web frameworks: - - **Django** is a full-stack framework with built-in features for ORM, admin interface, authentication, and template engine, promoting rapid development of complex web applications. - - **Flask** is a micro-framework providing flexibility and simplicity, allowing developers to choose components and libraries for custom applications, suitable for smaller projects and APIs. - -29. **Explain the use of Python's `pickle` module for object serialization. What are its advantages and potential security concerns?** - - **Answer:** The `pickle` module serializes Python objects into byte streams, facilitating object persistence and data interchange between Python applications. Advantages include ease of use and support for complex data structures. Security concerns arise from potential risks of executing malicious code when loading untrusted pickle data. - -30. **Discuss Python's support for functional programming paradigms with `map`, `filter`, and `reduce`. How do they enhance code readability and performance?** - - **Answer:** Functional programming features (`map`, `filter`, `reduce`) in Python promote concise and declarative coding style: - ```python - # Example of map - numbers = [1, 2, 3, 4, 5] - squared = list(map(lambda x: x ** 2, numbers)) - print(squared) # Output: [1, 4, 9, 16, 25] - - # Example of filter - even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) - print(even_numbers) # Output: [2, 4] - - # Example of reduce (requires importing functools) - from functools import reduce - product = reduce(lambda x, y: x * y, numbers) - print(product) # Output: 120 - ``` - -31. **Discuss Python's `collections.Counter` class. How can it be used for counting hashable objects? Provide examples of its usage.** - - **Answer:** `Counter` is a specialized dictionary subclass in the `collections` module used for counting hashable objects. - ```python - from collections import Counter - - # Example usage - words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'] - word_counts = Counter(words) - print(word_counts) # Output: Counter({'apple': 3, 'banana': 2, 'orange': 1}) - ``` - -32. **Explain the purpose and usage of Python's `logging` module for structured logging. How does it aid in application debugging and monitoring?** - - **Answer:** The `logging` module provides a flexible framework for emitting log messages from Python programs, supporting different log levels, output destinations, and formatting options. It aids in debugging, error tracking, and monitoring application behavior in production environments. - ```python - import logging - - # Configure logging - logging.basicConfig(level=logging.DEBUG, - format='%(asctime)s - %(levelname)s - %(message)s') - - # Example usage - def divide(x, y): - try: - result = x / y - except ZeroDivisionError: - logging.error('Tried to divide by zero') - else: - logging.info(f'Division result: {result}') - return result - - divide(10, 0) - ``` - -33. **Discuss Python's support for functional programming with `functools.partial`. How can it be used to create partial functions with fixed arguments?** - - **Answer:** `functools.partial` is used to create partial functions with fixed arguments from existing functions. - ```python - from functools import partial - - # Example usage - def power(base, exponent): - return base ** exponent - - square = partial(power, exponent=2) - print(square(5)) # Output: 25 - ``` - -34. **Explain Python's `multiprocessing` module. How does it support parallel processing with multiple processes?** - - **Answer:** The `multiprocessing` module allows parallel execution using multiple processes, leveraging multiple CPU cores and avoiding the Global Interpreter Lock (GIL) limitation of threads. It facilitates concurrent execution of CPU-bound tasks and enhances performance in multiprocessing environments. - ```python - from multiprocessing import Pool - - # Example usage - def square(n): - return n ** 2 - - if __name__ == '__main__': - with Pool(processes=3) as pool: - results = pool.map(square, [1, 2, 3, 4, 5]) - print(results) # Output: [1, 4, 9, 16, 25] - ``` - -35. **Discuss Python's support for metaprogramming with metaclasses. How can metaclasses be used to customize class creation behavior?** - - **Answer:** Metaclasses allow customization of class creation behavior by overriding the `__new__` and `__init__` methods of the `type` metaclass. They can be used to enforce constraints, add class-level methods, or modify attribute handling during class instantiation. - ```python - class MyMeta(type): - def __new__(cls, name, bases, dct): - dct['attr'] = 100 - return super().__new__(cls, name, bases, dct) - - class MyClass(metaclass=MyMeta): - pass - - print(MyClass.attr) # Output: 100 - ``` - -36. **Explain Python's support for `asyncio` and asynchronous programming. How does `asyncio` facilitate non-blocking I/O operations?** - - **Answer:** `asyncio` is a Python module that provides tools for asynchronous programming using coroutines (`async` and `await` keywords) and an event loop. It facilitates non-blocking I/O operations by allowing multiple tasks to be executed concurrently within a single thread, suitable for scalable network applications. - ```python - import asyncio - - async def async_task(): - print('Task 1') - await asyncio.sleep(1) - print('Task 2') - - asyncio.run(async_task()) - # Output: - # Task 1 - # (1 second delay) - # Task 2 - ``` - -37. **Discuss Python's support for context management with the `contextlib` module. How can it be used to define context managers?** - - **Answer:** The `contextlib` module simplifies the creation of context managers in Python using the `contextmanager` decorator, allowing resources to be managed using the `with` statement. - ```python - from contextlib import contextmanager - - @contextmanager - def file_opener(filename, mode): - try: - f = open(filename, mode) - yield f - finally: - f.close() - - with file_opener('example.txt', 'r') as f: - print(f.read()) - ``` - -38. **Explain Python's support for coroutines with `async` and `await` keywords. How do they facilitate asynchronous programming?** - - **Answer:** Coroutines in Python are defined using the `async` and `await` keywords, allowing non-blocking concurrent execution of tasks. `async` defines an asynchronous function (coroutine), while `await` suspends execution until the awaited coroutine completes, enabling efficient handling of I/O-bound operations without blocking the event loop. - -39. **Discuss Python's support for functional programming with `lambda` functions. How can `lambda` functions be used for concise and anonymous function definitions?** - - **Answer:** `lambda` functions in Python are anonymous functions defined using the `lambda` keyword, typically used for short, one-line function definitions. - ```python - # Example usage - square = lambda x: x ** 2 - print(square(5)) # Output: 25 - ``` - -40. **Explain Python's `argparse` module for command-line argument parsing. How does it simplify handling of command-line arguments and options?** - - **Answer:** The `argparse` module in Python simplifies parsing command-line arguments and options, providing support for argument types, default values, help messages, and validation, facilitating robust and user-friendly command-line interfaces for Python scripts. - ```python - import argparse - - parser = argparse.ArgumentParser(description='Process some integers.') - parser.add_argument('integers', metavar='N', type=int, nargs='+', - help='an integer for the accumulator') - parser.add_argument('--sum', dest='accumulate', action='store_const', - const=sum, default=max, - help='sum the integers (default: find the max)') - - args = parser.parse_args() - print(args.accumulate(args.integers)) - ``` - -41. **Discuss Python's `asyncio` module and event loop. How does `asyncio` facilitate asynchronous I/O operations and concurrency?** - - **Answer:** `asyncio` is a Python module that supports asynchronous I/O operations and concurrency by using coroutines (`async` and `await` keywords) and an event loop (`asyncio.run()`). It allows efficient scheduling of multiple I/O-bound tasks within a single-threaded environment, enhancing scalability and performance in network applications. - -42. **Explain Python's `concurrent.futures` module. How does it simplify concurrent programming with threads and processes?** - - **Answer:** The `concurrent.futures` module provides a high-level interface for asynchronously executing callable objects (`ThreadPoolExecutor` for threads, `ProcessPoolExecutor` for processes). It simplifies concurrent programming by managing thread/process pools, futures, and results, enabling parallel execution of tasks and improving performance in CPU-bound and I/O-bound applications. - ```python - from concurrent.futures import ThreadPoolExecutor - - def square(n): - return n ** 2 - - with ThreadPoolExecutor() as executor: - futures = [executor.submit(square, i) for i in range(10)] - results = [future.result() for future in futures] - print(results) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] - ``` - -43. **Discuss Python's support for database access using SQLAlchemy. How does SQLAlchemy facilitate object-relational mapping (ORM) and database interactions?** - - **Answer:** SQLAlchemy is a Python SQL toolkit and ORM framework that facilitates database access and interactions by providing a high-level, Pythonic interface for managing relational databases. It supports ORM for mapping Python objects to database tables, SQL expression language for querying databases, and database schema management, promoting code reusability, and abstraction of database operations. - ```python - from sqlalchemy import create_engine, Column, Integer, String - from sqlalchemy.ext.declarative import declarative_base - from sqlalchemy.orm import sessionmaker - - engine = create_engine('sqlite:///example.db', echo=True) - Base = declarative_base() - - class User(Base): - __tablename__ = 'users' - id = Column(Integer, primary_key=True) - name = Column(String) - - Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) - session = Session() - user = User(name='Alice') - session.add(user) - session.commit() - ``` - -44. **Explain Python's `os` module. How does it facilitate interaction with the operating system, file system, and environment variables?** - - **Answer:** The `os` module in Python provides a portable way to interact with the operating system, file system, and environment variables. It offers functions for manipulating files/directories (`os.path`), executing commands (`os.system`), accessing environment variables (`os.environ`), and managing processes (`os.fork`, `os.kill`), facilitating system-level operations and cross-platform compatibility. - -45. **Discuss Python's support for web scraping with libraries like `BeautifulSoup` and `requests`. How can these libraries be used for extracting and parsing web data?** - - **Answer:** Python supports web scraping using libraries like `BeautifulSoup` for parsing HTML/XML documents and `requests` for making HTTP requests. Together, they enable extraction and parsing of web data by retrieving web pages (`requests.get`), parsing HTML content (`BeautifulSoup`), navigating document elements (`find`, `find_all`), and extracting structured data from web pages, facilitating data aggregation and analysis from online sources. - -46. **Explain Python's support for functional programming with `map`, `filter`, and `reduce` functions. How do these functions enhance code readability and performance?** - - **Answer:** Functional programming functions (`map`, `filter`, `reduce`) in Python promote concise and declarative coding by applying operations to iterables: - ```python - # Example of map - numbers = [1, 2, 3, 4, 5] - squared = list(map(lambda x: x ** 2, numbers)) - print(squared) # Output: [1, 4, 9, 16, 25] - - # Example of filter - even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) - print(even_numbers) # Output: [2, 4] - - # Example of reduce (requires importing functools) - from functools import reduce - product = reduce(lambda x, y: x * y, numbers) - print(product) # Output: 120 - ``` - -47. **Discuss Python's support for context management with `with` statement and contextlib module. How does it simplify resource management and exception handling?** - - **Answer:** Python's `with` statement and `contextlib` module simplify context management and resource handling by encapsulating resource acquisition and release within a defined context (`__enter__` and `__exit__` methods). It ensures proper cleanup of resources (`file.close()`, `database.commit()`) and exception handling (`try-except-finally`) without boilerplate code, enhancing code readability and maintainability. - -48. **Explain Python's support for metaprogramming with `__getattr__`, `__setattr__`, and `__delattr__` methods. How can these methods be used for attribute access and manipulation?** - - **Answer:** Metaprogramming in Python allows customization of attribute access and manipulation using special methods (`__getattr__`, `__setattr__`, `__delattr__`). They enable dynamic attribute retrieval (`__getattr__`), assignment (`__setattr__`), and deletion (`__delattr__`), facilitating object-oriented programming paradigms and metaprogramming techniques for implementing custom behavior and data encapsulation. - ```python - class DynamicAttributes: - def __init__(self): - self._attrs = {} - - def __getattr__(self, name): - if name in self._attrs: - return self._attrs[name] - else: - raise AttributeError(f'{self.__class__.__name__} object has no attribute {name}') - - def __setattr__(self, name, value): - self._attrs[name] = value - - def __delattr__(self, name): - del self._attrs[name] - - obj = DynamicAttributes() - obj.name = 'Alice' - print(obj.name) # Output: Alice - del obj.name - ``` - -49. **Discuss Python's support for metaclasses. How can metaclasses be used to customize class creation behavior and enforce constraints?** - - **Answer:** Metaclasses in Python allow customization of class creation behavior by overriding the `__new__` and `__init__` methods of the `type` metaclass. They can enforce constraints, add class-level methods, or modify attribute handling during class instantiation, enabling advanced object-oriented programming patterns and metaprogramming techniques for implementing custom behavior and design patterns. - -50. **Explain Python's support for unit testing with the `unittest` framework. How does `unittest` facilitate test-driven development (TDD) and automated testing?** - - **Answer:** The `unittest` framework in Python supports unit testing by providing a built-in testing framework for organizing and executing test cases, fixtures, and assertions. It facilitates test-driven development (TDD) by promoting writing tests before code implementation, ensuring code correctness, functionality, and maintainability through automated testing and continuous integration practices. - ```python - import unittest - - def square(x): - return x ** 2 - - class TestSquare(unittest.TestCase): - def test_positive_numbers(self): - self.assertEqual(square(2), 4) - self.assertEqual(square(3), 9) - - def test_negative_numbers(self): - self.assertEqual(square(-2), 4) - self.assertEqual(square(-3), 9) - - if __name__ == '__main__': - unittest.main() - ``` - -These advanced-level Python interview questions cover a broad range of topics.They are designed to assess deeper understanding and practical knowledge of Python's advanced features. \ No newline at end of file diff --git a/docs/python/Interview ques/Basic.md b/docs/python/Interview ques/Basic.md deleted file mode 100644 index 00aeda0cb..000000000 --- a/docs/python/Interview ques/Basic.md +++ /dev/null @@ -1,661 +0,0 @@ ---- -id: basic-level -title: Basic Level Interview Question -sidebar_label: Basic Level -sidebar_position: 1 -tags: [python,Basic level,Interview Question] -description: In this tutorial, you'll overview some basic-level interview questions ---- - -1. **What is Python? What are the benefits of using Python?** - - **Answer:** Python is a high-level, interpreted, and general-purpose programming language. Benefits include simplicity and readability, a large standard library, community support, cross-platform compatibility, and a wide range of applications from web development to data analysis. - -2. **Explain the difference between lists and tuples in Python.** - - **Answer:** Lists are mutable (can be changed) and are defined using square brackets `[]`, while tuples are immutable (cannot be changed) and are defined using parentheses `()`. - -3. **How do you create a virtual environment in Python?** - - **Answer:** You can create a virtual environment using the `venv` module: - ```bash - python -m venv myenv - ``` - Activate the environment with: - - On Windows: `myenv\Scripts\activate` - - On Unix or MacOS: `source myenv/bin/activate` - -4. **What are Python decorators? Give an example.** - - **Answer:** Decorators are functions that modify the behavior of another function. They are often used to add functionality to existing code in a reusable way. - ```python - def my_decorator(func): - def wrapper(): - print("Something is happening before the function is called.") - func() - print("Something is happening after the function is called.") - return wrapper - - @my_decorator - def say_hello(): - print("Hello!") - - say_hello() - ``` - Output: - ``` - Something is happening before the function is called. - Hello! - Something is happening after the function is called. - ``` - -5. **How does Python handle memory management?** - - **Answer:** Python uses a combination of reference counting and a garbage collector to manage memory. The garbage collector can reclaim memory occupied by circular references that are no longer accessible. - -6. **What is a lambda function in Python? Provide an example.** - - **Answer:** A lambda function is a small anonymous function defined with the `lambda` keyword. It can take any number of arguments but has only one expression. - ```python - add = lambda x, y: x + y - print(add(2, 3)) # Output: 5 - ``` - -7. **What are Python’s built-in data types?** - - **Answer:** Some of Python’s built-in data types include: - - `int` (integer) - - `float` (floating-point number) - - `str` (string) - - `list` (list) - - `tuple` (tuple) - - `dict` (dictionary) - - `set` (set) - - `bool` (boolean) - -8. **Explain the difference between `==` and `is` in Python.** - - **Answer:** `==` checks for value equality (i.e., whether the values of two objects are the same), while `is` checks for identity equality (i.e., whether two references point to the same object in memory). - -9. **What is the purpose of the `with` statement in Python?** - - **Answer:** The `with` statement is used to wrap the execution of a block of code within methods defined by a context manager. It is commonly used for resource management, like opening and closing files. - ```python - with open('file.txt', 'r') as file: - data = file.read() - ``` - -10. **What is the difference between `append()` and `extend()` methods in Python lists?** - - **Answer:** `append()` adds its argument as a single element to the end of a list, whereas `extend()` iterates over its argument, adding each element to the list, extending the list. - - ```python - list1 = [1, 2, 3] - list1.append([4, 5]) - print(list1) # Output: [1, 2, 3, [4, 5]] - - list2 = [1, 2, 3] - list2.extend([4, 5]) - print(list2) # Output: [1, 2, 3, 4, 5] - ``` - -11. **What is the difference between `range()` and `xrange()` in Python?** - - **Answer:** In Python 2, `range()` returns a list, whereas `xrange()` returns an xrange object which generates values on the fly (lazy evaluation). In Python 3, `xrange()` is removed and `range()` behaves like `xrange()` from Python 2. - -12. **How can you concatenate two strings in Python?** - - **Answer:** You can concatenate two strings using the `+` operator or the `join()` method. - ```python - str1 = "Hello" - str2 = "World" - result = str1 + " " + str2 - print(result) # Output: Hello World - - result = " ".join([str1, str2]) - print(result) # Output: Hello World - ``` - -13. **What is the difference between `remove()`, `pop()`, and `del` in Python lists?** - - **Answer:** - - `remove()` removes the first occurrence of a value. - - `pop()` removes an element at a given index and returns it. - - `del` removes an element at a given index without returning it. - - ```python - lst = [1, 2, 3, 4, 5] - lst.remove(3) - print(lst) # Output: [1, 2, 4, 5] - - lst = [1, 2, 3, 4, 5] - popped_element = lst.pop(2) - print(popped_element) # Output: 3 - print(lst) # Output: [1, 2, 4, 5] - - lst = [1, 2, 3, 4, 5] - del lst[2] - print(lst) # Output: [1, 2, 4, 5] - ``` - -14. **What are `*args` and `**kwargs` in Python functions?** - - **Answer:** `*args` is used to pass a variable number of non-keyword arguments to a function, while `**kwargs` is used to pass a variable number of keyword arguments. - ```python - def func(*args, **kwargs): - print(args) - print(kwargs) - - func(1, 2, 3, a=4, b=5) - # Output: - # (1, 2, 3) - # {'a': 4, 'b': 5} - ``` - -15. **How do you create a dictionary in Python? Provide an example.** - - **Answer:** A dictionary is created using curly braces `{}` with key-value pairs separated by commas. - ```python - my_dict = { - 'name': 'Alice', - 'age': 25, - 'city': 'New York' - } - print(my_dict) - # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'} - ``` - -16. **Explain the difference between `local`, `global`, and `nonlocal` variables in Python.** - - **Answer:** - - `local` variables are defined within a function and are accessible only within that function. - - `global` variables are defined outside of any function and are accessible throughout the entire module. - - `nonlocal` variables are used in nested functions to refer to variables in the nearest enclosing scope that is not global. - - ```python - x = "global" - - def outer(): - x = "outer local" - - def inner(): - nonlocal x - x = "inner local" - print("inner:", x) - - inner() - print("outer:", x) - - outer() - print("global:", x) - - # Output: - # inner: inner local - # outer: inner local - # global: global - ``` - -17. **What is a module in Python? How do you import a module?** - - **Answer:** A module is a file containing Python code, which can define functions, classes, and variables. You can import a module using the `import` statement. - ```python - import math - print(math.sqrt(16)) # Output: 4.0 - ``` - -18. **How do you handle exceptions in Python? Provide an example.** - - **Answer:** Exceptions in Python are handled using the `try`, `except`, `else`, and `finally` blocks. - ```python - try: - result = 10 / 0 - except ZeroDivisionError: - print("Cannot divide by zero") - else: - print("Division successful") - finally: - print("This block is always executed") - - # Output: - # Cannot divide by zero - # This block is always executed - ``` - -19. **What is the purpose of the `pass` statement in Python?** - - **Answer:** The `pass` statement is a null operation that is used as a placeholder in loops, functions, classes, or conditionals where syntactically some code is required, but you don't want to execute any code. - ```python - def function_that_does_nothing(): - pass - ``` - -20. **How can you generate random numbers in Python?** - - **Answer:** You can generate random numbers using the `random` module. - ```python - import random - - print(random.randint(1, 10)) # Generates a random integer between 1 and 10 - print(random.random()) # Generates a random float between 0 and 1 - ``` - -21. **How do you check the data type of a variable in Python?** - - **Answer:** You can use the `type()` function to check the data type of a variable. - ```python - x = 10 - print(type(x)) # Output: - - y = "Hello" - print(type(y)) # Output: - ``` - -22. **What are docstrings in Python? How are they used?** - - **Answer:** Docstrings are string literals used to document a specific segment of code. They are defined by triple quotes `"""` or `'''` and are placed at the beginning of modules, classes, or functions. - ```python - def greet(name): - """This function greets the person passed in as a parameter""" - print(f"Hello, {name}") - - print(greet.__doc__) - # Output: This function greets the person passed in as a parameter - ``` - -23. **What are the differences between `__str__` and `__repr__` methods in Python?** - - **Answer:** `__str__` is used to define a human-readable string representation of an object, while `__repr__` is used to define an official string representation that can be used to recreate the object. - ```python - class Person: - def __init__(self, name, age): - self.name = name - self.age = age - - def __str__(self): - return f"Person(name={self.name}, age={self.age})" - - def __repr__(self): - return f"Person('{self.name}', {self.age})" - - p = Person("Alice", 30) - print(str(p)) # Output: Person(name=Alice, age=30) - print(repr(p)) # Output: Person('Alice', 30) - ``` - -24. **What is the difference between `==` and `!=` in Python?** - - **Answer:** `==` checks if two values are equal, while `!=` checks if two values are not equal. - ```python - a = 5 - b = 10 - - print(a == b) # Output: False - print(a != b) # Output: True - ``` - -25. **How do you convert a string to lowercase or uppercase in Python?** - - **Answer:** You can use the `lower()` method to convert a string to lowercase and the `upper()` method to convert a string to uppercase. - ```python - text = "Hello World" - print(text.lower()) # Output: hello world - print(text.upper()) # Output: HELLO WORLD - ``` - -26. **What is the difference between `split()` and `join()` methods in Python?** - - **Answer:** The `split()` method splits a string into a list based on a specified delimiter, while the `join()` method joins the elements of a list into a single string with a specified delimiter. - ```python - text = "Hello World" - words = text.split() - print(words) # Output: ['Hello', 'World'] - - joined_text = " ".join(words) - print(joined_text) # Output: Hello World - ``` - -27. **How do you create a set in Python?** - - **Answer:** A set is created using curly braces `{}` or the `set()` function. - ```python - my_set = {1, 2, 3} - print(my_set) # Output: {1, 2, 3} - - another_set = set([4, 5, 6]) - print(another_set) # Output: {4, 5, 6} - ``` - -28. **What is the difference between `read()`, `readline()`, and `readlines()` methods in file handling?** - - **Answer:** - - `read()` reads the entire file as a single string. - - `readline()` reads a single line from the file. - - `readlines()` reads all the lines in a file and returns a list of strings. - - ```python - with open('file.txt', 'r') as file: - content = file.read() - print(content) - - with open('file.txt', 'r') as file: - line = file.readline() - print(line) - - with open('file.txt', 'r') as file: - lines = file.readlines() - print(lines) - ``` - -29. **How do you create a class in Python? Provide an example.** - - **Answer:** You can create a class using the `class` keyword. - ```python - class Dog: - def __init__(self, name, age): - self.name = name - self.age = age - - def bark(self): - return f"{self.name} is barking!" - - my_dog = Dog("Buddy", 3) - print(my_dog.bark()) # Output: Buddy is barking! - ``` - -30. **What is the use of the `map()` function in Python? Provide an example.** - - **Answer:** The `map()` function applies a given function to each item in an iterable (like a list) and returns a map object (an iterator). - ```python - def square(x): - return x * x - - numbers = [1, 2, 3, 4] - squared_numbers = map(square, numbers) - - print(list(squared_numbers)) # Output: [1, 4, 9, 16] - ``` - -31. **What is the purpose of the `filter()` function in Python? Provide an example.** - - **Answer:** The `filter()` function constructs an iterator from elements of an iterable for which a function returns true. - ```python - def is_even(n): - return n % 2 == 0 - - numbers = [1, 2, 3, 4, 5, 6] - even_numbers = filter(is_even, numbers) - - print(list(even_numbers)) # Output: [2, 4, 6] - ``` - -32. **What are list comprehensions in Python? Provide an example.** - - **Answer:** List comprehensions provide a concise way to create lists. - ```python - numbers = [1, 2, 3, 4, 5] - squares = [x * x for x in numbers] - print(squares) # Output: [1, 4, 9, 16, 25] - ``` - -33. **How do you create a nested dictionary in Python? Provide an example.** - - **Answer:** A nested dictionary is a dictionary within a dictionary. - ```python - nested_dict = { - 'first': { - 'a': 1, - 'b': 2 - }, - 'second': { - 'c': 3, - 'd': 4 - } - } - print(nested_dict) - # Output: {'first': {'a': 1, 'b': 2}, 'second': {'c': 3, 'd': 4}} - ``` - -34. **What is the difference between mutable and immutable types in Python? Provide examples.** - - **Answer:** Mutable types can be changed after their creation, while immutable types cannot be changed. - - **Mutable:** List, Dictionary, Set - ```python - my_list = [1, 2, 3] - my_list[0] = 4 - print(my_list) # Output: [4, 2, 3] - ``` - - - **Immutable:** Tuple, String, Integer - ```python - my_tuple = (1, 2, 3) - # my_tuple[0] = 4 # This will raise an error - - my_string = "hello" - # my_string[0] = "H" # This will raise an error - ``` - -35. **How do you reverse a list in Python?** - - **Answer:** You can reverse a list using the `reverse()` method or slicing. - ```python - my_list = [1, 2, 3, 4, 5] - my_list.reverse() - print(my_list) # Output: [5, 4, 3, 2, 1] - - # Using slicing - reversed_list = my_list[::-1] - print(reversed_list) # Output: [1, 2, 3, 4, 5] - ``` - -36. **How do you merge two dictionaries in Python?** - - **Answer:** You can merge two dictionaries using the `update()` method or the `{**dict1, **dict2}` syntax. - ```python - dict1 = {'a': 1, 'b': 2} - dict2 = {'c': 3, 'd': 4} - - # Using update() - dict1.update(dict2) - print(dict1) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4} - - # Using {**dict1, **dict2} - merged_dict = {**dict1, **dict2} - print(merged_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4} - ``` - -37. **What is a lambda function in Python? Provide an example.** - - **Answer:** A lambda function is an anonymous function defined with the `lambda` keyword. - ```python - square = lambda x: x * x - print(square(5)) # Output: 25 - ``` - -38. **How do you create an empty set in Python?** - - **Answer:** You create an empty set using the `set()` function. Using `{}` creates an empty dictionary. - ```python - empty_set = set() - print(empty_set) # Output: set() - ``` - -39. **What is the use of the `enumerate()` function in Python?** - - **Answer:** The `enumerate()` function adds a counter to an iterable and returns it as an enumerate object. - ```python - my_list = ['a', 'b', 'c'] - for index, value in enumerate(my_list): - print(index, value) - # Output: - # 0 a - # 1 b - # 2 c - ``` - -40. **How do you check if a key exists in a dictionary in Python?** - - **Answer:** You can use the `in` keyword to check if a key exists in a dictionary. - ```python - my_dict = {'a': 1, 'b': 2} - print('a' in my_dict) # Output: True - print('c' in my_dict) # Output: False - ``` - -41. **What is the purpose of the `zip()` function in Python?** - - **Answer:** The `zip()` function takes iterables (can be zero or more), aggregates them in a tuple, and returns it. - ```python - list1 = [1, 2, 3] - list2 = ['a', 'b', 'c'] - zipped = zip(list1, list2) - print(list(zipped)) # Output: [(1, 'a'), (2, 'b'), (3, 'c')] - ``` - -42. **How do you create a shallow copy and a deep copy of an object in Python?** - - **Answer:** You can use the `copy` module to create shallow and deep copies. - ```python - import copy - - original = [[1, 2, 3], [4, 5, 6]] - - shallow_copy = copy.copy(original) - deep_copy = copy.deepcopy(original) - - original[0][0] = 99 - - print(original) # Output: [[99, 2, 3], [4, 5, 6]] - print(shallow_copy) # Output: [[99, 2, 3], [4, 5, 6]] - print(deep_copy) # Output: [[1, 2, 3], [4, 5, 6]] - ``` - -43. **What is a generator in Python? Provide an example.** - - **Answer:** A generator is a special type of iterator that generates values on the fly and uses the `yield` keyword. - ```python - def my_generator(): - yield 1 - yield 2 - yield 3 - - gen = my_generator() - for value in gen: - print(value) - # Output: - # 1 - # 2 - # 3 - ``` - -44. **What are the key differences between Python 2 and Python 3?** - - **Answer:** - - Print Statement: In Python 2, `print` is a statement; in Python 3, `print` is a function. - ```python - # Python 2 - print "Hello" - - # Python 3 - print("Hello") - ``` - - Integer Division: In Python 2, dividing two integers performs floor division. In Python 3, it performs true division. - ```python - # Python 2 - print 5 / 2 # Output: 2 - - # Python 3 - print(5 / 2) # Output: 2.5 - ``` - - Unicode: Python 3 uses Unicode by default for strings, whereas Python 2 has ASCII as default. - ```python - # Python 2 - print type(u"Hello") # Output: - print type("Hello") # Output: - - # Python 3 - print(type("Hello")) # Output: - ``` - -45. **How do you use the `itertools` module in Python? Provide an example.** - - **Answer:** The `itertools` module provides functions for creating iterators for efficient looping. - ```python - import itertools - - numbers = [1, 2, 3] - perm = itertools.permutations(numbers) - print(list(perm)) # Output: [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] - ``` - -46. **What is the `global` keyword used for in Python?** - - **Answer:** The `global` keyword is used to declare that a variable inside a function is global (i.e., not local to the function). - ```python - x = 10 - - def change_global(): - global x - x = 20 - - change_global() - print(x) # Output: 20 - ``` - -47. **How do you sort a list of tuples based on a specific element?** - - **Answer:** You can use the `sorted()` function with a `key` parameter. - ```python - data = [(1, 'b'), (2, 'a'), (3, 'c')] - sorted_data = sorted(data, key=lambda x: x[1]) - print(sorted_data) # Output: [(2, 'a'), (1, 'b'), (3, 'c')] - ``` - -48. **What is the difference between `any()` and `all()` functions in Python?** - - **Answer:** `any()` returns `True` if any element in the iterable is true, whereas `all()` returns `True` if all elements in the iterable are true. - ```python - numbers = [0, 1, 2, 3] - print(any(numbers)) # Output: True - print(all(numbers)) # Output: False - ``` - -49. **How do you remove duplicates from a list in Python?** - - **Answer:** You can remove duplicates by converting the list to a set and then back to a list. - ```python - numbers = [1, 2, 2, 3, 4, 4, 5] - unique_numbers = list(set(numbers)) - print(unique_numbers) # Output: [1, 2, 3, 4, 5] - ``` - -50. **What is the purpose of the `assert` statement in Python?** - - **Answer:** The `assert` statement is used for debugging purposes. It tests if a condition is true, and if not, it raises an `AssertionError` with an optional message. - ```python - x = 5 - assert x > 0, "x should be positive" - assert x < 0, "x should be negative" # This will raise an AssertionError - ``` - -51. **What are Python's built-in functions?** - - **Answer:** Python has many built-in functions like `len()`, `max()`, `min()`, `sum()`, `sorted()`, `print()`, `input()`, `type()`, `int()`, `str()`, and many more. These functions are always available for use. - -52. **How do you convert a list of strings to a single string with a delimiter?** - - **Answer:** You can use the `join()` method to concatenate a list of strings into a single string with a specified delimiter. - ```python - words = ['Hello', 'World'] - sentence = ' '.join(words) - print(sentence) # Output: Hello World - ``` - -53. **What is the use of the `frozenset` in Python?** - - **Answer:** `frozenset` is an immutable version of a set that cannot be modified after creation. - ```python - my_set = frozenset([1, 2, 3]) - print(my_set) # Output: frozenset({1, 2, 3}) - ``` - -54. **What are the different ways to handle missing values in a dataset using Python?** - - **Answer:** Missing values can be handled using various methods such as: - - Removing rows or columns with missing values. - - Filling missing values with a specific value, mean, median, or mode. - - Using forward fill or backward fill. - ```python - import pandas as pd - import numpy as np - - df = pd.DataFrame({ - 'A': [1, 2, np.nan, 4], - 'B': [np.nan, 2, 3, 4] - }) - - df.dropna() # Remove rows with missing values - df.fillna(0) # Fill missing values with 0 - df.fillna(method='ffill') # Forward fill - ``` - -55. **How do you create a Pandas DataFrame from a dictionary?** - - **Answer:** You can create a DataFrame using the `pd.DataFrame()` function with a dictionary. - ```python - import pandas as pd - - data = { - 'name': ['Alice', 'Bob', 'Charlie'], - 'age': [25, 30, 35] - } - - df = pd.DataFrame(data) - print(df) - ``` - -56. **What is the difference between `Series` and `DataFrame` in Pandas?** - - **Answer:** A `Series` is a one-dimensional labeled array capable of holding any data type, whereas a `DataFrame` is a two-dimensional labeled data structure with columns of potentially different types. - -57. **How do you read a CSV file into a Pandas DataFrame?** - - **Answer:** You can use the `pd.read_csv()` function to read a CSV file into a DataFrame. - ```python - import pandas as pd - - df = pd.read_csv('data.csv') - print(df) - ``` - -58. **What are NumPy arrays and how do you create one?** - - **Answer:** NumPy arrays are n-dimensional arrays that provide fast mathematical operations and efficient memory usage. - ```python - import numpy as np - - arr = np.array([1, 2, 3, 4, 5]) - print(arr) # Output: [1 2 3 4 5] - -These questions should provide a comprehensive overview of basic Python concepts and help prepare for an interview. \ No newline at end of file diff --git a/docs/python/Interview ques/Intermediate.md b/docs/python/Interview ques/Intermediate.md deleted file mode 100644 index a67a2333b..000000000 --- a/docs/python/Interview ques/Intermediate.md +++ /dev/null @@ -1,800 +0,0 @@ ---- -id: intermediate-level -title: Intermediate Level Interview Question -sidebar_label: Intermediate Level -sidebar_position: 2 -tags: [python,Interview Question,Intermediate Level ] -description: In this tutorial, you'll be focusing on intermediate-level interview questions. ---- - -1. **Explain the difference between `__str__()` and `__repr__()` methods in Python classes.** - - **Answer:** - - `__str__()` is used to compute the "informal" or nicely printable string representation of an object. It's meant to be readable. - - `__repr__()` computes the "official" string representation that is intended for debugging and re-creation of the object with `eval()`. - ```python - class MyClass: - def __init__(self, x, y): - self.x = x - self.y = y - - def __str__(self): - return f'MyClass({self.x}, {self.y})' - - def __repr__(self): - return f'MyClass({self.x}, {self.y})' - - obj = MyClass(10, 20) - print(str(obj)) # Output: MyClass(10, 20) - print(repr(obj)) # Output: MyClass(10, 20) - ``` - -2. **What are decorators in Python? How do you implement them?** - - **Answer:** Decorators are functions that modify the functionality of another function or class. They are used to wrap another function or class, adding some additional functionality before or after the original function or class. - ```python - def my_decorator(func): - def wrapper(): - print("Something is happening before the function is called.") - func() - print("Something is happening after the function is called.") - return wrapper - - @my_decorator - def say_hello(): - print("Hello!") - - say_hello() - # Output: - # Something is happening before the function is called. - # Hello! - # Something is happening after the function is called. - ``` - -3. **Explain the concept of `self` in Python.** - - **Answer:** `self` refers to the instance of a class. It allows you to access the instance's attributes and methods from within the class definition. - ```python - class MyClass: - def __init__(self, x): - self.x = x - - def print_value(self): - print(self.x) - - obj = MyClass(10) - obj.print_value() # Output: 10 - ``` - -4. **What are `classmethod` and `staticmethod` in Python?** - - **Answer:** - - `classmethod`: It is a method that is bound to the class rather than the instance of the class. It takes `cls` as the first parameter, which refers to the class itself. - - `staticmethod`: It is a method that is not bound to either the class or the instance. It behaves like a regular function but is defined inside a class for organizational purposes. - ```python - class MyClass: - class_attr = 10 - - @classmethod - def class_method(cls): - print(f'Class attribute: {cls.class_attr}') - - @staticmethod - def static_method(): - print('This is a static method') - - MyClass.class_method() # Output: Class attribute: 10 - MyClass.static_method() # Output: This is a static method - ``` - -5. **What is method resolution order (MRO) in Python?** - - **Answer:** Method Resolution Order (MRO) determines the order in which methods are inherited in the presence of multiple inheritance. It is computed using the C3 linearization algorithm. - ```python - class A: - def process(self): - print('A process()') - - class B(A): - def process(self): - print('B process()') - - class C(A): - def process(self): - print('C process()') - - class D(B, C): - pass - - obj = D() - obj.process() - # Output: B process() - ``` - -6. **Explain the use of `super()` in Python with an example.** - - **Answer:** `super()` is used to call methods of a superclass (parent class) in a derived class (child class). - ```python - class A: - def greet(self): - print('Hello from class A') - - class B(A): - def greet(self): - super().greet() # Call greet() method of class A - print('Hello from class B') - - obj = B() - obj.greet() - # Output: - # Hello from class A - # Hello from class B - ``` - -7. **How do you handle exceptions using `try`, `except`, `else`, and `finally` blocks in Python?** - - **Answer:** - - `try`: It is used to wrap the code that might throw an exception. - - `except`: It is used to handle the exception if `try` block raises one. - - `else`: It is executed if the `try` block executes without raising an exception. - - `finally`: It is always executed whether an exception occurred or not. - ```python - try: - result = 10 / 0 - except ZeroDivisionError: - print("Cannot divide by zero") - else: - print("Division successful") - finally: - print("This block is always executed") - ``` - -8. **How do you use Python's `logging` module for logging messages?** - - **Answer:** The `logging` module provides a flexible framework for emitting log messages from Python programs. - ```python - import logging - - logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') - - logging.debug('This is a debug message') - logging.info('This is an info message') - logging.warning('This is a warning message') - logging.error('This is an error message') - logging.critical('This is a critical message') - ``` - -9. **Explain the difference between `deepcopy()` and `copy()` functions in Python's `copy` module.** - - **Answer:** - - `copy()`: It creates a shallow copy of the object. The copied object itself is new, but the elements within it are references to the original elements. - - `deepcopy()`: It creates a deep copy of the object. The copied object and its elements are completely new, recursively copied from the original. - ```python - import copy - - original = [[1, 2, 3], [4, 5, 6]] - - shallow_copy = copy.copy(original) - deep_copy = copy.deepcopy(original) - - original[0][0] = 99 - - print(original) # Output: [[99, 2, 3], [4, 5, 6]] - print(shallow_copy) # Output: [[99, 2, 3], [4, 5, 6]] - print(deep_copy) # Output: [[1, 2, 3], [4, 5, 6]] - ``` - -10. **How do you use list comprehensions in Python? Provide an example.** - - **Answer:** List comprehensions provide a concise way to create lists. - ```python - numbers = [1, 2, 3, 4, 5] - squares = [x * x for x in numbers if x % 2 == 0] - print(squares) # Output: [4, 16] - ``` - -11. **What are `lambda` functions in Python? Provide an example.** - - **Answer:** `lambda` functions are anonymous functions defined with the `lambda` keyword. - ```python - square = lambda x: x * x - print(square(5)) # Output: 25 - ``` - -12. **How do you sort a dictionary by value in Python?** - - **Answer:** You can use the `sorted()` function with a custom key to sort a dictionary by its values. - ```python - my_dict = {'a': 3, 'b': 1, 'c': 2} - sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1])) - print(sorted_dict) # Output: {'b': 1, 'c': 2, 'a': 3} - ``` - -13. **What is the purpose of the `__init__()` method in Python classes?** - - **Answer:** The `__init__()` method (initializer or constructor) is automatically called when a new instance of a class is created. It initializes the object's attributes. - ```python - class MyClass: - def __init__(self, x): - self.x = x - - obj = MyClass(10) - print(obj.x) # Output: 10 - ``` - -14. **How do you handle file operations (open, read, write, close) in Python?** - - **Answer:** You can use the `open()` function to open a file, `read()` or `write()` methods to read from or write to it, and `close()` method to close it. - ```python - # Reading from a file - with open('file.txt', 'r') as file: - content = file.read() - print(content) - - # Writing to a file - with open('file.txt', 'w') as file: - file.write('Hello, World!') - ``` - -15. **How do you use regular expressions (`re` module) in Python?** - - **Answer:** The `re` module provides support for regular expressions in Python. - ```python - import re - - text = "Hello, my email is example@email.com" - pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' - - emails = re.findall(pattern, text) - print(emails) # Output: ['example@email.com'] - ``` - -16. **Explain the difference between `asyncio` and `threading` in Python.** - - **Answer:** - - `asyncio`: It is a library for writing concurrent code using the `async` and `await` keywords. It is single-threaded and cooperatively multitasks. - - `threading`: It is a standard module for creating and working with threads. Threads are OS-level lightweight processes, and Python threads are real system threads. - ```python - import asyncio - import threading - import time - - async def async_task(): - print('Async task starting') - await asyncio.sleep(2) - print('Async task done') - - def sync_task(): - print('Sync task starting') - time.sleep(2) - print('Sync task done') - - async def main(): - asyncio.create_task(async_task()) - await asyncio.sleep(1) - threading.Thread(target=sync_task).start() - - asyncio.run(main()) - ``` - -17. **Explain the concept of `yield` in Python and provide an example of its usage.** - - **Answer:** `yield` is used inside a function to turn it into a generator. It returns an iterator that generates values lazily as they are requested. - ```python - def my_generator(): - yield 1 - yield 2 - yield 3 - - gen = my_generator() - print(next(gen)) # Output: 1 - print(next(gen)) # Output: 2 - print(next(gen)) # Output: 3 - ``` - -18. **How do you serialize and deserialize Python objects?** - - **Answer:** Serialization is the process of converting a Python object into a byte stream, and deserialization is the reverse process. - ```python - import pickle - - # Serialization - data = {'name': 'Alice', 'age': 30} - serialized = pickle.dumps(data) - - # Deserialization - deserialized = pickle.loads(serialized) - print(deserialized) # Output: {'name': 'Alice', 'age': 30} - ``` - -19. **What are context managers in Python and how do you use them?** - - **Answer:** Context managers are objects that enable proper resource management. They are used with the `with` statement. - ```python - class MyContextManager: - def __enter__(self): - print('Entering context') - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - print('Exiting context') - - with MyContextManager() as cm: - print('Inside the context') - # Output: - # Entering context - # Inside the context - # Exiting context - ``` - -20. **Explain the purpose of `*args` and `**kwargs` in Python function definitions.** - - **Answer:** - - `*args`: It allows you to pass a variable number of positional arguments to a function. It collects extra positional arguments into a tuple. - - `**kwargs`: It allows you to pass a variable number of keyword arguments to a function. It collects extra keyword arguments into a dictionary. - ```python - def my_func(*args, **kwargs): - print(args) # Tuple of positional arguments - print(kwargs) # Dictionary of keyword arguments - - my_func(1, 2, 3, a='apple', b='banana') - # Output: - # (1, 2, 3) - # {'a': 'apple', 'b': 'banana'} - ``` - -21. **What are Python decorators with arguments and how do you implement them?** - - **Answer:** Decorators can take arguments by defining a function that returns a decorator function. - ```python - def repeat(num_times): - def decorator_repeat(func): - def wrapper(*args, **kwargs): - for _ in range(num_times): - result = func(*args, **kwargs) - return result - return wrapper - return decorator_repeat - - @repeat(num_times=3) - def greet(name): - print(f'Hello, {name}') - - greet('Alice') - # Output: - # Hello, Alice - # Hello, Alice - # Hello, Alice - ``` - -22. **Explain the use of `collections` module in Python with examples.** - - **Answer:** The `collections` module provides alternatives to Python's built-in data structures like dictionaries, lists, sets, and tuples. - ```python - from collections import defaultdict, namedtuple, Counter, deque - - # defaultdict - colors = defaultdict(int) - colors['red'] += 1 - print(colors['red']) # Output: 1 - - # namedtuple - Point = namedtuple('Point', ['x', 'y']) - p = Point(1, 2) - print(p.x, p.y) # Output: 1 2 - - # Counter - counts = Counter(['a', 'b', 'a', 'c']) - print(counts['a']) # Output: 2 - - # deque - d = deque([1, 2, 3]) - d.appendleft(0) - print(d) # Output: deque([0, 1, 2, 3]) - ``` - -23. **How do you use the `__slots__` attribute in Python classes?** - - **Answer:** `__slots__` is used to explicitly declare instance attributes. It can save memory by preventing the creation of instance dictionaries for attributes. - ```python - class MyClass: - __slots__ = ['x', 'y'] - - def __init__(self, x, y): - self.x = x - self.y = y - - obj = MyClass(10, 20) - print(obj.x, obj.y) # Output: 10 20 - ``` - -24. **Explain the purpose of the `@property` decorator in Python.** - - **Answer:** `@property` is used to define a method as a property of a class. It allows you to define a method that can be accessed like an attribute. - ```python - class Circle: - def __init__(self, radius): - self.radius = radius - - @property - def diameter(self): - return self.radius * 2 - - circle = Circle(5) - print(circle.diameter) # Output: 10 - ``` - -25. **What are some best practices for writing Python code?** - - **Answer:** - - Use meaningful variable and function names. - - Follow PEP 8 style guide for code readability. - - Write docstrings for all public modules, functions, classes, and methods. - - Use list comprehensions and generator expressions instead of loops where possible. - - Avoid using `global` variables unless absolutely necessary. - - Write unit tests for your code using `unittest` or `pytest`. - - Use virtual environments (`venv` or `conda`) for project isolation. - -26. **How do you profile Python code for performance optimization?** - - **Answer:** You can use Python's built-in `cProfile` module or external tools like `line_profiler` and `memory_profiler` to profile code and identify bottlenecks. - ```python - import cProfile - - def my_function(): - # Function code - - cProfile.run('my_function()') - ``` - -27. **Explain the GIL (Global Interpreter Lock) in Python and its impact on multi-threaded programs.** - - **Answer:** The GIL is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecodes simultaneously. It can impact multi-threaded programs by limiting CPU-bound concurrency but does not affect I/O-bound tasks or multiprocessing. - -28. **What are some differences between Python's `asyncio` and `multiprocessing` modules for concurrency?** - - **Answer:** - - `asyncio`: It is used for asynchronous programming with coroutines and event loops, suitable for I/O-bound tasks. - - `multiprocessing`: It is used for parallelism by spawning multiple OS-level processes, suitable for CPU-bound tasks. - ```python - import asyncio - import multiprocessing - - async def async_task(): - # Asynchronous task - - def sync_task(): - # Synchronous task - - # Example asyncio usage - asyncio.run(async_task()) - - # Example multiprocessing usage - p = multiprocessing.Process(target=sync_task) - p.start() - ``` - -29. **How do you manage Python dependencies in a project?** - - **Answer:** Use a package manager like `pip` and create a `requirements.txt` file listing all dependencies. Use `virtual environments` (`venv` or `conda`) to isolate project dependencies. - -30. **Explain how Python's `unittest` and `pytest` frameworks are used for testing.** - - **Answer:** - - `unittest`: It is Python's built-in unit testing framework, supporting test automation, sharing of setups, and shutdown code. - - `pytest`: It is a third-party testing framework with features like fixtures, parameterization, and easy plugin integration. - ```python - import unittest - - class MyTestCase(unittest.TestCase): - def test_addition(self): - self.assertEqual(1 + 1, 2) - - if __name__ == '__main__': - unittest.main() - - # Example using pytest - # test_my_module.py - import pytest - - def test_addition(): - assert 1 + 1 == 2 - - # Run with pytest command - ``` - -31. **Explain the use of `__new__()` and `__init__()` methods in Python classes.** - - **Answer:** - - `__new__()` method: It is responsible for creating a new instance of a class. It is a static method and is called before `__init__()` when an object is created. - - `__init__()` method: It initializes the newly created object. It is called after the object has been created by `__new__()`. - ```python - class MyClass: - def __new__(cls, *args, **kwargs): - print('Creating instance') - instance = super().__new__(cls) - return instance - - def __init__(self, x): - print('Initializing instance') - self.x = x - - obj = MyClass(10) - # Output: - # Creating instance - # Initializing instance - ``` - -32. **How do you handle circular imports in Python?** - - **Answer:** Circular imports occur when two or more modules import each other directly or indirectly. You can resolve them by restructuring code or using `import` statements within functions. - ```python - # Module A - from module_b import func_b - - def func_a(): - func_b() - - # Module B - from module_a import func_a - - def func_b(): - func_a() - ``` - -33. **Explain the concept of metaclasses in Python with an example.** - - **Answer:** Metaclasses are classes whose instances are classes themselves. They define the behavior of classes. Example using `type` as a metaclass: - ```python - class MyMeta(type): - def __new__(cls, name, bases, dct): - dct['attr'] = 100 - return super().__new__(cls, name, bases, dct) - - class MyClass(metaclass=MyMeta): - pass - - print(MyClass.attr) # Output: 100 - ``` - -34. **What are Python's magic methods (`__magic__`)? Provide examples of their usage.** - - **Answer:** Magic methods are special methods in Python that are surrounded by double underscores. They allow customization of classes to support various operations and behaviors. - ```python - class Vector: - def __init__(self, x, y): - self.x = x - self.y = y - - def __add__(self, other): - return Vector(self.x + other.x, self.y + other.y) - - def __str__(self): - return f'({self.x}, {self.y})' - - v1 = Vector(1, 2) - v2 = Vector(3, 4) - print(v1 + v2) # Output: (4, 6) - ``` - -35. **Explain the purpose of the `sys` module in Python.** - - **Answer:** The `sys` module provides access to system-specific parameters and functions. It can be used to interact with the interpreter and operating system. - ```python - import sys - - print(sys.version) # Output: Python version - print(sys.platform) # Output: Operating system platform - print(sys.argv) # Output: Command line arguments - ``` - -36. **What is the purpose of Python's `itertools` module? Provide examples of its usage.** - - **Answer:** The `itertools` module provides functions that create iterators for efficient looping. Examples include `count()`, `cycle()`, `chain()`, and `permutations()`. - ```python - import itertools - - # Example of itertools.count() - for i in itertools.count(1, 2): - if i > 10: - break - print(i) # Output: 1, 3, 5, 7, 9 - - # Example of itertools.chain() - list1 = [1, 2, 3] - list2 = ['a', 'b', 'c'] - combined = itertools.chain(list1, list2) - print(list(combined)) # Output: [1, 2, 3, 'a', 'b', 'c'] - ``` - -37. **How do you implement multiple inheritance in Python? What is the Method Resolution Order (MRO)?** - - **Answer:** Multiple inheritance allows a class to inherit from multiple base classes. The MRO defines the order in which base classes are searched when looking for a method or attribute. - ```python - class A: - def process(self): - print('A process()') - - class B(A): - def process(self): - print('B process()') - - class C(A): - def process(self): - print('C process()') - - class D(B, C): - pass - - obj = D() - obj.process() - # Output: B process() - ``` - -38. **Explain the concept of Python's `async` and `await` keywords for asynchronous programming.** - - **Answer:** `async` is used to define asynchronous functions (coroutines), and `await` is used to pause execution of an asynchronous function until a coroutine completes. - ```python - import asyncio - - async def async_task(): - print('Task 1') - await asyncio.sleep(1) - print('Task 2') - - asyncio.run(async_task()) - # Output: - # Task 1 - # (1 second delay) - # Task 2 - ``` - -39. **What are `__slots__` and when would you use them in Python?** - - **Answer:** `__slots__` is used to explicitly declare instance attributes. It can save memory by preventing the creation of instance dictionaries for attributes. - ```python - class MyClass: - __slots__ = ['x', 'y'] - - def __init__(self, x, y): - self.x = x - self.y = y - - obj = MyClass(10, 20) - print(obj.x, obj.y) # Output: 10 20 - ``` - -40. **Explain the purpose of the `functools` module in Python and provide examples of its usage.** - - **Answer:** The `functools` module provides higher-order functions for functional programming tasks. Examples include `partial()`, `reduce()`, and `lru_cache()`. - ```python - from functools import lru_cache - - @lru_cache(maxsize=32) - def fib(n): - if n < 2: - return n - return fib(n-1) + fib(n-2) - - print(fib(10)) # Output: 55 - ``` - -41. **Explain the difference between `os.path.join()` and `os.path.abspath()` in Python.** - - **Answer:** - - `os.path.join()`: It joins one or more path components intelligently using the correct separator for the operating system. - - `os.path.abspath()`: It returns the absolute pathname of a given path, resolving any symbolic links if present. - ```python - import os - - path = os.path.join('/Users', 'Alice', 'Documents', 'file.txt') - print(path) # Output: '/Users/Alice/Documents/file.txt' - - abs_path = os.path.abspath('file.txt') - print(abs_path) # Output: '/Users/Alice/Documents/file.txt' - ``` - -42. **How do you handle JSON data in Python? Provide an example.** - - **Answer:** Python's `json` module provides functions to encode Python objects as JSON strings and decode JSON strings into Python objects. - ```python - import json - - # Encoding Python object to JSON - data = {'name': 'Alice', 'age': 30} - json_str = json.dumps(data) - print(json_str) # Output: '{"name": "Alice", "age": 30}' - - # Decoding JSON to Python object - decoded_data = json.loads(json_str) - print(decoded_data) # Output: {'name': 'Alice', 'age': 30} - ``` - -43. **What are Python decorators used for, and how do you define a decorator with arguments?** - - **Answer:** Decorators are used to modify the behavior of functions or methods. Decorators with arguments are defined using a nested function that returns a decorator function. - ```python - def repeat(num_times): - def decorator_repeat(func): - def wrapper(*args, **kwargs): - for _ in range(num_times): - result = func(*args, **kwargs) - return result - return wrapper - return decorator_repeat - - @repeat(num_times=3) - def greet(name): - print(f'Hello, {name}') - - greet('Alice') - # Output: - # Hello, Alice - # Hello, Alice - # Hello, Alice - ``` - -44. **Explain the purpose of Python's `pickle` module.** - - **Answer:** The `pickle` module is used for serializing and deserializing Python objects. It can convert Python objects into a byte stream and vice versa. - ```python - import pickle - - # Serialize Python object to byte stream - data = {'name': 'Alice', 'age': 30} - serialized = pickle.dumps(data) - - # Deserialize byte stream back to Python object - deserialized = pickle.loads(serialized) - print(deserialized) # Output: {'name': 'Alice', 'age': 30} - ``` - -45. **What is a Python virtual environment (`venv`), and why would you use it?** - - **Answer:** A virtual environment (`venv`) is a self-contained directory that contains a Python installation for a specific version of Python, along with its own set of installed packages. It is used to isolate dependencies and project environments. - ```bash - # Creating a virtual environment - python -m venv myenv - - # Activating the virtual environment (Windows) - myenv\Scripts\activate - - # Activating the virtual environment (Unix/MacOS) - source myenv/bin/activate - ``` - -46. **Explain the use of Python's `requests` module for making HTTP requests.** - - **Answer:** The `requests` module allows you to send HTTP requests easily and handle the responses. - ```python - import requests - - # Making a GET request - response = requests.get('https://jsonplaceholder.typicode.com/posts/1') - print(response.status_code) # Output: 200 - print(response.json()) # Output: JSON response content - ``` - -47. **How do you implement a simple Flask application in Python?** - - **Answer:** Flask is a lightweight web framework for Python. Here's an example of a simple Flask application: - ```python - from flask import Flask - - app = Flask(__name__) - - @app.route('/') - def hello(): - return 'Hello, World!' - - if __name__ == '__main__': - app.run(debug=True) - ``` - -48. **What are context managers in Python, and how do you create one using the `contextlib` module?** - - **Answer:** Context managers in Python are objects that enable proper resource management using the `with` statement. You can create a context manager using the `contextlib` module's `contextmanager` decorator. - ```python - from contextlib import contextmanager - - @contextmanager - def file_manager(filename, mode): - try: - file = open(filename, mode) - yield file - finally: - file.close() - - with file_manager('example.txt', 'w') as f: - f.write('Hello, World!') - ``` - -49. **How do you use Python's `argparse` module for command-line argument parsing?** - - **Answer:** The `argparse` module makes it easy to write user-friendly command-line interfaces. It parses arguments and options from the command line. - ```python - import argparse - - parser = argparse.ArgumentParser(description='Process some integers.') - parser.add_argument('integers', metavar='N', type=int, nargs='+', - help='an integer for the accumulator') - parser.add_argument('--sum', dest='accumulate', action='store_const', - const=sum, default=max, - help='sum the integers (default: find the max)') - - args = parser.parse_args() - print(args.accumulate(args.integers)) - ``` - -50. **Explain the use of `@staticmethod` and `@classmethod` decorators in Python.** - - **Answer:** - - `@staticmethod`: It defines a static method that does not operate on instances of a class and does not have access to `self` or `cls`. - - `@classmethod`: It defines a class method that operates on the class itself rather than instances. It takes `cls` as the first parameter. - ```python - class MyClass: - class_attr = 10 - - @staticmethod - def static_method(): - print('This is a static method') - - @classmethod - def class_method(cls): - print(f'Class attribute: {cls.class_attr}') - - MyClass.static_method() # Output: This is a static method - MyClass.class_method() # Output: Class attribute: 10 - ``` - -These questions cover various intermediate-level topics in Python that are frequently asked in interviews. \ No newline at end of file diff --git a/docs/python/Interview ques/_category_.json b/docs/python/Interview ques/_category_.json deleted file mode 100644 index 416b85a01..000000000 --- a/docs/python/Interview ques/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Interview Questions", - "position": 20, - "link": { - "type": "generated-index", - "description": "hi" - } -} \ No newline at end of file diff --git a/docusaurus.config.js b/docusaurus.config.js index 952cc79c3..5662346c4 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -116,7 +116,7 @@ const config = { ], algolia: { - apiKey: "c2da29542646ed6c62329fff1bb0264f", + apiKey: "66c23e399ddb3c00367d40e3", indexName: "odeharborhubio", appId: "ZF3MPCPQHR", contextualSearch: false,