我必须对用户输入的名称进行排序,而不使用列表排序方法。到目前为止,这就是我所拥有的,但在定义“一”、“二”和“三”时,我遇到了问题。我需要程序通过每一个字母,以确保它是真正的字母。有人能帮忙吗?
name1=str(input("Enter name #1: "))
name2=str(input("Enter name #2: "))
name3=str(input("Enter name #3: "))
one = name1[0].upper() + name1[1].upper() + name1[2].upper()
two = name2[0].upper() + name2[1].upper() + name2[2].upper()
three = name3[0].upper() + name3[1].upper() + name3[2].upper()
if one < two and two < three:
print("These names in alphabetical order are: ", name1, name2, name3)
elif one < two and three < two:
print("These names in alphabetical order are: ", name1, name3, name2)
elif two < three and three < one:
print("These names in alphabetical order are: ", name2, name3, name1)
elif two < one and one < three:
print("These names in alphabetical order are: ", name2, name1, name3)
elif three < two and two < one:
print("These names in alphabetical order are: ", name3, name2, name1)
else:
print("These names in alphabetical order are: ", name3, name1, name2)提前谢谢!编辑我的问题是在定义‘1’2‘’和‘3’,它需要运行所有的字母在输入。现在,它贯穿前三个字母,但如果我添加下一个字母,并且只给出三个字母的名称,则会出现错误。如果我使用len函数,它会告诉我它是一个整数
发布于 2016-08-07 16:25:23
我需要程序通过每一个字母,以确保它是真正的字母。
这就是字符串比较所做的。代码的问题是将one、two和three限制在输入字符串的前三个字母上。相反,您应该大写整个名称并比较它们。
name1 = input("Enter name #1: ") # no need for str(...)
... # same for name2, name3
one = name1.upper() # uppercase whole nam, not just first three letters
... # same for two, three
answer = "These names in alphabetical order are: " # don't repeat this X times
if one < two < three: # comparison chaining
print(answer, name1, name2, name3)
elif one < three < two:
print(answer, name1, name3, name2)
elif ...:
# a whole bunch more
else:
print(answer, name3, name2, name1)发布于 2016-08-07 16:30:39
您可以使用好的旧排序算法。
letters = [name1.upper(),name2.upper(),name3.upper()]
for i in range(len(letters)):
for j in range(i,len(letters)):
if letters[i] > letters[j]:
letters[i],letters[j] = letters[j],letters[i]https://stackoverflow.com/questions/38816017
复制相似问题