[英]Python alphabetize 3 words
So I'm writing a code that alphabetizes three words, but I'm trying to be cool, and actually alphabetize it (if both words start with h, it will go to the second letter). 因此,我正在编写一个将三个单词按字母顺序排列的代码,但是我想保持冷静,实际上将其按字母顺序排列(如果两个单词都以h开头,它将转到第二个字母)。 I'm basically a beginner, so nothing advanced I'm just using while loops. 我基本上是一个初学者,所以我只是在使用while循环。 I got the code to work once, but then it stopped working. 我让代码可以工作一次,但是随后停止工作。 Out teacher in the direction said the function we write can't have a return, so here is my code. 方向老师说我们编写的函数不能返回,所以这是我的代码。
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)
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. as ==用于比较,而=用于python中的赋值。 Also 也
i=int(i)
is not needed as python can recognize 0 as an integer. 不需要,因为python可以将0识别为整数。 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. 另一个主要错误是您必须在循环结束时将i递增,即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: 也是错误的,因为仅当i <len(str1)和len(str1)<len(str2)和len(str2)<len(str3)时才是正确的!请相应地更改逻辑。下面是使用Python的简单内置函数的代码:
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')
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. 我坚信他希望您学习排序树或决策树的知识-因此您只需要if子句。 See sorting int array with only 3 elements for some solutions and further reading. 有关某些解决方案和更多信息,请参见仅对3个元素排序的int数组 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.