Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@ Personal solutions to [**Python** track][python_track] exercises from [**Exercis
2. ["**Guido's Gorgeous Lasagna**" solution](python/guidos-gorgeous-lasagna/lasagna.py).
3. ["**Ghost Gobble Arcade Game**" solution](python/ghost-gobble-arcade-game/arcade_game.py).
4. ["**Currency Exchange**" solution](python/currency-exchange/exchange.py).
5. ["**Meltdown Mitigation**" solution](python/meltdown-mitigation/conditionals.py).
<!-- Put next solution item here! -->

[python_version_badge]: https://img.shields.io/badge/Python%203.13-3776AB?logo=python&logoColor=FFD43B
[track_completion_badge]: https://img.shields.io/badge/Track%20completion-2.7%25-604fcd?logo=exercism&logoColor=604fcd&labelColor=e9ecef
[exercises_completed_badge]: https://img.shields.io/badge/Exercises%20completed-4%2F146-604fcd?logo=exercism&logoColor=604fcd&labelColor=e9ecef
[track_completion_badge]: https://img.shields.io/badge/Track%20completion-3.4%25-604fcd?logo=exercism&logoColor=604fcd&labelColor=e9ecef
[exercises_completed_badge]: https://img.shields.io/badge/Exercises%20completed-5%2F146-604fcd?logo=exercism&logoColor=604fcd&labelColor=e9ecef
[python_track]: https://exercism.org/tracks/python
[exercism]: https://exercism.org
50 changes: 50 additions & 0 deletions python/meltdown-mitigation/HINTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Hints

## General

- The Python Docs on [Control Flow Tools][control flow tools] and the Real Python tutorial on [conditionals][real python conditionals] are great places to start.
- The Python Docs on [Boolean Operations][boolean operations] can be a great refresher on `bools`, as can the Real Python tutorial on [booleans][python booleans].
- The Python Docs on [Comparisons][comparisons] and [comparisons examples][python comparisons examples] can be a great refresher for comparisons.

## 1. Check for criticality

- Comparison operators ([comparisons][comparisons review]) and boolean operations ([concept:python/bools]()) can be combined and used with conditionals.
- Conditional expressions must evaluate to `True` or `False`.
- `else` can be used for a code block that will execute when all conditional tests return `False`.

```python
>>> item = 'blue'
>>> item_2 = 'green'

>>> if len(item) >= 3 and len(item_2) < 5:
print('Both pass the test!')
elif len(item) >= 3 or len(item_2) < 5:
print('One passes the test!')
else:
print('None pass the test!')
...
One passes the test!
```

## 2. Determine the Power output range

- Comparison operators can be combined and used with conditionals.
- Any number of `elif` statements can be used as decision "branches".
- Each "branch" can have a separate `return`, although it might be considered "bad form" by linting tools.
- If the linter complains, consider assigning the output of a branch to a common variable, and then `return`ing that variable.

## 3. Fail Safe Mechanism

- Comparison operators can be combined and used with conditionals.
- Any number of `elif` statements can be used as decision "branches".
- Each "branch" can have a separate `return`, although it might be considered "bad form" by linting tools.
- If the linter complains, consider assigning the output of a branch to a common variable, and then `return`ing that variable.


[boolean operations]: https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
[comparisons review]: https://www.learnpython.dev/02-introduction-to-python/090-boolean-logic/20-comparisons/
[comparisons]: https://docs.python.org/3/library/stdtypes.html#comparisons
[control flow tools]: https://docs.python.org/3/tutorial/controlflow.html
[python booleans]: https://realpython.com/python-boolean/
[python comparisons examples]: https://www.tutorialspoint.com/python/comparison_operators_example.htm
[real python conditionals]: https://realpython.com/python-conditional-statements/
171 changes: 171 additions & 0 deletions python/meltdown-mitigation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
# Meltdown Mitigation

Welcome to Meltdown Mitigation on Exercism's Python Track.
If you get stuck on the exercise, check out `HINTS.md`, but try and solve it without using those first :)

## Introduction

In Python, [`if`][if statement], `elif` (_a contraction of 'else and if'_) and `else` statements are used to [control the flow][control flow tools] of execution and make decisions in a program.
Unlike many other programming languages, Python versions 3.9 and below do not offer a formal case-switch statement, instead using multiple `elif` statements to serve a similar purpose.

Python 3.10 introduces a variant case-switch statement called `structural pattern matching`, which will be covered separately in another concept.

Conditional statements use expressions that must resolve to `True` or `False` -- either by returning a `bool` type directly, or by evaluating as ["truthy" or "falsy"][truth value testing].

```python
x = 10
y = 5

# The comparison '>' returns the bool 'True',
# so the statement is printed.
if x > y:
print("x is greater than y")
...
>>> x is greater than y
```

When paired with `if`, an optional `else` code block will execute when the original `if` condition evaluates to `False`:

```python
x = 5
y = 10

# The comparison '>' here returns the bool 'False',
# so the 'else' block is executed instead of the 'if' block.
if x > y:
print("x is greater than y")
else:
print("y is greater than x")
...
>>> y is greater than x
```

`elif` allows for multiple evaluations/branches.

```python
x = 5
y = 10
z = 20

# The 'elif' statement allows for the checking of more conditions.
if x > y:
print("x is greater than y and z")
elif y > z:
print("y is greater than x and z")
else:
print("z is greater than x and y")
...
>>> z is greater than x and y
```

[Boolean operations][boolean operations] and [comparisons][comparisons] can be combined with conditionals for more complex testing:

```python
>>> def classic_fizzbuzz(number):
if number % 3 == 0 and number % 5 == 0:
say = 'FizzBuzz!'
elif number % 5 == 0:
say = 'Buzz!'
elif number % 3 == 0:
say = 'Fizz!'
else:
say = str(number)

return say

>>> classic_fizzbuzz(15)
'FizzBuzz!'

>>> classic_fizzbuzz(13)
'13'
```

[boolean operations]: https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
[comparisons]: https://docs.python.org/3/library/stdtypes.html#comparisons
[control flow tools]: https://docs.python.org/3/tutorial/controlflow.html#more-control-flow-tools
[if statement]: https://docs.python.org/3/reference/compound_stmts.html#the-if-statement
[truth value testing]: https://docs.python.org/3/library/stdtypes.html#truth-value-testing

## Instructions

In this exercise, we'll develop a simple control system for a nuclear reactor.

For a reactor to produce the power it must be in a state of _criticality_.
If the reactor is in a state less than criticality, it can become damaged.
If the reactor state goes beyond criticality, it can overload and result in a meltdown.
We want to mitigate the chances of meltdown and correctly manage reactor state.

The following three tasks are all related to writing code for maintaining ideal reactor state.

## 1. Check for criticality

The first thing a control system has to do is check if the reactor is _balanced in criticality_.
A reactor is said to be balanced in criticality if it satisfies the following conditions:

- The temperature is less than 800 K.
- The number of neutrons emitted per second is greater than 500.
- The product of temperature and neutrons emitted per second is less than 500000.

Implement the function `is_criticality_balanced()` that takes `temperature` measured in kelvin and `neutrons_emitted` as parameters, and returns `True` if the criticality conditions are met, `False` if not.

```python
>>> is_criticality_balanced(750, 600)
True
```

## 2. Determine the Power output range

Once the reactor has started producing power its efficiency needs to be determined.
Efficiency can be grouped into 4 bands:

1. `green` -> efficiency of 80% or more,
2. `orange` -> efficiency of less than 80% but at least 60%,
3. `red` -> efficiency below 60%, but still 30% or more,
4. `black` -> less than 30% efficient.

The percentage value can be calculated as `(generated_power/theoretical_max_power)*100`
where `generated_power` = `voltage` * `current`.
Note that the percentage value is usually not an integer number, so make sure to consider the
proper use of the `<` and `<=` comparisons.

Implement the function `reactor_efficiency(<voltage>, <current>, <theoretical_max_power>)`, with three parameters: `voltage`,
`current`, and `theoretical_max_power`.
This function should return the efficiency band of the reactor : 'green', 'orange', 'red', or 'black'.

```python
>>> reactor_efficiency(200,50,15000)
'orange'
```

## 3. Fail Safe Mechanism

Your final task involves creating a fail-safe mechanism to avoid overload and meltdown.
This mechanism will determine if the reactor is below, at, or above the ideal criticality threshold.
Criticality can then be increased, decreased, or stopped by inserting (or removing) control rods into the reactor.

Implement the function called `fail_safe()`, which takes 3 parameters: `temperature` measured in kelvin,
`neutrons_produced_per_second`, and `threshold`, and outputs a status code for the reactor.

- If `temperature * neutrons_produced_per_second` < 90% of `threshold`, output a status code of 'LOW'
indicating that control rods must be removed to produce power.

- If the value `temperature * neutrons_produced_per_second` is within 10% of the `threshold` (so either 0-10% less than the threshold, at the threshold, or 0-10% greater than the threshold), the reactor is in _criticality_ and the status code of 'NORMAL' should be output, indicating that the reactor is in optimum condition and control rods are in an ideal position.

- If `temperature * neutrons_produced_per_second` is not in the above-stated ranges, the reactor is
going into meltdown and a status code of 'DANGER' must be passed to immediately shut down the reactor.

```python
>>> fail_safe(temperature=1000, neutrons_produced_per_second=30, threshold=5000)
'DANGER'
```

## Source

### Created by

- @sachsom95
- @BethanyG

### Contributed to by

- @kbuc
87 changes: 87 additions & 0 deletions python/meltdown-mitigation/conditionals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""Functions to prevent a nuclear meltdown."""


def is_criticality_balanced(temperature, neutrons_emitted):
"""Verify criticality is balanced.

Parameters:
temperature (int or float): The temperature value in kelvin.
neutrons_emitted (int or float): The number of neutrons emitted per second.

Returns:
bool: Is criticality balanced?

Note:
A reactor is said to be balanced in criticality if it satisfies the following conditions:
- The temperature is less than 800 K.
- The number of neutrons emitted per second is greater than 500.
- The product of temperature and neutrons emitted per second is less than 500000.

"""

if temperature >= 800:
return False
if neutrons_emitted <= 500:
return False
if temperature * neutrons_emitted >= 5e5:
return False
return True


def reactor_efficiency(voltage, current, theoretical_max_power):
"""Assess reactor efficiency zone.

Parameters:
voltage (int or float): Voltage value.
current (int or float): Current value.
theoretical_max_power (int or float): The power level that corresponds to a 100% efficiency.

Returns:
str: One of ('green', 'orange', 'red', or 'black').

Note:
Efficiency can be grouped into 4 bands:
1. green -> efficiency of 80% or more,
2. orange -> efficiency of less than 80% but at least 60%,
3. red -> efficiency below 60%, but still 30% or more,
4. black -> less than 30% efficient.

The percentage value is calculated as
(generated power/ theoretical max power)*100
where generated power = voltage * current
"""

generated_power = voltage * current
efficiency = generated_power / theoretical_max_power * 100
if efficiency >= 80:
return 'green'
if efficiency >= 60:
return 'orange'
if efficiency >= 30:
return 'red'
return 'black'


def fail_safe(temperature, neutrons_produced_per_second, threshold):
"""Assess and return status code for the reactor.

Parameters:
temperature (int or float): The value of the temperature in kelvin.
neutrons_produced_per_second (int or float): The neutron flux.
threshold (int or float): The threshold for the category.

Returns:
str: One of ('LOW', 'NORMAL', 'DANGER').

Note:
1. 'LOW' -> `temperature * neutrons per second` < 90% of `threshold`
2. 'NORMAL' -> `temperature * neutrons per second` +/- 10% of `threshold`
3. 'DANGER' -> `temperature * neutrons per second` is not in the above-stated ranges
"""

status = temperature * neutrons_produced_per_second
if status < threshold * 0.9:
return 'LOW'
if status <= threshold * 1.1:
return 'NORMAL'
return 'DANGER'
Loading
Loading