Compare commits

...

2 Commits

Author SHA1 Message Date
perro tuerto f167dd7412 Ejercicios 7b-d 2023-04-20 10:56:05 -07:00
perro tuerto 7993456cb4 Algo de formato 2023-04-20 10:08:00 -07:00
16 changed files with 214 additions and 38 deletions

View File

@ -1,9 +1,6 @@
"""
# hello.py
The window that appears should contain a cursor awaiting your input,
but its different from the interactive shell, which runs Python instructions
Python Basics as soon as you press enter.
Your First Program
Page 11
"""
print("Nombre:")

View File

@ -1,16 +1,6 @@
"""
# collatz()
Write a function named collatz() that has one parameter named number. If
number is even, then collatz() should print number / 2 and return this value.
If number is odd, then collatz() should print and return 3 * number + 1.
Then write a program that lets the user type in an integer and that
keeps calling collatz() on that number until the function returns the value 1.
(Amazingly enough, this sequence actually works for any integersooner or
later, using this sequence, youll arrive at 1! Even mathematicians arent sure
why. Your program is exploring whats called the Collatz sequence, sometimes
called the simplest impossible math problem.)
Practice Projects
Page 76
"""
import time

View File

@ -1,3 +1,9 @@
"""
Practice Projects: Comma Code
Page 107
"""
def add(ls):
if len(ls) > 0:
ls = list(map(lambda x: str(x), ls))

View File

@ -1,3 +1,8 @@
"""
Practice Projects: Coin Flip Streaks
Page 107
"""
import random

View File

@ -1,3 +1,8 @@
"""
Practice Projects: Character Picture Grid
Page 108
"""
grid = [
[".", ".", ".", ".", ".", "."],
[".", "0", "0", ".", ".", "."],

View File

@ -1,3 +1,8 @@
"""
Practice Projects: Chess Dictionary Validator
Page 127
"""
import sys
tests = [

View File

@ -1,8 +1,13 @@
"""
Practice Projects: Fantasy Game Inventory
Page 127
"""
import sys
tests = [
{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12},
{'rope': 1, 'torch': 6, 'gold coin': "a", 'dagger': 1, 'arrow': 12},
{"rope": 1, "torch": 6, "gold coin": 42, "dagger": 1, "arrow": 12},
{"rope": 1, "torch": 6, "gold coin": "a", "dagger": 1, "arrow": 12},
None,
]

View File

@ -1,9 +1,14 @@
"""
Practice Projects: List to Dictionary Function for Fantasy Game Inventory
Page 128
"""
import sys
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
dragonLoot = ["gold coin", "dagger", "gold coin", "gold coin", "ruby"]
tests = [
{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12},
{'rope': 1, 'torch': 6, 'gold coin': "a", 'dagger': 1, 'arrow': 12},
{"rope": 1, "torch": 6, "gold coin": 42, "dagger": 1, "arrow": 12},
{"rope": 1, "torch": 6, "gold coin": "a", "dagger": 1, "arrow": 12},
None,
]

View File

@ -1,3 +1,8 @@
"""
Practice Projects: Table Printer
Page 154
"""
tableData = [
["apples", "oranges", "cherries", "banana"],
["Alice", "Bob", "Carol", "David"],

View File

@ -1,3 +1,8 @@
"""
Practice Projects: Zombie Dice Bots
Page 155
"""
import random
import zombiedice

View File

@ -1,6 +1,12 @@
"""
Project: Phone Number and Email Address Extractor
Page 179
"""
import re
import pyperclip
def to_int(string):
string = re.sub(r"\D", "", string)
if string:
@ -8,18 +14,22 @@ def to_int(string):
else:
return None
def rgx_phones():
return re.compile(
r"((\+(\d+)\s*)?(([ |\d|\-|\.|\(|\)]){7,}\d)(\s+ext\S*\s+(\d+))?)", re.I
r"((\+(\d+)\s*)?(([ |\d|\-|\.|\(|\)]){7,}\d)(\s+ext\S*\s+(\d+))?)",
re.I,
)
def rgx_emails():
return re.compile(r"[\w\-]+@[\w\-]+\.\w{2,}", re.I)
def parse_phone(phone):
lbraces = len(re.findall(r'.*\(.*', phone[0]))
rbraces = len(re.findall(r'.*\).*', phone[0]))
if lbraces == rbraces and re.match(r'^[\+|\d]', phone[0]):
lbraces = len(re.findall(r".*\(.*", phone[0]))
rbraces = len(re.findall(r".*\).*", phone[0]))
if lbraces == rbraces and re.match(r"^[\+|\d]", phone[0]):
code = to_int(phone[2])
ext = to_int(phone[6])
res = to_int(phone[3])
@ -28,9 +38,11 @@ def parse_phone(phone):
res = f"{res} ext. {ext}" if ext else res
return res
def get_phones(content):
return list(filter(None, map(parse_phone, rgx_phones().findall(content))))
content = pyperclip.paste()
phones = get_phones(content)
emails = rgx_emails().findall(content)

39
exercises/ex07/ex07b.py Normal file
View File

@ -0,0 +1,39 @@
"""
Project: Date Detection
Page 186
"""
import re
import datetime
tests = """
1/1/1911
02/1/2000
12/12/2012
No 123/1/1911
No 1/123/1911
No 1/1/11
Inválido 32/12/1212
Inválido 3/13/1212
Inválido 3/12/3000
Inválido 3/12/00
Inválido 29/02/2023
"""
def find_date(string):
rgx = re.compile(r"\b(\d{1,2})/(\d{1,2})/(\d{4})")
finds = rgx.findall(string)
dates = []
for find in finds:
d, m, y = int(find[0]), int(find[1]), int(find[2])
if y > 999 and y < 3000:
try:
dates.append(datetime.date(y, m, d).isoformat())
except Exception:
pass
return dates
dates = find_date(tests)
print(dates)

32
exercises/ex07/ex07c.py Normal file
View File

@ -0,0 +1,32 @@
"""
Project: Strong Password Detection
Page 186
"""
import re
tests = [
"",
"a",
"aaaaaaaa",
"AAAAAAAA",
"11111111",
"aAaAaAaA",
"a1a1a1a1",
"A1A1A1A1",
"aA1aA1aA1",
]
def check_pass(string):
withupper = True if re.match(r".*[A-Z]", string) else False
withlower = True if re.match(r".*[a-z]", string) else False
withdigit = True if re.match(r".*\d", string) else False
if len(string) >= 8 and withupper and withlower and withdigit:
print(f"'{string}' is a strong pass")
else:
print(f"'{string}' is NOT a strong pass")
for test in tests:
check_pass(test)

25
exercises/ex07/ex07d.py Normal file
View File

@ -0,0 +1,25 @@
"""
Project: Regex Version of the strip() Method
Page 186
"""
import re
tests = {
"Hola": None,
" Hola ": None,
"bHola": "b",
"\tHola,\tmundo\t": "\t",
}
def rgx_strip(string, char=" "):
string = re.sub(r"^" + char + r"+", "", string)
return re.sub(char + r"+$", "", string)
for key, val in tests.items():
if val is None:
print(f"'{key}' -> '{rgx_strip(key)}'")
else:
print(f"'{key}' -> '{rgx_strip(key, val)}'")

View File

@ -1,29 +1,66 @@
"""
Project: Sandwich Maker
Page 198
"""
import pyinputplus as pyip
prices, order, total = {
"bread": { "wheat": 1.0, "white": .9, "sourdough": 1.1, },
"protein": { "chicken": 1.0, "turkey": 1.1, "ham": .9, "tofu": .8, },
"cheese": { "cheddar": .9, "swiss": 1.0, "mozzarella.": 1.1, }
}, {}, 0
prices, order, total = (
{
"bread": {
"wheat": 1.0,
"white": 0.9,
"sourdough": 1.1,
},
"protein": {
"chicken": 1.0,
"turkey": 1.1,
"ham": 0.9,
"tofu": 0.8,
},
"cheese": {
"cheddar": 0.9,
"swiss": 1.0,
"mozzarella.": 1.1,
},
},
{},
0,
)
def add(key, ismenu=False):
isadd = pyip.inputYesNo(prompt=f"Do you want {key}? [y/n]\n") == "yes"
if isadd and ismenu:
return pyip.inputMenu(list(prices[key].keys()), numbered=True, prompt=f"Please, select {key}:\n")
return pyip.inputMenu(
list(prices[key].keys()),
numbered=True,
prompt=f"Please, select {key}:\n",
)
elif isadd:
return True
else:
return False
order["bread"] = pyip.inputMenu(list(prices["bread"].keys()), numbered=True, prompt="Please, select bread:\n")
order["protein"] = pyip.inputMenu(list(prices["protein"].keys()), numbered=True, prompt="Please, select protein:\n")
order["bread"] = pyip.inputMenu(
list(prices["bread"].keys()),
numbered=True,
prompt="Please, select bread:\n",
)
order["protein"] = pyip.inputMenu(
list(prices["protein"].keys()),
numbered=True,
prompt="Please, select protein:\n",
)
order["cheese"] = add("cheese", True)
order["mayo"] = add("mayo")
order["mustard"] = add("mustard")
order["lettuce"] = add("lettuce")
order["tomato"] = add("tomato")
order["quantity"] = pyip.inputInt(prompt="How many sandwiches? [number]:\n", greaterThan=0)
order["quantity"] = pyip.inputInt(
prompt="How many sandwiches? [number]:\n", greaterThan=0
)
sandwich = "sandwich" if order["quantity"] == 1 else "sandwiches"
print(f"Your order\n{order['quantity']} {sandwich} with:")
@ -39,9 +76,8 @@ for key in order.keys():
else:
print(f"{prompt}NO {key}")
subtotal = round(total * order["quantity"], 2)
taxes = round(subtotal * .16, 2)
taxes = round(subtotal * 0.16, 2)
total = round(subtotal + taxes, 2)
print(f"SUBTOTAL: {subtotal}")
print(f"TAXES: {taxes}")
print(f"TOTAL: {total}")

View File

@ -0,0 +1,4 @@
"""
Project: Write Your Own Multiplication Quiz
Page 199
"""