【问题标题】:Python alphabetize 3 wordsPython 按字母顺序排列 3 个单词
【发布时间】:2018-07-13 16:24:31
【问题描述】:

所以我正在编写一个按字母顺序排列三个单词的代码,但我想保持冷静,实际上是按字母顺序排列(如果两个单词都以 h 开头,它将转到第二个字母)。我基本上是一个初学者,所以没有什么先进的,我只是在使用 while 循环。我让代码工作了一次,但后来它停止工作了。方向out老师说我们写的函数不能有return,所以这是我的代码。

def printInOrder(str1, str2, str3):
    i = 0
    i = int(i)
    list_1 = [str1, str2, str3]
    while i < len(str1) < len(str2) < len(str3):
        if list_1[0][i] = list_1[1][i] = list_1[2][i]:
            i += 1 
        elif list_1[0][i] < list_1[1][i] < list_1[2][i]:
            first = list_1[0]
            second = list_1[1]
            third = list_1[2]
        elif list_1[0][i] < list_1[2][i] < list_1[1][i]:
            first = list_1[0]
            second = list_1[2]
            third = list_1[1]
        elif list_1[1][i] < list_1[0][i] < list_1[2][i]:
            first = list_1[1]
            second = list_1[0]
            third = list_1[2]
        elif list_1[1][i] < list_1[2][i] < list_1[0][i]:
            first = list_1[1]
            second = list_1[2]
            third = list_1[0]
        elif list_1[2][i] < list_1[0][i] < list_1[1][i]:
            first = list_1[2]
            second = list_1[0]
            third = list_1[1]
        else:
            first = list_1[2]
            second = list_1[1]
            third = list_1[0]


    first = str(first)
    second = str(second)
    third = str(third)
    print(first,second,third)

【问题讨论】:

  • 一个不隐式返回的函数返回None
  • 错误信息是什么?
  • 您的意思是对它们进行排序?只需使用sorted 内置函数即可。
  • 我们的老师不会让我们使用排序。错误消息是索引超出范围,另外一次,它只需要输入而不打印任何内容
  • 那么您的老师正在布置不切实际的作业。试试eval('so'+'rt')

标签: python function while-loop


【解决方案1】:

在我看来,您提出的解决方案与老师的意图相矛盾。我强烈假设他希望你学习排序树或决策树 - 所以你只需要 if 子句。有关一些解决方案和进一步阅读,请参阅sorting int array with only 3 elements

【讨论】:

    【解决方案2】:

    你需要做:

    if list_1[0][i] == list_1[1][i] == list_1[2][i] 
    

    as == 用于比较,= 用于在 python 中赋值。还有

    i=int(i) 
    

    不需要,因为 python 可以将 0 识别为整数。我们不需要为变量指定类型。 另一个主要错误是你必须在循环结束时增加 i,i=i+1。条件:

    i < len(str1) < len(str2)< len(str3) 
    

    也是错误的,因为只有当 i

    def printInOrder(str1, str2, str3):
        list_1 = [str1, str2, str3]
        list_1.sort()
        first = list_1[0]
        second = list_1[1]
        third = list_1[2]
        print first,second,third
    printInOrder('hat','harry','ham')
    

    【讨论】:

      猜你喜欢
      • 2012-11-28
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-24
      相关资源
      最近更新 更多