Python Data Science Jobs & Interviews
20.3K 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
#python #programming #question #simulation #intermediate #matryoshka

Write a Python program to simulate a Matryoshka doll game with the following requirements:

1. Create a class Matryoshka that represents a nested doll with attributes: size (int), color (string), and contents (list of smaller Matryoshka objects).
2. Implement methods to:
- Add a smaller Matryoshka inside the current one
- Remove the smallest Matryoshka from the set
- Display all dolls in the nesting hierarchy
3. Create a main function that:
- Builds a nesting of 4 Matryoshka dolls (largest to smallest)
- Displays the complete nesting
- Removes the smallest doll
- Displays the updated nesting

class Matryoshka:
def __init__(self, size, color):
self.size = size
self.color = color
self.contents = []

def add_doll(self, doll):
if doll.size < self.size:
self.contents.append(doll)
else:
print(f"Cannot add doll of size {doll.size} into size {self.size} doll")

def remove_smallest(self):
if not self.contents:
print("No dolls to remove")
return None

# Find the smallest doll recursively
smallest = self._find_smallest()
if smallest:
self._remove_doll(smallest)
return smallest
return None

def _find_smallest(self):
if not self.contents:
return self
smallest = self
for doll in self.contents:
result = doll._find_smallest()
if result.size < smallest.size:
smallest = result
return smallest

def _remove_doll(self, target):
if self.contents:
for i, doll in enumerate(self.contents):
if doll == target:
self.contents.pop(i)
return
elif doll._remove_doll(target):
return

def display(self, level=0):
indent = " " * level
print(f"{indent}{self.color} ({self.size})")
for doll in self.contents:
doll.display(level + 1)

def main():
# Create nesting of 4 Matryoshka dolls (largest to smallest)
large = Matryoshka(4, "Red")
medium = Matryoshka(3, "Blue")
small = Matryoshka(2, "Green")
tiny = Matryoshka(1, "Yellow")

# Build the nesting
large.add_doll(medium)
medium.add_doll(small)
small.add_doll(tiny)

# Display initial nesting
print("Initial nesting:")
large.display()
print()

# Remove the smallest doll
removed = large.remove_smallest()
if removed:
print(f"Removed: {removed.color} ({removed.size})")

# Display updated nesting
print("\nUpdated nesting:")
large.display()

if __name__ == "__main__":
main()


Output:
Initial nesting:
Red (4)
Blue (3)
Green (2)
Yellow (1)

Removed: Yellow (1)

Updated nesting:
Red (4)
Blue (3)
Green (2)


By: @DataScienceQ 🚀
#python #programming #question #simulation #intermediate #philosophers_dinner

Write a Python program to simulate the Dining Philosophers problem with the following requirements:

1. Create a class Philosopher that represents a philosopher with attributes: name (string), left_fork (int), right_fork (int), and eating (boolean).
2. Implement methods for:
- Attempting to pick up forks (with a delay)
- Eating
- Releasing forks
3. Use threading to simulate 5 philosophers sitting around a circular table.
4. Ensure no deadlock occurs by implementing a strategy where philosophers pick up forks in order (e.g., odd-numbered philosophers pick up left fork first, even-numbered pick up right fork first).
5. Display the state of each philosopher (thinking, eating, or waiting) at regular intervals.

import threading
import time
import random

class Philosopher:
def __init__(self, name, left_fork, right_fork):
self.name = name
self.left_fork = left_fork
self.right_fork = right_fork
self.eating = False

def eat(self):
print(f"{self.name} is trying to eat...")
# Pick up left fork
self.left_fork.acquire()
print(f"{self.name} picked up left fork")

# Pick up right fork
self.right_fork.acquire()
print(f"{self.name} picked up right fork")

# Eat
self.eating = True
print(f"{self.name} is eating")
time.sleep(random.uniform(1, 3))

# Release forks
self.right_fork.release()
self.left_fork.release()
print(f"{self.name} finished eating")
self.eating = False

def philosopher_thread(philosopher, num_philosophers):
while True:
# Think
print(f"{philosopher.name} is thinking")
time.sleep(random.uniform(1, 3))

# Try to eat
philosopher.eat()

# Main simulation
if __name__ == "__main__":
# Create 5 forks (semaphores)
forks = [threading.Semaphore(1) for _ in range(5)]

# Create 5 philosophers
philosophers = [
Philosopher("Philosopher 1", forks[0], forks[1]),
Philosopher("Philosopher 2", forks[1], forks[2]),
Philosopher("Philosopher 3", forks[2], forks[3]),
Philosopher("Philosopher 4", forks[3], forks[4]),
Philosopher("Philosopher 5", forks[4], forks[0])
]

# Start threads for each philosopher
threads = []
for i, philosopher in enumerate(philosophers):
thread = threading.Thread(target=philosopher_thread, args=(philosopher, len(philosophers)))
threads.append(thread)
thread.start()

# Wait for all threads to complete (infinite loop)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("Simulation ended")


By: @DataScienceQ 🚀
#python #programming #question #simulation #intermediate #ludo

Write a Python program to simulate a simplified Ludo game between a user and a computer with the following requirements:

1. Create a game class `LudoGame` with attributes: player_position (int), computer_position (int), and current_player (string).
2. Implement methods for:
- Rolling a die (random number 1-6)
- Moving a player piece based on the roll
- Checking if a player has won (reached position 50)
- Switching turns between player and computer
3. The game should alternate turns between the user and computer.
4. When the user plays, prompt them to press Enter to roll the die.
5. Display the current positions of both players after each move.
6. End the game when either player reaches or exceeds position 50.

```python
import random

class LudoGame:
def __init__(self):
self.player_position = 0
self.computer_position = 0
self.current_player = "user"

def roll_dice(self):
return random.randint(1, 6)

def move_player(self, player):
dice_roll = self.roll_dice()
print(f"Dice roll: {dice_roll}")

if player == "user":
self.player_position += dice_roll
else:
self.computer_position += dice_roll

print(f"Player position: {self.player_position}")
print(f"Computer position: {self.computer_position}")

def check_winner(self):
if self.player_position >= 50:
return "user"
elif self.computer_position >= 50:
return "computer"
return None

def switch_turn(self):
self.current_player = "computer" if self.current_player == "user" else "user"

def play_game(self):
print("Welcome to Simplified Ludo!")
print("Reach position 50 to win.")

while True:
print(f"\n{self.current_player}'s turn:")

if self.current_player == "user":
input("Press Enter to roll the dice...")
self.move_player("user")
else:
self.move_player("computer")

winner = self.check_winner()
if winner:
print(f"\n{winner.capitalize()} wins!")
break

self.switch_turn()

# Start the game
game = LudoGame()
game.play_game()
```

By: @DataScienceQ 🚀
Advanced Real-World Simulation Problem Solving Test

1. Write a Python program to simulate the diffusion process of particles in a 2D grid over time.

2. What will be the output of this code simulating a simple queue model?
def process_queue(events):
    queue = []
    for e in events:
        if e == 'arrive':
            queue.append(1)
        elif e == 'serve' and queue:
            queue.pop(0)
    return len(queue)

print(process_queue(['arrive', 'arrive', 'serve', 'arrive', 'serve', 'serve']))


3. Which numerical method is most appropriate for solving the motion equations of a pendulum with friction?

a) Euler’s Method
b) Runge-Kutta Method
c) Monte Carlo Method
d) Finite Element Method

4. Describe how Monte Carlo simulations can be used to estimate the value of pi.

5. Given the output below, what kind of simulation does this represent and what is being measured?
Temperature: 300 K, Pressure: 1 atm, Particles: 5000
Average Velocity: 500 m/s


6. Implement a cellular automaton simulator for Conway’s Game of Life, taking initial states as input.

7. Explain the difference between discrete-event simulation and continuous simulation.

8. What is the output of this simulation of random walk?
import random
position = 0
for _ in range(3):
    step = random.choice([-1, 1])
    position += step
print(position)


9. Write a function simulating an M/M/1 queue and calculating the average wait time for a given arrival and service rate.

10. What are the limitations of agent-based simulations in modeling complex systems?

11. How does time step selection affect the accuracy and performance of a numerical simulation?

12. Given a system modeled by differential equations, write Python code using scipy.integrate.odeint to solve it.

13. Which data structure is most suited to efficiently manage a priority queue of events in a discrete-event simulation?

a) list
b) heap
c) dictionary
d) set

14. What will this code print that simulates a simple predator-prey model?
def model(rabbits, foxes):
    rabbits += 5 - 0.1 * rabbits * foxes
    foxes += 0.05 * rabbits * foxes - 2
    return int(rabbits), int(foxes)
r, f = 30, 5
for _ in range(3):
    r, f = model(r, f)
print(r, f)


15. Describe how hybrid simulation combines discrete-event and continuous models.

16. Write code to simulate a traffic light control system with three states (Green, Yellow, Red) and timed transitions.

17. What challenges are involved in verifying and validating simulation models?

18. What output do you expect from the following Gillespie algorithm step?
import numpy as np
reactions = [0.3, 0.7]
r = np.random.random()
cum_prop = np.cumsum(reactions)
print(np.searchsorted(cum_prop, r))


19. How can parallel processing improve the performance of large-scale simulations?

20. Write a Python program to simulate radioactive decay for a given number of atoms and decay probability per step.

#Simulation #Modeling #NumericalMethods #RealWorldProblems #AdvancedProgramming

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