【问题标题】:What is going on in the following python code?以下 python 代码中发生了什么?
【发布时间】:2017-12-27 20:31:31
【问题描述】:

我正在尝试在脑海中处理此代码并获取输出。我一直得到 1 作为不正确的答案。有人可以解释为什么吗?

def testString(aString):
  aDict = {}
 for letter in aString:
     num = aString.count(letter)
     if num not in aDict:
         aDict[num] = letter
     else:
         return num
 return -1


text = 'eager'
print(testString(text))

【问题讨论】:

  • 你期望输出什么?
  • 你需要修复你的缩进
  • 我希望 -1 作为输出。这就是练习题后面的正确答案
  • 我已经手动完成了迭代并发布了答案。假设缩进被纠正,它肯定是 1。

标签: python python-2.7 python-3.x


【解决方案1】:

这不是用语言解释的最简单的代码 sn-p。此函数有效地跟踪一个字母出现的次数,一旦检测到第二个字母与前一个字母出现的次数相同,它就会返回该字母的出现次数。

因为在这个例子中'e'出现了两次,'a'出现了一次,'g'也出现了,一旦代码在这里终止并且将返回'1'

【讨论】:

    【解决方案2】:

    看到ea后,aDict就是{2: 'e', 1: 'a'}。查看g时,num又是1,这已经是aDict中的一个key,所以返回了1

    【讨论】:

    • 我尝试在电脑上运行代码,输出为-1。我不明白为什么。我也认为是1。但答案是-1。我不明白为什么。
    • 你最初说你得到了 1 和 'eager' 作为输入,而我得到了 1,所以如果你现在得到不同的东西,你一定是改变了代码或输入或其他东西。
    【解决方案3】:

    我已经格式化了你的代码:

    def testString(aString):
        aDict = {}
        for letter in aString:
            num = aString.count(letter)
            if num not in aDict:
                aDict[num] = letter
            else:
                return num
        return -1
    
    
    text = 'eager'
    print(testString(text))
    

    循环的每次迭代:

    # First iteration
    aDict = {}
    letter = 'e'
    num = 2
    if 2 not in aDict: #True
        aDict[2] = 'e'
    else:
        return 2
    
    # Second iteration
    aDict = {2: 'e'}
    letter = 'a'
    num = 1
    if 1 not in aDict: #True
        aDict[1] = 'a'
    else:
        return 1
    
    # Third iteration
    aDict = {2: 'e', 1: 'a'}
    letter = 'g'
    num = 1
    if 1 not in aDict: #False
        aDict[1] = 'g'
    else:
        return 1 #returns 1
    

    【讨论】:

    • 我尝试在电脑上运行代码,输出为-1。我不明白为什么。我也认为是1。但答案是-1。我不明白为什么。
    • 您的缩进可能是错误的。检查return -1 是否不在for 循环内。
    猜你喜欢
    • 2014-05-13
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    相关资源
    最近更新 更多