Python练习题答案: 字符串后缀【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战

字符串后缀【难度:2级】:

答案1:

def string_suffix(str_):
    tot = 0
    for i in xrange(len(str_)):
        for a, b in zip(str_, str_[i:]):
            if a != b:
                break
            tot += 1
    return tot​

答案2:

def similarity(strng1, strng2):
    result = 0
    for c1, c2 in zip(strng1, strng2):
        if c1 != c2:
            break
        result += 1
    return result

def string_suffix(strng):
    return sum(similarity(strng[i:], strng) for i in range(len(strng)))

答案3:

def string_suffix(s, t = None):
  if t is None: t = s
  return 0 if len(t) == 0 else reduce(lambda (f, cnt), (i, c): (f, cnt + 1) if f and c == s[i] else (False, cnt), enumerate(t), (True, 0))[1] + string_suffix(s, t[1:])

答案4:

from os.path import commonprefix

def string_suffix(s):
    return sum(len(commonprefix([s, s[i:]])) for i in range(len(s)))

答案5:

def string_suffix(s):
    total = len(s)
    suffixes = [s[y:] for y in range(len(s)) if s[y] == s[0]][1:]
    for suff in suffixes:
        for y,l in zip(s,suff):
            if l == y:
                total += 1
            else:
                break
    return total​

答案6:

def string_suffix(s):
  sim = lambda s1, s2: ([c1 == c2 for c1, c2 in zip(s1, s2)]+[False]).index(False)
  return sum(sim(s, s[i:]) for i in range(len(s)))

答案7:

string_suffix=lambda s:sum(s[:j-i]==s[i:j] for j in range(1,len(s)+1) for i in range(j))

答案8:

def string_suffix(str_):
    return sum(next((c for c, (a, b) in enumerate(zip(str_, str_[d:])) if a != b), len(str_[d:])) for d in range(len(str_)))

答案9:

def string_suffix(s):
    li,c = [s[i:] for i in range(len(s))],0
    for i in li:
        temp = 0
        for j in range(len(i)):
            if i[j] == s[j] : temp += 1
            else : break
        c += temp
    return c​

答案10:

def string_suffix(s):
    total = 0
    l = len(s)
    for i in range(l):
        j = 0
        while j < l - i and s[i:][j] == s[j]:
            j += 1
        total += j
    return total​




Python基础训练营景越Python基础训练营QQ群

在这里插入图片描述
欢迎各位同学加群讨论,一起学习,共同成长!

你可能感兴趣的:(Python编程初级练习题)