forked from mouredev/retos-programacion-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request mouredev#6468 from Paula2409/main
Reto mouredev#8 - Python
- Loading branch information
Showing
8 changed files
with
329 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
"""/* | ||
* Llamar a una API es una de las tareas más comunes en programación. | ||
* | ||
* Implementa una llamada HTTP a una API (la que tú quieras) y muestra su | ||
* resultado a través de la terminal. Por ejemplo: Pokémon, Marvel... | ||
* | ||
* Aquí tienes un listado de posibles APIs: | ||
* https://github.com/public-apis/public-apis | ||
*/ | ||
""" | ||
import requests | ||
|
||
def request_http(): | ||
request = requests.get('https://developer.oxforddictionaries.com/') | ||
print(request.status_code) # prints 200 (ok) | ||
print(request.headers) # print(headers of API) | ||
print(request.json) # <bound method Response.json of <Response [200]>> | ||
print(request.text) # text HTML and CSS | ||
|
||
request_http() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
""" | ||
/* | ||
* Dada una URL con parámetros, crea una función que obtenga sus valores. | ||
* No se pueden usar operaciones del lenguaje que realicen esta tarea directamente. | ||
* | ||
* Ejemplo: En la url https://retosdeprogramacion.com?year=2023&challenge=0 | ||
* los parámetros serían ["2023", "0"] | ||
*/ | ||
""" | ||
|
||
def url_params(url): | ||
parameters = [] | ||
|
||
url_parameters = url.split("?") | ||
print(url_parameters) | ||
|
||
url_parameters.remove(url_parameters[0]) | ||
url_parameters = "".join(url_parameters).split("&") | ||
print(url_parameters) | ||
|
||
for param,values in enumerate(url_parameters): | ||
for value in values: | ||
if value == "=": | ||
parameters.append(values[values.index(value)+1::]) | ||
print(parameters) | ||
|
||
url_params("https://retosdeprogramacion.com?year=2023&challenge=0") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
""" | ||
* Crea una función que sea capaz de detectar si existe un viernes 13 en el mes y el año indicados. | ||
* - La función recibirá el mes y el año y retornará verdadero o falso. | ||
""" | ||
|
||
from datetime import date, time, datetime | ||
|
||
def friday_thirteen(): | ||
""" | ||
This function takes a month and a year and determines if there was a 13 friday. | ||
Args: | ||
month(str): any month | ||
year(str): any year | ||
Returns: | ||
bool: returns if it had been a 13 friday at that date. | ||
""" | ||
month = input("Ingrese un mes (mm): ") | ||
year = input("Ingrese un año (yyyy): ") | ||
|
||
if len(month) == 2 and len(year) == 4: | ||
date_check = datetime.strptime('13'+month+year, '%d%m%Y') | ||
weekday = date_check.weekday() # returns the number of the week day. Starts at monday with '0' | ||
|
||
if weekday == 4: | ||
return True | ||
return False | ||
else: | ||
print("Las fechas no son validas") | ||
|
||
print(friday_thirteen()) |
81 changes: 81 additions & 0 deletions
81
Retos/Reto #13 - ADIVINA LA PALABRA [Media]/python/Paula2409.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
""" | ||
/* | ||
* Crea un pequeño juego que consista en adivinar palabras en un número máximo de intentos: | ||
* - El juego comienza proponiendo una palabra aleatoria incompleta | ||
* - Por ejemplo "m_ur_d_v", y el número de intentos que le quedan | ||
* - El usuario puede introducir únicamente una letra o una palabra (de la misma longitud que | ||
* la palabra a adivinar) | ||
* - Si escribe una letra y acierta, se muestra esa letra en la palabra. Si falla, se resta | ||
* uno al número de intentos | ||
* - Si escribe una resolución y acierta, finaliza el juego, en caso contrario, se resta uno | ||
* al número de intentos | ||
* - Si el contador de intentos llega a 0, el jugador pierde | ||
* - La palabra debe ocultar de forma aleatoria letras, y nunca puede comenzar ocultando más del 60% | ||
* - Puedes utilizar las palabras que quieras y el número de intentos que consideres | ||
*/ | ||
""" | ||
import random | ||
def process_word(): | ||
""" | ||
A word guessing game where the player can guess letters or the | ||
whole word with limited attempts. | ||
Args: | ||
None | ||
Returns: | ||
None | ||
""" | ||
words = ['teclado', 'anteojos','monitor', 'calefactor','edificio','cinturon', | ||
'boligrafo','habitacion','libros','persona','planeta','televisor','telefono','direccion'] | ||
|
||
hidden_letters = [] | ||
new_word_to_guess = word_to_guess = random.choice(words) | ||
quantity_letters_to_hide = int(len(new_word_to_guess)*0.6) | ||
list_positions = [quantity_letters for quantity_letters in range(quantity_letters_to_hide)] | ||
while len(list_positions) != 0: | ||
letter_to_hide = random.randrange(len(new_word_to_guess)) | ||
if letter_to_hide not in hidden_letters: | ||
hidden_letters.append(letter_to_hide) | ||
list_positions.pop() | ||
for position in hidden_letters: | ||
new_word_to_guess = new_word_to_guess.replace(new_word_to_guess[position],"_",1) | ||
return [new_word_to_guess,word_to_guess] | ||
|
||
def guess_word(): | ||
new_word_to_guess = process_word()[0] | ||
word_to_guess = process_word()[1] | ||
intentos = 5 | ||
while intentos != 0: | ||
print("""Escriba la opcion: | ||
1. Adivinar por letra | ||
2. Adivinar por palabra | ||
3. Volver a empezar | ||
4. Salir | ||
""") | ||
option = input() | ||
while option != 4: | ||
if option == 1: | ||
guess = input("Escriba la letra: ") | ||
if guess in word_to_guess: | ||
new_word_to_guess.replace("_",guess) | ||
print(f"La palabra es: {new_word_to_guess}") | ||
else: | ||
print(f"Lo siento. Esa letra no esta en la palabra. La palabra es: {new_word_to_guess}") | ||
intentos -= 1 | ||
elif option == 2: | ||
guess = input("Escriba la palabra: ") | ||
if guess == word_to_guess: | ||
print(f"Bien! La palabra es: {word_to_guess}") | ||
else: | ||
print(f"Lo siento, esa no es la palabra") | ||
intentos -= 1 | ||
elif option == 3: | ||
guess_word() | ||
if "_" not in new_word_to_guess: | ||
print(f"Has adivinado la palabra, es: {new_word_to_guess}") | ||
|
||
print(f"No ha podido adivinar la palabra: {word_to_guess}") | ||
|
||
print(process_word()) | ||
guess_word() |
41 changes: 41 additions & 0 deletions
41
Retos/Reto #14 - OCTAL Y HEXADECIMAL [Fácil]/python/Paula2409.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
""" | ||
/* | ||
* Crea una función que reciba un número decimal y lo trasforme a Octal | ||
* y Hexadecimal. | ||
* - No está permitido usar funciones propias del lenguaje de programación que | ||
* realicen esas operaciones directamente. | ||
*/ | ||
""" | ||
def octal_hexadecimal(number): | ||
table_hexa = {'10':'A', '11':'B', '12':'C', '13':'D', '14':'E', '15':'F'} | ||
number_octal,number_hexa = number,number | ||
result_octal, result_hexa = [],[] | ||
|
||
''' Calculate Octal number''' | ||
while number_octal > 0: | ||
result_octal.append(str(number_octal % 8)) | ||
number_octal = number_octal // 8 | ||
|
||
octal = "".join(result_octal[::-1]) | ||
|
||
''' Another way to return ''' | ||
# for digit in result_octal[::-1]: | ||
# octal += str(digit) | ||
|
||
'''Calculate Hexadecimal number ''' | ||
while number_hexa > 0: | ||
if str(number_hexa % 16) in table_hexa: | ||
result_hexa.append(table_hexa[str(number_hexa % 16)]) | ||
else: | ||
result_hexa.append(str(number_hexa % 16)) | ||
number_hexa = number_hexa // 16 | ||
|
||
hexadecimal = "".join(result_hexa[::-1]) | ||
|
||
if number == 0: | ||
octal,hexadecimal = 0,0 | ||
return f"The number {number} in octal is: {octal} and in hexadecimal is: {hexadecimal}" | ||
|
||
print(octal_hexadecimal(0)) | ||
print(octal_hexadecimal(100)) | ||
print(octal_hexadecimal(1000)) |
52 changes: 52 additions & 0 deletions
52
Retos/Reto #6 - PIEDRA, PAPEL, TIJERA, LAGARTO, SPOCK [Media]/python/Paula2409.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
""" | ||
/* | ||
* Crea un programa que calcule quien gana más partidas al piedra, | ||
* papel, tijera, lagarto, spock. | ||
* - El resultado puede ser: "Player 1", "Player 2", "Tie" (empate) | ||
* - La función recibe un listado que contiene pares, representando cada jugada. | ||
* - El par puede contener combinaciones de "🗿" (piedra), "📄" (papel), | ||
* "✂️" (tijera), "🦎" (lagarto) o "🖖" (spock). | ||
* - Ejemplo. Entrada: [("🗿","✂️"), ("✂️","🗿"), ("📄","✂️")]. Resultado: "Player 2". | ||
* - Debes buscar información sobre cómo se juega con estas 5 posibilidades. | ||
*/ | ||
""" | ||
game_rules = { | ||
'🗿': ['🦎','✂️'], # rock crushes lizard and scissors | ||
'📄': ['🗿','🖖'], # paper covers rock and invalidates spock | ||
'✂️': ['📄','🦎'], # scissors cuts paper and beheads lizard | ||
'🦎': ['🖖', '📄'], # lizard poison spock and eats paper | ||
'🖖': ['✂️', '🗿'] # spock breaks scissors and crushes rock | ||
} | ||
|
||
def rock_paper_scissors(play): | ||
""" | ||
Determines the winner of a game based on the rules of | ||
'rock, paper, scissors, lizard, spock'. | ||
Args: | ||
play(list): a list with the option of each player | ||
Returns: | ||
str: returns which player wins | ||
""" | ||
points_player1, points_player2 = 0,0 | ||
index_play = 0 | ||
while index_play < len(play): | ||
if play[index_play][0] in game_rules[play[index_play][1]]: | ||
points_player2 += 1 | ||
print(f'Points player 2: {points_player2}') | ||
else: | ||
points_player1 += 1 | ||
print(f'Points player 1: {points_player1}') | ||
|
||
index_play += 1 | ||
if points_player1 > points_player2: | ||
return 'Player 1' | ||
elif points_player2 > points_player1: | ||
return 'Player 2' | ||
else: | ||
return 'Tie' | ||
|
||
print(rock_paper_scissors([("🗿","✂️"), ("✂️","🗿"), ("📄","✂️")])) | ||
|
||
|
5 changes: 5 additions & 0 deletions
5
Retos/Reto #8 - EL GENERADOR PSEUDOALEATORIO [Media]/python/Paula2409.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
import datetime | ||
|
||
now = datetime.datetime.now().microsecond | ||
print(now) | ||
print(now%101) |
70 changes: 70 additions & 0 deletions
70
Retos/Reto #9 - HETEROGRAMA, ISOGRAMA Y PANGRAMA [Fácil]/python/Paula2409.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
""" | ||
/* | ||
* Crea 3 funciones, cada una encargada de detectar si una cadena de | ||
* texto es un heterograma, un isograma o un pangrama. | ||
* - Debes buscar la definición de cada uno de estos términos. | ||
*/ | ||
""" | ||
import string | ||
|
||
def evaluate_text(): | ||
""" | ||
The function evaluates whether a given text is a heterogram, isogram, or pangram based on the | ||
occurrence of letters in the text. | ||
Args: | ||
text (str): any text given by user | ||
Returns: | ||
str: returns if the text is a heterogram, an isogram and a pangram. | ||
""" | ||
# Input a word or phrase | ||
text = input("Ingrese un texto o palabra para evaluar: ") | ||
# Process the input | ||
new_text = text.lower().replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u').replace(' ', '') | ||
simbols = string.punctuation | ||
|
||
letters_present = {} | ||
|
||
for char in new_text: | ||
if char in simbols: | ||
new_text = new_text.replace(char, "") | ||
else: | ||
if char in letters_present: | ||
letters_present[char] += 1 | ||
else: | ||
letters_present[char] = 1 | ||
|
||
values = list(letters_present.values()) | ||
|
||
def is_heterogram(): | ||
# Heterogram: is a word, phrase or sentence in which no letter of the alphabet occurs more than once. | ||
if len(set(values)) == 1: | ||
return f"The text '{text}' is a heterogram" | ||
else: | ||
return f"The text '{text}' is not a heterogram" | ||
|
||
|
||
def is_isogram(): | ||
# Isogram: word or phrase in which each letter occurs the same number of times. | ||
for value in values: | ||
if value != values[0]: | ||
return f"The text '{text}' is an Isogram" | ||
return f"The text '{text}' is not an Isogram" | ||
|
||
def is_pangrama(): | ||
# Pangrama: word, phrase or sentence in which all letters of the alphabet are present. | ||
letters = list(string.ascii_lowercase) + ['ñ'] | ||
for letter in letters: | ||
if letter in text: | ||
letters.remove(letter) | ||
if len(letters) == 0: | ||
return f"The text '{text}' is a pangram" | ||
else: | ||
return f"The text '{text}' is not a pangram" | ||
|
||
print(is_heterogram()) | ||
print(is_isogram()) | ||
print(is_pangrama()) | ||
|
||
evaluate_text() |