使用子字符串搜索元素

时间:2019-12-02 04:02:22

标签: python string binary substring

我正在尝试模拟一个游戏,在其中我们通过询问选定的元素是否具有某些子字符串来搜索选定的元素。搜索集是一定长度k的所有二进制字符串。我们可以询问它是否具有某个子字符串。目的是使用尽可能少的问题来猜测所选元素。我的代码应该这样做的方法是选择出现在尽可能接近整个搜索集一半的子字符串,然后删除该子集或除该子集以外的所有内容。我正在搜索所有子字符串。当我运行代码时,会发生以下错误:

Traceback (most recent call last):
  File "main.py", line 50, in <module>
    print(playtime(1))
  File "main.py", line 44, in playtime
    y = playermove(parameter, x)
  File "main.py", line 24, in playermove
    checkmovelist = [abs(1/2 - i/(2**j)) for i in binlist]
  File "main.py", line 24, in <listcomp>
    checkmovelist = [abs(1/2 - i/(2**j)) for i in binlist]
TypeError: unsupported operand type(s) for /: 'str' and 'int'

当我摆脱playtime()函数时,代码将正确编译。但是,我似乎找不到该函数中的任何错误。有什么想法吗? (此外,我尝试使用有关调试代码的链接,但仍然找不到该错误)。

import itertools
def binaryseq(k):
  return ["".join(seq) for seq in itertools.product("01", repeat=k)]

def substringcounter(n,m):
  count = 0
  for i in binaryseq(m):
    if i.find(n) >= 0:
      count = count + 1
  return count

def initparameterset(l):
  #initial parameter setup
  movelist = []
  sublist = []
  for j in range (1,l+1):
    for p in binaryseq(j):
      movelist.append((substringcounter(p,l))) 
      sublist.append(p)
  return sublist

#playermove
def playermove(binlist,j):
  checkmovelist = [abs(1/2 - i/(2**j)) for i in binlist]
  s = checkmovelist.index(min(checkmovelist))
  return binlist[s]
  #computer response

#in sim respone
def elim(alist, string1):
  blist = alist.copy()
  for i in alist:
    if i.find(string1) >= 0:
      alist.pop(i)
  if len(alist) >= 0.5 * len(blist):
    return alist
  else:
    return blist

def playtime(x):
  parameter = initparameterset(x).copy()
  gamecount = 1
  while(len(parameter) > 0):
    y = playermove(parameter, x)
    elim(parameter,y)
    parameter = elim(parameter,y)
    gamecount += 1
  return gamecount

print(playtime(1))

0 个答案:

没有答案