Skip to content

Commit 8cf8527

Browse files
authored
Merge pull request mouredev#7760 from davidrguez98/main
mouredev#42 - Python
2 parents 82ffd43 + 7c3df0d commit 8cf8527

File tree

3 files changed

+348
-0
lines changed

3 files changed

+348
-0
lines changed
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
""" /*
2+
* EJERCICIO:
3+
* ¡Rubius tiene su propia skin en Fortnite!
4+
* Y va a organizar una competición para celebrarlo.
5+
* Esta es la lista de participantes:
6+
* https://x.com/Rubiu5/status/1840161450154692876
7+
*
8+
* Desarrolla un programa que obtenga el número de seguidores en
9+
* Twitch de cada participante, la fecha de creación de la cuenta
10+
* y ordene los resultados en dos listados.
11+
* - Usa el API de Twitch: https://dev.twitch.tv/docs/api/reference
12+
* (NO subas las credenciales de autenticación)
13+
* - Crea un ranking por número de seguidores y por antigüedad.
14+
* - Si algún participante no tiene usuario en Twitch, debe reflejarlo.
15+
*/
16+
``` """
17+
18+
#EJERCICIO
19+
20+
import env
21+
import requests
22+
23+
CLIENT_ID = env.CLIENT_ID
24+
CLIENT_SECRET = env.CLIENT_SECRET
25+
26+
def get_access_token(client_id: str, client_secret: str) -> str:
27+
28+
url = "https://id.twitch.tv/oauth2/token"
29+
30+
params = {
31+
"client_id": client_id,
32+
"client_secret": client_secret,
33+
"grant_type": "client_credentials"
34+
}
35+
36+
response = requests.post(url, params=params)
37+
return response.json().get("access_token")
38+
39+
def get_user_info(token: str, client_id: str, login: str):
40+
41+
url = "https://api.twitch.tv/helix/users"
42+
43+
headers = {
44+
"Authorization": f"Bearer {token}",
45+
"Client-Id": client_id
46+
}
47+
48+
params = {"login": login}
49+
50+
response = requests.get(url, headers=headers, params=params)
51+
response.raise_for_status()
52+
data = response.json().get("data", None)
53+
54+
55+
if not data:
56+
return None
57+
return data[0]
58+
59+
def get_total_followers(token: str, client_id: str, id: str) -> int:
60+
61+
url = "https://api.twitch.tv/helix/channels/followers"
62+
63+
headers = {
64+
"Authorization": f"Bearer {token}",
65+
"Client-Id": client_id
66+
}
67+
68+
params = {"broadcaster_id": id}
69+
70+
response = requests.get(url, headers=headers, params=params)
71+
response.raise_for_status()
72+
return response.json().get("total", 0)
73+
74+
users = [
75+
"littleragergirl", "ache", "adricontreras4", "agustin51", "alexby11", "ampeterby7", "tvander",
76+
"arigameplays", "arigeli_", "auronplay", "axozer", "beniju03", "bycalitos",
77+
"byviruzz", "carreraaa", "celopan", "srcheeto", "crystalmolly", "darioemehache",
78+
"dheylo", "djmariio", "doble", "elvisayomastercard", "elyas360", "folagorlives", "thegrefg",
79+
"guanyar", "hika", "hiperop", "ibai", "ibelky_", "illojuan", "imantado",
80+
"irinaissaia", "jesskiu", "jopa", "jordiwild", "kenaivsouza", "mrkeroro10",
81+
"thekiddkeo95", "kikorivera", "knekro", "kokoop", "kronnozomberoficial", "leviathan",
82+
"litkillah", "lolalolita", "lolitofdez", "luh", "luzu", "mangel", "mayichi",
83+
"melo", "missasinfonia", "mixwell", "jaggerprincesa", "nategentile7", "nexxuz",
84+
"lakshartnia", "nilojeda", "nissaxter", "olliegamerz", "orslok", "outconsumer", "papigavitv",
85+
"paracetamor", "patica1999", "paulagonu", "pausenpaii", "perxitaa", "nosoyplex",
86+
"polispol1", "quackity", "recuerd0p", "reventxz", "rivers_gg", "robertpg", "roier",
87+
"ceuvebrokenheart", "rubius", "shadoune666", "silithur", "spok_sponha", "elspreen", "spursito",
88+
"bystaxx", "suzyroxx", "vicens", "vitu", "werlyb", "xavi", "xcry", "elxokas",
89+
"thezarcort", "zeling", "zormanworld", "mouredev"
90+
]
91+
users_data = []
92+
not_found_users = []
93+
94+
token = get_access_token(CLIENT_ID, CLIENT_SECRET)
95+
96+
for user_name in users:
97+
98+
user = get_user_info(token, CLIENT_ID, user_name)
99+
100+
if user is None:
101+
not_found_users.append(user_name)
102+
else:
103+
followers = get_total_followers(token, CLIENT_ID, user["id"])
104+
users_data.append({
105+
"user_name": user_name,
106+
"created_at": user["created_at"],
107+
"followers": followers
108+
})
109+
110+
sort_by_followers = sorted(users_data, key=lambda x: x["followers"], reverse=True)
111+
sort_by_date = sorted(users_data, key=lambda x: x["created_at"])
112+
113+
print("Ranking por número de seguidores:")
114+
for id, user, in enumerate(sort_by_followers):
115+
print(f"{id + 1} - {user["user_name"]}: {user["followers"]} seguidores.")
116+
117+
print()
118+
119+
print("Ranking por antiguedad:")
120+
for id, user, in enumerate(sort_by_date):
121+
print(f"{id + 1} - {user["user_name"]}: Creado el {user["created_at"]}.")
122+
123+
print()
124+
125+
if not_found_users:
126+
print("Usuarios no encontrados:")
127+
for user in not_found_users:
128+
print(user)
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
""" /*
2+
* EJERCICIO:
3+
* ¿Has visto la camiseta.rar?
4+
* https://x.com/MoureDev/status/1841531938961592740
5+
*
6+
* Crea un programa capaz de comprimir un archivo
7+
* en formato .zip (o el que tú quieras).
8+
* - No subas el archivo o el zip.
9+
*/ """
10+
11+
#EJERCICIO
12+
13+
import zipfile
14+
import os
15+
16+
def zip_file(path: str, file: str) -> str:
17+
18+
file_path = os.path.join(path, file)
19+
20+
if os.path.exists(file_path):
21+
22+
zip_file = f"{file}.zip"
23+
24+
zip_path = os.path.join(path, zip_file)
25+
26+
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
27+
zipf.write(file_path, file)
28+
print(f"El archivo {file} comprimido como {zip_file}.")
29+
return zip_file
30+
31+
else:
32+
print(f"El archivo {file} no existe en el directorio {path}")
33+
34+
return None
35+
36+
def unzip_file(path: str, file: str):
37+
38+
file_path = os.path.join(path, file)
39+
40+
if os.path.exists(file_path):
41+
42+
zip_path = os.path.join(path, file)
43+
44+
with zipfile.ZipFile(zip_path, "r") as zipf:
45+
zipf.extractall(path)
46+
print(f"El archivo {file} descomprimido en {path}.")
47+
48+
else:
49+
print(f"El archivo {file} no existe en el directorio {path}")
50+
51+
52+
path = os.path.dirname(os.path.abspath(__file__))
53+
file = "Matisseprint3.pdf"
54+
55+
zip = zip_file(path, file)
56+
57+
if zip != None:
58+
59+
os.remove(os.path.join(path, file))
60+
61+
unzip_file(path, zip)
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
""" /*
2+
* EJERCICIO:
3+
* ¡El último videojuego de Dragon Ball ya está aquí!
4+
* Se llama Dragon Ball: Sparking! ZERO.
5+
*
6+
* Simula un Torneo de Artes Marciales, al más puro estilo
7+
* de la saga, donde participarán diferentes luchadores, y el
8+
* sistema decidirá quién es el ganador.
9+
*
10+
* Luchadores:
11+
* - Nombre.
12+
* - Tres atriotasobutos: velocidad, ataque y defensa
13+
* (con valores entre 0 a 100 que tú decidirás).
14+
* - Comienza cada batalla con 100 de salud.
15+
* Batalla:
16+
* - En cada batalla se enfrentan 2 luchadores.
17+
* - El luchador con más velocidad comienza atacando.
18+
* - El daño se calcula restando el daño de ataque del
19+
* atacante menos la defensa del oponente.
20+
* - El oponente siempre tiene un 20% de posibilidad de
21+
* esquivar el ataque.
22+
* - Si la defensa es mayor que el ataque, recibe un 10%
23+
* del daño de ataque.
24+
* - Después de cada turno y ataque, el oponente pierde salud.
25+
* - La batalla finaliza cuando un luchador pierde toda su salud.
26+
* Torneo:
27+
* - Un torneo sólo es válido con un número de luchadores
28+
* potencia de 2.
29+
* - El torneo debe crear parejas al azar en cada ronda.
30+
* - Los luchadores se enfrentan en rondas eliminatorias.
31+
* - El ganador avanza a la siguiente ronda hasta que sólo
32+
* quede uno.
33+
* - Debes mostrar por consola todo lo que sucede en el torneo,
34+
* así como el ganador.
35+
*/ """
36+
37+
#EJERCICIO
38+
39+
import random
40+
41+
class Fighter:
42+
43+
def __init__(self, name: str, speed: int, attack: int, defense: int):
44+
self.name = name
45+
self.speed = speed
46+
self.attack = attack
47+
self.defense = defense
48+
self.health = 100
49+
50+
def reset_health(self):
51+
self.health = 100
52+
53+
def is_alive(self) -> bool:
54+
return self.health > 0
55+
56+
def take_damage(self, damage: int):
57+
58+
attack_damage = 0
59+
60+
if random.random() < 0.2:
61+
print(f"{self.name} ha esquivado el ataque.")
62+
else:
63+
if self.defense >= damage:
64+
attack_damage = damage * 0.1
65+
else:
66+
attack_damage = damage - self.defense
67+
68+
attack_damage = int(attack_damage)
69+
70+
self.health = max(self.health - attack_damage, 0)
71+
print(f"El luchador {self.name} recibe {attack_damage} de daño.")
72+
print(f"Salud restante {self.health}")
73+
74+
class Battle:
75+
76+
def __init__(self, fighter1: Fighter, fighter2: Fighter):
77+
self.fighter1 = fighter1
78+
self.fighter2 = fighter2
79+
80+
def fight(self) -> Fighter:
81+
82+
print(f"\n=== {self.fighter1.name} vs {self.fighter2.name} ===")
83+
84+
while self.fighter1.is_alive() and self.fighter2.is_alive():
85+
86+
if self.fighter1.speed > self.fighter2.speed:
87+
self.turn(self.fighter1, self.fighter2)
88+
if self.fighter2.is_alive():
89+
self.turn(self.fighter2, self.fighter1)
90+
else:
91+
self.turn(self.fighter2, self.fighter1)
92+
if self.fighter1.is_alive():
93+
self.turn(self.fighter1, self.fighter2)
94+
95+
if self.fighter1.is_alive():
96+
print(f"\nEl luchador {self.fighter1.name} ha ganado la batalla.")
97+
return self.fighter1
98+
else:
99+
print(f"\nEl luchador {self.fighter2.name} ha ganado la batalla.")
100+
return self.fighter2
101+
102+
def turn(self, attacker: Fighter, defender: Fighter):
103+
print(f"\n{attacker.name} ataca a {defender.name}")
104+
defender.take_damage(attacker.attack)
105+
106+
class Tournament:
107+
108+
def __init__(self, fighters: list):
109+
if not self.is_power_of_two(len(fighters)):
110+
raise ValueError("El número de luchadores debe de ser una potencia de 2.")
111+
self.fighters = fighters
112+
113+
def start(self):
114+
round = 1
115+
while len(self.fighters) > 1:
116+
117+
print(f"\n=== Ronda: {round} ===")
118+
119+
random.shuffle(self.fighters)
120+
121+
winners = []
122+
123+
for index in range(0, len(self.fighters), 2):
124+
fighter1 = self.fighters[index]
125+
fighter2 = self.fighters[index + 1]
126+
127+
battle = Battle(fighter1, fighter2)
128+
winner = battle.fight()
129+
winners.append(winner)
130+
131+
self.fighters = winners
132+
round += 1
133+
134+
print(f"\nEl ganador del torneo es {self.fighters[0].name}")
135+
136+
def is_power_of_two(self, n) -> bool:
137+
if n <= 0:
138+
return False
139+
while n % 2 == 0:
140+
n //= 2
141+
return n == 1
142+
143+
144+
145+
146+
147+
fighters = [
148+
Fighter("Goku", 90, 95, 80),
149+
Fighter("Vegeta", 95, 90, 82),
150+
Fighter("Piccolo", 80, 85, 90),
151+
Fighter("Freezer", 95, 90, 75),
152+
Fighter("Krillin", 95, 90, 75),
153+
Fighter("Célula", 92, 70, 73),
154+
Fighter("Gohan", 97, 95, 70),
155+
Fighter("Trunks", 88, 88, 88)
156+
]
157+
158+
tournament = Tournament(fighters)
159+
tournament.start()

0 commit comments

Comments
 (0)