【问题标题】:beginner python program assistance [duplicate]初学者python程序帮助[重复]
【发布时间】:2016-09-07 01:22:28
【问题描述】:

代码应该按字母顺序返回最长的字符串。对于这个字符串,它应该是“beggh”。我需要帮助确定问题。

编辑:副本上批准的答案无效。我不确定这是否是因为这是在 python 3 而不是 2 或什么。旧代码在我的下面。

s = 'azcbobobegghakl'
temp_s = ''
startingChar = 0
currentChar = 0
endingChar = 1

for x in range(len(s)-1):
    if s[endingChar] >= s[currentChar]:
        temp_s = s[startingChar:endingChar+1]
        endingChar += 1
        currentChar += 1
    else:
        startingChar += 1
        endingChar += 1
        currentChar += 1
print('Longest substring in alphabetical order is: ', temp_s)

这是旧代码:

s = input('enter characters: ')
longest = s[0]
current = s[0]
for c in s[1:]:
    if c >= current[-1]:
        current += c
    else:
        if len(current) > len(longest):
            longest = current
        current = c
print('Longest substring in alphabetical order is:'), longest

【问题讨论】:

  • 您可以将任何字符串视为由许多较小的、按字母顺序排列的子字符串组成,这些子字符串背靠背出现。一种简单的方法是在沿着字符串移动时找到所有这样的子字符串,并找出最长的那个。

标签: python loops


【解决方案1】:

我认为 ord() 在这里可能对您有所帮助。

例如 ord('a') = 97。要使 'a' 具有第一个值,请考虑使用 ord('a') - 96。获取 'b' 的值将是相似的,即。 ord('b') - 96.

然后遍历你的字符串,检查字符串中下一个值的 ord() 是否等于或大于你之前的值。

【讨论】:

  • 你不需要ord()你可以直接比较字符,例如'b' >= 'a' == True
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-28
  • 1970-01-01
  • 2016-01-10
  • 1970-01-01
相关资源
最近更新 更多