Python Data Science Jobs & Interviews
20.4K subscribers
188 photos
4 videos
25 files
326 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
⁉️ Interview question
What happens when you call `plt.plot()` without specifying a figure or axes, and then immediately call `plt.show()`?

The function `plt.plot()` automatically creates a new figure and axes if none exist, and `plt.show()` displays the current figure. However, if multiple plots are created without clearing the figure, they may overlap or appear in unexpected orders due to matplotlib's internal state management. This behavior can lead to confusion, especially when working with loops or subplots.

#️⃣ tags: #matplotlib #python #datavisualization #plotting #beginner #codingchallenge

By: @DataScienceQ 🚀
⁉️ Interview question
How does `plt.subplot()` differ from `plt.subplots()` when creating a grid of plots?

`plt.subplot()` creates a single subplot in a grid by specifying row and column indices, requiring separate calls for each subplot. In contrast, `plt.subplots()` creates the entire grid at once, returning both the figure and an array of axes objects, making it more efficient for managing multiple subplots. However, using `plt.subplot()` can lead to overlapping or misaligned plots if not carefully managed, especially when adding elements like titles or labels.

#️⃣ tags: #matplotlib #python #plotting #subplots #datavisualization #beginner #codingchallenge

By: @DataScienceQ 🚀
⁉️ Interview question
What is the purpose of `scipy.integrate.quad()` and how does it handle functions with singularities?

`scipy.integrate.quad()` computes definite integrals using adaptive quadrature, which recursively subdivides intervals to improve accuracy. When dealing with functions that have singularities (e.g., discontinuities or infinite values), it may fail or return inaccurate results unless the integration limits are adjusted or the singularity is isolated. In such cases, splitting the integral at the singularity point or using specialized methods like `quad` with `points` parameter can help achieve better convergence, though improper handling might lead to warnings or unexpected outputs.

#️⃣ tags: #scipy #python #numericalintegration #scientificcomputing #mathematics #codingchallenge #beginner

By: @DataScienceQ 🚀
Please open Telegram to view this post
VIEW IN TELEGRAM
⁉️ Interview question
How does `scipy.optimize.minimize()` choose between different optimization algorithms, and what happens if the initial guess is far from the minimum?

`scipy.optimize.minimize()` selects an algorithm based on the `method` parameter (e.g., 'BFGS', 'Nelder-Mead', 'COBYLA'), each suited for specific problem types. If the initial guess is far from the true minimum, some methods may converge slowly or get stuck in local minima, especially for non-convex functions. The function also allows passing bounds and constraints to guide the search, but poor initialization can lead to suboptimal results or failure to converge, particularly when using gradient-based methods without proper scaling or preprocessing of input data.

#️⃣ tags: #scipy #python #optimization #scientificcomputing #numericalanalysis #machinelearning #codingchallenge #beginner

By: @DataScienceQ 🚀
1
1. What is the output of the following code?
x = [1, 2, 3]
y = x
y.append(4)
print(x)


2. Which of the following data types is immutable in Python?
A) List
B) Dictionary
C) Set
D) Tuple

3. Write a Python program to reverse a string without using built-in functions.

4. What will be printed by this code?
def func(a, b=[]):
b.append(a)
return b

print(func(1))
print(func(2))


5. Explain the difference between == and is operators in Python.

6. How do you handle exceptions in Python? Provide an example.

7. What is the output of:
print(2 ** 3 ** 2)


8. Which keyword is used to define a function in Python?
A) def
B) function
C) func
D) define

9. Write a program to find the factorial of a number using recursion.

10. What does the *args parameter do in a function?

11. What will be the output of:
list1 = [1, 2, 3]
list2 = list1.copy()
list2[0] = 10
print(list1)


12. Explain the concept of list comprehension with an example.

13. What is the purpose of the __init__ method in a Python class?

14. Write a program to check if a given string is a palindrome.

15. What is the output of:
a = [1, 2, 3]
b = a[:]
b[0] = 10
print(a)


16. Describe how Python manages memory (garbage collection).

17. What will be printed by:
x = "hello"
y = "world"
print(x + y)


18. Write a Python program to generate the first n Fibonacci numbers.

19. What is the difference between range() and xrange() in Python 2?

20. What is the use of the lambda function in Python? Give an example.

#PythonQuiz #CodingTest #ProgrammingExam #MultipleChoice #CodeOutput #PythonBasics #InterviewPrep #CodingChallenge #BeginnerPython #TechAssessment #PythonQuestions #SkillCheck #ProgrammingSkills #CodePractice #PythonLearning #MCQ #ShortAnswer #TechnicalTest #PythonSyntax #Algorithm #DataStructures #PythonProgramming

By: @DataScienceQ 🚀
1👏1
1. What is the output of the following code?
x = [1, 2, 3]
y = x
y[0] = 4
print(x)

2. Which of the following is NOT a valid way to create a dictionary in Python?
A) dict(a=1, b=2)
B) {a: 1, b: 2}
C) dict([('a', 1), ('b', 2)])
D) {1: 'a', 2: 'b'}

3. Write a function that takes a list of integers and returns a new list containing only even numbers.

4. What will be printed by this code?
def func(a, b=[]):
b.append(a)
return b
print(func(1))
print(func(2))

5. What is the purpose of the __slots__ attribute in a Python class?

6. Which built-in function can be used to remove duplicates from a list while preserving order?

7. Explain the difference between map(), filter(), and reduce() with examples.

8. What does the @staticmethod decorator do in Python?

9. Write a generator function that yields Fibonacci numbers up to a given limit.

10. What is the output of this code?
import copy
a = [1, 2, [3, 4]]
b = copy.deepcopy(a)
b[2][0] = 5
print(a[2][0])

11. Which of the following is true about Python’s GIL (Global Interpreter Lock)?
A) It allows multiple threads to execute Python bytecode simultaneously.
B) It prevents race conditions in multithreaded programs.
C) It limits CPU-bound multi-threaded performance.
D) It is disabled in PyPy.

12. How would you implement a context manager using a class?

13. What is the result of bool([]) and why?

14. Write a recursive function to calculate the factorial of a number.

15. What is the difference between is and == in Python?

16. Explain how Python handles memory management for objects.

17. What is the output of this code?
class A:
def __init__(self):
self.x = 1

class B(A):
def __init__(self):
super().__init__()
self.y = 2

obj = B()
print(hasattr(obj, 'x') and hasattr(obj, 'y'))

18. Describe the use of *args and **kwargs in function definitions.

19. Write a program that reads a text file and counts the frequency of each word.

20. What is monkey patching in Python and when might it be useful?

#Python #AdvancedPython #ProgrammingTest #CodingChallenge #PythonInterview #PythonDeveloper #CodeQuiz #HighLevelPython #LearnPython #PythonSkills #PythonExpert

By: @DataScienceQ 🚀
🔥1
1. What is the output of the following code?
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = a.T
b[0, 0] = 99
print(a)

2. Which of the following functions is used to create an array with values spaced at regular intervals?
A) np.linspace()
B) np.arange()
C) np.logspace()
D) All of the above

3. Write a function that takes a 1D NumPy array and returns a new array where each element is squared, but only if it’s greater than 5.

4. What will be printed by this code?
import numpy as np
x = np.array([1, 2, 3])
y = x.copy()
y[0] = 5
print(x[0])

5. Explain the difference between np.meshgrid() and np.mgrid in generating coordinate matrices.

6. How would you efficiently compute the outer product of two vectors using NumPy?

7. What is the result of np.sum(np.eye(3), axis=1)?

8. Write a program to generate a 5x5 matrix filled with random integers from 1 to 100, then find the maximum value in each row.

9. What happens when you use np.resize() on an array with shape (3,) to resize it to (5,)?

10. Which method can be used to flatten a multi-dimensional array into a 1D array without copying data?

11. What is the output of this code?
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
result = arr[[0, 1], [1, 2]]
print(result)

12. Describe how np.take() works and provide an example using a 2D array.

13. Write a function that calculates the Euclidean distance between all pairs of points in a 2D array of coordinates.

14. What is the purpose of np.frombuffer() and when might it be useful?

15. How do you perform matrix multiplication using np.matmul() and @ operator? Are they always equivalent?

16. Write a program to filter out all elements in a 2D array that are outside the range [10, 90].

17. What does np.nan_to_num() do and why is it important in numerical computations?

18. How can you efficiently transpose a large 3D array of shape (100, 100, 100) using np.transpose() or swapaxes()?

19. Explain the concept of "views" vs "copies" in NumPy and give an example where a view leads to unexpected behavior.

20. Write a function that computes the covariance matrix of a dataset represented as a 2D NumPy array.

#NumPy #AdvancedPython #DataScience #InterviewPrep #PythonLibrary #ScientificComputing #MachineLearning #CodingChallenge #HighLevelNumPy #PythonDeveloper #TechnicalInterview #DataAnalysis

By: @DataScienceQ 🚀
Advanced Python Interview Preparation Test (20 Questions)

1. Which of the following is NOT a valid way to create a dictionary in Python?
A) {}
B) dict()
C) {} = dict
D) dict(a=1, b=2)

2. What will be the output of the following code?

   def func(x, y=[]):
y.append(x)
return y
print(func(1))
print(func(2))

3. Write a Python function that takes a list of integers and returns a new list containing only the even numbers using a list comprehension.

4. Explain the difference between __str__ and __repr__ methods in Python classes.

5. Which decorator is used to define a class method in Python?
A) @staticmethod
B) @classmethod
C) @property
D) @abstractmethod

6. What does the *args parameter do in a function definition?
A) Accepts keyword arguments
B) Accepts any number of positional arguments
C) Accepts a single argument
D) Accepts only integer values

7. What will be the output of the following code?

   import copy
a = [1, 2, [3, 4]]
b = copy.deepcopy(a)
b[2][0] = 'x'
print(a)

8. Write a generator function that yields the Fibonacci sequence up to a given number n.

9. Describe how the GIL (Global Interpreter Lock) affects multithreading in Python.

10. What is the purpose of the with statement in Python? Provide an example.

11. Which of the following statements about Python's garbage collector is true?
A) It uses reference counting exclusively
B) It uses both reference counting and a cyclic garbage collector
C) It only runs when memory is low
D) It is disabled by default

12. What will be the output of the following code?

   x = [1, 2, 3]
y = x
y[0] = 4
print(x)

13. Implement a context manager using the contextlib module that prints "Entering" when entered and "Exiting" when exited.

14. Explain what a metaclass is in Python and give an example of its use.

15. Which of the following is true about Python’s asyncio library?
A) It allows for true parallel execution
B) It enables cooperative multitasking
C) It requires threading for I/O operations
D) It cannot handle CPU-bound tasks

16. What will be the output of this code?

   def outer():
x = 10
def inner():
nonlocal x
x += 5
return x
return inner()
print(outer())

17. Write a Python program that reads a file line by line and counts the number of lines starting with a specific prefix (e.g., "ERROR").

18. What is the significance of the __slots__ attribute in a Python class?

19. How does Python handle exceptions in generators?

20. Given a list of dictionaries, write a one-liner using sorted() and lambda to sort the list by the value of the key 'age' in descending order.

#PythonInterview #AdvancedPython #ProgrammingTest #CodingChallenge #PythonExperts

By: @DataScienceQ 🚀
#Python #InterviewQuestion #DataStructures #Algorithm #Programming #CodingChallenge

Question:
How does Python handle memory management, and can you demonstrate the difference between list and array in terms of memory efficiency with a practical example?

Answer:

Python uses automatic memory management through a private heap space managed by the Python memory manager. It employs reference counting and a garbage collector to reclaim memory when objects are no longer referenced. However, the way different data structures store data impacts memory efficiency.

For example, a list in Python stores pointers to objects, which adds overhead due to dynamic resizing and object indirection. In contrast, an array from the array module stores primitive values directly, reducing memory usage for homogeneous data.

Here’s a practical example comparing memory usage between a list and an array:

import array
import sys

# Create a list of integers
my_list = [i for i in range(1000)]
print(f"List size: {sys.getsizeof(my_list)} bytes")

# Create an array of integers (type 'i' for signed int)
my_array = array.array('i', range(1000))
print(f"Array size: {sys.getsizeof(my_array)} bytes")

Output:
List size: 9088 bytes
Array size: 4032 bytes

Explanation:
- The list uses more memory because each element is a Python object (e.g., int), and the list stores references to these objects. Additionally, the list has internal overhead for resizing.
- The array stores raw integer values directly in a contiguous block of memory, avoiding object overhead and resulting in much lower memory usage.

This makes array more efficient for large datasets of homogeneous numeric types, while list offers flexibility at the cost of higher memory consumption.

By: @DataScienceQ 🚀
1
#Python #InterviewQuestion #OOP #Inheritance #Polymorphism #Programming #CodingChallenge

Question:
How does method resolution order (MRO) work in Python when multiple inheritance is involved, and can you provide a code example to demonstrate the diamond problem and how Python resolves it using C3 linearization?

Answer:

In Python, method resolution order (MRO) determines the sequence in which base classes are searched when executing a method. When multiple inheritance is used, especially in cases like the "diamond problem" (where a class inherits from two classes that both inherit from a common base), Python uses the C3 linearization algorithm to establish a consistent MRO.

The C3 linearization ensures that:
- The subclass appears before its parents.
- Parents appear in the order they are listed.
- A parent class appears before any of its ancestors.

Here’s an example demonstrating the diamond problem and how Python resolves it:

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

# Check MRO
print("MRO of D:", [cls.__name__ for cls in D.mro()])
# Output: ['D', 'B', 'C', 'A', 'object']

# Call the method
d = D()
d.process()

Output:
MRO of D: ['D', 'B', 'C', 'A', 'object']
B.process

Explanation:
- The D class inherits from B and C, both of which inherit from A.
- Without proper MRO, calling d.process() could lead to ambiguity (e.g., should it call B.process or C.process?).
- Python uses C3 linearization to compute MRO as: D -> B -> C -> A -> object.
- Since B comes before C in the inheritance list, B.process is called first.
- This avoids the diamond problem by ensuring a deterministic and predictable order.

This mechanism allows developers to write complex class hierarchies without runtime ambiguity, making Python's multiple inheritance safe and usable.

By: @DataScienceQ 🚀
1