Skip to content

Commit 746e6af

Browse files
authored
Merge pull request #59 from josemoracard/jose8-35-square-each-odd-number
exercises 35-square-each-odd-number to 41-frequency-of-words
2 parents b597f4f + b95c13d commit 746e6af

File tree

32 files changed

+472
-184
lines changed

32 files changed

+472
-184
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# `35` Square odd numbers
2+
3+
## 📝 Instrucciones:
4+
5+
1. Escribe una función llamada `square_odd_numbers()` que acepte un string de números separados por comas como entrada, eleve al cuadrado solo los números impares y devuelva los resultados en una lista.
6+
7+
## 📎 Ejemplo de entrada:
8+
9+
```py
10+
square_odd_numbers("1,2,3,4,5,6,7,8,9")
11+
```
12+
13+
## 📎 Ejemplo de salida:
14+
15+
```py
16+
[1, 9, 25, 49, 81]
17+
```
Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,17 @@
1-
Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers.
2-
Suppose the following input is supplied to the program:
3-
1,2,3,4,5,6,7,8,9
4-
Then, the output should be:
5-
1,3,5,7,9
6-
7-
Hints:
8-
In case of input data being supplied to the question, it should be assumed to be a console input.
1+
# `35` Square odd numbers
2+
3+
## 📝 Instructions:
4+
5+
1. Write a function named `square_odd_numbers()` that accepts a string of comma-separated numbers as input, squares only the odd numbers, and returns the results as a list.
6+
7+
## 📎 Example input:
8+
9+
```py
10+
square_odd_numbers("1,2,3,4,5,6,7,8,9")
11+
```
12+
13+
## 📎 Example output:
14+
15+
```py
16+
[1, 9, 25, 49, 81]
17+
```
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Your code here
Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,26 @@
1-
values = raw_input()
2-
numbers = [x for x in values.split(",") if int(x)%2!=0]
3-
print ",".join(numbers)
1+
# Your code here
2+
def square_odd_numbers(numbers_str):
3+
numbers_list = numbers_str.split(',')
4+
squared_odd_numbers = []
5+
6+
for num_str in numbers_list:
7+
if num_str.isdigit():
8+
num = int(num_str)
9+
10+
if num % 2 != 0:
11+
squared_odd_numbers.append(num**2)
12+
13+
return squared_odd_numbers
14+
15+
print(square_odd_numbers("1,2,3,4,5,6,7"))
16+
17+
18+
### SOLUTION 2 ### (List Comprehension)
19+
20+
# def square_odd_numbers(numbers):
21+
# number_list = [int(num) for num in numbers.split(',')]
22+
# squared_odd_numbers = [num**2 for num in number_list if num % 2 != 0]
23+
24+
# return squared_odd_numbers
25+
26+
# print(square_odd_numbers("1,2,3,4,5,6,7"))

exercises/36-net-amount/README.es.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# `36` Net amount
2+
3+
## 📝 Instrucciones:
4+
5+
1. Escribe una función llamada `net_amount()` que calcule el saldo neto de una cuenta bancaria basándose en un registro de transacciones ingresado por parámetro. El formato del registro de transacciones se muestra a continuación:
6+
7+
+ D 100
8+
+ W 200
9+
10+
`D` significa depósito y `W` significa retiro.
11+
12+
## 📎 Ejemplo de entrada:
13+
14+
```py
15+
net_amount("D 300 D 300 W 200 D 100")
16+
```
17+
18+
## 📎 Ejemplo de salida:
19+
20+
```py
21+
500
22+
```

exercises/36-net-amount/README.md

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,22 @@
1-
Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following:
2-
D 100
3-
W 200
4-
5-
D means deposit while W means withdrawal.
6-
Suppose the following input is supplied to the program:
7-
D 300
8-
D 300
9-
W 200
10-
D 100
11-
Then, the output should be:
12-
500
1+
# `36` Net amount
2+
3+
## 📝 Instructions:
4+
5+
1. Write a function named `net_amount()` that computes the net amount of a bank account based on a transaction log from input. The transaction log format is shown as following:
6+
7+
+ D 100
8+
+ W 200
9+
10+
`D` means deposit while `W` means withdrawal.
1311

14-
Hints:
15-
In case of input data being supplied to the question, it should be assumed to be a console input.
12+
## 📎 Example input:
13+
14+
```py
15+
net_amount("D 300 D 300 W 200 D 100")
16+
```
17+
18+
## 📎 Example output:
19+
20+
```py
21+
500
22+
```

exercises/36-net-amount/app.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Your code here
Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
1+
# Your code here
12
def net_amount(param):
2-
netAmount = 0
3+
total = 0
34
values = param.split()
45
for x in range(len(values)):
56
if values[x] == 'D':
6-
netAmount+=int(values[x+1])
7+
total+=int(values[x+1])
78
elif values[x] == 'W':
8-
netAmount-=int(values[x+1])
9-
return netAmount
9+
total-=int(values[x+1])
10+
return total
11+
12+
print(net_amount("D 300 W 200 D 400"))

exercises/36-net-amount/test.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
import pytest, io, sys, json, mock, re, os
22
path = os.path.dirname(os.path.abspath(__file__))+'/app.py'
33

4-
@pytest.mark.it('The function net_amount must exist')
5-
def test_function_existence(capsys, app):
6-
assert app.net_amount
7-
84
@pytest.mark.it('The function net_amount must exist')
95
def test_function_existence(capsys, app):
106
assert app.net_amount
@@ -19,4 +15,4 @@ def test_output_2(capsys, app):
1915

2016
@pytest.mark.it('The solution should work with other parameters. Testing with "W 300 D 300 W 200 D 300"')
2117
def test_output_negative(capsys, app):
22-
assert app.net_amount("W 300 D 300 W 200 W 300") == -500
18+
assert app.net_amount("W 300 D 300 W 200 W 300") == -500
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# `37` Validity of password
2+
3+
## 📝 Instrucciones:
4+
5+
Un sitio web requiere que los usuarios ingresen un nombre de usuario y una contraseña para registrarse. Escribe una función llamada `valid_password()` para verificar la validez de la contraseña ingresada por los usuarios. A continuación, se detallan los criterios para verificar la contraseña:
6+
7+
1. Al menos 1 letra entre [a-z].
8+
2. Al menos 1 número entre [0-9].
9+
3. Al menos 1 letra entre [A-Z].
10+
4. Al menos 1 carácter de [$#@].
11+
5. Longitud mínima de la contraseña: 6.
12+
6. Longitud máxima de la contraseña: 12.
13+
14+
Tu programa debe aceptar una contraseña y verificarla según los criterios anteriores. Si la contraseña es validada correctamente, la función devuelve el siguiente string `"Valid password"`, de lo contrario devuelve `"Invalid password. Please try again"`.
15+
16+
## 📎 Ejemplo de entrada:
17+
18+
```py
19+
valid_password("ABd1234@1")
20+
```
21+
22+
## 📎 Ejemplo de salida:
23+
24+
```py
25+
"Valid password"
26+
```
27+
28+
## 💡 Pistas:
29+
30+
+ Lee sobre expresiones regulares en Python.
31+
32+
+ Necesitarás importar el módulo 're' (regular expressions) para poder usar la función `search()`.
33+
34+
+ Para importarlo, copia y pega lo siguiente al inicio de tu archivo `import re`.
Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,34 @@
1-
A website requires the users to input username and password to register. Write a program to check the validity of password input by users.
2-
Following are the criteria for checking the password:
1+
# `37` Validity of password
2+
3+
## 📝 Instructions:
4+
5+
A website requires the users to input a username and password to register. Write a function named `valid_password()` to check the validity of password input by users. Following are the criteria for checking the password:
36

47
1. At least 1 letter between [a-z].
58
2. At least 1 number between [0-9].
6-
1. At least 1 letter between [A-Z].
7-
3. At least 1 character from [$#@].
8-
4. Minimum length of transaction password: 6.
9-
5. Maximum length of transaction password: 12.
9+
3. At least 1 letter between [A-Z].
10+
4. At least 1 character from [$#@].
11+
5. Minimum length of password: 6.
12+
6. Maximum length of password: 12.
1013

14+
Your program should accept a password and verify it according to the previous criteria. If the password is successfully validated, the function returns the following string `"Valid password"`. Otherwise, it returns `"Invalid password. Please try again"`.
1115

12-
Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma.
16+
## 📎 Example input:
1317

14-
### Example
18+
```py
19+
valid_password("ABd1234@1")
20+
```
1521

16-
If the following passwords are given as input to the program:
22+
## 📎 Example output:
1723

24+
```py
25+
"Valid password"
1826
```
19-
ABd1234@1,a F1#,2w3E*,2We3345
20-
```
21-
Then, the output of the program should be:
22-
```
23-
ABd1234@1
24-
```
25-
26-
### Hints:
2727

28-
In case of input data being supplied to the question, it should be assumed to be a console input.
28+
## 💡 Hints:
29+
30+
+ Read about regular expressions in Python.
31+
32+
+ You will need to import the 're' module (regular expressions) to be able to use the `search()` function.
33+
34+
+ To import it, copy and paste the following at the beginning of your file: `import re`.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Your code here
Lines changed: 11 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,13 @@
1+
# Your code here
12
import re
3+
24
def valid_password(password):
3-
value = []
4-
items=[x for x in password.split(',')]
5-
for p in items:
6-
if len(p)<6 or len(p)>12:
7-
continue
8-
else:
9-
pass
10-
if not re.search("[a-z]",p):
11-
continue
12-
elif not re.search("[0-9]",p):
13-
continue
14-
elif not re.search("[A-Z]",p):
15-
continue
16-
elif not re.search("[$#@]",p):
17-
continue
18-
elif re.search("\s",p):
19-
continue
20-
else:
21-
pass
22-
value.append(p)
23-
return (",".join(value))
5+
pattern = re.compile(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$#@]).{6,12}$')
6+
7+
if not pattern.match(password):
8+
return "Invalid password. Please try again"
9+
else:
10+
return "Valid password"
11+
12+
13+
print(valid_password("ABd1234@1"))

exercises/37-validity-of-password/test.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,12 @@ def test_function_existence(capsys, app):
88

99
@pytest.mark.it('The function should return the expected output')
1010
def test_expected_output(capsys, app):
11-
assert app.valid_password("ABd1234@1,a F1#,2w3E*,2We3345") == "ABd1234@1"
11+
assert app.valid_password("ABd1234@1") == "Valid password"
1212

1313
@pytest.mark.it('Your solution should work as expected for valid passwords')
1414
def test_expected_another_output(capsys, app):
15-
assert app.valid_password("Lmd4567@2,a F1#,2w3E*,2We3345") == "Lmd4567@2"
15+
assert app.valid_password("Lmd4567@2") == "Valid password"
1616

1717
@pytest.mark.it('Your solution should work as expected when there is no valid password input')
1818
def test_expected_output_no_valid_entries(capsys, app):
19-
assert app.valid_password("ABd12,a F1#,2w3E*,2We3345") == ""
19+
assert app.valid_password("ABd12") == "Invalid password. Please try again"
Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,29 @@
11
# `38` Sort Tuples Ascending
2-
Debe escribir un programa para ordenar las tuplas (nombre, edad, altura) por orden ascendente donde el nombre es `string`, la edad y la altura son `números`.
2+
3+
## 📝 Instrucciones:
4+
5+
Escribe una función llamada `sort_tuples_ascending()` para ordenar las tuplas (`name`, `age`, `score`) en orden ascendente, donde `name`, `age` y `score` son strings. El criterio de orden es:
6+
7+
1. Ordenar según el nombre.
8+
2. Luego, ordenar según la edad.
9+
3. Después, ordenar por puntuación.
10+
11+
La prioridad es `name` > `age` > `score`.
12+
13+
## 📎 Ejemplo de entrada:
14+
15+
```py
16+
sort_tuples_ascending(['Tom,19,80', 'John,20,90', 'Jony,17,91', 'Jony,17,93', 'Jason,21,85'])
17+
```
18+
19+
## 📎 Ejemplo de salida:
20+
21+
```py
22+
[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Jason', '21', '85'), ('Tom', '19', '80')]
23+
```
24+
25+
## 💡 Pistas:
26+
27+
+ Utilizamos `itemgetter` para habilitar múltiples claves de orden.
28+
29+
+ Observa que la salida es una lista con tuplas en su interior.
Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,29 @@
11
# `38` Sort Tuples Ascending
22

3+
## 📝 Instructions:
34

4-
## :pencil: Instructions:
5-
You are required to write a program to sort the (`name`, `age`, `height`) tuples by ascending order where name is `string`, age and height are numbers. The tuples are input by console. The sort criteria is:
5+
Write a function `sort_tuples_ascending()` to sort the (`name`, `age`, `score`) tuples by ascending order, where `name`, `age` and `score` are all strings. The sort criteria is:
66

7-
1. Sort based on name;
8-
2. Then sort based on age;
7+
1. Sort based on name.
8+
2. Then sort based on age.
99
3. Then sort by score.
10-
The priority is that name > age > score.
11-
If the following tuples are given as input to the program:
12-
> - `Tom,19,80`
13-
> - `John,20,90`
14-
> - `Jony,17,91`
15-
> - `Jony,17,93`
16-
> - `Jason,21,85`
17-
18-
> - Then, the output of the program should be:
19-
`[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Jason', '21', '85'), ('Tom', '19', '80')]`
20-
21-
## :bulb: Hint:
22-
In case of input data being supplied to the question, it should be assumed to be a console input.
23-
We use itemgetter to enable multiple sort keys.
10+
11+
The priority is `name` > `age` > `score`.
12+
13+
## 📎 Example input:
14+
15+
```py
16+
sort_tuples_ascending(['Tom,19,80', 'John,20,90', 'Jony,17,91', 'Jony,17,93', 'Jason,21,85'])
17+
```
18+
19+
## 📎 Example output:
20+
21+
```py
22+
[('Jason', '21', '85'), ('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Tom', '19', '80')]
23+
```
24+
25+
## 💡 Hints:
26+
27+
+ We use `itemgetter` to enable multiple sort keys.
28+
29+
+ Notice that the output is a list with tuples inside.

0 commit comments

Comments
 (0)