For this project, I am trying to arrange the input from this function:
arithmetic_arranger(["32 8", "1 - 3801", "9999 9999", "523 - 49"])
So it looks like this:
32 1 9999 523
8 - 3801 9999 - 49
---- ------ ------ -----
40 -3800 19998 474
There are four spaces in between each problem. By my results keep printing like this:
32
698
-----
730, 3801
- 2
------
3799, 45
43
----
88, 123
49
-----
172,
This is my code:
def arth(x, solve):
fnlStr = ""
for item in x:
arth = item.split()
val1 = int(arth[0])
val2 = int(arth[2])
len1 = len(arth[0])
len2 = len(arth[2])
if arth[1] == " ":
sum = val1 val2
else:
sum = val1 - val2
if(len1 > len2):
dash = len1 2
else:
dash = len2 2
def strCrt(x, y, s):
return(x.ljust(y, s))
String = ""
numL1 = dash - len1
numL2 = dash - (len2 1)
numL3 = dash - len(str(sum))
lineStr = strCrt(String, dash, "-")
spaceL1 = strCrt(String, numL1, " ")
spaceL2 = strCrt(String, numL2, " ")
spaceL3 = strCrt(String, numL3, " ")
fnlStr = (f"{spaceL1}{val1}\n{arth[1]}{spaceL2}{val2}\n{lineStr}\n{spaceL3}{sum},")
return(fnlStr)
print(arth(["32 698", "3801 - 2", "45 43", "123 49"], True))
The problem may start from how I return the string at the bottom, so I tried this:
fnlArr.append(f"{spaceL1}{val1}\n{arth[1]}{spaceL2}{val2}\n{lineStr}\n{spaceL3}{sum},")
return(fnlArr)
print(arth(["32 698", "3801 - 2", "45 43", "123 49"], True))
But that still gave me some problems, returning this:
[' 32\n 698\n-----\n 730,', ' 3801\n- 2\n------\n 3799,', ' 45\n 43\n----\n 88,', ' 123\n 49\n-----\n 172,']
How should I change up my code so it arranges the problems side by side and not below eachother or formatted wierd in a list? Any help would be greatly appriciated, i'm sorry for any simple errors in my code, I am very new. Thank you.
CodePudding user response:
You can create a list where you put the split expression (using str.split(maxsplit=1)
), the ---
-part and the result.
Then you can transpose this list (using zip(*...)
) and print it line-by-line:
def arithmetic_arranger(exprs):
out = []
for e in exprs:
e = e.split(maxsplit=1)
max_len = len(max(e, key=len))
out.append(
[f"{ee:>{max_len}}" for ee in e ["-" * max_len, eval("".join(e))]]
)
for row in zip(*out):
print(" ".join(row))
arithmetic_arranger(["32 8", "1 - 3801", "9999 9999", "523 - 49"])
Prints:
32 1 9999 523
8 - 3801 9999 - 49
--- ------ ------ ----
40 -3800 19998 474
CodePudding user response:
def arithmetic_arranger(exprs): out = [] for e in exprs: e = e.split(maxsplit=1) max_len = len(max(e, key=len)) out.append( [f"{ee:>{max_len}}" for ee in e ["-" * max_len, eval("".join(e))]] )
for row in zip(*out):
print(" ".join(row))
arithmetic_arranger(["32 8", "1 - 3801", "9999 9999", "523 - 49"])