Python Data Science Jobs & Interviews
20.3K subscribers
187 photos
4 videos
25 files
325 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
πŸ’‘ Python: Converting Numbers to Human-Readable Words

Transforming numerical values into their word equivalents is crucial for various applications like financial reports, check writing, educational software, or enhancing accessibility. While complex to implement from scratch for all cases, Python's num2words library provides a robust and easy solution. Install it with pip install num2words.

from num2words import num2words

# Example 1: Basic integer
number1 = 123
words1 = num2words(number1)
print(f"'{number1}' in words: {words1}")

# Example 2: Larger integer
number2 = 543210
words2 = num2words(number2, lang='en') # Explicitly set language
print(f"'{number2}' in words: {words2}")

# Example 3: Decimal number
number3 = 100.75
words3 = num2words(number3)
print(f"'{number3}' in words: {words3}")

# Example 4: Negative number
number4 = -45
words4 = num2words(number4)
print(f"'{number4}' in words: {words4}")

# Example 5: Number for an ordinal form
number5 = 3
words5 = num2words(number5, to='ordinal')
print(f"Ordinal '{number5}' in words: {words5}")


Code explanation: This script uses the num2words library to convert various integers, decimals, and negative numbers into their English word representations. It also demonstrates how to generate ordinal forms (third instead of three) and explicitly set the output language.

#Python #TextProcessing #NumberToWords #num2words #DataManipulation

━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
πŸ’‘ Python Dictionary Cheatsheet: Key Operations

This lesson provides a quick, comprehensive guide to Python dictionaries. Dictionaries are unordered, mutable collections of key-value pairs, essential for mapping data. This cheatsheet covers creation, access, modification, and useful methods.

# 1. Dictionary Creation
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
empty_dict = {}
another_dict = dict(brand="Ford", model="Mustang") # Using keyword arguments
from_tuples = dict([("a", 1), ("b", 2)]) # From a list of key-value tuples
dict_comprehension = {i: i*i for i in range(3)} # {0: 0, 1: 1, 2: 4}

# 2. Accessing Values
name = my_dict["name"] # Alice
age = my_dict.get("age") # 30 (safer, returns None if key not found)
job = my_dict.get("job", "Unemployed") # Unemployed (default value if key not found)

# 3. Adding and Updating Elements
my_dict["email"] = "[email protected]" # Adds new key-value pair
my_dict["age"] = 31 # Updates existing value
my_dict.update({"city": "London", "occupation": "Engineer"}) # Updates/adds multiple pairs

# 4. Removing Elements
removed_age = my_dict.pop("age") # Removes 'age' and returns its value (31)
del my_dict["city"] # Deletes the 'city' key-value pair
# my_dict.popitem() # Removes and returns a (key, value) pair (Python 3.7+ guaranteed last inserted)
my_dict.clear() # Empties the dictionary

# Re-create for further examples
person = {"name": "Bob", "age": 25, "city": "Paris", "occupation": "Artist"}

# 5. Iterating Through Dictionaries
# print("--- Keys ---")
for key in person: # Iterates over keys by default
# print(key)
pass
# print("--- Values ---")
for value in person.values():
# print(value)
pass
# print("--- Items (Key-Value Pairs) ---")
for key, value in person.items():
# print(f"{key}: {value}")
pass

# 6. Dictionary Information
num_items = len(person) # 4
keys_list = list(person.keys()) # ['name', 'age', 'city', 'occupation']
values_list = list(person.values()) # ['Bob', 25, 'Paris', 'Artist']
items_list = list(person.items()) # [('name', 'Bob'), ('age', 25), ...]

# 7. Checking for Key Existence
has_name = "name" in person # True
has_country = "country" in person # False

# 8. Copying Dictionaries
person_copy = person.copy() # Shallow copy
person_deep_copy = dict(person) # Another way for shallow copy

# 9. fromkeys() - Create dictionary from keys with default value
default_value_dict = dict.fromkeys(["a", "b", "c"], 0) # {'a': 0, 'b': 0, 'c': 0}


Code explanation: This script demonstrates essential Python dictionary operations. It covers various ways to create dictionaries, access values using direct key lookup and the safer get() method, and how to add or update key-value pairs. It also shows different methods for removing elements (pop(), del, clear()), and iterating through dictionary keys, values, or items. Finally, it illustrates how to get dictionary size, retrieve lists of keys/values/items, check for key existence, and create copies or new dictionaries using fromkeys().

#Python #Dictionaries #DataStructures #Programming #Cheatsheet

━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❀1
🧠 Quiz: Which of the following is the most Pythonic and efficient way to iterate through a list my_list and access both each item and its corresponding index?

A) i = 0; while i < len(my_list): item = my_list[i]; i += 1
B) for index, item in enumerate(my_list):
C) for index in range(len(my_list)): item = my_list[index]
D) for item in my_list: index = my_list.index(item)

βœ… Correct answer: B

Explanation: The enumerate() function is specifically designed to provide both the index and the item while iterating over a sequence, making the code cleaner, more readable, and generally more efficient than manual indexing or while loops. Option D is inefficient as list.index(item) scans the list for each item, especially if duplicates exist.

#PythonTips #Pythonic #Programming

━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
πŸ’‘ Python Lists: Adding and Extending

Use .append() to add a single item to the end of a list. Use .extend() to add all items from an iterable (like another list) to the end.

# Create a list of numbers
my_list = [10, 20, 30]

# Add a single element
my_list.append(40)
# my_list is now [10, 20, 30, 40]
print(f"After append: {my_list}")

# Add elements from another list
another_list = [50, 60]
my_list.extend(another_list)
# my_list is now [10, 20, 30, 40, 50, 60]
print(f"After extend: {my_list}")


Code explanation: The code first initializes a list. .append(40) adds the integer 40 to the end. Then, .extend() takes each item from another_list and adds them individually to the end of my_list.

#Python #PythonLists #DataStructures #CodingTips #PythonCheatsheet

━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
πŸ’‘ Python Conditionals: if, elif, and else

The if-elif-else structure allows your program to execute different code blocks based on a series of conditions. It evaluates them sequentially:

β€’ if: The first condition to check. If it's True, its code block runs, and the entire structure is exited.
β€’ elif: (short for "else if") If the preceding if (or elif) was False, this condition is checked. You can have multiple elif blocks.
β€’ else: This is an optional final block. Its code runs only if all preceding if and elif conditions were False.

This provides a clear and efficient way to handle multiple mutually exclusive scenarios.

# A program to categorize a number
number = 75

if number < 0:
category = "Negative"
elif number == 0:
category = "Zero"
elif 0 < number <= 50:
category = "Small Positive (1-50)"
elif 50 < number <= 100:
category = "Medium Positive (51-100)"
else:
category = "Large Positive (>100)"

print(f"The number {number} is in the category: {category}")
# Output: The number 75 is in the category: Medium Positive (51-100)


Code explanation: The script evaluates the variable number. It first checks if it's negative, then if it's zero. After that, it checks two positive ranges using elif. Since 75 is greater than 50 and less than or equal to 100, the condition 50 < number <= 100 is met, the category is set to "Medium Positive", and the final else block is skipped.

#Python #ControlFlow #IfStatement #PythonTips #ProgrammingLogic

━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
🧠 Quiz: What is one of the most critical first steps when starting a new data analysis project?

A) Select the most complex predictive model.
B) Immediately remove all outliers from the dataset.
C) Perform Exploratory Data Analysis (EDA) to understand the data's main characteristics.
D) Normalize all numerical features.

βœ… Correct answer: C

Explanation: EDA is crucial because it helps you summarize the data's main features, identify patterns, spot anomalies, and check assumptions before you proceed with more formal modeling. Steps like modeling or removing outliers should be informed by the initial understanding gained from EDA.

#DataAnalysis #DataScience #Statistics

━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❀4
🧠 Quiz: Which keyword is used to implement inheritance between classes in Java?

A) implements
B) extends
C) inherits
D) uses

βœ… Correct answer: B

Explanation: In Java, the extends keyword is used to indicate that a class is inheriting from another class, forming an "is-a" relationship. The implements keyword is used for interfaces.

#Java #OOP #Inheritance

━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
🧠 Quiz: Which submodule of Matplotlib is commonly imported with the alias plt to create plots and visualizations?

A) matplotlib.animation
B) matplotlib.pyplot
C) matplotlib.widgets
D) matplotlib.cm

βœ… Correct answer: B

Explanation: matplotlib.pyplot is the most widely used module in Matplotlib, providing a convenient, MATLAB-like interface for creating a variety of plots and charts. It's standard practice to import it as import matplotlib.pyplot as plt.

#Matplotlib #Python #DataVisualization

━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❀1πŸ”₯1
This channels is for Programmers, Coders, Software Engineers.

0️⃣ Python
1️⃣ Data Science
2️⃣ Machine Learning
3️⃣ Data Visualization
4️⃣ Artificial Intelligence
5️⃣ Data Analysis
6️⃣ Statistics
7️⃣ Deep Learning
8️⃣ programming Languages

βœ… https://t.iss.one/addlist/8_rRW2scgfRhOTc0

βœ… https://t.iss.one/Codeprogrammer
Please open Telegram to view this post
VIEW IN TELEGRAM
❀1
🧠 Quiz: What is the most "Pythonic" way to create a new list containing the squares of numbers from an existing list called nums?

A) Using a for loop and the .append() method.
B) new_list = [num**2 for num in nums]
C) Using a while loop with an index counter.
D) new_list = (num**2 for num in nums)

βœ… Correct answer: B

Explanation: This is a list comprehension. It's a concise, readable, and often faster way to create a new list from an iterable compared to a traditional for loop. Option D creates a generator expression, not a list.

#Python #ProgrammingTips #PythonQuiz

━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❔ Interview question

What is the order of execution of decorators if there are several on one function?

Answer: Decorators are executed from bottom to top β€” the bottom one is called first, then the upper one, wrapping the function in several layers.

tags: #interview

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

What is the difference between using tensor.detach() and wrapping code in with torch.no_grad()?

Answer: with torch.no_grad() is a context manager that globally disables gradient calculation for all operations within its block. It's used during inference to reduce memory usage and speed up computation. tensor.detach() is a tensor-specific method that creates a new tensor sharing the same data but detached from the current computation graph. This stops gradients from flowing back to the original graph through this tensor, effectively creating a fork.

tags: #interview #pytorch #machinelearning

➑ @DataScienceQ
❔ Interview question

When saving a PyTorch model, what is the difference between saving the entire model versus saving just the model's state_dict? Which approach is generally recommended and why?

Answer: Saving the entire model (torch.save(model, PATH)) pickles the entire Python object, including the model architecture and its parameters. Saving just the state_dict (torch.save(model.state_dict(), PATH)) saves only a dictionary of the model's parameters (weights and biases).

The recommended approach is to save the
state_dict because it is more flexible and robust. It decouples the saved weights from the specific code that defined the model, making your code easier to refactor and share without breaking the loading process.

tags: #interview #pytorch #machinelearning

➑ @DataScienceQ

━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❔ Interview question

What is the purpose of a pooling layer in a Convolutional Neural Network (CNN)?

Answer: A pooling layer (like Max Pooling or Average Pooling) is used to progressively reduce the spatial size (width and height) of the feature maps. This serves two main purposes: 1) It reduces the number of parameters and computational complexity, which helps to control overfitting. 2) It introduces a degree of translation invariance, meaning the network becomes more robust to small shifts and distortions in the position of features in the input image.

tags: #interview #cnn #deeplearning

━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❔ Interview question

What is the difference between the == (loose comparison) and === (strict comparison) operators in PHP?

Answer: The == operator is for loose comparison, checking for value equality after type juggling. For example, 1 == "1" is true. The === operator is for strict comparison, checking for both value AND type equality, without any type conversion. So, 1 === "1" is false. It's generally safer to use === to avoid unexpected bugs.

tags: #interview #php

━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❔ Interview question

What is the difference between isset() and empty() in PHP?

Answer: isset() returns true only if a variable is declared and is not NULL. In contrast, empty() returns true if a variable is considered "falsy", which includes NULL, false, 0, "0", an empty string "", or an empty array. A key difference is that a variable like $var = 0; is set (so isset() is true), but also considered empty (so empty() is true).

tags: #interview #php

━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❀1
❔ Interview question

Why is it better to use os.path.join() to construct paths instead of simple string concatenation?

Answer: Because os.path.join() handles cross-platform compatibility automatically. Operating systems use different path separators (e.g., / for Linux/macOS and \ for Windows). Hardcoding a separator like 'folder' + '/' + 'file' will break on a different OS. os.path.join('folder', 'file') correctly produces folder/file or folder\file depending on the system, making the code robust and portable.

tags: #interview #python #os

━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❀1
Clean Code Tip:

For functions with expensive, repeated computations, manual memoization (caching) adds boilerplate and clutters your logic. Use the @lru_cache decorator from functools to get a powerful, ready-made cache with a single line of code. It's a pro-level move for clean, high-performance Python. πŸš€

Example:

import time
from functools import lru_cache

# The verbose way with manual caching
def fibonacci_manual(n, cache={}):
if n in cache:
return cache[n]
if n < 2:
return n

# Simulate an expensive computation
time.sleep(0.5)

result = fibonacci_manual(n - 1) + fibonacci_manual(n - 2)
cache[n] = result
return result

print("--- Manual Caching Way ---")
start_time = time.time()
print(f"Result: {fibonacci_manual(10)}")
print(f"First call took: {time.time() - start_time:.2f}s")

start_time = time.time()
print(f"Result: {fibonacci_manual(10)}")
print(f"Second call (cached) took: {time.time() - start_time:.2f}s")


# The clean, Pythonic way using @lru_cache
@lru_cache(maxsize=None)
def fibonacci_lru(n):
if n < 2:
return n

# Simulate an expensive computation
time.sleep(0.5)

return fibonacci_lru(n - 1) + fibonacci_lru(n - 2)

print("\n--- Clean @lru_cache Way ---")
start_time = time.time()
print(f"Result: {fibonacci_lru(10)}")
print(f"First call took: {time.time() - start_time:.2f}s")

start_time = time.time()
print(f"Result: {fibonacci_lru(10)}")
print(f"Second call (cached) took: {time.time() - start_time:.2f}s")


━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❀2
❔ Interview Question

How to get the current module's name?

Answer: The module name is available through the built-in variable name. If the module is imported, name contains its full name in the namespace. If the module is run as the main script, name automatically takes the value "main".

tags:
#interview

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