Hey everyone I have been struggling on the longest palindrome algorithm challenge in python 2.7. I am getting close but have a small error I can't figure out. I have the palindrome working, but cannot get longest palindrome to print correct, either gives me a character buffer error or prints 0.
def palindrome(string):
string = "".join(str.split(" ")).lower()
i = 0
while i < len(string):
if string[i] != string[(len(string) - 1) - i]:
return False
i += 1
return True
print palindrome("never odd or even")
def longest_palindrome(string):
best_palindrome = 0
i1 = 0
while i1 < len(string):
length = 1
while (i1 + length) <= len(string):
substring = string.split(i1,length)
if palindrome(substring) and (best_palindrome == 0 or len(substring) > len(best_palindrome)):
best_palindrome = substring
length += 1
i1 += 1
return best_palindrome
print longest_palindrome("abcbd")
From what I understand, your first method was to check if a string is a palindrome or not and your second method is to find the longest palindrome.
The palindrome code that you posted always returned true no matter what the input was because
string = "".join(str.split(" ")).lower()
returns an empty string. I changed this part of your code to
string = string.replace(" ", "").lower()
which I believe gives you the desired effect of removing all spaces and making the string into lowercase.
Next, your second method should be looping through all possible substrings of the inputted string and check if a) its a palindrome and b) if it is longer than the previous largest palindrome.
An example for the string "doloa" would be:
doloa; is palindrome=false;
dolo; is palindrome=false;
dol; is palindrome=false;
do; is palindrome=false;
d; is palindrome=true; is bigger than previous large palindrome=true;
oloa; is palindrome=false;
olo; is palindrome=true; is bigger than previous large palindrome=true;
you would continue this loop for the whole string, and in the end, your variable 'best_palindrome' should contain the largest palindrome.
I fixed your code and I believe this should work (please tell me if this is your desired output).
def palindrome(string):
comb = string.replace(" ", "").lower()
# print(comb)
# print(len(comb))
i = 0
while i < len(comb):
# print(comb[i] + ":" + comb[(len(comb) - 1) - i] + " i: " + str(i) + ", opposite: " + str((len(comb) - 1) - i))
if comb[i] != comb[(len(comb) - 1) - i]:
return False
i += 1
return True
print palindrome("never odd or even")
def longest_palindrome(string):
best_palindrome = ""
i1 = 0
while i1 < len(string):
length = 0
while (i1 + length) <= len(string):
substring = string.replace(" ", "").lower()
substring = substring[i1:len(substring)-length]
#print("Substring: " + str(substring))
if palindrome(substring) and (best_palindrome == "" or len(substring) > len(best_palindrome)):
best_palindrome = substring
length += 1
i1 += 1
return best_palindrome
print longest_palindrome("bgologdds")
Note: I change the name of some of the variables and I also added some print strings for debugging. You can delete those or uncomment them for future debugging.
Related
def is_palindrome(input_string):
# We'll create two strings, to compare them
new_string = input_string.strip()
print(new_string)
# Traverse through each letter of the input string
newstringseperated = new_string.split()
n = len(new_string)
if n%2 == 0:
for i in range(n//2 - 1):
if newstringseperated[i] != newstringseperated[n-1-i]:
print("False")
hello = 1
if hello == 1:
print("False")
else:
print("True")
if (n%2) != 0:
for i in range((n-1)//2):
if newstringseperated[i] != newstringseperated[n-1-i]:
hello2 = 1
if hello2 == 1:
print("False")
else:
print("True")
I tried to execute this code on the words "kayak" and "deed".
It is showing index error for both of them. What is the problem here? Can someone help me find the mistake?
You have a number of problems here. As #John says, you want to use n // 2 - 1 rather than n / 2 - 1 so that the result is an integer. If you use re.sub() instead of split(), you can get rid of whitespace in the middle of your input strings and get rid of tabs as well as spaces. The big issue is that splitting the input string to create newstringseperated and using that is messing you up. If you instead operate on new_string directly, your code will work. Another small detail...you can break as soon as you recognize a mismatch. This version of your code does what I think you're expecting:
import re
def is_palindrome(input_string):
# We'll create two strings, to compare them
new_string = re.sub(r'\s+', '', input_string)
print(new_string)
# Traverse through each letter of the input string
# newstringseperated = new_string.split()
n = len(new_string)
if n % 2 == 0:
hello = 0
for i in range(n // 2 - 1):
if new_string[i] != new_string[n - 1 - i]:
hello = 1
break
if hello == 1:
print("False")
else:
print("True")
# Add any non-blank letters to the
# end of one string, and to the front
# of the other string.
if (n % 2) != 0:
hello2 = 0
for i in range((n - 1) // 2):
if new_string[i] != new_string[n - 1 - i]:
hello2 = 1
break
if hello2 == 1:
print("False")
else:
print("True")
is_palindrome("kayak")
is_palindrome("deed")
is_palindrome("abcde")
is_palindrome("abcd")
Result:
kayak
True
deed
True
abcde
False
abcd
False
It is better to not have the two cases (odd vs even lengths) in your code. Here's a way to have just one version of your inner logic:
import re
def is_palindrome(input_string):
new_string = re.sub(r'\s+', '', input_string)
print(new_string)
# Traverse through each letter of the input string
n = len(new_string)
for i in range(n // 2 - 1 + n % 2):
if new_string[i] != new_string[n - 1 - i]:
hello = 1
break
else:
hello = 0
print("False" if hello == 1 else "True")
This produces the same result.
Just reverse the string and test so no looping needed:
def is_palindrome(txt):
txt = txt.replace(' ', '')
return txt == txt[::-1]
First of all, to delete whitespaces, use replace() instead of strip() as it takes care of whitespaces in the middle of the string as well.
Secondly, the bigger problem is the split() method. It creates a list of substrings based on a specific separator and what you are essentially doing is comparing words instead of characters. Honestly, you don't even need this method to check for palindrome, just modifying the code a bit like this should work fine:
def is_palindrome(input_string):
new_string = input_string.replace(" ", "")
n = len(new_string)
for i in range(n // 2):
if new_string[i] != new_string[n - 1 - i]:
print("False")
return False
print("True")
return True
I had to do this on my phone but this should work if your looking for a palindrome:
txt = "hannah"
txt2 = "kayak"
txt3 = "blaat"
def palin(txt):
first_half = len(txt) // 2
start_second_half = first_half -1 if len(txt)%2==0 else first_half
return txt[:first_half] == txt[-1:start_second_half:-1]
print(palin(txt))
print(palin(txt2))
print(palin(txt3))
My goal is to write a function which change every even letter into upper letter and odd to lower (space also count as a one element).
This is my code
def to_weird_case(s):
for i in s:
if len(i) % 2 == 0:
s[i] = i.upper() + s(i+1)
else:
s[i] = i.lower() + s(i+2)
return i
I think it should be quite correct, but it gives me error.
line 7, in to_weird_case
s[i] = i.lower() + s(str(i)+2)
TypeError: must be str, not int
EDIT:
I have a sugesstion but I don't know how to make it. I try it for myself and back here.
This needs to definitly explicietly state that the zero indexing uppercase is for each word.
Do you know guys how to make it?
So we can analyze your code and just explain what you typed:
def to_weird_case(s):
for i in s: # s is your string, and i is the actual character
if len(i) % 2 == 0: # if your length of the character can be divided by 2. Hmm this is weird
s[i] = i.upper() + s(i+1) # s[i] change a character in the string but you should provide an index (i) so an integer and not a character. But this is not supported in Python.
else:
s[i] = i.lower() + s(i+2)
return i # This will exit after first iteraction, so to_weird_case("this") will return "t".
So what you need to is first create a output string and fill that. And when iteration over s, you want the index of the char and the char value itself.
def to_weird_case(s):
output = ""
for i, myChar in enumerate(s):
if i % 2 == 0:
output += myChar.upper()
else:
output += myChar.lower()
return output
my_sentence = "abcdef"
print(to_weird_case(my_sentence))
And when you want to ignore spaces, you need to keep track of actual characters (excluding spaces)
def to_weird_case(s):
output = ""
count = 0
for myChar in s:
if myChar.isspace():
output += myChar
else:
if count % 2 == 0:
output += myChar.upper()
else:
output += myChar.lower()
count += 1
return output
my_sentence = "abc def"
print(to_weird_case(my_sentence))
Test this yourself
def to_weird_case(s):
for i in s:
print (i)
After doing this you will find that i gives you characters.
if len(i) % 2 == 0:
This line is incorrect as you are trying to find the length of a single character. len(s) would be much better.
So the code will be like
def to_weird_case(s):
s2 = "" #We create another string as strings are immutable in python
for i in range(len(s)):
if i % 2 == 0:
s2 = s2 + s[i].upper()
else:
s2 = s2 + s[i].lower()
return s2
From #RvdK analysis, you'ld have seen where corrections are needed. In addition to what has been pointed out, I want you to note that s[i] will work fine only if i is an integer, but in your case where (by assumption) i is a string you'll encounter several TypeErrors. From my understanding of what you want to do, it should go this way:
def to_weird_case(s):
for i in s:
if s.index(i) % 2 == 0:
s[s.index(i)] = i.upper() + s[s.index(i)]
elif s.index(i) % 2 == 1:
s[s.index(i)] = i.lower() + s[s.index(i)]
return i # or possibly return s
It is possible to do in a single line using a list comprehension
def funny_case(s):
return "".join([c.upper() if idx%2==0 else c.lower() for idx,c in enumerate(s)])
If you want to treat each word separately then you can split it up in to a list of words and "funny case" each word individually, see below code
original = "hello world"
def funny_case(s):
return "".join([c.upper() if idx%2==0 else c.lower() for idx,c in enumerate(s) ])
def funny_case_by_word(s):
return " ".join((funny_case(word) for word in s.split()))
print(funny_case_by_word(original))
Corrected code is as follows
def case(s):
txt=''
for i in range(len(s)):
if i%2==0:
txt+=s[i].upper()
else:
txt+=s[i].lower()
return txt
String assignment gives error in Python therefore i recommend considering my approach
When looping over elements of s, you get the letter itself, not its index. You can use enumerate to get both index and letter.
def to_weird_case(s):
result = ''
for index, letter in enumerate(s):
if index % 2 == 0:
result += letter.upper()
else:
result += letter.lower()
return result
correct code:
def to_weird_case(s):
str2 = ""
s.split() # through splitting string is converted to list as it is easy to traverse through list
for i in range(0,len(s)):
n = s[i] # storing value in n
if(i % 2 == 0):
str2 = str2 + n.upper()
else:
str2 = str2 + n.lower()
return str2
str1 = "hello world"
r = to_weird_case(str1)
print(r)
I want to write a program that prints the longest sub string in alphabetical order from the string s and I don't know what I am doing wrong, I just started coding a few days ago and this is the best I've come up with.
s = 'vvrsmxxlplnawxxcmcvuxrgi'
alphabet =['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
Current_Sequence=''
Max_Sequence=''
runs=0
current_runs = ''
max_runs=''
for I in str(s)[1:]:
runs +=1
if alphabet.index(I) >= alphabet.index(s[runs-1]):
Current_Sequence += str(I)
current_runs += str(runs)
else:
if (len(str(Current_Sequence))) > (len(str(Max_Sequence))) :
Max_Sequence = str(Current_Sequence)
Current_Sequence=''
max_runs= int(str(current_runs)[0])
current_runs=''
else:
Current_Sequence=''
current_runs=''
if (len(Max_Sequence)) >= (len(Current_Sequence)):
print('Longest substring in alphabetical order is: ' + s[max_runs-1] + str(Max_Sequence))
if (len(Current_Sequence)) > (len(Max_Sequence)):
print('Longest substring in alphabetical order is: ' + s[current_runs[0]-1] + str(Current_Sequence))
* ERROR: Expected 'awxx', got 'vwxx'. *
in another trial where s = 'zyxwvutsrqponmlkjihgfedcba' the result was
* ERROR: Expected 'z', got 'unsupported operand type(s) for -: 'str' and 'int''. *
any input will help, as I am young and very new to code
You don't have to change very much.
Just a few lines:
You want to start at the first character
for I in str(s)[0:]:
As soon as the sequence restarts you also want to add the current letter - that broke the chain - to your new sequence. Therefore you don't need max_runs anymore
Current_Sequence=I
Move the runs +=1 to the end of the for loop.
Remove max_runs from the print
print('Longest substring in alphabetical order is: ' + str(Max_Sequence))
Full code:
s = 'kjddbyydx'
alphabet =['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
Current_Sequence=''
Max_Sequence=''
runs=0
for I in str(s)[0:]:
if alphabet.index(I) >= alphabet.index(s[runs-1]):
Current_Sequence += str(I)
else:
if (len(str(Current_Sequence))) > (len(str(Max_Sequence))) :
Max_Sequence = str(Current_Sequence)
Current_Sequence=I
else:
Current_Sequence = I
runs +=1
if (len(Max_Sequence)) >= (len(Current_Sequence)):
print('Longest substring in alphabetical order is: ' + str(Max_Sequence))
if (len(Current_Sequence)) > (len(Max_Sequence)):
print('Longest substring in alphabetical order is: ' + str(Current_Sequence))
Code using enumerate instead of a for loop:
for runs, I in enumerate(s):
if alphabet.index(I) >= alphabet.index(s[runs-1]):
Current_Sequence += str(I)
else:
if (len(str(Current_Sequence))) > (len(str(Max_Sequence))) :
Max_Sequence = str(Current_Sequence)
Current_Sequence=I
else:
Current_Sequence = I
if (len(Max_Sequence)) >= (len(Current_Sequence)):
print('Longest substring in alphabetical order is: ' + str(Max_Sequence))
if (len(Current_Sequence)) > (len(Max_Sequence)):
print('Longest substring in alphabetical order is: ' + str(Current_Sequence))
you program looks ok. maybe this will help you to trace what is wrong
def max_substr(s):
max_s = s[0:1]
cur_s = max_s
for i in range(1, len(s)):
ch = s[i : i + 1]
if ch >= cur_s[-1]:
cur_s = cur_s + ch
if len(cur_s) > len(max_s):
max_s = cur_s
else:
cur_s = ch
return max_s
print(max_substr("vvrsmxxlplnawxxcmcvuxrgi"))
You can use zip to offset the string by one, accumulate the substrings, and select the longest one.
s = 'vvrsmxxlplnawxxcmcvuxrgi'
li = []
st = ""
for c1,c2 in zip(s,s[1:]):
if c2 >= c1:
st += c1
elif st != "":
li.append(st+c1)
st =""
print(max(li, key = len))
Output:
awxx
I'm trying to write a code that basically requires me to find the letter that comes alphabetically first and print. Although the printing is required in another function. Need to use the while loop
this what I've gotten so far.
def alphabetically_first(word):
n = 0
p = 0
while n + 1 < len(word):
if word[n] < word[n+1]:
p = word[n]
elif word[n + 1] < word [n]:
p = word[n+1]
n += 1
print p
return
I have this code that I found on another topic, but it sorts the substring by contiguous characters and not by alphabetical order. How do I correct it for alphabetical order? It prints out lk, and I want to print ccl. Thanks
ps: I'm a beginner in python
s = 'cyqfjhcclkbxpbojgkar'
from itertools import count
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(set(substr)) != (end - start): # found duplicates or EOS
break
if (ord(max(sorted(substr))) - ord(min(sorted(substr))) + 1) == len(substr):
maxsubstr = substr
return maxsubstr
bla = (long_alphabet(s))
print "Longest substring in alphabetical order is: %s" %bla
s = 'cyqfjhcclkbxpbojgkar'
r = ''
c = ''
for char in s:
if (c == ''):
c = char
elif (c[-1] <= char):
c += char
elif (c[-1] > char):
if (len(r) < len(c)):
r = c
c = char
else:
c = char
if (len(c) > len(r)):
r = c
print(r)
Try changing this:
if len(set(substr)) != (end - start): # found duplicates or EOS
break
if (ord(max(sorted(substr))) - ord(min(sorted(substr))) + 1) == len(substr):
to this:
if len(substr) != (end - start): # found duplicates or EOS
break
if sorted(substr) == list(substr):
That will display ccl for your example input string. The code is simpler because you're trying to solve a simpler problem :-)
You can improve your algorithm by noticing that the string can be broken into runs of ordered substrings of maximal length. Any ordered substring must be contained in one of these runs
This allows you to just iterate once through the string O(n)
def longest_substring(string):
curr, subs = '', ''
for char in string:
if not curr or char >= curr[-1]:
curr += char
else:
curr, subs = '', max(curr, subs, key=len)
return max(curr, subs, key=len)
s = 'cyqfjhcclkbxpbojgkar'
longest = ""
max =""
for i in range(len(s) -1):
if(s[i] <= s[i+1] ):
longest = longest + s[i]
if(i==len(s) -2):
longest = longest + s[i+1]
else:
longest = longest + s[i]
if(len(longest) > len(max)):
max = longest
longest = ""
if(len(s) == 1):
longest = s
if(len(longest) > len(max)):
print("Longest substring in alphabetical order is: " + longest)
else:
print("Longest substring in alphabetical order is: " + max)
In a recursive way, you can import count from itertools
Or define a same method:
def loops( I=0, S=1 ):
n = I
while True:
yield n
n += S
With this method, you can obtain the value of an endpoint, when you create any substring in your anallitic process.
Now looks the anallize method (based on spacegame issue and Mr. Tim Petters suggestion)
def anallize(inStr):
# empty slice (maxStr) to implement
# str native methods
# in the anallize search execution
maxStr = inStr[0:0]
# loop to read the input string (inStr)
for i in range(len(inStr)):
# loop to sort and compare each new substring
# the loop uses the loops method of past
# I = sum of:
# (i) current read index
# (len(maxStr)) current answer length
# and 1
for o in loops(i + len(maxStr) + 1):
# create a new substring (newStr)
# the substring is taked:
# from: index of read loop (i)
# to: index of sort and compare loop (o)
newStr = inStr[i:o]
if len(newStr) != (o - i):# detect and found duplicates
break
if sorted(newStr) == list(newStr):# compares if sorted string is equal to listed string
# if success, the substring of sort and compare is assigned as answer
maxStr = newStr
# return the string recovered as longest substring
return maxStr
Finally, for test or execution pourposes:
# for execution pourposes of the exercise:
s = "azcbobobegghakl"
print "Longest substring in alphabetical order is: " + anallize( s )
The great piece of this job started by: spacegame and attended by Mr. Tim Petters, is in the use of the native str methods and the reusability of the code.
The answer is:
Longest substring in alphabetical order is: ccl
In Python character comparison is easy compared to java script where the ASCII values have to be compared. According to python
a>b gives a Boolean False and b>a gives a Boolean True
Using this the longest sub string in alphabetical order can be found by using the following algorithm :
def comp(a,b):
if a<=b:
return True
else:
return False
s = raw_input("Enter the required sting: ")
final = []
nIndex = 0
temp = []
for i in range(nIndex, len(s)-1):
res = comp(s[i], s[i+1])
if res == True:
if temp == []:
#print i
temp.append(s[i])
temp.append(s[i+1])
else:
temp.append(s[i+1])
final.append(temp)
else:
if temp == []:
#print i
temp.append(s[i])
final.append(temp)
temp = []
lengths = []
for el in final:
lengths.append(len(el))
print lengths
print final
lngStr = ''.join(final[lengths.index(max(lengths))])
print "Longest substring in alphabetical order is: " + lngStr
Use list and max function to reduce the code drastically.
actual_string = 'azcbobobegghakl'
strlist = []
i = 0
while i < len(actual_string)-1:
substr = ''
while actial_string[i + 1] > actual_string[i] :
substr += actual_string[i]
i += 1
if i > len(actual_string)-2:
break
substr += actual-string[i]
i += 1
strlist.append(subst)
print(max(strlist, key=len))
Wow, some really impressing code snippets here...
I want to add my solution, as I think it's quite clean:
s = 'cyqfjhcclkbxpbojgkar'
res = ''
tmp = ''
for i in range(len(s)):
tmp += s[i]
if len(tmp) > len(res):
res = tmp
if i > len(s)-2:
break
if s[i] > s[i+1]:
tmp = ''
print("Longest substring in alphabetical order is: {}".format(res))
Without using a library, but using a function ord() which returns ascii value for a character.
Assumption: input will be in lowercase, and no special characters are used
s = 'azcbobobegghakl'
longest = ''
for i in range(len(s)):
temp_longest=s[i]
for j in range(i+1,len(s)):
if ord(s[i])<=ord(s[j]):
temp_longest+=s[j]
i+=1
else:
break
if len(temp_longest)>len(longest):
longest = temp_longest
print(longest)
Slightly different implementation, building up a list of all substrings in alphabetical order and returning the longest one:
def longest_substring(s):
in_orders = ['' for i in range(len(s))]
index = 0
for i in range(len(s)):
if (i == len(s) - 1 and s[i] >= s[i - 1]) or s[i] <= s[i + 1]:
in_orders[index] += s[i]
else:
in_orders[index] += s[i]
index += 1
return max(in_orders, key=len)
s = "azcbobobegghakl"
ls = ""
for i in range(0, len(s)-1):
b = ""
ss = ""
j = 2
while j < len(s):
ss = s[i:i+j]
b = sorted(ss)
str1 = ''.join(b)
j += 1
if str1 == ss:
ks = ss
else:
break
if len(ks) > len(ls):
ls = ks
print("The Longest substring in alphabetical order is "+ls)
This worked for me
s = 'cyqfjhcclkbxpbojgkar'
lstring = s[0]
slen = 1
for i in range(len(s)):
for j in range(i,len(s)-1):
if s[j+1] >= s[j]:
if (j+1)-i+1 > slen:
lstring = s[i:(j+1)+1]
slen = (j+1)-i+1
else:
break
print("Longest substring in alphabetical order is: " + lstring)
Output: Longest substring in alphabetical order is: ccl
input_str = "cyqfjhcclkbxpbojgkar"
length = len(input_str) # length of the input string
iter = 0
result_str = '' # contains latest processed sub string
longest = '' # contains longest sub string alphabetic order
while length > 1: # loop till all char processed from string
count = 1
key = input_str[iter] #set last checked char as key
result_str += key # start of the new sub string
for i in range(iter+1, len(input_str)): # discard processed char to set new range
length -= 1
if(key <= input_str[i]): # check the char is in alphabetic order
key = input_str[i]
result_str += key # concatenate the char to result_str
count += 1
else:
if(len(longest) < len(result_str)): # check result and longest str length
longest = result_str # if yes set longest to result
result_str = '' # re initiate result_str for new sub string
iter += count # update iter value to point the index of last processed char
break
if length is 1: # check for the last iteration of while loop
if(len(longest) < len(result_str)):
longest = result_str
print(longest);
finding the longest substring in alphabetical order in Python
in python shell 'a' < 'b' or 'a' <= 'a' is True
result = ''
temp = ''
for char in s:
if (not temp or temp[-1] <= char):
temp += char
elif (temp[-1] > char):
if (len(result) < len(temp)):
result = temp
temp = char
if (len(temp) > len(result)):
result = temp
print('Longest substring in alphabetical order is:', result)
s=input()
temp=s[0]
output=s[0]
for i in range(len(s)-1):
if s[i]<=s[i+1]:
temp=temp+s[i+1]
if len(temp)>len(output):
output=temp
else:
temp=s[i+1]
print('Longest substring in alphabetic order is:' + output)
I had similar question on one of the tests on EDX online something. Spent 20 minutes brainstorming and couldn't find solution. But the answer got to me. And it is very simple. The thing that stopped me on other solutions - the cursor should not stop or have unique value so to say if we have the edx string s = 'azcbobobegghakl' it should output - 'beggh' not 'begh'(unique set) or 'kl'(as per the longest identical to alphabet string). Here is my answer and it works
n=0
for i in range(1,len(s)):
if s[n:i]==''.join(sorted(s[n:i])):
longest_try=s[n:i]
else:
n+=1
In some cases, input is in mixed characters like "Hello" or "HelloWorld"
**Condition 1:**order determination is case insensitive, i.e. the string "Ab" is considered to be in alphabetical order.
**Condition 2:**You can assume that the input will not have a string where the number of possible consecutive sub-strings in alphabetical order is 0. i.e. the input will not have a string like " zxec ".
string ="HelloWorld"
s=string.lower()
r = ''
c = ''
last=''
for char in s:
if (c == ''):
c = char
elif (c[-1] <= char):
c += char
elif (c[-1] > char):
if (len(r) < len(c)):
r = c
c = char
else:
c = char
if (len(c) > len(r)):
r = c
for i in r:
if i in string:
last=last+i
else:
last=last+i.upper()
if len(r)==1:
print(0)
else:
print(last)
Out:elloW
```python
s = "cyqfjhcclkbxpbojgkar" # change this to any word
word, temp = "", s[0] # temp = s[0] for fence post problem
for i in range(1, len(s)): # starting from 1 not zero because we already add first char
x = temp[-1] # last word in var temp
y = s[i] # index in for-loop
if x <= y:
temp += s[i]
elif x > y:
if len(temp) > len(word): #storing longest substring so we can use temp for make another substring
word = temp
temp = s[i] #reseting var temp with last char in loop
if len(temp) > len(word):
word = temp
print("Longest substring in alphabetical order is:", word)
```
My code store longest substring at the moment in variable temp, then compare every string index in for-loop with last char in temp (temp[-1]) if index higher or same with (temp[-1]) then add that char from index in temp. If index lower than (temp[-1]) checking variable word and temp which one have longest substring, after that reset variable temp so we can make another substring until last char in strings.
s = 'cyqfjhcclkbxpbojgkar'
long_sub = '' #longest substring
temp = '' # temporarily hold current substr
if len(s) == 1: # if only one character
long_sub = s
else:
for i in range(len(s) - 1):
index = i
temp = s[index]
while index < len(s) - 1:
if s[index] <= s[index + 1]:
temp += s[index + 1]
else:
break
index += 1
if len(temp) > len(long_sub):
long_sub = temp
temp = ''
print(long_sub)
For comprehensibility, I also add this code snippet based on regular expressions. It's hard-coded and seems clunky. On the other hand, it seems to be the shortest and easiest answer to this problem. And it's also among the most efficient in terms of runtime complexity (see graph).
import re
def longest_substring(s):
substrings = re.findall('a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*', s)
return max(substrings, key=len)
(Unfortunately, I'm not allowed to paste a graph here as a "newbie".)
Source + Explanation + Graph: https://blog.finxter.com/python-how-to-find-the-longest-substring-in-alphabetical-order/
Another way:
s = input("Please enter a sentence: ")
count = 0
maxcount = 0
result = 0
for char in range(len(s)-1):
if(s[char]<=s[char+1]):
count += 1
if(count > maxcount):
maxcount = count
result = char + 1
else:
count = 0
startposition = result - maxcount
print("Longest substring in alphabetical order is: ", s[startposition:result+1])