python编程单词排序,Python-按字母顺序排列单词

The program must print the name which is alphabetically the last one out of 8 elements.

The names/words can be inputted in any way through code.

I think I should be using lists and in range() here. I had an idea of comparing the first/second/third/... letter of the input name with the letters of the previous one and then putting it at the end of the list or in front of the previous one (depending on the comparison), and then repeating that for the next name. At the end the program would print the last member of the list.

解决方案

Python's string comparisons are lexical by default, so you should be able to call max and get away with it:

In [15]: sentence

Out[15]: ['this', 'is', 'a', 'sentence']

In [16]: max(sentence)

Out[16]: 'this'

Of course, if you want to do this manually:

In [16]: sentence

Out[16]: ['this', 'is', 'a', 'sentence']

In [17]: answer = ''

In [18]: for word in sentence:

....: if word > answer:

....: answer = word

....:

In [19]: print answer

this

Or you can sort your sentence:

In [20]: sentence

Out[20]: ['this', 'is', 'a', 'sentence']

In [21]: sorted(sentence)[-1]

Out[21]: 'this'

Or, sort it reversed:

In [25]: sentence

Out[25]: ['this', 'is', 'a', 'sentence']

In [26]: sorted(sentence, reverse=True)[0]

Out[26]: 'this'

But if you want to fully manual (which is so painful):

def compare(s1, s2):

for i,j in zip(s1, s2):

if ord(i)

return -1

elif ord(i)>ord(j):

return 1

if len(s1)

return -1

elif len(s1)>len(s2):

return 1

else return 0

answer = sentence[0]

for word in sentence[1:]:

if compare(answer, word) == -1:

answer = word

# answer now contains the biggest word in your sentence

If you want this to be agnostic of capitalization, be sure to call str.lower() on your words first:

sentence = [word.lower() for word in sentence] # do this before running any of the above algorithms

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值