Python Forum

Full Version: Strings inside other strings - substrings
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have to write a function that takes a string argument str, returns the longest substring of str in which the
letters occur in alphabetical order. For example if the string is 'azcbobobegghakl', then the function
should return 'beggh' In the case of ties, print the rst substring. For example, if s = 'abcbcd', then the
function should return 'abc'.

I wrote this so far, this only returns True if there is a substring inside a string:
import sys
#s1 is the small string, s2 is the bigger string, and k is the index
s1 = sys.argv[1]
s2= sys.argv[2]
k = 0
#k=0, same as the first index of a list with the index 0
def substring(s1, s2, k): #len stands for length, which is the number of characters in a word
	if s1 in s2[k:]: #this function finds the substring s1 in s2
		return True
	return False

print(substring(s1,s2,k)) #Prints out the presence of s1 in s2 (boolean value)
I don't understand. The function you have to write takes only one input and searches for alphabetical letters. Why did you write a function that searches for a specific substring?

To solve the problem you stated, you will want to loop through characters in the string (for loop). Check each one against the previous one for being alphabetical (ord() or less than operator), and keep track of the longest one so far (if condition using len).
As @ichabod801 said, your function needs only one parameter (the source string), and should return a string. The return string can be:
  • Empty if source string is empty
  • One character long if only one character in source string
  • One character long if no alphabetical sequences
  • Up to the same length as the source string

(You could decide on alternative rules). You also need to consider whether or not to take account of upper and lower case (or initial upper case, or initialisation of individual words).

Like @ichabod801, I don't understand the substring check. What I'd expect to see is a loop that walks through each character of the source string, with a candidate return string building up until the required sequence is broken. You would store that candidate whilst checking for another sequence. If a new sequence is larger, it will replace the previous candidate.