所以我试图测试是否有回文。这是我的代码:
此函数返回一个较大字符串的前半部分的字符串。(“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
此代码获取两个 3 位数字的每个乘积,并检查它是否是回文
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))
这只是输出每个数字。我测试了每种方法,它们返回的是空字符串。(我假设),这就是为什么每个数字都通过回文检查和打印的原因。