when the the last index on string has "x" or "X" (It is represent as 10) so if I have something like "1x", which mean 11 (1 + 10)
当字符串的最后一个索引有“x”或“x”(表示为10)时,如果我有“1x”,也就是11 (1 + 10)
def main():
s1 = "013162959x"
partial_sums(s1)
def partial_sums(s1):
lst =[]
sum = 0
for i in range(len(s1)):
if (i == len(s1) -1) and (s1[i] == "x" or "X"):
sum = sum + int(s1[i]) + 10
else:
sum = sum + int(s1[i])
lst.append(sum)
print(lst)
main()
I got an ValueError: invalid literal for int() with base 10: 'x'
我得到了一个ValueError:以10为基数的int()的无效文字。
the output should be [0, 1, 4, 5, 11, 13, 22, 27, 36, 46]
输出应该是[0,1,4,5,11,13,22,27,36,46]
When the string contain No "X" value it work fine.
当字符串不包含“X”值时,它可以正常工作。
def main():
s1 = "0131629592"
partial_sums(s1)
def partial_sums(s1):
lst1 =[]
sum = 0
for i in range(len(s1)):
sum = sum + int(s1[i])
lst1.append(sum)
print(lst1)
main()
How can I fix it?
我怎样才能修好它?
1 个解决方案
#1
1
This statement:
这句话:
if (i == len(s1) -1) and (s1[i] == "x" or "X"):
sum = sum + int(s1[i]) + 10
still calls int
on s1[i]
even though s1[i]
is "x"
. You simply want sum += 10
.
仍然在s1[i]上调用int,尽管s1[i]是“x”。你只要求和+= 10。
However, note that or
doesn't work the way you're using it. To quote the docs, "The expression x or y
first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned." IOW, "a" == "b" or "c"
returns "c"
, not False, and "c"
evaluates as True.
但是,请注意,或者不按照您使用它的方式工作。要引用文档,“表达式x或y首先计算x;如果x为真,则返回其值;否则,将计算y并返回结果值。IOW, "a" = "b"或"c"返回"c",而不是False, "c"的计算结果为True。
Also, since sum
is a really useful builtin, it's probably a bad idea to shadow it with a variable of your own with the same name. total
is often used instead.
另外,由于sum是一个非常有用的内置函数,所以将它与同名的变量进行阴影可能是一个坏主意。total经常被使用。
#1
1
This statement:
这句话:
if (i == len(s1) -1) and (s1[i] == "x" or "X"):
sum = sum + int(s1[i]) + 10
still calls int
on s1[i]
even though s1[i]
is "x"
. You simply want sum += 10
.
仍然在s1[i]上调用int,尽管s1[i]是“x”。你只要求和+= 10。
However, note that or
doesn't work the way you're using it. To quote the docs, "The expression x or y
first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned." IOW, "a" == "b" or "c"
returns "c"
, not False, and "c"
evaluates as True.
但是,请注意,或者不按照您使用它的方式工作。要引用文档,“表达式x或y首先计算x;如果x为真,则返回其值;否则,将计算y并返回结果值。IOW, "a" = "b"或"c"返回"c",而不是False, "c"的计算结果为True。
Also, since sum
is a really useful builtin, it's probably a bad idea to shadow it with a variable of your own with the same name. total
is often used instead.
另外,由于sum是一个非常有用的内置函数,所以将它与同名的变量进行阴影可能是一个坏主意。total经常被使用。