Write a program longest_sequence.py that prompts the user for a string w of lowercase letters and outputs the longest sequence of consecutive letters that occur in w, but with possibly other letters in between, starting as close as possible to the beginning of w.
Insert your code into longest_sequence.py.
If you are stuck, but only when you are stuck, then use longest_sequence_scaffold_1.py. If you are still stuck, but only when you are still stuck, then use longest_sequence_scaffold_2.py.
需求:找string中最长连续字母串,但是中间可有别的不连续字符串
难点是每次跳过的部分的再次遍历
#马丁代码
# Prompts the user for a string w of lowercase letters and outputs the
# longest sequence of consecutive letters that occur in w,
# but with possibly other letters in between, starting as close
# as possible to the beginning of w.
#
# Written by Eric Martin for COMP9021
import sys
word = input('Please input a string of lowercase letters: ')
if not all(c.islower() for c in word):
print('Incorrect input.')
sys.exit()
longest_length = 0
start = None
current_start = 0
while current_start < len(word) - longest_length:
current_length = 1
last_in_sequence = ord(word[current_start])
for i in range(current_start + 1, len(word)):
if last_in_sequence+1==ord(word[i]):
current_length+=1
last_in_sequence=ord(word[i])
#else:
#current_start=i+1
#last_in_sequence=ord(word[i])
#current_start=last_in_sequence+1
#break
# Replace pass above with your code
if current_length > longest_length:
longest_length=current_length
start=current_start
# Replace pass above with your code
while (current_start < len(word) - 1 and
ord(word[current_start + 1]) - ord(word[current_start]) == 1):#找到上一轮中第一次没遍历到的起点
current_start+=1
# Replace pass above with your code
current_start += 1
print('The solution is: ', end = '')
for i in range(longest_length):
print(chr(ord(word[start]) + i), end = '')
print()
网友评论