Reputation: 13
I'm trying to pick out the longest set of characters in alphabetical order in a string. However I could not figure out how to compare two variables and I initially tried using len(str)
for the two variables, current_biggest
and rn_str
.
However that lead to errors saying
'object of type 'int' has no len()'
I have then tried a few different work arounds until you see the current failed list comparison. Its odd because I can check if they're equal but not if one is longer than the other. Any advice on how to fix it as well as an additonal more efficent method would be appreciate. I'm new to coding and would like to soak up as much as possible.
s = 'abcdebjnmzkloppk'
for i in range(len(s)-1):
current_biggest = ['m']
rn_str =['m']
if (s[i] >= s[i+1]) and (i < len(s)):
rn_str = i
if rn_str >= current_biggest:
current_biggest = rn_str
del rn_str
print(current_biggest)
Upvotes: 0
Views: 281
Reputation: 22544
The cause of the error is given in your error message: you are trying to compare an integer and a list.
Early in your code you define both current_biggest
and rn_str
to be lists of strings. But later in your code you reassign rn_str
to i
, which is an integer. Later you try to compare current_biggest
and rn_str
, which then have different types, so the comparison does not work.
You have no comments in your code, so your desired algorithm is not clear. Your problem description is also not clear, so I cannot give you more help. But your problem seems to be one of two common problems: find an increasing sub-sequence of a given sequence, where one problem requires the sub-sequence to be consecutive and the other does not. Clarify your problem then do a web search on it--both these problems have many answers on the web and on this very site.
Upvotes: 1
Reputation: 51
def isInAlphabeticalOrder(word):
count = 0
sorted_word = sorted(word)
for i in range(len(word) - 1):
if word[i] == sorted_word[i]:
count += 1
return word[:count+1], count
s = 'abcdefghij'
g = 'abuizyhijkl'
c = 'acb'
print(isInAlphabeticalOrder(s))
#returns the alphabetical string + the count of correct following letters
print(isInAlphabeticalOrder(g))
#abui, 3
print(isInAlphabeticalOrder(c))
#ac 1
The count variable tells you how many letters in a given string are alphabetically ordered (from the beginning until the first not ordered letter).
Upvotes: 0
Reputation: 1
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(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)
Further details of solution consists in this link: Find the longest substring in alphabetical order
Upvotes: 0