Finding Longest String In Numerical Order In A String In Python
Solution 1:
Strings are indexed at 0. So if you try to access some_str[len(some_str)]
you will get an IndexError
because the highest index of that string is len(some_str) - 1
. Change your while
condition to: while a < len(myString):
. Also, you shouldn't use string
as a variable, as it may overshadow the python string
module name.
Solution 2:
The problem is that you are incrementing a
one too many times. Therefore, the program breaks when a equals the length of the string (a = 16
). Changing your 3rd line to while a < len(string):
should fix it.
Also, I'm not quite sure what you're doing with your variables. You declare r1, which is never used, and you use r2 without declaring it. The problem can be solved more easily than your method - the following code seems to do what you want:
>>> r=longest=''
>>> for a in range(1:len(string)):
if (string[a-1] <= string[a]) or len(r)==0:
r += string[a]
else:
r = string[a] // We need to reset r if the string is not in numerical orderiflen(r) > len(longest):
longest = r
a += 1
>>> longest
'1223455'
Solution 3:
First make sure you have several things to test and the expected results, including boundary cases.
strings = {
'1223123341223455': '1223455', # at the end'1': '1', # just one'12321': '123', # at the start'212321': '123', # in the middle'': '', # empty'123234': '123', # two of same length, take the first'12231233412234552': '1223455', # at the end -1 testing the try
}
Then search for the longest string without appending the actual characters found so far to some temporary string. That is inefficient. You only need to know the start index of the longest string and its length:
deflongest(s):
max_start = 0
this_start = 0
max_length_minus_one = 0for x inrange(len(s)-1):
if s[x] > s[x+1]:
length_found = x - this_start
if length_found > max_length_minus_one:
max_length_minus_one = length_found
max_start = this_start
this_start = x + 1try:
# test the final string position
length_found = x + 1 - this_start
if length_found > max_length_minus_one:
max_length_minus_one = length_found
max_start = this_start
except UnboundLocalError:
pass# empty string throws this exceptionreturn s[max_start:max_start+max_length_minus_one+1]
Now run this on the test cases and check the output:
for s, check in strings.iteritems():
res = longest(s)
printrepr(s), repr(res), 'OK'if res == check else'<<<<< ERROR'
Solution 4:
string = '1223123341223455'
longest = ''
r = ''for i in range(len(string)):
j = i+1
r += string[i]
if j > len(string)-1 or string[i] > string[j]:
iflen(r) > len(longest):
longest = r
r = ''print longest # 1223455
Post a Comment for "Finding Longest String In Numerical Order In A String In Python"