MITx: 6.00.1x Alphabetical Substrings (python)

Assumesis a string of lower case characters.

Write a program that prints the longest substring ofsin which the letters occur in alphabetical order. For example, ifs = ‘azcbobobegghakl’, then your program should print

Longest substring in alphabetical order is: beggh

In the case of ties, print the first substring. For example, ifs = ‘abcbcd’, then your program should print

Longest substring in alphabetical order is: abc

For problems such as these, do not includeraw_inputstatements or define the variablesin any way. Our automated testing will provide a value ofsfor you – so the code you submit in the following box should assumesis already defined. If you are confused by this instruction, please review L4 Problems 10 and 11 before you begin this problem set.

Note: This problem is fairly challenging. We encourage you to work smart. If you’ve spent more than a few hours on this problem, we suggest that you move on to a different part of the course. If you have time, come back to this problem after you’ve had a break and cleared your head.

# from string import lowercases = raw_input("Please input a String:")from itertools import countdef find_substring(input_string):maxsubstr = input_string[0:0]for start in range(len(input_string)):for end in count(start+len(maxsubstr)+1):substr = input_string[start:end]if len(substr)!=(end – start):breakif sorted(substr) == list(substr):maxsubstr = substrreturn maxsubstrlog_substr = find_substring(s)print ("Longest substring in alphabetical order is:"+log_substr)#lowe = 'abcdefghijklmnopqrstuvwxyz' # cont = []# sub = []# for i in s:#if len(sub) >= 1 and lowe.index(sub[-1]) + 1 != lowe.index(i):#cont.append(''.join(sub))#sub = []#sub.append(i) # cont = sorted(cont, key = len, reverse=True)# print cont[0]# cont = []# sub = []# for i in s:#if len(sub) >= 1 and lowercase.index(sub[-1]) + 1 != lowercase.index(i):#cont.append(''.join(sub))#sub = []#sub.append(i) # cont = sorted(cont, key = len, reverse=True)# print cont[0]# counter = 0# i = 0# length = len(s)# temp = s[0]# substr = s[0]# while (i<=length-1):#if s[i]<s[i+1]:#temp += s[i+1]#counter += 1#elif s[i]>s[i+1]:#if len(substr)<len(temp):#substr = temp#temp = s[i+1]#i = i + 1# if len(temp)>len(substr):#substr = temp# print 'Longest substring in alphabetical order is:',substr#s = 'cyqfjhcclkbxpbojgkar'# def long_alphabet(input_string):#maxsubstr = input_string[0:0] # empty slice (to accept subclasses of str)#for start in range(len(input_string)): # O(n)#for end in count(start + len(maxsubstr) + 1): # O(m)#substr = input_string[start:end] # O(m)#if len(substr) != (end – start): # found duplicates or EOS#break#if sorted(substr) == list(substr):#maxsubstr = substr#return maxsubstr# bla = (long_alphabet(s))# print "Longest substring in alphabetical order is: %s" %bla

,一个背包,几本书,所有喜欢的歌,

MITx: 6.00.1x Alphabetical Substrings (python)

相关文章:

你感兴趣的文章:

标签云: