Question 6 (Advanced):
In Python's context managers, what is the purpose of the
A) Memory allocation and garbage collection
B) Database connection pooling
C) Resource initialization and cleanup
D) Thread synchronization
#Python #ContextManagers #ResourceManagement #Advanced
In Python's context managers, what is the purpose of the
__enter__ and __exit__ methods?A) Memory allocation and garbage collection
B) Database connection pooling
C) Resource initialization and cleanup
D) Thread synchronization
#Python #ContextManagers #ResourceManagement #Advanced
Question 8 (Advanced):
What is the time complexity of checking if an element exists in a Python
A) O(1)
B) O(n)
C) O(log n)
D) O(n^2)
#Python #DataStructures #TimeComplexity #Advanced
✅ By: https://t.iss.one/DataScienceQ
What is the time complexity of checking if an element exists in a Python
set?A) O(1)
B) O(n)
C) O(log n)
D) O(n^2)
#Python #DataStructures #TimeComplexity #Advanced
✅ By: https://t.iss.one/DataScienceQ
❤1
Question 1 (Advanced):
When using Python's
A) Windows lacks proper fork() implementation
B) Linux handles memory management differently
C) macOS has better garbage collection
D) Windows requires explicit process naming
#Python #Multiprocessing #ParallelComputing #Advanced
✅ By: https://t.iss.one/DataScienceQ
When using Python's
multiprocessing module, why is if __name__ == '__main__': required for Windows but often optional for Linux/macOS? A) Windows lacks proper fork() implementation
B) Linux handles memory management differently
C) macOS has better garbage collection
D) Windows requires explicit process naming
#Python #Multiprocessing #ParallelComputing #Advanced
✅ By: https://t.iss.one/DataScienceQ
Question 23 (Advanced):
How does Python's "Name Mangling" (double underscore prefix) work in class attribute names, and what's its practical purpose?
Options:
A) Completely hides the attribute
B) Renames it to
C) Makes it immutable
D) Converts it to a method
#Python #OOP #NameMangling #Advanced
✅ By: https://t.iss.one/DataScienceQ
How does Python's "Name Mangling" (double underscore prefix) work in class attribute names, and what's its practical purpose?
class Test:
def __init__(self):
self.public = 10
self._protected = 20
self.__private = 30 # Name mangling
obj = Test()
print(dir(obj)) # What happens to __private?
Options:
A) Completely hides the attribute
B) Renames it to
_Test__private C) Makes it immutable
D) Converts it to a method
#Python #OOP #NameMangling #Advanced
✅ By: https://t.iss.one/DataScienceQ
❔ Interview question
What is the output of the following code?
Answer:
15
tags: #python #advanced #coding #programming #interview #nonlocal #function #dev
By: t.iss.one/DataScienceQ 🚀
What is the output of the following code?
def outer():
x = 10
def inner():
nonlocal x
x += 5
return x
return inner()
result = outer()
print(result)
Answer:
tags: #python #advanced #coding #programming #interview #nonlocal #function #dev
By: t.iss.one/DataScienceQ 🚀
⁉️ Interview question
What is the output of the following code?
Answer:
3
#⃣ tags: #python #advanced #coding #programming #interview #deepcopy #mutable #dev
By: t.iss.one/DataScienceQ 🚀
What is the output of the following code?
import copy
a = [1, 2, [3, 4]]
b = copy.deepcopy(a)
b[2][0] = 'X'
print(a[2][0])
Answer:
#⃣ tags: #python #advanced #coding #programming #interview #deepcopy #mutable #dev
By: t.iss.one/DataScienceQ 🚀
Telegram
Python Data Science Jobs & Interviews
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
Admin: @Hussein_Sheikho
⁉️ Interview question
What is the output of the following code?
Answer:
[1, 2]
#⃣ tags: #python #advanced #coding #programming #interview #defaultarguments #mutable #dev
By: t.iss.one/DataScienceQ 🚀
What is the output of the following code?
def func(a, b=[]):
b.append(a)
return b
print(func(1))
print(func(2))
Answer:
#⃣ tags: #python #advanced #coding #programming #interview #defaultarguments #mutable #dev
By: t.iss.one/DataScienceQ 🚀
⁉️ Interview question
What is the output of the following code?
Answer:
1
#️⃣ tags: #python #advanced #coding #programming #interview #strmethod #object #dev
By: t.iss.one/DataScienceQ 🚀
What is the output of the following code?
class A:
def __init__(self):
self.x = 1
def __str__(self):
return str(self.x)
a = A()
print(a)
Answer:
#️⃣ tags: #python #advanced #coding #programming #interview #strmethod #object #dev
By: t.iss.one/DataScienceQ 🚀
#python #programming #question #advanced #datastructures #datahandling
Write a comprehensive Python program that demonstrates advanced data handling techniques with various data structures:
1. Create and manipulate nested dictionaries representing a database of employees with complex data types.
2. Use JSON to serialize and deserialize a complex data structure containing lists, dictionaries, and custom objects.
3. Implement a class to represent a student with attributes and methods for data manipulation.
4. Use collections.Counter to analyze frequency of items in a dataset.
5. Demonstrate the use of defaultdict for grouping data by categories.
6. Implement a generator function to process large datasets efficiently.
7. Use itertools to create complex combinations and permutations of data.
8. Handle missing data using pandas DataFrames with different strategies (filling, dropping).
9. Convert between different data formats (dictionary, list, DataFrame, JSON).
10. Perform data validation using type hints and Pydantic models.
Write a comprehensive Python program that demonstrates advanced data handling techniques with various data structures:
1. Create and manipulate nested dictionaries representing a database of employees with complex data types.
2. Use JSON to serialize and deserialize a complex data structure containing lists, dictionaries, and custom objects.
3. Implement a class to represent a student with attributes and methods for data manipulation.
4. Use collections.Counter to analyze frequency of items in a dataset.
5. Demonstrate the use of defaultdict for grouping data by categories.
6. Implement a generator function to process large datasets efficiently.
7. Use itertools to create complex combinations and permutations of data.
8. Handle missing data using pandas DataFrames with different strategies (filling, dropping).
9. Convert between different data formats (dictionary, list, DataFrame, JSON).
10. Perform data validation using type hints and Pydantic models.
import json
from collections import Counter, defaultdict
from itertools import combinations, permutations
import pandas as pd
from typing import Dict, List, Any, Optional
from pydantic import BaseModel, Field
import numpy as np
# 1. Create nested dictionary representing employee database
employee_db = {
'employees': [
{
'id': 1,
'name': 'Alice Johnson',
'department': 'Engineering',
'salary': 85000,
'projects': ['Project A', 'Project B'],
'skills': {'Python': 8, 'JavaScript': 6, 'SQL': 7},
'hobbies': ['reading', 'hiking']
},
{
'id': 2,
'name': 'Bob Smith',
'department': 'Marketing',
'salary': 75000,
'projects': ['Project C'],
'skills': {'Photoshop': 9, 'SEO': 8, 'Copywriting': 7},
'hobbies': ['gaming', 'cooking']
},
{
'id': 3,
'name': 'Charlie Brown',
'department': 'Engineering',
'salary': 92000,
'projects': ['Project A', 'Project D'],
'skills': {'Python': 9, 'C++': 7, 'Linux': 8},
'hobbies': ['coding', 'swimming']
}
]
}
# 2. JSON serialization and deserialization
print("JSON Serialization:")
json_data = json.dumps(employee_db, indent=2)
print(json_data)
print("\nJSON Deserialization:")
loaded_data = json.loads(json_data)
print(f"Loaded data type: {type(loaded_data)}")
# 3. Student class with methods
class Student(BaseModel):
name: str
age: int
grades: List[float]
major: str = Field(..., alias='major')
def average_grade(self) -> float:
return sum(self.grades) / len(self.grades)
def is_honors_student(self) -> bool:
return self.average_grade() >= 3.5
def get_skill_level(self, skill: str) -> Optional[int]:
if hasattr(self, 'skills') and skill in self.skills:
return self.skills[skill]
return None
# 4. Using Counter to analyze data
print("\nUsing Counter to analyze skills:")
all_skills = []
for emp in employee_db['employees']:
all_skills.extend(emp['skills'].keys())
skill_counter = Counter(all_skills)
print("Skill frequencies:", skill_counter)
# 5. Using defaultdict for grouping data
print("\nUsing defaultdict to group employees by department:")
dept_groups = defaultdict(list)
for emp in employee_db['employees']:
dept_groups[emp['department']].append(emp['name'])
for dept, names in dept_groups.items():
print(f"{dept}: {names}")
# 6. Generator function for processing large datasets
def large_dataset_generator(size: int):
"""Generator that yields numbers from 1 to size"""
for i in range(1, size + 1):
yield i * 2 # Double each number
print("\nUsing generator to process large dataset:")
gen = large_dataset_generator(1000)
print("First 10 values from generator:", [next(gen) for _ in range(10)])
# 7. Using itertools for combinations and permutations
#python #programming #question #advanced #imageprocessing #opencv
Write a Python program that demonstrates advanced image processing techniques using various libraries and approaches:
1. Load an image from file and display it in multiple formats (RGB, grayscale, HSV).
2. Perform color space conversion between RGB, Grayscale, and HSV.
3. Apply different types of filters (Gaussian, median, bilateral) to reduce noise.
4. Implement edge detection using Canny and Sobel operators.
5. Use morphological operations (erosion, dilation, opening, closing) on binary images.
6. Detect and draw contours in the image.
7. Apply image thresholding (simple, adaptive, Otsu's method).
8. Implement image transformations (rotation, scaling, translation).
9. Use OpenCV's feature detection algorithms (SIFT, ORB) to find keypoints.
10. Save processed images in different formats (JPEG, PNG, TIFF).
Write a Python program that demonstrates advanced image processing techniques using various libraries and approaches:
1. Load an image from file and display it in multiple formats (RGB, grayscale, HSV).
2. Perform color space conversion between RGB, Grayscale, and HSV.
3. Apply different types of filters (Gaussian, median, bilateral) to reduce noise.
4. Implement edge detection using Canny and Sobel operators.
5. Use morphological operations (erosion, dilation, opening, closing) on binary images.
6. Detect and draw contours in the image.
7. Apply image thresholding (simple, adaptive, Otsu's method).
8. Implement image transformations (rotation, scaling, translation).
9. Use OpenCV's feature detection algorithms (SIFT, ORB) to find keypoints.
10. Save processed images in different formats (JPEG, PNG, TIFF).
import cv2
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
# 1. Load image and display basic information
def load_and_display_info(image_path):
img = cv2.imread(image_path)
if img is None:
raise FileNotFoundError(f"Image not found: {image_path}")
print("Image loaded successfully")
print(f"Shape: {img.shape}")
print(f"Data type: {img.dtype}")
print(f"Dimensions: {len(img.shape)}")
return img
# 2. Display image in different formats
def display_images(images, titles, figsize=(15, 10)):
fig, axes = plt.subplots(2, 4, figsize=figsize)
axes = axes.ravel()
for i, (img, title) in enumerate(zip(images, titles)):
if len(img.shape) == 2: # Grayscale
axes[i].imshow(img, cmap='gray')
else: # Color
axes[i].imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
axes[i].set_title(title)
axes[i].axis('off')
plt.tight_layout()
plt.show()
# 3. Convert color spaces
def convert_color_spaces(img):
# RGB to Grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# RGB to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Grayscale to RGB
gray_rgb = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
return gray, hsv, gray_rgb
# 4. Apply different filters
def apply_filters(img):
# Gaussian blur
gaussian = cv2.GaussianBlur(img, (5, 5), 0)
# Median filter
median = cv2.medianBlur(img, 5)
# Bilateral filter
bilateral = cv2.bilateralFilter(img, 9, 75, 75)
return gaussian, median, bilateral
# 5. Edge detection
def edge_detection(img):
# Convert to grayscale first
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Canny edge detection
canny = cv2.Canny(gray, 100, 200)
# Sobel edge detection
sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
sobel = np.sqrt(sobel_x**2 + sobel_y**2)
return canny, sobel
# 6. Morphological operations
def morphological_operations(img):
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Threshold to create binary image
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# Erosion
kernel = np.ones((5, 5), np.uint8)
erosion = cv2.erode(binary, kernel, iterations=1)
# Dilation
dilation = cv2.dilate(binary, kernel, iterations=1)
# Opening (erosion followed by dilation)
opening = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)
# Closing (dilation followed by erosion)
closing = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
return erosion, dilation, opening, closing
# 7. Thresholding methods
def thresholding_methods(img):
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Simple thresholding
_, thresh_simple = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# Adaptive thresholding
thresh_adaptive = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY, 11, 2)
#python #programming #question #advanced #osoperations
Write a Python program that demonstrates advanced operating system interactions with the following requirements:
1. List all files and directories in the current directory with detailed information (size, modification time).
2. Create a new directory and move a file into it.
3. Execute a system command to list processes and capture its output.
4. Get the current user's home directory and environment variables.
5. Check if a process is running by name.
6. Set and get environment variables.
7. Create a temporary file and clean it up after use.
By: @DataScienceQ 🚀
Write a Python program that demonstrates advanced operating system interactions with the following requirements:
1. List all files and directories in the current directory with detailed information (size, modification time).
2. Create a new directory and move a file into it.
3. Execute a system command to list processes and capture its output.
4. Get the current user's home directory and environment variables.
5. Check if a process is running by name.
6. Set and get environment variables.
7. Create a temporary file and clean it up after use.
import os
import subprocess
import shutil
import tempfile
import psutil
from pathlib import Path
import sys
# 1. List files and directories with detailed information
def list_directory_details():
print("Directory contents with details:")
for entry in os.scandir('.'):
try:
stat = entry.stat()
print(f"{entry.name:<20} {stat.st_size:>8} bytes, "
f"modified: {stat.st_mtime}")
except Exception as e:
print(f"{entry.name}: Error - {e}")
# 2. Create directory and move file
def create_and_move_file():
# Create new directory
new_dir = "test_directory"
os.makedirs(new_dir, exist_ok=True)
# Create a test file
test_file = "test_file.txt"
with open(test_file, 'w') as f:
f.write("This is a test file.")
# Move file to new directory
destination = os.path.join(new_dir, test_file)
shutil.move(test_file, destination)
print(f"Moved {test_file} to {destination}")
# 3. Execute system command and capture output
def execute_system_command():
# List processes using ps command
result = subprocess.run(['ps', '-eo', 'pid,comm'],
capture_output=True, text=True)
print("\nRunning processes:")
print(result.stdout)
# 4. Get user information
def get_user_info():
print(f"\nCurrent user: {os.getlogin()}")
print(f"Home directory: {os.path.expanduser('~')}")
print(f"Current working directory: {os.getcwd()}")
# 5. Check if process is running
def check_process_running(process_name):
for proc in psutil.process_iter(['name']):
try:
if process_name.lower() in proc.info['name'].lower():
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return False
# 6. Environment variables
def manage_environment_variables():
# Get environment variables
print(f"\nPATH variable: {os.environ.get('PATH')}")
print(f"HOME variable: {os.environ.get('HOME')}")
# Set a new environment variable
os.environ['TEST_VAR'] = 'Hello from Python'
print(f"Set TEST_VAR: {os.environ.get('TEST_VAR')}")
# 7. Temporary files
def use_temporary_files():
# Create temporary file
with tempfile.NamedTemporaryFile(delete=False) as temp:
temp.write(b"This is a temporary file.")
temp_path = temp.name
print(f"Created temporary file: {temp_path}")
# Clean up
os.unlink(temp_path)
print("Temporary file deleted.")
# Main function to demonstrate all techniques
def main():
print("=== Operating System Operations Demo ===\n")
# 1. List directory details
list_directory_details()
# 2. Create directory and move file
create_and_move_file()
# 3. Execute system command
execute_system_command()
# 4. Get user info
get_user_info()
# 5. Check if process is running
print(f"\nIs Python running? {check_process_running('python')}")
# 6. Manage environment variables
manage_environment_variables()
# 7. Use temporary files
use_temporary_files()
print("\nAll operations completed successfully.")
if __name__ == "__main__":
main()
By: @DataScienceQ 🚀
👍2
Question:
What are the differences between shallow copy and deep copy in Python, and when can using a shallow copy lead to unexpected behavior? Provide an example illustrating this.
Answer:
A shallow copy creates a new object but inserts references to the items found in the original object. A deep copy creates a new object and recursively copies all objects found in the original, meaning that the copy and original are fully independent.
Using a shallow copy can lead to unexpected behavior when the original object contains nested mutable objects because changes to nested objects in the copy will reflect in the original.
Example demonstrating the issue:
Notice that modifying the nested list in the shallow copy also affected the original.
How to avoid this:
Use
#Python #Advanced #ShallowCopy #DeepCopy #MutableObjects #CopyModule
What are the differences between shallow copy and deep copy in Python, and when can using a shallow copy lead to unexpected behavior? Provide an example illustrating this.
Answer:
A shallow copy creates a new object but inserts references to the items found in the original object. A deep copy creates a new object and recursively copies all objects found in the original, meaning that the copy and original are fully independent.
Using a shallow copy can lead to unexpected behavior when the original object contains nested mutable objects because changes to nested objects in the copy will reflect in the original.
Example demonstrating the issue:
import copy
original = [[1, 2], [3, 4]]
shallow_copy = copy.copy(original)
shallow_copy.append(99)
print("Original:", original) # Outputs: [[1, 2, 99], [3, 4]]
print("Shallow Copy:", shallow_copy) # Outputs: [[1, 2, 99], [3, 4]]
Notice that modifying the nested list in the shallow copy also affected the original.
How to avoid this:
Use
deepcopy from the copy module to create a fully independent copy:deep_copy = copy.deepcopy(original)
deep_copy.append(100)
print("Original:", original) # Outputs: [[1, 2, 99], [3, 4]]
print("Deep Copy:", deep_copy) # Outputs: [[1, 2, 99, 100], [3, 4]]
#Python #Advanced #ShallowCopy #DeepCopy #MutableObjects #CopyModule
❤2👍1