所以我正在编写一个按字母顺序排列三个单词的代码,但我试图变得很酷,并且实际上按字母顺序排列(如果两个单词都以h开头,它将转到第二个字母)。我基本上是一个初学者,所以没有什么先进的我只是使用while循环。我让代码工作一次,但后来它停止了工作。老师在方向上说我们写的函数不能有回报,所以这是我的代码。
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)
答案 0 :(得分:0)
You need to make:
if list_1[0][i] == list_1[1][i] == list_1[2][i]
as == is for comparison and = is for assignment in python. Also
i=int(i)
is not needed as python can recognize 0 as an integer. We need not specify types for variables. Another major error is that you have to increment i at the end of the loop,i=i+1. The condition:
i < len(str1) < len(str2)< len(str3)
is also wrong as this condition is true only if i< len(str1) and len(str1)< len(str2) and len(str2)< len(str3) which need not be the case everytime!Change your logic accordingly.. Using Python's easy built-in functions here is the code:
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')
答案 1 :(得分:0)
In my opinion you are contradicting your teachers intentions with your proposed solution. I strongly assume (s)he would like you to learn about sorting trees or decision trees - so you will only neede if-clauses. See sorting int array with only 3 elements for some solutions and further reading.