primeiro commit com exercicios de Exercism realizados até esta data
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"authors": [
|
||||
"behrtam"
|
||||
],
|
||||
"contributors": [
|
||||
"AndrejTS",
|
||||
"cmccandless",
|
||||
"csabella",
|
||||
"Dog",
|
||||
"fortrieb",
|
||||
"gabriellhrn",
|
||||
"ikhadykin",
|
||||
"mandel01",
|
||||
"N-Parsons",
|
||||
"pheanex",
|
||||
"pranasziaukas",
|
||||
"tqa236",
|
||||
"tsamoglou"
|
||||
],
|
||||
"files": {
|
||||
"solution": [
|
||||
"say.py"
|
||||
],
|
||||
"test": [
|
||||
"say_test.py"
|
||||
],
|
||||
"example": [
|
||||
".meta/example.py"
|
||||
]
|
||||
},
|
||||
"blurb": "Given a number from 0 to 999,999,999,999, spell out that number in English.",
|
||||
"source": "A variation on the JavaRanch CattleDrive, Assignment 4",
|
||||
"source_url": "https://web.archive.org/web/20240907035912/https://coderanch.com/wiki/718804"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"track":"python","exercise":"say","id":"e89bd649c9b44a949d63bb0d5e57d36b","url":"https://exercism.org/tracks/python/exercises/say","handle":"sanctushck","is_requester":true,"auto_approve":false}
|
||||
@@ -0,0 +1,130 @@
|
||||
# Help
|
||||
|
||||
## Correr os testes
|
||||
|
||||
Usamos o [pytest][pytest: Getting Started Guide] como executor de testes do nosso site.
|
||||
Vais precisar de instalar o `pytest` na tua máquina de desenvolvimento se quiseres correr os testes do percurso Python localmente.
|
||||
Também vais precisar de instalar os seguintes plugins do `pytest`:
|
||||
|
||||
- [pytest-cache][pytest-cache]
|
||||
- [pytest-subtests][pytest-subtests]
|
||||
|
||||
Encontras informação mais detalhada no [guia de testes de Python][Python track tests page] do nosso site.
|
||||
|
||||
|
||||
### Correr os testes
|
||||
|
||||
Para correres os testes incluídos, navega até à pasta onde o exercício está guardado usando o `cd` no teu terminal (_substitui `<exercise-folder-location>` abaixo pelo teu caminho_).
|
||||
Os ficheiros de teste terminam habitualmente em `_test.py` e são os mesmos testes que correm no site quando uma solução é submetida.
|
||||
|
||||
Linux/MacOS
|
||||
```bash
|
||||
$ cd <path/to/exercise-folder-location>
|
||||
```
|
||||
|
||||
Windows
|
||||
```powershell
|
||||
PS C:\Users\foobar> cd <path\to\exercise-folder-location>
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
De seguida, corre o comando `pytest` no teu terminal, substituindo `<exercise_test.py>` pelo nome do ficheiro de teste:
|
||||
|
||||
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 ====================
|
||||
```
|
||||
|
||||
|
||||
### Opções comuns
|
||||
- `-o` : substitui o `pytest.ini` predefinido (_podes usar esta opção para evitar avisos de marcadores_)
|
||||
- `-v` : ativa a saída detalhada.
|
||||
- `-x` : para de correr os testes na primeira falha.
|
||||
- `--ff` : corre as falhas do teste anterior antes de correr os outros casos de teste.
|
||||
|
||||
Para opções adicionais, usa `python3 -m pytest -h` ou `py -m pytest -h`.
|
||||
|
||||
|
||||
### Corrigir avisos
|
||||
|
||||
Se não usares `pytest -o markers=task` ao invocar o `pytest`, podes receber um `PytestUnknownMarkWarning` nos testes que usam a nossa nova sintaxe:
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
Para evitares escrever `pytest -o markers=task` em todos os testes que corres, podes usar um ficheiro de configuração `pytest.ini`.
|
||||
Criámos um que podes descarregar a partir do nível de topo do diretório do percurso Python: [pytest.ini][pytest.ini].
|
||||
|
||||
Também podes criar o teu próprio ficheiro `pytest.ini` com o seguinte conteúdo:
|
||||
|
||||
```ini
|
||||
[pytest]
|
||||
markers =
|
||||
task: A concept exercise task.
|
||||
```
|
||||
|
||||
Colocar o ficheiro `pytest.ini` no diretório _root_ ou _working_ dos teus exercícios do percurso Python regista os marcadores e faz parar os avisos.
|
||||
Encontras mais informação sobre os marcadores do pytest na documentação do `pytest` sobre [marcar funções de teste][pytest: marking test functions with attributes] e na documentação do `pytest` sobre [trabalhar com marcadores personalizados][pytest: working with custom markers].
|
||||
|
||||
Encontras informação sobre como personalizar as configurações do pytest na documentação do `pytest` sobre [formatos de ficheiros de configuração][pytest: configuration file formats].
|
||||
|
||||
|
||||
### Estender o teu IDE ou editor de código
|
||||
|
||||
Muitos IDEs e editores de código têm suporte integrado para usar o `pytest` e outras ferramentas de qualidade de código.
|
||||
Podes encontrar algumas opções da comunidade na nossa [página de ferramentas do percurso Python][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
|
||||
|
||||
## Submeter a tua solução
|
||||
|
||||
Podes submeter a tua solução com o comando `exercism submit say.py`.
|
||||
Este comando envia a tua solução para o site do Exercism e imprime o URL da página da solução.
|
||||
|
||||
É possível submeter uma solução incompleta, o que te permite:
|
||||
|
||||
- Ver como outras pessoas resolveram o exercício
|
||||
- Pedir ajuda a um mentor
|
||||
|
||||
## Precisas de ajuda?
|
||||
|
||||
Se quiseres ajuda para resolver o exercício, consulta as seguintes páginas:
|
||||
|
||||
- A [documentação do percurso Python](https://exercism.org/docs/tracks/python)
|
||||
- A [categoria de programação do percurso Python no fórum](https://forum.exercism.org/c/programming/python)
|
||||
- A [categoria de programação do Exercism no fórum](https://forum.exercism.org/c/programming/5)
|
||||
- As [Perguntas Frequentes](https://exercism.org/docs/using/faqs)
|
||||
|
||||
Se esses recursos não forem suficientes, podes submeter a tua solução (incompleta) para pedir mentoria.
|
||||
|
||||
Abaixo encontras alguns recursos para obter ajuda, caso tenhas problemas:
|
||||
|
||||
- [A PSF](https://www.python.org) aloja as transferências do Python, a documentação e recursos da comunidade.
|
||||
- Os [Fóruns da Comunidade Python](https://discuss.python.org/) servem para obter ajuda, discutir PEPs, falar com os principais contribuidores do Python e muito mais.
|
||||
- [A Comunidade do Exercism no Discord](https://exercism.org/r/discord)
|
||||
- [Os Fóruns de Discussão da Comunidade do Exercism](https://forum.exercsim.org)
|
||||
- A [Comunidade Python no Discord](https://pythondiscord.com/) é uma comunidade muito prestável e ativa.
|
||||
- O [/r/learnpython/](https://www.reddit.com/r/learnpython/) é um subreddit pensado para quem está a aprender Python.
|
||||
- O [#python no Libera.chat](https://www.python.org/community/irc/) é o sítio onde os programadores responsáveis pela linguagem se juntam e põem o trabalho em dia.
|
||||
- Os [Fóruns da Comunidade Free Code Camp](https://forum.freecodecamp.org/)
|
||||
- O [Pythontutor](http://pythontutor.com/) para percorrer pequenos excertos de código visualmente.
|
||||
|
||||
Além disso, o [StackOverflow](http://stackoverflow.com/questions/tagged/python) é um bom sítio para procurar o teu problema ou a tua dúvida e ver se já foi respondida.
|
||||
Se não foi, podes sempre [perguntar](https://stackoverflow.com/help/how-to-ask) ou [responder](https://stackoverflow.com/help/how-to-answer) à pergunta de outra pessoa.
|
||||
@@ -0,0 +1,66 @@
|
||||
# Diz
|
||||
|
||||
Bem-vindo ao Diz no percurso Python do Exercism.
|
||||
Se precisares de ajuda para correr os testes ou para submeter o teu código, consulta o `HELP.md`.
|
||||
|
||||
## Introduction
|
||||
|
||||
O teu amigo Yaʻqūb trabalha ao balcão da delicatessen mais movimentada da cidade, a cortar, a pesar e a embrulhar encomendas para uma fila infindável de clientes com fome.
|
||||
Para as coisas não pararem, cada cliente tira uma senha numerada quando chega.
|
||||
|
||||
Quando é altura de chamar a pessoa seguinte, o Yaʻqūb lê o número em voz alta, sempre por palavras completas em inglês, para garantir que toda a gente o ouve com clareza.
|
||||
|
||||
## Instructions
|
||||
|
||||
Dado um número, a tua tarefa é escrevê-lo por palavras em inglês, exatamente como o teu amigo o diria em voz alta.
|
||||
Yaʻqūb espera usar números de 0 até 999 999 999 999.
|
||||
|
||||
Exemplos:
|
||||
|
||||
- 0 → zero
|
||||
- 1 → one
|
||||
- 12 → twelve
|
||||
- 123 → one hundred twenty-three
|
||||
- 1 234 → one thousand two hundred thirty-four
|
||||
|
||||
## Mensagens de exceção
|
||||
|
||||
Por vezes é necessário [lançar uma exceção](https://docs.python.org/3/tutorial/errors.html#raising-exceptions). Quando o fazes, deves incluir sempre uma **mensagem de erro significativa** que indique qual é a origem do erro. Isto torna o teu código mais legível e ajuda bastante na depuração. Nos casos em que sabes que a origem do erro será de um determinado tipo, podes optar por lançar um dos [tipos de erro incorporados](https://docs.python.org/3/library/exceptions.html#base-classes), mas deves continuar a incluir uma mensagem significativa.
|
||||
|
||||
Este exercício em particular exige que uses a [instrução raise](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement) para "lançar" um `ValueError` se o valor de entrada de `say()` estiver fora do intervalo. Os testes só passam se fizeres `raise` da `exception` e incluíres uma mensagem com ela.
|
||||
|
||||
Para lançar um `ValueError` com uma mensagem, escreve a mensagem como argumento do tipo `exception`:
|
||||
|
||||
```python
|
||||
# if the number is negative
|
||||
raise ValueError("input out of range")
|
||||
|
||||
# if the number is larger than 999,999,999,999
|
||||
raise ValueError("input out of range")
|
||||
```
|
||||
|
||||
## Source
|
||||
|
||||
### Created by
|
||||
|
||||
- @behrtam
|
||||
|
||||
### Contributed to by
|
||||
|
||||
- @AndrejTS
|
||||
- @cmccandless
|
||||
- @csabella
|
||||
- @Dog
|
||||
- @fortrieb
|
||||
- @gabriellhrn
|
||||
- @ikhadykin
|
||||
- @mandel01
|
||||
- @N-Parsons
|
||||
- @pheanex
|
||||
- @pranasziaukas
|
||||
- @tqa236
|
||||
- @tsamoglou
|
||||
|
||||
### Based on
|
||||
|
||||
A variation on the JavaRanch CattleDrive, Assignment 4 - https://web.archive.org/web/20240907035912/https://coderanch.com/wiki/718804
|
||||
@@ -0,0 +1,4 @@
|
||||
def say(number):
|
||||
output: str = ""
|
||||
|
||||
return output
|
||||
@@ -0,0 +1,85 @@
|
||||
# These tests are auto-generated with test data from:
|
||||
# https://github.com/exercism/problem-specifications/tree/main/exercises/say/canonical-data.json
|
||||
# File last updated on 2023-07-19
|
||||
|
||||
import unittest
|
||||
|
||||
from say import (
|
||||
say,
|
||||
)
|
||||
|
||||
|
||||
class SayTest(unittest.TestCase):
|
||||
def test_zero(self):
|
||||
self.assertEqual(say(0), "zero")
|
||||
|
||||
def test_one(self):
|
||||
self.assertEqual(say(1), "one")
|
||||
|
||||
def test_fourteen(self):
|
||||
self.assertEqual(say(14), "fourteen")
|
||||
|
||||
def test_twenty(self):
|
||||
self.assertEqual(say(20), "twenty")
|
||||
|
||||
def test_twenty_two(self):
|
||||
self.assertEqual(say(22), "twenty-two")
|
||||
|
||||
def test_thirty(self):
|
||||
self.assertEqual(say(30), "thirty")
|
||||
|
||||
def test_ninety_nine(self):
|
||||
self.assertEqual(say(99), "ninety-nine")
|
||||
|
||||
def test_one_hundred(self):
|
||||
self.assertEqual(say(100), "one hundred")
|
||||
|
||||
def test_one_hundred_twenty_three(self):
|
||||
self.assertEqual(say(123), "one hundred twenty-three")
|
||||
|
||||
def test_two_hundred(self):
|
||||
self.assertEqual(say(200), "two hundred")
|
||||
|
||||
def test_nine_hundred_ninety_nine(self):
|
||||
self.assertEqual(say(999), "nine hundred ninety-nine")
|
||||
|
||||
def test_one_thousand(self):
|
||||
self.assertEqual(say(1000), "one thousand")
|
||||
|
||||
def test_one_thousand_two_hundred_thirty_four(self):
|
||||
self.assertEqual(say(1234), "one thousand two hundred thirty-four")
|
||||
|
||||
def test_one_million(self):
|
||||
self.assertEqual(say(1000000), "one million")
|
||||
|
||||
def test_one_million_two_thousand_three_hundred_forty_five(self):
|
||||
self.assertEqual(
|
||||
say(1002345), "one million two thousand three hundred forty-five"
|
||||
)
|
||||
|
||||
def test_one_billion(self):
|
||||
self.assertEqual(say(1000000000), "one billion")
|
||||
|
||||
def test_a_big_number(self):
|
||||
self.assertEqual(
|
||||
say(987654321123),
|
||||
"nine hundred eighty-seven billion six hundred fifty-four million three hundred twenty-one thousand one hundred twenty-three",
|
||||
)
|
||||
|
||||
def test_numbers_below_zero_are_out_of_range(self):
|
||||
with self.assertRaises(ValueError) as err:
|
||||
say(-1)
|
||||
|
||||
self.assertEqual(type(err.exception), ValueError)
|
||||
self.assertEqual(err.exception.args[0], "input out of range")
|
||||
|
||||
def test_numbers_above_999_999_999_999_are_out_of_range(self):
|
||||
with self.assertRaises(ValueError) as err:
|
||||
say(1000000000000)
|
||||
|
||||
self.assertEqual(type(err.exception), ValueError)
|
||||
self.assertEqual(err.exception.args[0], "input out of range")
|
||||
|
||||
# Additional tests for this track
|
||||
def test_one_hundred_seventy(self):
|
||||
self.assertEqual(say(170), "one hundred seventy")
|
||||
Reference in New Issue
Block a user