#Could anyone explain how to do this in python?

21 messages · Page 1 of 1 (latest)

cinder holly
#
for x in range number
    for y in range number
        if operation is +
            v = x + y
        print v
#

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

balmy roost
#

Thank you

cinder holly
#

Once you've got a solution I can show you how I'd do it wolfwink

balmy roost
#

My brain is so fried, i cant do this

#

I haven't done python in like 3 or 4 months jesus

cinder holly
#

haha you don't wanna see the crazy solution I came up with 🤣

balmy roost
#

I do want to see lmao

cinder holly
#

||```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 🤣

balmy roost
#

Lets just say i will understand this in a few years...

cinder holly
#

(I can show you a proper solution at some other point haha)

balmy roost
#

I really would appreciate a simple solution

cinder holly
#

||```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
balmy roost
#

Thanks haha

#

Could you explain how to set up the grid/table itself so i understand for future reference?

cinder holly
#

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

balmy roost
#

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?

cinder holly
#

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.