简体   繁体   English

Python - 确定单词是否使用此语言

[英]Python - Determine if a word is in this language or not

I'm having trouble solving this homework question. 我在解决这个家庭作业问题时遇到了麻烦。 If anyone can just give me any tips or something to start off with, that would be great! 如果有人可以给我任何提示或什么开始,那将是伟大的! Thanks in advance! 提前致谢!

Bob and Joe decide to create a new language. Bob和Joe决定创建一种新语言。 The words in their language only consist of the letters A, B, and C. The first words they invent are AB and C. Then they decide that all the other words are of the form AuB or vCw where u, v and w are all previously invented words. 他们语言中的单词只包含字母A,B和C.他们发明的第一个单词是AB和C.然后他们决定所有其他单词的形式是AuB或vCw,其中u,v和w都是以前发明过的话。 (Note that v and w might be the same word.) Write a function in_language that consumes a string s and produces True if s is in the language and False otherwise. (注意,v和w可能是同一个单词。)编写一个使用字符串s的函数in_language,如果s在语言中则生成True,否则生成False。

Examples: 例子:

in_language('C') => True
in_language('AB') => True
in_language('ACB') => True
in_language('ABCAB') => True
in_language('ACBCABCAB') => True

in_language('') => False (empty string with length 0)
in_language('A') => False
in_language('A^BD%AB') => False
in_language('BCA') => False
in_language('ACBACB') => False

This is a simple recursion algorithm: 这是一个简单的递归算法:

  1. if a word is empty, return False 如果单词为空,则返回False
  2. if a word is AB or C return True 如果一个单词是AB或C返回True
  3. if a word begins with A and ends with B, return True if the inner part is a valid word (recursion) 如果一个单词以A开头并以B结尾,如果内部部分是有效单词(递归),则返回True
  4. Else for each letter C in the word, return True if the left part and right part are both a valid word (recursion) 对于单词中的每个字母C,如果左侧部分和右侧部分都是有效单词(递归),则返回True
  5. if none of the above is true, return false 如果以上都不是真的,则返回false

Here's an implementation as asked by SwankyLegg 这是SwankyLegg提出的一个实现

def in_language(word):
    if word in ('AB', 'C'):
        return True
    if len(word) < 3: #The only valid words with 2 or less letters are AB and C
        return False
    if word[0] == 'A' and word[-1] == 'B' and in_language(word[1:-1]):
        return True
    else:
        for i, letter in enumerate(word):
            if letter == 'C' and in_language(word[:i]) and in_language(word[i+1:]):
                return True
    return False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM