我正在嘗試編寫一個函數,它接收浮點數列表並確定該列表中是否存在重複的數字序列。如果有重複序列,則按照該序列計算數字。Python:查找浮點數字串中重複數字序列的長度
這些例子是什麼,我想我的功能做
例1:
function = '1.0 8.0 4.0 2.0 1.0 8.0 4.0 2.0 1.0 8.0 4.0 2.0 1.0 8.0'
result = find_repeating_sequence(function)
# repeating sequence = 1.0, 8.0, 4.0, 2.0
# so result should equal 4 in this case
例2:
function = '1.0 8.0 4.0 1.0 2.0 1.0 8.0 4.0 1.0 2.0 1.0 8.0'
result = find_repeating_sequence(function)
# repeating sequence = 1.0, 8.0, 4.0, 1.0, 2.0
# so result should equal 5 in this case
例3:
function = '1.0 8.0 4.0 2.0 1.0 7.0 6.0 3.0 2.0 5.0 9.0'
result = find_repeating_sequence(function)
# repeating sequence doesn't exist
# so result should equal None in this case
例4 :
function = '1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0'
result = find_repeating_sequence(function)
# repeating sequence = 1.0, 11.0
# so result should equal 2 in this case
到目前爲止,我所得到的是:
def find_repeating_sequence(function):
regex = re.compile(r'(.+ .+)(\1)+')
match = regex.search(function)
result = match
if result == None:
print "There was no repeating sequence found!"
else:
print "Repeating sequence found!"
print match.group(1)
result = match.group(1)
return result
這適用於在這個意義上,match.group(1)
給人的重複序列的例子。但由於某些原因len(match.group(1))
不會返回正確的數字。
例如像1:
print match.group(1)
給1.0 8.0 4.0 2.0
但print len(match.group(1))
給15
而且它不會爲示例4返回正確的值: print match.group(1)
給1.0 11.0 1.0 11.0 1.0 11.0 1.0 11.0
而且print len(match.group(1))
給出35
我在做什麼錯?
UPDATE:
由於其中一個答案下面我以LEN(match.group(1).split())
但是出於某種原因,如果 解決print len(match.group(1))
問題function = 1.0 2.0 4.0 8.0 1.0 2.0 4.0 8.0 1.0 2.0 4.0 8.0 1.0 2.0 4.0 8.0
print match.group(1)
給出1.0 2.0 4.0 8.0 1.0 2.0 4.0 8.0
和不1.0 2.0 4.0 8.0
1.0 8.0 4.0 2.0 1.0 8.0 4。您的搜索字符串中不包含0 2.0,您是否混合了這些數字? – radicarl
@radicarl道歉,是的,我複製了錯誤的號碼。我現在糾正了這個問題中的錯誤。 – Catherine