【问题标题】:Converting a javascript Coding to Python Coding for Elfish Program将 javascript 编码转换为 Elfish 程序的 Python 编码
【发布时间】:2019-10-02 13:32:20
【问题描述】:

我正在寻找一个程序来做精灵实例。然后我在网上找到了这个 javascript 代码。

var containsE;
var containsL; 
var containsF; 

function elfish(str){

    var checkLetter = str[str.length - 1]; 
    if (checkLetter === "e"){
        containsE = true;
    }
    else if (checkLetter === "l"){
        containsL = true; 
    }
    else if (checkLetter === "f"){
        containsF = true; 
    }
    // base case 
    if (str.length === 0)
        if (containsE && containsL && containsF){
            return true; 
        }
        else {
            return false; 
        }
    // if not base case     
    return elfish(str.slice(0, str.length - 1)); 
}

elfish("whiteleaf"); 

不知是否可以指导我将代码转换成python并附上解释? python版本是2.73

【问题讨论】:

  • 你能解释一下代码的期望输出应该是什么吗?
  • 自己试试吧。如果您有具体问题,可以在这里提问。
  • 嗨,所以对于输出,如果用户输入单词 waffles 那么它是一个精灵

标签: javascript python coding-style


【解决方案1】:

我认为这里没有什么特别要解释的。在您的情况下,Python 非常不言自明。为了保持可读性,我在 if 语句中添加了括号。你可以离开他们:

while True:
    # type in which word you want
    s = input() 
    # if some letter in your string was found
    if ('e' in s) and ('l' in s) and ('f' in s): 
        print('true')
    else:
        print('false')

【讨论】:

  • 感谢您的指导和解释!
  • 如果这解决了您的问题,如果您将其标记为已回答,我会很高兴。 :)
猜你喜欢
  • 2023-03-24
  • 1970-01-01
  • 2016-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多