Arithmetic Arranger 类型错误

huangapple go评论112阅读模式
英文:

Arithmetic Arranger TypeError

问题

在你的代码中,错误的原因是你尝试对字符串进行索引赋值,这是不允许的,因为字符串是不可变的。你可以使用列表来保存你的排列结果,然后将字符串连接起来。以下是修复后的代码:

def arithmetic_arranger(problems, show=True):
    arranged_problems = ["", "", "", ""]

    if len(problems) > 5:
        return "Error: Too many problems."

    for i, ele in enumerate(problems):
        sub = ele.split()
        num1 = sub[0]
        oper = sub[1]
        num2 = sub[2]

        if oper not in "+-":
            return "Error: Operator must be '+' or '-'."

        if not num1.isdigit() or not num2.isdigit():
            return "Error: Numbers must only contain digits."

        if len(num1) > 4 or len(num2) > 4:
            return "Error: Numbers cannot be more than four digits."

        ray = "-"

        maxlen_line = max(len(num1), len(num2)
        ach = maxlen_line + 2

        line_num1 = f"{num1:>{ach}}"
        line_num2 = oper + f"{num2:>{ach-1}}"
        line_rays = ray * ach

        arranged_problems[0] += "    " + line_num1
        arranged_problems[1] += "    " + line_rays
        arranged_problems[2] += "    " + line_num2

        answ = 0
        if oper == "+":
            answ = int(num1) + int(num2)
        else:
            answ = int(num1) - int(num2

        line_answ = f"{str(answ):>{ach}}"
        arranged_problems[3] += "    " + line_answ

    if show:
        arranged_problems = "\n".join(arranged_problems)
    else:
        arranged_problems = "\n".join(arranged_problems[:3])

    return arranged_problems

这个修复后的代码将排列结果保存在列表中,然后将它们连接起来以生成最终的输出。这样就避免了尝试对字符串进行不支持的索引赋值操作。

英文:

I have to build a function that returns an arithmetic arrangement.
Input: arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])
Output:

   32      3801      45      123
+ 698    -    2    + 43    +  49
-----    ------    ----    -----

If the other argument is True, arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"], True):
Output:

  32         1      9999      523
+  8    - 3801    + 9999    -  49
----    ------    ------    -----
40     -3800     19998      474

I made this one:

def arithmetic_arranger(problems, show = True):
#["1 + 3", "1 - a", "1 * 4"]
arranged_problems = []
#too many problems supplied
if len(problems)>5:
return "Error: Too many problems."
for i, ele in enumerate(problems):
sub = ele.split()
num1 = sub[0]
oper = sub[1]
num2 = sub[2]
#appropriate operators "+","-"
if sub[1] not  in "-+":
return "Error: Operator must be '+' or '-'."
#only contain digits
if sub[0].isdigit() and sub[2].isdigit() is False:
return "Error: Numbers must only contain digits."
#max 4 digits
if len(sub[0])>4 or len(sub[2])>4:
return "Error: Numbers cannot be more than four digits."
ray = "-"
maxlen_line = max(len(num1), len(num2))
ach = maxlen_line + 2
line_num1 = f"{num1:>{ach}}"
line_num2 = oper + f"{num2:>{ach-1}}"
line_rays = ray*ach
try:
arranged_problems[0] += (" "*4) + line_num1
except IndexError:
arranged_problems.append(line_num1)
try:
arranged_problems[1] += (" "*4) + line_rays
except IndexError:
arranged_problems.append(line_rays)
try:
arranged_problems[2] += (" "*4) + line_num2
except IndexError:
arranged_problems.append(line_num2)
answ = 0 
if oper == "+":
answ = int(num1) + int(num2)
else:
answ = int(num1) - int(num2)
line_answ = f"{str(answ):>{ach}}"
try:
arranged_problems[3] += (" "*4) + line_answ
except IndexError:
arranged_problems.append(line_answ)
if show == True:
arranged_problems = f"{arranged_problems[0]}\n{arranged_problems[1]}\n{arranged_problems[2]}\n{arranged_problems[3]}"
else:
arranged_problems = f"{arranged_problems[0]}\n{arranged_problems[1]}\n{arranged_problems[2]}"
return arranged_problems

And this my result:

Traceback (most recent call last):
File "/home/runner/boilerplate-arithmetic-formatter/main.py", line 7, in <module>
print(arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]))
File "/home/runner/boilerplate-arithmetic-formatter/arithmetic_arranger.py", line 32, in arithmetic_arranger
arranged_problems[0] += (" "*4) + line_num1
TypeError: 'str' object does not support item assignment

I do not understand why because in arranged_problems[0] each argument is a str.

Thanks!

答案1

得分: 0

当您到达第54-57行时:

    if show == True:
      arranged_problems = f"{arranged_problems[0]}\n{arranged_problems[1]}\n{arranged_problems[2]}\n{arranged_problems[3]}"
    else:
      arranged_problems = f"{arranged_problems[0]}\n{arranged_problems[1]}\n{arranged_problems[2]}"

您将arranged_problems分配为字符串。此后,它不再是一个列表。在下一个循环迭代期间,您到达第32行:

arranged_problems[0] += (" " * 4) + line_num1

这一行试图重新分配字符串的字符数组中的值。由于字符串是不可变的,这将引发错误。(" " * 4) + line_num1 部分可以正常评估为一个字符串,但一旦arranged_problems变成一个字符串,您就无法对其进行重新分配。

要解决此问题,您需要更改第54-57行的分配,以便不覆盖arranged_problems为一个字符串。

英文:

When you get to line 54-57:

    if show == True:
arranged_problems = f"{arranged_problems[0]}\n{arranged_problems[1]}\n{arranged_problems[2]}\n{arranged_problems[3]}"
else:
arranged_problems = f"{arranged_problems[0]}\n{arranged_problems[1]}\n{arranged_problems[2]}"

You are assigning arranged_problems as a string. It is no longer a list after this. During the next loop iteration, you then get to line 32:

arranged_problems[0] += (" "*4) + line_num1

which tries to reassign a value in the string's character array. As strings are immutable, this throws that error. The (" "*4) + line_num1 section can evaluate to a string fine, but once arranged_problems is a string you can't assign into it.

To fix this, you need to change the assignment at lines 54-57 so that you aren't overwriting arranged_problems with a string.

huangapple
  • 本文由 发表于 2023年2月10日 13:08:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75407182.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定