Python Data Science Jobs & Interviews
20.5K subscribers
189 photos
4 videos
25 files
330 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
🔥 Trending Repository: tech-interview-handbook

📝 Description: 💯 Curated coding interview preparation materials for busy software engineers

🔗 Repository URL: https://github.com/yangshun/tech-interview-handbook

🌐 Website: https://www.techinterviewhandbook.org

📖 Readme: https://github.com/yangshun/tech-interview-handbook#readme

📊 Statistics:
🌟 Stars: 130K stars
👀 Watchers: 2.2k
🍴 Forks: 15.8K forks

💻 Programming Languages: TypeScript - JavaScript - Python

🏷️ Related Topics:
#algorithm #algorithms #interview_practice #interview_questions #coding_interviews #interview_preparation #system_design #algorithm_interview #behavioral_interviews #algorithm_interview_questions


==================================
🧠 By: https://t.iss.one/DataScienceM
1
#python #programming #question #fibonacci #intermediate #algorithm

Write a Python program that implements three different methods to generate the Fibonacci sequence up to the nth term:

1. Use an iterative approach with a loop.
2. Use recursion with memoization.
3. Use dynamic programming with a list.

For each method, calculate the 20th Fibonacci number and measure the execution time. Print the results for each method along with their respective times.

import time

def fibonacci_iterative(n):
if n <= 1:
return n
a, b = 0, 1
for i in range(2, n + 1):
a, b = b, a + b
return b

def fibonacci_recursive_memo(n, memo={}):
if n in memo:
return memo[n]
if n <= 1:
return n
memo[n] = fibonacci_recursive_memo(n - 1, memo) + fibonacci_recursive_memo(n - 2, memo)
return memo[n]

def fibonacci_dp(n):
if n <= 1:
return n
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]

# Test all three methods for the 20th Fibonacci number
n = 20

# Method 1: Iterative
start_time = time.time()
result_iter = fibonacci_iterative(n)
iter_time = time.time() - start_time

# Method 2: Recursive with memoization
start_time = time.time()
result_rec = fibonacci_recursive_memo(n)
rec_time = time.time() - start_time

# Method 3: Dynamic Programming
start_time = time.time()
result_dp = fibonacci_dp(n)
dp_time = time.time() - start_time

print(f"20th Fibonacci number using iterative method: {result_iter} (Time: {iter_time:.6f} seconds)")
print(f"20th Fibonacci number using recursive method: {result_rec} (Time: {rec_time:.6f} seconds)")
print(f"20th Fibonacci number using DP method: {result_dp} (Time: {dp_time:.6f} seconds)")

By: @DataScienceQ 🚀
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
Q: How does a binary search algorithm work, and why is it more efficient than linear search?

Binary search is a powerful algorithm used to find an element in a sorted array by repeatedly dividing the search interval in half. It's much faster than linear search because instead of checking every element one by one, it eliminates half of the remaining elements with each step.

How it works (step-by-step):
1. Start with the entire array.
2. Compare the target value with the middle element.
3. If they match, return the index.
4. If the target is smaller, search the left half.
5. If the target is larger, search the right half.
6. Repeat until the element is found or the interval is empty.

Example (Python code for beginners):

def binary_search(arr, target):
left = 0
right = len(arr) - 1

while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1

# Example usage
numbers = [1, 3, 5, 7, 9, 11, 13]
result = binary_search(numbers, 7)
print("Found at index:", result) # Output: Found at index: 3

Why it's better:
- Linear search: O(n) time complexity — checks each element.
- Binary search: O(log n) — cuts search space in half each time.

Try running this code with different numbers to see how fast it finds the target!

#Algorithm #BinarySearch #Programming #BeginnerCode #TechTips #CodingBasics

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
In Python, the itertools module is a powerhouse for creating efficient iterators that handle combinatorial, grouping, and infinite sequence operations—essential for acing coding interviews with elegant solutions! 🌪

import itertools

# Infinite iterators - Handle streams with precision
count = itertools.count(start=10, step=2)
print(list(itertools.islice(count, 3))) # Output: [10, 12, 14]

cycle = itertools.cycle('AB')
print(list(itertools.islice(cycle, 4))) # Output: ['A', 'B', 'A', 'B']

repeat = itertools.repeat('Hello', 3)
print(list(repeat)) # Output: ['Hello', 'Hello', 'Hello']


# Combinatorics made easy - Solve permutation puzzles
print(list(itertools.permutations('ABC', 2)))
# Output: [('A','B'), ('A','C'), ('B','A'), ('B','C'), ('C','A'), ('C','B')]

print(list(itertools.combinations('ABC', 2)))
# Output: [('A','B'), ('A','C'), ('B','C')]

print(list(itertools.combinations_with_replacement('AB', 2)))
# Output: [('A','A'), ('A','B'), ('B','B')]


# Cartesian products - Matrix operations simplified
print(list(itertools.product([1,2], ['a','b'])))
# Output: [(1,'a'), (1,'b'), (2,'a'), (2,'b')]

# Practical use: Generate all possible IP octets
octets = [str(i) for i in range(256)]
ips = itertools.product(octets, repeat=4)
print('.'.join(next(ips))) # Output: 0.0.0.0


# Grouping consecutive duplicates - Log analysis superpower
data = 'AAAABBBCCDAA'
groups = [list(g) for k, g in itertools.groupby(data)]
print([k + str(len(g)) for k, g in itertools.groupby(data)])
# Output: ['A4', 'B3', 'C2', 'D1', 'A2']

# Real-world application: Compress sensor data streams
sensor_data = [1,1,1,2,2,3,3,3,3]
compressed = [(k, len(list(g))) for k, g in itertools.groupby(sensor_data)]
print(compressed) # Output: [(1,3), (2,2), (3,4)]


# Chaining multiple iterables - Database query optimization
list1 = [1,2,3]
list2 = ['a','b','c']
chained = itertools.chain(list1, list2)
print(list(chained)) # Output: [1,2,3,'a','b','c']

# Memory-efficient merging of large files
def merge_files(*filenames):
return itertools.chain.from_iterable(open(f) for f in filenames)


# Slicing iterators like lists - Pagination made easy
numbers = itertools.islice(range(100), 5, 15, 2)
print(list(numbers)) # Output: [5,7,9,11,13]

# Interview favorite: Generate Fibonacci with islice
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a+b
print(list(itertools.islice(fib(), 10))) # Output: [0,1,1,2,3,5,8,13,21,34]


# tee iterator - Process data in parallel pipelines
data = [1,2,3,4]
iter1, iter2 = itertools.tee(data, 2)
print(sum(iter1), max(iter2)) # Output: 10 4

# Warning: Consume original iterator immediately!
original = iter([1,2,3])
t1, t2 = itertools.tee(original)
print(list(t1), list(t2)) # Output: [1,2,3] [1,2,3]


# Interview Gold: Find all subsets (power set)
def powerset(iterable):
s = list(iterable)
return itertools.chain.from_iterable(
itertools.combinations(s, r) for r in range(len(s)+1)
)
print(list(powerset('ABC')))
# Output: [(), ('A',), ('B',), ('C',), ('A','B'), ('A','C'), ('B','C'), ('A','B','C')]


# Interview Gold: Solve "Word Break" problem
def word_break(s, word_dict):
dp = [False] * (len(s)+1)
dp[0] = True
for i in range(1, len(s)+1):
for j in range(i):
if dp[j] and s[j:i] in word_dict:
dp[i] = True
break
return dp[-1]
print(word_break("leetcode", {"leet", "code"})) # Output: True


# Pro Tip: Memory-efficient large data processing
with open('huge_file.txt') as f:
# Process 1000-line chunks without loading entire file
for chunk in iter(lambda: list(itertools.islice(f, 1000)), []):
process(chunk)


By: @DataScienceQ ⭐️

#Python #CodingInterview #itertools #DataStructures #Algorithm #Programming #TechJobs #LeetCode #DeveloperTips #CareerGrowth
Please open Telegram to view this post
VIEW IN TELEGRAM