Python Data Science Jobs & Interviews
20.6K subscribers
192 photos
4 videos
25 files
334 links
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.

Admin: @Hussein_Sheikho
Download Telegram
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
🔥32
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
Question:
What is the purpose of the __call__ method in a Python class and provide an example of its use.

Answer:
The __call__ method allows an instance of a class to be called as if it were a function. This is useful for creating callable objects.

For example:

class Adder:
    def __init__(self, increment):
        self.increment = increment

    def __call__(self, value):
        return value + self.increment

add_five = Adder(5)
print(add_five(10))  # Outputs: 15


➡️ @DataScienceQ 💛
Please open Telegram to view this post
VIEW IN TELEGRAM
3
Forwarded from Free Online Courses
⭐️ Hello my advertiser friend!

I’m Eng. Hussein Sheikho 👋 and I’m excited to share our special promotional offer with you! 🎯

💥 Promo Offer:
Promote your ad across all our listed channels for only $35! 💰
📢 We accept all types and formats of advertisements.

Publishing Plan:
Your ad will be published for 20 days across all our channels,
plus it will be pinned for 7 days 🔝

🧑‍💻 For Programming Channel Owners Only:
Want your tech channel to grow fast? 🚀
You can add your channel to our promo folder for just $20/month
average growth rate 2000+ subscribers/month 📈

📩 Contact me for more details:
👉 t.iss.one/HusseinSheikho

🌱 Let’s grow together!

Our Share folder (our channels) 👇
https://t.iss.one/addlist/8_rRW2scgfRhOTc0
Please open Telegram to view this post
VIEW IN TELEGRAM
2
Python Data Science Jobs & Interviews pinned «⭐️ Hello my advertiser friend! I’m Eng. Hussein Sheikho 👋 and I’m excited to share our special promotional offer with you! 🎯 💥 Promo Offer: Promote your ad across all our listed channels for only $35! 💰 📢 We accept all types and formats of advertisements.…»
Interview Question

What is the structure of a JWT token?

Answer: JWT (JSON Web Token) consists of three parts separated by dots:

▶️ Header — contains the token type (JWT) and the signing algorithm, such as HMAC SHA256 or RSA

▶️ Payload — includes so-called “claims”: data like user ID, token expiration, roles, and other metadata

▶️ Signature — created from the header and payload using a secret key. It ensures the token’s content has not been tampered with.

These parts are base64 encoded and joined by dots: header.payload.signature.


tags: #interview

@DataScienceQ
Please open Telegram to view this post
VIEW IN TELEGRAM
2
#MachineLearning #CNN #DeepLearning #Python #TensorFlow #NeuralNetworks #ComputerVision #Programming #ArtificialIntelligence

Question:
How does a Convolutional Neural Network (CNN) process and classify images, and can you provide a detailed step-by-step implementation in Python using TensorFlow/Keras for a basic image classification task?

Answer:
A Convolutional Neural Network (CNN) is designed to automatically learn spatial hierarchies of features from images through convolutional layers, pooling layers, and fully connected layers. It excels in image classification tasks by detecting edges, textures, and patterns in a hierarchical manner.

Here’s a detailed, medium-level Python implementation using TensorFlow/Keras to classify images from the CIFAR-10 dataset:

import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

# Load and preprocess the data
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()

# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0

# Define class names
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']

# Build the CNN model
model = models.Sequential()

# First Convolutional Layer
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))

# Second Convolutional Layer
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))

# Third Convolutional Layer
model.add(layers.Conv2D(64, (3, 3), activation='relu'))

# Flatten and Dense Layers
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax')) # 10 classes

# Compile the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

# Train the model
history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))

# Evaluate the model
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(f'\nTest accuracy: {test_acc}')

# Visualize training history
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Model Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()

### Key Steps Explained:
1. Data Loading & Normalization: The CIFAR-10 dataset contains 60,000 32x32 color images across 10 classes. We normalize pixel values to [0,1] for better convergence.
2. Convolutional Layers: Use Conv2D with filters (e.g., 32, 64) to detect features like edges and textures. Each layer applies filters via convolution operations.
3. MaxPooling: Reduces spatial dimensions (downsampling) while retaining important features.
4. Flattening: Converts the 2D feature maps into a 1D vector for the dense layers.
5. Fully Connected Layers: Dense layers perform classification using learned features.
6. Softmax Output: Produces probabilities for each class.
7. Compilation & Training: Uses Adam optimizer and sparse categorical crossentropy loss for multi-class classification.

This example demonstrates how CNNs extract hierarchical features and achieve good performance on image classification tasks.

By: @DataScienceQ 🚀
Please open Telegram to view this post
VIEW IN TELEGRAM
2