#Could anyone explain how to do this in python?
21 messages · Page 1 of 1 (latest)
That's the basic psuedo code for what you need to do
Just add each of the operations you want to do and then add in the header and column labels
Thank you
Once you've got a solution I can show you how I'd do it 
My brain is so fried, i cant do this
I haven't done python in like 3 or 4 months jesus
haha you don't wanna see the crazy solution I came up with 🤣
I do want to see lmao
||```py
from operator import add, sub, mul
from typing import Generator, Callable, TypeAlias, Sequence
ColumnGenerator: TypeAlias = Generator[int | str, None, None]
RowGenerator: TypeAlias = Generator[ColumnGenerator, None, None]
Operator: TypeAlias = Callable[[int, int], int]
def safe_div(a: int, b: int) -> int | str:
return a // b if b != 0 else "?"
COLUMN_WIDTH = 3
OPERATIONS = {
"+": add,
"-": sub,
"*": mul,
"/": safe_div,
"^": pow,
}
def build_table(size: int, operator: Operator) -> RowGenerator:
for row in range(size):
yield (operator(row, column) for column in range(size))
def format_column(v: int | str) -> str:
f = {
int: f"{COLUMN_WIDTH},",
str: f">{COLUMN_WIDTH}",
}[type(v)]
return f"{v:{f}}"
def render_table(table: RowGenerator, size: int, operation: str):
header = f"{format_column(operation)} | {' '.join(map(format_column, range(size)))}"
print(header)
print("-" * len(header))
for i, row in enumerate(table):
print(f"{format_column(i)} | {' '.join(map(format_column, row))}")
def generate_math_table(size: int, operation: str):
if operation not in OPERATIONS:
raise ValueError(f"Invalid operation {operation!r}")
table = build_table(size, OPERATIONS[operation])
render_table(table, size, operation)
def get_int(message: str) -> int:
value = None
while value is None:
v = input(message)
try:
value = int(v)
except ValueError:
print("{v!r} is not a valid integer")
return value
def get_str(message: str, options: Sequence[str] | None = None) -> str:
value = None
while value is None:
v = input(message).casefold()
if options and v not in options:
print(f"{v!r} is not one of {', '.join(options)}")
else:
value = v
return value
def main():
number = get_int("Enter a number: ")
operator = get_str("Enter an operator: ", OPERATIONS)
generate_math_table(number, operator)
if name == "main":
main()
It's a bit overboard, I don't even think it'd be cheating for you to look at it 🤣
Lets just say i will understand this in a few years...
(I can show you a proper solution at some other point haha)
I really would appreciate a simple solution
||```py
number = int(input("Enter a number: "))
operator = input("Enter an operator: ")
header = f" {operator} | "
for i in range(number):
header += f"{i:3}"
print(header)
print("-" * len(header))
for y in range(number):
row = f"{y:3} | "
for x in range(number):
v = "?"
if operator == "+":
v = x + y
elif operator == "-":
v = x - y
elif operator == "*":
v = x * y
elif operator == "/" and y != 0:
v = int(x / y)
row += f"{v:>3}"
print(row)
Beginner friendly solution for learning purposes haha
Thanks haha
Could you explain how to set up the grid/table itself so i understand for future reference?
A grid is 2d, has width and height, so you need 1 loop that moves one row at a time (height) and runs a second loop that moves one column at a time (width). 2d = 2 loops nested
I just dont understand these lines, header += f"{i:3}", row = f"{y:3} | ", row += f"{v:>3}". What is the purpose of f?, and what is the purpose of the colons and greater signs?
f"..." is for format strings that allow you to insert values into the string.
f"..{example:>3}" this inserts the variable example into the string. The >3 tells it that example should be at least 3 characters wide and should be right (>) aligned.