我正在查看长度为4的序列中0和1的所有可能组合。因此,我在数据帧或列表中有2 ^ 4行。 (我不介意格式,只要可以分别查看每个组合)。在这些组合中,我正在搜索特殊的重叠模式。
patterns=["00","101","1100"]
因此,在“ 0000”的第一个组合中,我希望Python告诉我它发现了3个事件(我不在乎这三个事件中的哪个)。
我找到了诸如search()之类的函数,但它们仅给出了全部 16种组合的模式总数,而不是每个模式都单独提供。另外,我无法适应正确的数据样式。尝试过str.count()但即使将数据帧转换为字符串后,再次对我似乎也不起作用。
我能想到的最好的是:
import itertools
sequ=[x for x in itertools.product(states,repeat=n)] #generates all the
possible seq-s of the variable
from re import finditer
patterns=["00","101","1100"]
for match in finditer(patterns, sequ):
print(match.span())
但是,这仅适用于简单模式,例如patterns=["00"]
答案 0 :(得分:3)
def main():
n = int(input("Enter number of digits: "))
for i in range(0, 1<<n):
gray=i^(i>>1)
print ("{:0{}b}".format(gray,n))
main()
#Input: 4
#Output:
#0000
#0001
#0011
#0010
#0110
#0111
#0101
#0100
#1100
#1101
#1111
#1110
#1010
#1011
#1001
#1000
我认为这就是您想要的。
无需为此使用数据框。有点翻转
编辑:
def graylist(n):
outlist = []
for i in range(0, 1<<n):
gray=i^(i>>1)
# print ("{:0{}b}".format(gray,n))
outlist.append('{:0{}b}'.format(gray,n))
return outlist
alist = graylist(4)
def countingpattern(alist, string):
count = 0
for item in alist:
for i in range(len(item)):
if item[i:i+len(string)] == string:
count += 1
return count
print (countingpattern(alist, '00')) #12
print (countingpattern(alist, '101')) #4
print (countingpattern(alist, '1100')) #1
要查看所有模式,我们可以将结果放入字典中。
def countingpatterndict(alist, string):
adict = {}
for item in alist:
count = 0
for i in range(len(item)):
if item[i:i+len(string)] == string:
count += 1
adict[item] = count
return adict
print (countingpatterndict(alist, '00'))
#'0000': 3, '0001': 2, '0011': 1, '0010': 1, ...
print (countingpatterndict(alist, '101'))
#'1110': 0, '1010': 1, '1011': 1, ...
print (countingpatterndict(alist, '111'))
#'1101': 0, '1111': 2, '1110': 1, ...
进一步编辑:
def graylist(n):
outlist = []
for i in range(0, 1<<n):
gray=i^(i>>1)
outlist.append('{:0{}b}'.format(gray,n))
return outlist
def countingpatterndict(alist, string):
adict = {}
for item in alist:
count = 0
for i in range(len(item)):
if item[i:i+len(string)] == string:
count += 1
adict[item] = count
return adict
alist = graylist(20)
import time
import pandas as pd
z1 = time.clock()
df = pd.DataFrame.from_dict(countingpatterndict(alist, '101'), orient='index')
z2 = time.clock() - z1
print (z2) #5.716345938402242 seconds
print (df)
df.to_csv('result.csv')