如何使用上一个和下一个字母作为可能的一对来计算彼此相邻的对

时间:2018-05-29 16:07:32

标签: python string counter

这是我的代码。

def count_pairs( s ):
  paired = 0
  unpaired = set(s)
  print unpaired
  for x in unpaired:
    paired = paired + s.count (x + x)
  return paired


print ( count_pairs("ddogccatppig") )
print ( count_pairs("dogcatpig") )
print ( count_pairs("xxyyzz") )
print ( count_pairs("a") )
print ( count_pairs("abc") )
print ( count_pairs("aabb") )
print ( count_pairs("dogcatpigaabbcc") )
print ( count_pairs("aabbccdogcatpig") )
print ( count_pairs("dogabbcccatpig") )
print ( count_pairs("aaaa") )
print ( count_pairs("AAAAAAAAA") )

我希望能够在不使用set命令的情况下获取对,并计算count_pairs和下一个字母的最后一个字母。

2 个答案:

答案 0 :(得分:0)

您正在寻找非重叠重复字母的计数,这是str.count返回的内容。您可以通过while循环复制此内容,以避免setstr.count

def count_pairs(s):
    c = 0
    i = 0
    while i < len(s)-1:
        if s[i] == s[i+1]:
            c += 1
            i += 2
        else:
            i += 1
    return c

答案 1 :(得分:0)

递归解决方案

def count_pairs (s):
  def loop (pairs, x, y = None, *rest):
    if y is None:
      return pairs
    elif x == y:
      return loop (pairs + 1, y, *rest)
    else:
      return loop (pairs, y, *rest)
  return loop (0, *s)

print (count_pairs ("ddogccatppig"))    # 3
print (count_pairs ("dogcatpig"))       # 0
print (count_pairs ("xxyyzz"))          # 3 
print (count_pairs ("a"))               # 0
print (count_pairs ("abc"))             # 0
print (count_pairs ("aabb"))            # 2
print (count_pairs ("dogcatpigaabbcc")) # 3
print (count_pairs ("aabbccdogcatpig")) # 3
print (count_pairs ("dogabbcccatpig"))  # 3
print (count_pairs ("aaaa"))            # 3
print (count_pairs ("AAAAAAAAA"))       # 8

上面,字符串aaaa会产生 3 对,因为[aa]aaa[aa]aaa[aa],其中[..]表示找到一对。如果您不想计算重叠对,则需要稍微更改loop

def count_pairs (s):
  def loop (pairs, x = None, y = None, *rest):
    if x is None or y is None:
      return pairs
    elif x == y:
      return loop (pairs + 1, y, *rest)
      return loop (pairs + 1, *rest)
    else:
      return loop (pairs, y, *rest)
  return loop (0, *s)

print (count_pairs ("ddogccatppig"))    # 3
print (count_pairs ("dogcatpig"))       # 0
print (count_pairs ("xxyyzz"))          # 3 
print (count_pairs ("a"))               # 0
print (count_pairs ("abc"))             # 0
print (count_pairs ("aabb"))            # 2
print (count_pairs ("dogcatpigaabbcc")) # 3
print (count_pairs ("aabbccdogcatpig")) # 3
print (count_pairs ("dogabbcccatpig"))  # 2
print (count_pairs ("aaaa"))            # 2
print (count_pairs ("AAAAAAAAA"))       # 4