我正在尝试测试某个字符串是否是回文。以下是我的代码:
这个函数返回一个较长字符串的前半部分。 (“TEST”返回“TE”,“HELLO”返回“HE”)
def takeStart(s):
start = ""
# The following determines the final index of the first half
if len(s)%2==0:
a = (len(s)/2)-1
else:
a = ((len(s)-1)/2)-1
for i in range(a):
start+=s[i]
return start
这个函数返回一个字符串的后半部分。("TEST" 返回 "ST", "HELLO" 返回 "LO")
def takeEnd(s):
end = ""
# The following determines the beginning index of the second half
if len(s)%2==0:
a = (len(s)/2)
else:
a = ((len(s)-1)/2)
for i in range(a,len(s)):
end+=s[i]
return end
这个函数可以翻转一个字符串。("TEST" 翻转后为 "TSET","HELLO" 翻转后为 "OLLEH")
def flip(s):
flipped = ""
for i in range(1,len(s)):
flipped+=s[len(s)-i]
flipped+=s[0]
return flipped
这段代码会计算两个三位数相乘的结果,并检查该结果是否为回文数。
for i in range(100,1000):
for q in range(100,1000):
a = i*q
if takeStart(str(a)) == flip(takeEnd(str(a))):
print(str(a))
当运行此代码时,它输出:
Traceback (most recent call last):
File "[redacted]", line 39, in <module>
if takeStart(str(a)) == flip(takeEnd(str(a))):
File "[redacted]", line 14, in takeStart
for i in range(a):
TypeError: 'float' object cannot be interpreted as an integer
好的,我认为只需要将a转换为整数就可以了。
这样做似乎移除了所有错误,但是没有任何输出。(偶尔会有新行出现,这让我觉得代码在运行但没有输出数据)
有什么想法吗?为什么会这样?
更新:我的代码现在是:
def takeStart(s):
start = ""
if len(s)%2==0:
a = (len(s)//2)
else:
a = (len(s)-1)//2
return start[0:a]
def takeEnd(s):
end = ""
if len(s)%2==0:
a = (len(s)//2)
else:
a = ((len(s)-1)//2)
return end[int(a):len(s)]
def flip(s):
return s[::-1]
for i in range(100,1000):
for q in range(100,1000):
a = i*q
if takeStart(str(a)) == flip(takeEnd(str(a))):
print(str(a))
这只是输出每一个数字。 我测试了每种方法,它们都返回空字符串。(我猜的),这就是为什么每个数字都通过了回文检查并被打印出来。
a
由于除法运算的结果而变成了float
...你可以使用//
强制进行整数除法,但我还没有想太多这是否是你想要做的...正如@abarnet所提到的-有更简单的方法来完成这个(看起来像一个欧拉挑战...) - Jon Clements