给定一个字符串,波兰表示法中最长的WFF之一的长度是多少?

时间:2015-03-21 04:52:45

标签: python string algorithm python-2.7 polish-notation

我正在尝试to write在Python中使用WFF&#N; N Proof游戏(无版权侵权)的常用流行的Count-A-WFF版本。好吧,不那么受欢迎。

我认为我已经根据需要提供了所有功能,直到4个字母的字符串为止。

def maximum_string(s):
if cs(s) == True:
    return len(s)
elif len(s) == 2:
    l1 = [cs(s[0]), cs(s[1])]
    if True in l1:
        return len(s) - 1
    else:
        return 0
elif len(s) == 3:
    first = s[0] + s[1]
    second = s[0] + s[2]
    third = s[1] + s[2]
    l1 = [cs(first), cs(second), cs(third)]
    if True in l1:
        return len(s) - 1
    l2 = [cs(s[0]), cs(s[1]), cs(s[2])]
    if True in l2:
        return len(s) - 2
    else:
        return 0
elif len(s) == 4:
    first = s[0]+s[1]+s[2]
    second = s[0]+s[1]+s[3]
    third = s[1]+s[2]+s[3]
    fourth = s[0]+s[2]+s[3]
    l1 = [cs(first), cs(second), cs(third), cs(fourth)]
    if True in l1:
        return 3
    first = s[0] + s[1]
    second = s[0] + s[2]
    third = s[0] + s[3]
    fourth = s[1] + s[2]
    fifth = s[1] + s[3]
    sixth = s[2] + s[3]
    l2 = [cs(first), cs(second), cs(third), cs(fourth), cs(fifth), cs(sixth)]
    if True in l2:
        return 2
    first = s[0]
    second = s[1]
    third = s[2]
    fourth = s[3]
    l3 = [cs(first), cs(second), cs(third), cs(fourth)]
    if True in l3:
        return 1
    else:
        return 0

def cs(string):
global length_counter, counter, letter
counter = 1
length_counter = 0
letters_left = len(string)
while letters_left != 0 and length_counter < len(string):
    letter = string[length_counter]
    if letter == 'C' or letter == 'A' or letter == 'K' or letter == 'E' or letter == "K":
        counter += 1 
    elif letter == 'N':
        counter += 0
    else:
        counter -= 1  
    length_counter += 1
    letters_left -= 1
if counter == 0 and len(string) == length_counter:
    return True
else:
    return False

在给定任何字符串S的情况下,maximum_string辅助函数用于查找可以从S的字母中生成的最长可能的wff之一的长度。当然,我可以继续我目前用于maximum_string辅助函数最长为13.但是,组合爆炸是显而易见的。那么,是否有更优雅的方法来完成最大字符串辅助函数?

1 个答案:

答案 0 :(得分:1)

实际上,我之前使用的一个函数将返回一个字符串与波兰表示法中的排列相距多远的距离。因此,这比我预期的要简单得多。这就是我要找的东西:

def maximum_string(string):
    global length_counter, counter, letter
    counter = 1
    length_counter = 0
    letters_left = len(string)
    while letters_left != 0 and length_counter < len(string):
        letter = string[length_counter]
        if letter == 'C' or letter == 'A' or letter == 'K' or letter == 'E' or letter == "K":
            counter += 1 
        elif letter == 'N':
            counter += 0
        else:
            counter -= 1  
        length_counter += 1
        letters_left -= 1
    if ('p' in string) or ('q' in string) or ('r' in string) or ('s' in string) or ('t' in string) or ('u' in string):
        return len(string) - abs(counter)
    else:
        return 0