Add more languages

This commit is contained in:
Daniel Siepmann 2024-03-24 21:06:12 +01:00
parent 58c6b09200
commit 8cd12c1122
Signed by: Daniel Siepmann
GPG key ID: 33D6629915560EF4
34 changed files with 1389 additions and 17 deletions

View file

@ -0,0 +1,35 @@
{
"authors": [
"k4rtik"
],
"contributors": [
"bitfield",
"ekingery",
"ferhatelmas",
"hilary",
"kytrinyx",
"leenipper",
"petertseng",
"robphoenix",
"SebastianKristof",
"sebito91",
"tleen"
],
"files": {
"solution": [
"hello_world.go"
],
"test": [
"hello_world_test.go"
],
"example": [
".meta/example.go"
],
"invalidator": [
"go.mod"
]
},
"blurb": "The classical introductory exercise. Just say \"Hello, World!\".",
"source": "This is an exercise to introduce users to using Exercism",
"source_url": "https://en.wikipedia.org/wiki/%22Hello,_world!%22_program"
}

View file

@ -0,0 +1 @@
{"track":"go","exercise":"hello-world","id":"eb8d02cbc5514a39b18dd8500a96ef7d","url":"https://exercism.org/tracks/go/exercises/hello-world","handle":"DanielSiepmann","is_requester":true,"auto_approve":false}

41
go/hello-world/HELP.md Normal file
View file

@ -0,0 +1,41 @@
# Help
## Running the tests
To run the tests run the command `go test` from within the exercise directory.
If the test suite contains benchmarks, you can run these with the `--bench` and `--benchmem`
flags:
go test -v --bench . --benchmem
Keep in mind that each reviewer will run benchmarks on a different machine, with
different specs, so the results from these benchmark tests may vary.
## Submitting your solution
You can submit your solution using the `exercism submit hello_world.go` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Go track's documentation](https://exercism.org/docs/tracks/go)
- The [Go track's programming category on the forum](https://forum.exercism.org/c/programming/go)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [How to Write Go Code](https://golang.org/doc/code.html)
- [Effective Go](https://golang.org/doc/effective_go.html)
- [Go Resources](http://golang.org/help)
- [StackOverflow](http://stackoverflow.com/questions/tagged/go)

45
go/hello-world/README.md Normal file
View file

@ -0,0 +1,45 @@
# Hello World
Welcome to Hello World on Exercism's Go Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
The classical introductory exercise.
Just say "Hello, World!".
["Hello, World!"][hello-world] is the traditional first program for beginning programming in a new language or environment.
The objectives are simple:
- Modify the provided code so that it produces the string "Hello, World!".
- Run the test suite and make sure that it succeeds.
- Submit your solution and check it at the website.
If everything goes well, you will be ready to fetch your first real exercise.
[hello-world]: https://en.wikipedia.org/wiki/%22Hello,_world!%22_program
## Source
### Created by
- @k4rtik
### Contributed to by
- @bitfield
- @ekingery
- @ferhatelmas
- @hilary
- @kytrinyx
- @leenipper
- @petertseng
- @robphoenix
- @SebastianKristof
- @sebito91
- @tleen
### Based on
This is an exercise to introduce users to using Exercism - https://en.wikipedia.org/wiki/%22Hello,_world!%22_program

3
go/hello-world/go.mod Normal file
View file

@ -0,0 +1,3 @@
module greeting
go 1.18

View file

@ -0,0 +1,6 @@
package greeting
// HelloWorld greets the world.
func HelloWorld() string {
return "Hello, World!"
}

View file

@ -0,0 +1,40 @@
package greeting
import "testing"
// Define a function named HelloWorld that takes no arguments,
// and returns a string.
// In other words, define a function with the following signature:
// HelloWorld() string
func TestHelloWorld(t *testing.T) {
expected := "Hello, World!"
if observed := HelloWorld(); observed != expected {
t.Fatalf("HelloWorld() = %v, want %v", observed, expected)
}
}
// BenchmarkHelloWorld() is a benchmarking function. These functions follow the
// form `func BenchmarkXxx(*testing.B)` and can be used to test the performance
// of your implementation. They may not be present in every exercise, but when
// they are you can run them by including the `-bench` flag with the `go test`
// command, like so: `go test -v --bench . --benchmem`
//
// You will see output similar to the following:
//
// BenchmarkHelloWorld 2000000000 0.46 ns/op
//
// This means that the loop ran 2000000000 times at a speed of 0.46 ns per loop.
//
// While benchmarking can be useful to compare different iterations of the same
// exercise, keep in mind that others will run the same benchmarks on different
// machines, with different specs, so the results from these benchmark tests may
// vary.
func BenchmarkHelloWorld(b *testing.B) {
if testing.Short() {
b.Skip("skipping benchmark in short mode.")
}
for i := 0; i < b.N; i++ {
HelloWorld()
}
}

View file

@ -0,0 +1,31 @@
{
"authors": [
"tehsphinx"
],
"contributors": [
"ekingery",
"andrerfcsantos",
"bobtfish"
],
"files": {
"solution": [
"lasagna.go"
],
"test": [
"lasagna_test.go"
],
"exemplar": [
".meta/exemplar.go"
],
"invalidator": [
"go.mod"
]
},
"forked_from": [
"csharp/lucians-luscious-lasagna"
],
"blurb": "Learn about packages, functions, and variables by helping Gopher cook lasagna.",
"custom": {
"taskIdsEnabled": true
}
}

View file

@ -0,0 +1 @@
{"track":"go","exercise":"lasagna","id":"520c741b507a484ba5da65b0e5a6a0da","url":"https://exercism.org/tracks/go/exercises/lasagna","handle":"DanielSiepmann","is_requester":true,"auto_approve":false}

41
go/lasagna/HELP.md Normal file
View file

@ -0,0 +1,41 @@
# Help
## Running the tests
To run the tests run the command `go test` from within the exercise directory.
If the test suite contains benchmarks, you can run these with the `--bench` and `--benchmem`
flags:
go test -v --bench . --benchmem
Keep in mind that each reviewer will run benchmarks on a different machine, with
different specs, so the results from these benchmark tests may vary.
## Submitting your solution
You can submit your solution using the `exercism submit lasagna.go` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Go track's documentation](https://exercism.org/docs/tracks/go)
- The [Go track's programming category on the forum](https://forum.exercism.org/c/programming/go)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [How to Write Go Code](https://golang.org/doc/code.html)
- [Effective Go](https://golang.org/doc/effective_go.html)
- [Go Resources](http://golang.org/help)
- [StackOverflow](http://stackoverflow.com/questions/tagged/go)

44
go/lasagna/HINTS.md Normal file
View file

@ -0,0 +1,44 @@
# Hints
## General
- An [integer value][integers] can be defined as one or more consecutive digits.
- If you see a `panic:` error when running the tests, this is because you have not implemented one of the functions (it should say which one) or you have left the boilerplate in place. You need to remove the `panic(...)` line from the supplied code and replace it with a real implementation.
## 1. Define the expected oven time in minutes
- You need to define a [constant][constants] and assign it the expected oven time in minutes.
- If you see an `undefined: OvenTime` error then double check that you have the constant defined.
- If you see an `invalid operation: got != tt.expected (mismatched types float64 and int)` error then you have likely put a decimal point into the `OvenTime` causing Go to infer the type as a floating point number. Remove the decimal and the type will be inferred as an `int`.
- If you see a `syntax error: non-declaration statement outside function body` error then it is likely that you forgot the `const` keyword.
- If you see a `syntax error: unexpected :=, expecting =` error then you are likely trying to assign the constant using `:=` like a variable; constants are assigned using `=` not `:=`.
## 2. Calculate the remaining oven time in minutes
- You need to define a [function][functions] with a single parameter.
- You have to [explicitly return an integer][return] from a function.
- The function's parameter is an [integer][integers].
- You can [call][calls] one of the other functions you've defined previously.
- You can use the [mathematical operator for subtraction][operators] to subtract values.
## 3. Calculate the preparation time in minutes
- You need to define a [function][functions] with a single parameter.
- You have to [explicitly return an integer][return] from a function.
- The function's parameter is an [integer][integers].
- You can use the [mathematical operator for multiplication][operators] to multiply values.
## 4. Calculate the elapsed working time in minutes
- You need to define a [function][functions] with two parameters.
- You have to [explicitly return an integer][return] from a function.
- The function's parameter is an [integer][integers].
- You can [call][calls] one of the other functions you've defined previously.
- You can use the [mathematical operator for addition][operators] to add values.
[functions]: https://tour.golang.org/basics/4
[return]: https://golang.org/ref/spec#Return_statements
[operators]: https://golang.org/ref/spec#Operators
[integers]: https://golang.org/ref/spec#Integer_literals
[calls]: https://golang.org/ref/spec#Calls
[constants]: https://tour.golang.org/basics/15

151
go/lasagna/README.md Normal file
View file

@ -0,0 +1,151 @@
# Gopher's Gorgeous Lasagna
Welcome to Gopher's Gorgeous Lasagna on Exercism's Go Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
If you get stuck on the exercise, check out `HINTS.md`, but try and solve it without using those first :)
## Introduction
[Go](https://golang.org) is a statically typed, compiled programming language.
This exercise introduces three major language features: Packages, Functions, and Variables.
## Packages
Go applications are organized in packages.
A package is a collection of source files located in the same directory.
All source files in a directory must share the same package name.
When a package is imported, only entities (functions, types, variables, constants) whose names start with a capital letter can be used / accessed.
The recommended style of naming in Go is that identifiers will be named using `camelCase`, except for those meant to be accessible across packages which should be `PascalCase`.
```go
package lasagna
```
## Variables
Go is statically-typed, which means all variables [must have a defined type](https://en.wikipedia.org/wiki/Type_system) at compile-time.
Variables can be defined by explicitly specifying a type:
```go
var explicit int // Explicitly typed
```
You can also use an initializer, and the compiler will assign the variable type to match the type of the initializer.
```go
implicit := 10 // Implicitly typed as an int
```
Once declared, variables can be assigned values using the `=` operator.
Once declared, a variable's type can never change.
```go
count := 1 // Assign initial value
count = 2 // Update to new value
count = false // This throws a compiler error due to assigning a non `int` type
```
## Constants
Constants hold a piece of data just like variables, but their value cannot change during the execution of the program.
Constants are defined using the `const` keyword and can be numbers, characters, strings or booleans:
```go
const Age = 21 // Defines a numeric constant 'Age' with the value of 21
```
## Functions
Go functions accept zero or more parameters.
Parameters must be explicitly typed, there is no type inference.
Values are returned from functions using the `return` keyword.
A function is invoked by specifying the function name and passing arguments for each of the function's parameters.
Note that Go supports two types of comments.
Single line comments are preceded by `//` and multiline comments are inserted between `/*` and `*/`.
```go
package greeting
// Hello is a public function.
func Hello (name string) string {
return hi(name)
}
// hi is a private function.
func hi (name string) string {
return "hi " + name
}
```
## Instructions
In this exercise you're going to write some code to help you cook a brilliant lasagna from your favorite cooking book.
You have four tasks, all related to the time spent cooking the lasagna.
## 1. Define the expected oven time in minutes
Define the `OvenTime` constant with how many minutes the lasagna should be in the oven. According to the cooking book, the expected oven time in minutes is 40:
```go
OvenTime
// => 40
```
## 2. Calculate the remaining oven time in minutes
Define the `RemainingOvenTime()` function that takes the actual minutes the lasagna has been in the oven as a parameter and returns how many minutes the lasagna still has to remain in the oven, based on the expected oven time in minutes from the previous task.
```go
func RemainingOvenTime(actual int) int {
// TODO
}
RemainingOvenTime(30)
// => 10
```
## 3. Calculate the preparation time in minutes
Define the `PreparationTime` function that takes the number of layers you added to the lasagna as a parameter and returns how many minutes you spent preparing the lasagna, assuming each layer takes you 2 minutes to prepare.
```go
func PreparationTime(numberOfLayers int) int {
// TODO
}
PreparationTime(2)
// => 4
```
## 4. Calculate the elapsed working time in minutes
Define the `ElapsedTime` function that takes two parameters: the first parameter is the number of layers you added to the lasagna, and the second parameter is the number of minutes the lasagna has been in the oven.
The function should return how many minutes in total you've worked on cooking the lasagna, which is the sum of the preparation time in minutes, and the time in minutes the lasagna has spent in the oven at the moment.
```go
func ElapsedTime(numberOfLayers, actualMinutesInOven int) int {
// TODO
}
ElapsedTime(3, 20)
// => 26
```
## Source
### Created by
- @tehsphinx
### Contributed to by
- @ekingery
- @andrerfcsantos
- @bobtfish

3
go/lasagna/go.mod Normal file
View file

@ -0,0 +1,3 @@
module lasagna
go 1.18

18
go/lasagna/lasagna.go Normal file
View file

@ -0,0 +1,18 @@
package lasagna
// TODO: define the 'OvenTime' constant
// RemainingOvenTime returns the remaining minutes based on the `actual` minutes already in the oven.
func RemainingOvenTime(actualMinutesInOven int) int {
panic("RemainingOvenTime not implemented")
}
// PreparationTime calculates the time needed to prepare the lasagna based on the amount of layers.
func PreparationTime(numberOfLayers int) int {
panic("PreparationTime not implemented")
}
// ElapsedTime calculates the time elapsed cooking the lasagna. This time includes the preparation time and the time the lasagna is baking in the oven.
func ElapsedTime(numberOfLayers, actualMinutesInOven int) int {
panic("ElapsedTime not implemented")
}

View file

@ -0,0 +1,94 @@
package lasagna
import "testing"
type lasagnaTests struct {
name string
layers, time, expected int
}
func TestOvenTime(t *testing.T) {
tests := []lasagnaTests{
{
name: "Calculates how many minutes the lasagna should be in the oven",
layers: 0,
time: 40,
expected: 40,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := OvenTime; got != tt.expected {
t.Errorf("OvenTime(%d) = %d; want %d", tt.expected, got, tt.expected)
}
})
}
}
func TestRemainingOvenTime(t *testing.T) {
tests := []lasagnaTests{
{
name: "Remaining minutes in oven",
layers: 0,
time: 15,
expected: 25,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := RemainingOvenTime(tt.time); got != tt.expected {
t.Errorf("RemainingOvenTime(%d) = %d; want %d", tt.time, got, tt.expected)
}
})
}
}
func TestPreparationTime(t *testing.T) {
tests := []lasagnaTests{
{
name: "Preparation time in minutes for one layer",
layers: 1,
time: 0,
expected: 2,
},
{
name: "Preparation time in minutes for multiple layers",
layers: 4,
time: 0,
expected: 8,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := PreparationTime(tt.layers); got != tt.expected {
t.Errorf("PreparationTime(%d) = %d; want %d", tt.layers, got, tt.expected)
}
})
}
}
func TestElapsedTime(t *testing.T) {
tests := []lasagnaTests{
{
name: "Total time in minutes for one layer",
layers: 1,
time: 30,
expected: 32,
},
{
name: "Total time in minutes for multiple layers",
layers: 4,
time: 8,
expected: 16,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ElapsedTime(tt.layers, tt.time); got != tt.expected {
t.Errorf("ElapsedTime(%d, %d) = %d; want %d", tt.layers, tt.time, got, tt.expected)
}
})
}
}

View file

@ -15,7 +15,7 @@ def exchange_money(budget, exchange_rate):
:return: float - exchanged value of the foreign currency you can receive.
"""
pass
return budget / exchange_rate
def get_change(budget, exchanging_value):
@ -26,7 +26,7 @@ def get_change(budget, exchanging_value):
:return: float - amount left of your starting currency after exchanging.
"""
pass
return budget - exchanging_value
def get_value_of_bills(denomination, number_of_bills):
@ -37,7 +37,7 @@ def get_value_of_bills(denomination, number_of_bills):
:return: int - calculated value of the bills.
"""
pass
return denomination * number_of_bills
def get_number_of_bills(amount, denomination):
@ -48,7 +48,7 @@ def get_number_of_bills(amount, denomination):
:return: int - number of bills that can be obtained from the amount.
"""
pass
return amount // denomination
def get_leftover_of_bills(amount, denomination):
@ -59,7 +59,7 @@ def get_leftover_of_bills(amount, denomination):
:return: float - the amount that is "leftover", given the current denomination.
"""
pass
return amount % denomination
def exchangeable_value(budget, exchange_rate, spread, denomination):
@ -72,4 +72,9 @@ def exchangeable_value(budget, exchange_rate, spread, denomination):
:return: int - maximum value you can get.
"""
pass
exchange = exchange_rate / 100
cost = exchange - spread
result = budget - cost * denomination
return result

View file

@ -9,7 +9,7 @@ def eat_ghost(power_pellet_active, touching_ghost):
:return: bool - can the ghost be eaten?
"""
pass
return power_pellet_active and touching_ghost
def score(touching_power_pellet, touching_dot):
@ -20,7 +20,7 @@ def score(touching_power_pellet, touching_dot):
:return: bool - has the player scored or not?
"""
pass
return touching_power_pellet or touching_dot
def lose(power_pellet_active, touching_ghost):
@ -31,7 +31,7 @@ def lose(power_pellet_active, touching_ghost):
:return: bool - has the player lost the game?
"""
pass
return not power_pellet_active and touching_ghost
def win(has_eaten_all_dots, power_pellet_active, touching_ghost):
@ -43,4 +43,4 @@ def win(has_eaten_all_dots, power_pellet_active, touching_ghost):
:return: bool - has the player won the game?
"""
pass
return has_eaten_all_dots and not lose(power_pellet_active, touching_ghost)

View file

@ -0,0 +1,22 @@
{
"authors": [
"sachsom95",
"BethanyG"
],
"contributors": [
"kbuc"
],
"files": {
"solution": [
"conditionals.py"
],
"test": [
"conditionals_test.py"
],
"exemplar": [
".meta/exemplar.py"
]
},
"icon": "circular-buffer",
"blurb": "Learn about conditionals and avoid a meltdown by developing a simple control system for a Nuclear Reactor."
}

View file

@ -0,0 +1 @@
{"track":"python","exercise":"meltdown-mitigation","id":"4b91cf86ba56457fb003c8c9681fff64","url":"https://exercism.org/tracks/python/exercises/meltdown-mitigation","handle":"DanielSiepmann","is_requester":true,"auto_approve":false}

View file

@ -0,0 +1,130 @@
# Help
## Running the tests
We use [pytest][pytest: Getting Started Guide] as our website test runner.
You will need to install `pytest` on your development machine if you want to run tests for the Python track locally.
You should also install the following `pytest` plugins:
- [pytest-cache][pytest-cache]
- [pytest-subtests][pytest-subtests]
Extended information can be found in our website [Python testing guide][Python track tests page].
### Running Tests
To run the included tests, navigate to the folder where the exercise is stored using `cd` in your terminal (_replace `{exercise-folder-location}` below with your path_).
Test files usually end in `_test.py`, and are the same tests that run on the website when a solution is uploaded.
Linux/MacOS
```bash
$ cd {path/to/exercise-folder-location}
```
Windows
```powershell
PS C:\Users\foobar> cd {path\to\exercise-folder-location}
```
<br>
Next, run the `pytest` command in your terminal, replacing `{exercise_test.py}` with the name of the test file:
Linux/MacOS
```bash
$ python3 -m pytest -o markers=task {exercise_test.py}
==================== 7 passed in 0.08s ====================
```
Windows
```powershell
PS C:\Users\foobar> py -m pytest -o markers=task {exercise_test.py}
==================== 7 passed in 0.08s ====================
```
### Common options
- `-o` : override default `pytest.ini` (_you can use this to avoid marker warnings_)
- `-v` : enable verbose output.
- `-x` : stop running tests on first failure.
- `--ff` : run failures from previous test before running other test cases.
For additional options, use `python3 -m pytest -h` or `py -m pytest -h`.
### Fixing warnings
If you do not use `pytest -o markers=task` when invoking `pytest`, you might receive a `PytestUnknownMarkWarning` for tests that use our new syntax:
```bash
PytestUnknownMarkWarning: Unknown pytest.mark.task - is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/mark.html
```
To avoid typing `pytest -o markers=task` for every test you run, you can use a `pytest.ini` configuration file.
We have made one that can be downloaded from the top level of the Python track directory: [pytest.ini][pytest.ini].
You can also create your own `pytest.ini` file with the following content:
```ini
[pytest]
markers =
task: A concept exercise task.
```
Placing the `pytest.ini` file in the _root_ or _working_ directory for your Python track exercises will register the marks and stop the warnings.
More information on pytest marks can be found in the `pytest` documentation on [marking test functions][pytest: marking test functions with attributes] and the `pytest` documentation on [working with custom markers][pytest: working with custom markers].
Information on customizing pytest configurations can be found in the `pytest` documentation on [configuration file formats][pytest: configuration file formats].
### Extending your IDE or Code Editor
Many IDEs and code editors have built-in support for using `pytest` and other code quality tools.
Some community-sourced options can be found on our [Python track tools page][Python track tools page].
[Pytest: Getting Started Guide]: https://docs.pytest.org/en/latest/getting-started.html
[Python track tools page]: https://exercism.org/docs/tracks/python/tools
[Python track tests page]: https://exercism.org/docs/tracks/python/tests
[pytest-cache]:http://pythonhosted.org/pytest-cache/
[pytest-subtests]:https://github.com/pytest-dev/pytest-subtests
[pytest.ini]: https://github.com/exercism/python/blob/main/pytest.ini
[pytest: configuration file formats]: https://docs.pytest.org/en/6.2.x/customize.html#configuration-file-formats
[pytest: marking test functions with attributes]: https://docs.pytest.org/en/6.2.x/mark.html#raising-errors-on-unknown-marks
[pytest: working with custom markers]: https://docs.pytest.org/en/6.2.x/example/markers.html#working-with-custom-markers
## Submitting your solution
You can submit your solution using the `exercism submit conditionals.py` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Python track's documentation](https://exercism.org/docs/tracks/python)
- The [Python track's programming category on the forum](https://forum.exercism.org/c/programming/python)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
Below are some resources for getting help if you run into trouble:
- [The PSF](https://www.python.org) hosts Python downloads, documentation, and community resources.
- [The Exercism Community on Discord](https://exercism.org/r/discord)
- [Python Community on Discord](https://pythondiscord.com/) is a very helpful and active community.
- [/r/learnpython/](https://www.reddit.com/r/learnpython/) is a subreddit designed for Python learners.
- [#python on Libera.chat](https://www.python.org/community/irc/) this is where the core developers for the language hang out and get work done.
- [Python Community Forums](https://discuss.python.org/)
- [Free Code Camp Community Forums](https://forum.freecodecamp.org/)
- [CodeNewbie Community Help Tag](https://community.codenewbie.org/t/help)
- [Pythontutor](http://pythontutor.com/) for stepping through small code snippets visually.
Additionally, [StackOverflow](http://stackoverflow.com/questions/tagged/python) is a good spot to search for your problem/question to see if it has been answered already.
If not - you can always [ask](https://stackoverflow.com/help/how-to-ask) or [answer](https://stackoverflow.com/help/how-to-answer) someone else's question.

View file

@ -0,0 +1,48 @@
# 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`
## 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`
[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/

View file

@ -0,0 +1,171 @@
# Meltdown Mitigation
Welcome to Meltdown Mitigation on Exercism's Python Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
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 great 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:
return 'FizzBuzz!'
elif number % 5 == 0:
return 'Buzz!'
elif number % 3 == 0:
return 'Fizz!'
else:
return str(number)
>>> 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 critical 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

View file

@ -0,0 +1,56 @@
"""Functions to prevent a nuclear meltdown."""
def is_criticality_balanced(temperature, neutrons_emitted):
"""Verify criticality is balanced.
:param temperature: int or float - temperature value in kelvin.
:param neutrons_emitted: int or float - number of neutrons emitted per second.
:return: bool - is criticality balanced?
A reactor is said to be critical 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.
"""
pass
def reactor_efficiency(voltage, current, theoretical_max_power):
"""Assess reactor efficiency zone.
:param voltage: int or float - voltage value.
:param current: int or float - current value.
:param theoretical_max_power: int or float - power that corresponds to a 100% efficiency.
:return: str - one of ('green', 'orange', 'red', or 'black').
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
"""
pass
def fail_safe(temperature, neutrons_produced_per_second, threshold):
"""Assess and return status code for the reactor.
:param temperature: int or float - value of the temperature in kelvin.
:param neutrons_produced_per_second: int or float - neutron flux.
:param threshold: int or float - threshold for category.
:return: str - one of ('LOW', 'NORMAL', 'DANGER').
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
"""
pass

View file

@ -0,0 +1,82 @@
import unittest
import pytest
from conditionals import (is_criticality_balanced,
reactor_efficiency,
fail_safe)
class MeltdownMitigationTest(unittest.TestCase):
"""Test cases for Meltdown mitigation exercise.
"""
@pytest.mark.task(taskno=1)
def test_is_criticality_balanced(self):
"""Testing border cases around typical points.
T, n == (800, 500), (625, 800), (500, 1000), etc.
"""
test_data = ((750, 650, True), (799, 501, True), (500, 600, True),
(1000, 800, False), (800, 500, False), (800, 500.01, False),
(799.99, 500, False), (500.01, 999.99, False), (625, 800, False),
(625.99, 800, False), (625.01, 799.99, False), (799.99, 500.01, True),
(624.99, 799.99, True), (500, 1000, False), (500.01, 1000, False),
(499.99, 1000, True))
for variant, data in enumerate(test_data, start=1):
temp, neutrons_emitted, expected = data
with self.subTest(f'variation #{variant}', temp=temp, neutrons_emitted=neutrons_emitted, expected=expected):
# pylint: disable=assignment-from-no-return
actual_result = is_criticality_balanced(temp, neutrons_emitted)
failure_message = (f'Called is_criticality_balanced({temp}, {neutrons_emitted}). '
f' The function returned {actual_result}, '
f'but the test expected {expected} as the return value.')
self.assertEqual(actual_result, expected, failure_message)
@pytest.mark.task(taskno=2)
def test_reactor_efficiency(self):
voltage = 10
theoretical_max_power = 10000
# The numbers are chosen so that current == 10 x percentage
test_data = ((1000, 'green'), (999, 'green'), (800, 'green'),
(799, 'orange'), (700, 'orange'), (600, 'orange'),
(599, 'red'), (560, 'red'), (400, 'red'), (300, 'red'),
(299, 'black'), (200, 'black'), (0, 'black'))
for variant, data in enumerate(test_data, start=1):
current, expected = data
with self.subTest(f'variation #{variant}', voltage=voltage, current=current,
theoretical_max_power=theoretical_max_power, expected=expected):
# pylint: disable=assignment-from-no-return
actual_result = reactor_efficiency(voltage, current, theoretical_max_power)
failure_message =(f'Called reactor_efficiency({voltage}, {current}, {theoretical_max_power}). '
f'The function returned {actual_result}, '
f'but the test expected {expected} as the return value.')
self.assertEqual(actual_result, expected, failure_message)
@pytest.mark.task(taskno=3)
def test_fail_safe(self):
temp = 10
threshold = 10000
test_data = ((399, 'LOW'), (300, 'LOW'), (1, 'LOW'),
(0, 'LOW'), (901, 'NORMAL'), (1000, 'NORMAL'),
(1099, 'NORMAL'), (899, 'LOW'), (700, 'LOW'),
(400, 'LOW'), (1101, 'DANGER'), (1200, 'DANGER'))
for variant, (neutrons_per_second, expected) in enumerate(test_data, start=1):
with self.subTest(f'variation #{variant}', temp=temp, neutrons_per_second=neutrons_per_second,
threshold=threshold, expected=expected):
# pylint: disable=assignment-from-no-return
actual_result = fail_safe(temp, neutrons_per_second, threshold)
failure_message = (f'Called fail_safe({temp}, {neutrons_per_second}, {threshold}). '
f'The function returned {actual_result}, '
f'but the test expected {expected} as the return value.')
self.assertEqual(actual_result, expected, failure_message)

View file

@ -0,0 +1,42 @@
{
"authors": [
"EduardoBautista"
],
"contributors": [
"ashleygwilliams",
"ClashTheBunny",
"coriolinus",
"cwhakes",
"dvoytik",
"EduardoBautista",
"efx",
"ErikSchierboom",
"hydhknn",
"IanWhitney",
"ijanos",
"kytrinyx",
"lutostag",
"nfiles",
"petertseng",
"regnerjr",
"rofrol",
"stringparser",
"xakon",
"ZapAnton"
],
"files": {
"solution": [
"src/lib.rs",
"Cargo.toml"
],
"test": [
"tests/hello-world.rs"
],
"example": [
".meta/example.rs"
]
},
"blurb": "Exercism's classic introductory exercise. Just say \"Hello, World!\".",
"source": "This is an exercise to introduce users to using Exercism",
"source_url": "https://en.wikipedia.org/wiki/%22Hello,_world!%22_program"
}

View file

@ -0,0 +1 @@
{"track":"rust","exercise":"hello-world","id":"f0bf2083fc314cb88a1cb31a4e806a10","url":"https://exercism.org/tracks/rust/exercises/hello-world","handle":"DanielSiepmann","is_requester":true,"auto_approve":false}

8
rust/hello-world/.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
# Generated by Cargo
# will have compiled files and executables
/target/
**/*.rs.bk
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
Cargo.lock

View file

@ -0,0 +1,4 @@
[package]
edition = "2021"
name = "hello-world"
version = "1.1.0"

View file

@ -0,0 +1,92 @@
# Getting Started
These exercises lean on Test-Driven Development (TDD), but they're not
an exact match.
The following steps assume that you are in the same directory as the exercise.
You must have Rust installed.
Follow the [Installation chapter in the Rust book](https://doc.rust-lang.org/book/ch01-01-installation.html).
The [Rust language section](http://exercism.org/languages/rust)
section from exercism is also useful.
## Step 1
Run the test suite. It can be run with `cargo`, which is installed with Rust.
```sh
$ cargo test
```
This will compile the `hello-world` crate and run the test, which fails.
```sh
running 1 test
test hello_world ... FAILED
failures:
---- hello_world stdout ----
thread 'hello_world' panicked at 'assertion failed: `(left == right)`
(left: `"Hello, World!"`, right: `"Goodbye, Mars!"`)', tests/hello-world.rs:5
failures:
hello_world
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
```
### Understanding Test Failures
The `hello_world` failure states that it is expecting the value,
`"Hello, World!"`, to be returned from `hello()`.
The left side of the assertion (at line 5) should be equal to the right side.
```sh
---- hello_world stdout ----
thread 'hello_world' panicked at 'assertion failed: `(left == right)`
(left: `"Hello, World!"`, right: `"Goodbye, Mars!"`)', tests/hello-world.rs:5
```
### Fixing the Error
To fix it, open up `src/lib.rs` and change the `hello` function to return
`"Hello, World!"` instead of `"Goodbye, Mars!"`.
```rust
pub fn hello() -> &'static str {
"Hello, World!"
}
```
## Step 2
Run the test again. This time, it will pass.
```sh
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
Running target/debug/deps/hello_world-bd1f06dc726ef14f
running 1 test
test hello_world ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests hello-world
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
```
## Submit
Once the test is passing, you can submit your code with the following
command:
```sh
$ exercism submit
```

86
rust/hello-world/HELP.md Normal file
View file

@ -0,0 +1,86 @@
# Help
## Running the tests
Execute the tests with:
```bash
$ cargo test
```
All but the first test have been ignored. After you get the first test to
pass, open the tests source file which is located in the `tests` directory
and remove the `#[ignore]` flag from the next test and get the tests to pass
again. Each separate test is a function with `#[test]` flag above it.
Continue, until you pass every test.
If you wish to run _only ignored_ tests without editing the tests source file, use:
```bash
$ cargo test -- --ignored
```
If you are using Rust 1.51 or later, you can run _all_ tests with
```bash
$ cargo test -- --include-ignored
```
To run a specific test, for example `some_test`, you can use:
```bash
$ cargo test some_test
```
If the specific test is ignored, use:
```bash
$ cargo test some_test -- --ignored
```
To learn more about Rust tests refer to the online [test documentation][rust-tests].
[rust-tests]: https://doc.rust-lang.org/book/ch11-02-running-tests.html
## Submitting your solution
You can submit your solution using the `exercism submit src/lib.rs Cargo.toml` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Rust track's documentation](https://exercism.org/docs/tracks/rust)
- The [Rust track's programming category on the forum](https://forum.exercism.org/c/programming/rust)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
## Rust Installation
Refer to the [exercism help page][help-page] for Rust installation and learning
resources.
## Submitting the solution
Generally you should submit all files in which you implemented your solution (`src/lib.rs` in most cases). If you are using any external crates, please consider submitting the `Cargo.toml` file. This will make the review process faster and clearer.
## Feedback, Issues, Pull Requests
The GitHub [track repository][github] is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help!
If you want to know more about Exercism, take a look at the [contribution guide].
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
[help-page]: https://exercism.org/tracks/rust/learning
[github]: https://github.com/exercism/rust
[contribution guide]: https://exercism.org/docs/community/contributors

View file

@ -0,0 +1,56 @@
# Hello World
Welcome to Hello World on Exercism's Rust Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
The classical introductory exercise.
Just say "Hello, World!".
["Hello, World!"][hello-world] is the traditional first program for beginning programming in a new language or environment.
The objectives are simple:
- Modify the provided code so that it produces the string "Hello, World!".
- Run the test suite and make sure that it succeeds.
- Submit your solution and check it at the website.
If everything goes well, you will be ready to fetch your first real exercise.
[hello-world]: https://en.wikipedia.org/wiki/%22Hello,_world!%22_program
In the Rust track, tests are run using the command `cargo test`.
## Source
### Created by
- @EduardoBautista
### Contributed to by
- @ashleygwilliams
- @ClashTheBunny
- @coriolinus
- @cwhakes
- @dvoytik
- @EduardoBautista
- @efx
- @ErikSchierboom
- @hydhknn
- @IanWhitney
- @ijanos
- @kytrinyx
- @lutostag
- @nfiles
- @petertseng
- @regnerjr
- @rofrol
- @stringparser
- @xakon
- @ZapAnton
### Based on
This is an exercise to introduce users to using Exercism - https://en.wikipedia.org/wiki/%22Hello,_world!%22_program

View file

@ -0,0 +1,4 @@
// &'static is a "lifetime specifier", something you'll learn more about later
pub fn hello() -> &'static str {
"Goodbye, Mars!"
}

View file

@ -0,0 +1,4 @@
#[test]
fn hello_world() {
assert_eq!("Hello, World!", hello_world::hello());
}

View file

@ -2,17 +2,23 @@
pkgs ? import <nixpkgs> { }
}:
let
lua = pkgs.lua.withPackages(ps: with ps; [ busted]);
python = pkgs.python311.withPackages(ps: with ps; [ pytest ]);
in pkgs.mkShellNoCC {
pkgs.mkShellNoCC {
name = "exercism";
buildInputs = [
# coreutils provides "make" for c compiling
pkgs.coreutils
lua
python
(pkgs.lua.withPackages(ps: with ps; [ busted]))
(pkgs.python311.withPackages(ps: with ps; [ pytest ]))
pkgs.go
# Rust (needs gcc compiler)
pkgs.gcc
pkgs.rustc
pkgs.cargo
];
shellHook = ''