PyData Careers
20.7K subscribers
196 photos
4 videos
26 files
342 links
Python Data Science jobs, interview tips, and career insights for aspiring professionals.
Download Telegram
Question:
Explain the differences between synchronous and asynchronous programming in Python.

Answer:
Synchronous programming executes tasks sequentially, meaning one task must complete before the next begins. In contrast, asynchronous programming allows tasks to be started and operated concurrently, allowing for non-blocking execution. This can improve efficiency, especially in I/O-bound applications.

For instance, using asyncio:
import asyncio

async def async_function():
    print('Start')
    await asyncio.sleep(1)
    print('End')

asyncio.run(async_function())


In this example, async_function allows the program to perform other tasks while waiting for the sleep duration to complete.

By: @DataScienceQ πŸš€
❀1
Question:
How does scope work in JavaScript, particularly with arrow functions?

Answer:
In JavaScript, scope refers to the visibility of variables and functions in certain parts of your code. There are two main types of scope: global and local. Arrow functions have a lexical binding of this, meaning they don't create their own this context; instead, they inherit it from the enclosing scope. This makes them particularly useful in callbacks and when you want to preserve the context of this.

Example:

const obj = {
    value: 10,
    method: function() {
        setTimeout(() => {
            console.log(this.value);
        }, 1000);
    }
};
obj.method(); // logs 10


By: @DataScienceQ πŸš€
❀2πŸ€”1
Question: What is the purpose of the functools.partial function in Python?

Answer:The functools.partial function in Python allows you to create a new function with some of the parameters of an existing function fixed to specific values. This can be useful for creating more specific functions from general ones.

For example:
from functools import partial

def multiply(x, y):
return x * y

multiply_by_2 = partial(multiply, 2)
print(multiply_by_2(5)) # Outputs 10



In this example, multiply_by_2 is a new function that multiplies any given input by 2.

By: @DataScienceQ ⭐️
Please open Telegram to view this post
VIEW IN TELEGRAM
❀1
Question: Explain the difference between lists and tuples.

Answer:Lists are mutable, meaning you can change their content after creation (e.g., adding or removing elements). Tuples, on the other hand, are immutable; once created, their content cannot be altered.

By: @DataScienceQ ⭐️
❀2
Question:
How can you use Python’s asyncio and concurrent.futures to efficiently handle both I/O-bound and CPU-bound tasks in a single application, and what are the best practices for structuring such a system?

Answer:
To efficiently handle both I/O-bound (e.g., network requests, file I/O) and CPU-bound (e.g., data processing, math operations) tasks in Python, you should combine asyncio for I/O-bound work and concurrent.futures.ThreadPoolExecutor or ProcessPoolExecutor for CPU-bound tasks. This avoids blocking the event loop and maximizes performance.

Here’s an example:

import asyncio
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import aiohttp
import requests

# Simulated I/O-bound task (e.g., API call)
async def fetch_url(session, url):
try:
async with session.get(url) as response:
return await response.text()
except Exception as e:
return f"Error: {e}"

# Simulated CPU-bound task (e.g., heavy computation)
def cpu_intensive_task(n):
return sum(i * i for i in range(n))

# Main function using asyncio + thread/process pools
async def main():
# I/O-bound tasks with asyncio
urls = [
"https://httpbin.org/json",
"https://httpbin.org/headers",
"https://httpbin.org/status/200"
]

# Use aiohttp for concurrent HTTP requests
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await asyncio.gather(*tasks)

print("I/O-bound results:", results)

# CPU-bound tasks with ProcessPoolExecutor
with ProcessPoolExecutor() as executor:
# Run CPU-intensive work in separate processes
futures = [executor.submit(cpu_intensive_task, 1000000) for _ in range(3)]
cpu_results = [future.result() for future in futures]

print("CPU-bound results:", cpu_results)

# Run the async main function
if __name__ == "__main__":
asyncio.run(main())

Explanation:
- asyncio handles I/O-bound tasks asynchronously without blocking the main thread.
- aiohttp is used for efficient HTTP requests.
- ProcessPoolExecutor runs CPU-heavy functions in separate processes (bypassing GIL).
- Mixing both ensures optimal resource usage: async for I/O, multiprocessing for CPU.

Best practices:
- Use ThreadPoolExecutor for light I/O or blocking code.
- Use ProcessPoolExecutor for CPU-intensive work.
- Avoid mixing async and blocking code directly β€” always offload CPU tasks.
- Use asyncio.gather() to run multiple coroutines concurrently.

#Python #AsyncIO #Concurrency #Multithreading #Multiprocessing #AdvancedPython #Programming #WebDevelopment #Performance

By: @DataScienceQ πŸš€
❀1
Question:
What are Python's built-in data types?

Answer:
Python's built-in data types include:
- int: for integers
- float: for floating-point numbers
- str: for strings
- list: for lists
- tuple: for tuples
- dict: for dictionaries
- set: for sets
- bool: for boolean values.

By: @DataScienceQ πŸš€
Please open Telegram to view this post
VIEW IN TELEGRAM
Question:
What is the purpose of the zip() function in Python and how can it be used effectively?

Answer:
The zip() function in Python is used to combine multiple iterable objects (like lists or tuples) into a single iterable of tuples, where the i-th tuple contains the i-th element from each of the passed iterables. It is particularly useful for pairing up data.

Example:

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
result = zip(list1, list2)
print(list(result))  # Outputs: [(1, 'a'), (2, 'b'), (3, 'c')]


It can also be used in loops for simultaneous iteration:

for number, letter in zip(list1, list2):
    print(number, letter)
# Outputs:
# 1 a
# 2 b
# 3 c


By: @DataScienceQ πŸš€
Please open Telegram to view this post
VIEW IN TELEGRAM
Question:
What is type hinting in Python, and how does it enhance code quality?

Answer:
Type hinting in Python provides a way to statically indicate the types of variables, function parameters, and return values. It enhances code quality by making code more readable and allowing for static analysis tools to catch type-related errors before runtime. Type hints are not enforced at runtime but serve as documentation to inform developers about expected types.

Example:

def add(a: int, b: int) -> int:
    return a + b


By: @DataScienceQ πŸš€
Please open Telegram to view this post
VIEW IN TELEGRAM
Question:
How can you create a custom exception in Python and what is its typical use case?

Answer:
You can create a custom exception in Python by inheriting from the built-in Exception class. Custom exceptions are useful for signaling specific error conditions in your application logic, making your code more informative and easier to debug.

Example:

class MyCustomError(Exception):
    pass

try:
    raise MyCustomError('This is a custom error!')
except MyCustomError as e:
    print(e)  # Output: This is a custom error!


By: @DataScienceQ πŸš€
Please open Telegram to view this post
VIEW IN TELEGRAM
❀1
❔ Interview question

Why does range(1000) take almost no memory?

Answer: Because range is not a list but a sequence object that lazily computes values as accessed. It stores only start, stop, and step, not all numbers at once. Thanks to this, for example, range(10**9) takes as much memory as range(10).

tags: #interview

➑ @DataScienceQ ⭐️
Please open Telegram to view this post
VIEW IN TELEGRAM
❀4
❔ Interview question

What happens to a list if you delete almost all its elements?

Answer: list in Python does not automatically reduce allocated memory after deleting elements. For example, if the list had 1,000,000 elements and only 100 remain, it still occupies memory for a million elements until it is recreated (lst = lst[:] or lst = list(lst)).

tags: #interview

➑ @DataScienceQ 🌱
Please open Telegram to view this post
VIEW IN TELEGRAM
❀3
Question: How do you convert a list to a set in Python?

Answer:You can convert a list to a set by using the set() function.

For example:
my_list = [1, 2, 2, 3]  
my_set = set(my_list)
print(my_set)


This will output {1, 2, 3}.
❀1
How can you design a Python class to represent a geometric shape (e.g., Circle, Rectangle) with inheritance and method overriding, ensuring each shape calculates its area and perimeter correctly? Implement a base class Shape with abstract methods for area and perimeter, then create derived classes for Circle and Rectangle. Include validation for input parameters and demonstrate polymorphism by storing multiple shapes in a list and iterating through them to calculate total area and perimeter.

from abc import ABC, abstractmethod
import math

class Shape(ABC):
"""Abstract base class for geometric shapes."""

@abstractmethod
def area(self) -> float:
"""Calculate the area of the shape."""
pass

@abstractmethod
def perimeter(self) -> float:
"""Calculate the perimeter of the shape."""
pass

class Circle(Shape):
"""Represents a circle with a given radius."""

def __init__(self, radius: float):
if radius <= 0:
raise ValueError("Radius must be positive.")
self.radius = radius

def area(self) -> float:
return math.pi * self.radius ** 2

def perimeter(self) -> float:
return 2 * math.pi * self.radius

class Rectangle(Shape):
"""Represents a rectangle with width and height."""

def __init__(self, width: float, height: float):
if width <= 0 or height <= 0:
raise ValueError("Width and height must be positive.")
self.width = width
self.height = height

def area(self) -> float:
return self.width * self.height

def perimeter(self) -> float:
return 2 * (self.width + self.height)

# Example usage
shapes = [
Circle(5),
Rectangle(4, 6),
Circle(3),
Rectangle(7, 2)
]

total_area = 0
total_perimeter = 0

for shape in shapes:
total_area += shape.area()
total_perimeter += shape.perimeter()

print(f"Total Area: {total_area:.2f}")
print(f"Total Perimeter: {total_perimeter:.2f}")

# Demonstrate polymorphism
for shape in shapes:
print(f"{shape.__class__.__name__}: Area = {shape.area():.2f}, Perimeter = {shape.perimeter():.2f}")

Answer: The question explores object-oriented programming concepts in Python using inheritance and abstraction. The solution defines an abstract base class Shape with two abstract methods (area and perimeter) that must be implemented by all derived classes. Two concrete classes, Circle and Rectangle, inherit from Shape and provide their own implementations of the required methods. Input validation is enforced through error checking in the constructors. The example demonstrates polymorphism by storing different shape types in a single list and processing them uniformly. This approach promotes code reusability, maintainability, and extensibility, making it ideal for academic and real-world applications involving geometric calculations.

#Python #OOP #Inheritance #Polymorphism #Abstraction #GeometricShapes #Programming #Academic #IntermediateLevel #ObjectOriented

By: @DataScienceQ πŸš€
❀2
Question: Explain the difference between mutable and immutable objects.

Answer:Mutable objects can be changed after their creation (e.g., lists, dictionaries), while immutable objects cannot be modified (e.g., strings, tuples). This distinction affects how data structures behave when passed around in functions.
❀4
❔ Interview Question

Why is list.sort() faster than sorted(list) when sorting the same list?

Answer: The list.sort() method performs an in-place sort, modifying the original list without creating a new copy. This makes it more efficient in terms of memory and performance.

The sorted(list) function creates a new sorted list, which requires additional memory allocation and copying of elements before sorting, potentially increasing time and memory costs.


tags: #interview

➑ @DataScienceQ
Please open Telegram to view this post
VIEW IN TELEGRAM
πŸ”₯3❀2
❔ Python Interview Question

Why is dict.get(key) often preferred over directly accessing keys in a dictionary using dict[key]?

Answer: Using dict.get(key) avoids a KeyError if the key doesn't exist by returning None (or a default value) instead. Direct access with dict[key] raises an exception when the key is missing, which can interrupt program flow and requires explicit error handling.

tags: #interview

➑ @DataScienceQ
❀1
Question:
What are Python's built-in functions for working with sets?

Answer:
Python has several built-in functions for working with sets, such as `add()`, `remove()`, `union()`, `intersection()`, etc.

Example usage is as follows:

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Adding an element
set1.add(4)

# Removing an element
set1.remove(2)

# Union
set_union = set1.union(set2)

# Intersection
set_intersection = set1.intersection(set2)
print(set_union) # Outputs: {1, 3, 4, 5}
print(set_intersection) # Outputs: {3}
❀2
Question: What are Python set comprehensions?

Answer:Set comprehensions are similar to list comprehensions but create a set instead of a list. The syntax is:
{expression for item in iterable if condition}


For example, to create a set of squares of even numbers:
squares_set = {x**2 for x in range(10) if x % 2 == 0}



This will create a set with the values
{0, 4, 16, 36, 64}

https://t.iss.one/DataScienceQ 🌟
Please open Telegram to view this post
VIEW IN TELEGRAM
❀4
❔ Interview question

What is the difference between "is" and "=="?

Answer: The "is" operator checks whether two objects are the same object in memory, whereas the "==" operator checks whether the values of those objects are equal.

tags: #interview

➑ @DataScienceQ ⭐
Please open Telegram to view this post
VIEW IN TELEGRAM
❀3
Question:
What is the purpose of the super() function in Python?

Answer:
The super() function returns a temporary object that allows you to call methods of the superclass in a subclass. It plays a crucial role in implementing inheritance, allowing you to extend or modify behaviors of methods inherited from parent classes.
For example:
class Parent:
    def greet(self):
        return 'Hello from Parent'

class Child(Parent):
    def greet(self):
        return super().greet() + ' and Child'

child = Child()
print(child.greet())  # Hello from Parent and Child

➑️ @DataScienceQ
Please open Telegram to view this post
VIEW IN TELEGRAM
❀1