1
def findLongRepeats(strToSearch):
"""Search strTosearch to find the first location of longest repeated string
of a single digit e.g '1111'. Do this for each digit from 0 to 9"""
numbers = ['0','1','2','3','4','5','6','7','8','9']
for number in numbers: #reads a number line one at time
number_count = 0 #sets the count to 0
number = int(number)
longrepeats = [] #creates a new list
for x in strToSearch: #reads each digit one by one
if x == number: #if x is true it will add 1 to the number count
number_count += 1
if x != number: # if x is not flase it will add number count into the long repeat list
longrepeats.append(number_count)
number_count = 0
print "Found", max(longrepeats), number+'\'s in a row at character position', strToSearch.index(number*max(longrepeats))
def main():
"""DocT"""
File = open("pidigits.txt","rU") #opens file for reading
Thousand_String = 0
strLine =''
for line in File: #reads each line
line = line.strip()
if '3.' in line:
line = line.replace('3.','')
Thousand_String += len(line)
strLine += str(line)
#print line
#File.close()
print
print "Number of pi digits to process:",Thousand_String
print
findLongRepeats(strLine)
print line
main()
「的時候,當我運行的功能findLong重複 - 得到這個錯誤:類型錯誤:不支持的操作數類型(S)爲+:「詮釋」和「海峽」努力「打印」
File "PA5_.py", line 53, in main
findLongRepeats(strLine)
**File "PA5_.py", line 18, in findLongRepeats
print "Found", max(longrepeats), number+'\'s in a row at character position', strToSearch.index(number*max(longrepeats))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
。
我無法弄清楚如何修正這個錯誤,請幫助
如果OP實際上希望數字是一個整數,這是一個比我更好的答案,但我非常肯定,首先將int轉換爲int是不必要的。這就是說,即使沒有投射到int一些不錯的格式仍然會更好。 – 2012-04-09 01:46:38
@NolenRoyalty正確的,即使他想插入字符串到字符串,他仍然應該使用字符串格式。 – agf 2012-04-09 01:49:41
感謝您的快速回復,我會嘗試一下。我剛剛發佈了輸出,因此您可以更好地瞭解此代碼假設要生成的內容。 – 2012-04-09 02:10:00