Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #11928

Re: extended slicing and negative stop value problem

References <CAOVPiMgP2kOfr83GK5uOo_-FJOPsrHJW-O_fGgnwkKfBSEQTbw@mail.gmail.com> <mailman.270.1313864985.27778.python-list@python.org> <9c3643a8-ba91-4b0b-8144-f4a6260d6cf0@j14g2000prh.googlegroups.com>
Date 2011-08-20 20:53 +0100
Subject Re: extended slicing and negative stop value problem
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.271.1313870035.27778.python-list@python.org> (permalink)

Show all headers | View raw


On Sat, Aug 20, 2011 at 7:52 PM, Max <maxmoroz@gmail.com> wrote:
> That doesn't work if it's set in a loop or if it's calculated as a
> formula. For example, this very simple code doesn't work because of
> the "-1 problem".
>

Right, which is what I meant by setting it to an explicit None:

if input[starting_pos:ending_pos+1] == input[ending_pos :
starting_pos-1 if starting_pos >= 0 else None : -1]:

You're right that it starts to get ugly, though.

Of course, there are other ways to find the longest palindromic
substring in a string:

# I wouldn't bother counting a one-character "palindrome"
for substr_length in range(len(input),1,-1):
   for starting_pos in range(len(input)-substr_length+1):
       ending_pos = starting_pos + substr_length - 1
       testme = input[starting_pos:ending_pos+1]
       if testme == testme[::-1]:
          print(testme)
          exit(0)

That is, snip out the string and then reverse that snipped piece,
rather than reverse-slicing from the original. This doesn't solve the
issue of slicing backwards with variable halts, though.

ChrisA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Re: extended slicing and negative stop value problem Chris Angelico <rosuav@gmail.com> - 2011-08-20 19:29 +0100
  Re: extended slicing and negative stop value problem Max <maxmoroz@gmail.com> - 2011-08-20 11:52 -0700
    Re: extended slicing and negative stop value problem Chris Angelico <rosuav@gmail.com> - 2011-08-20 20:53 +0100
  Re: extended slicing and negative stop value problem Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-08-21 06:40 +1000
    Re: extended slicing and negative stop value problem Max <maxmoroz@gmail.com> - 2011-08-21 10:27 -0700
      Re: extended slicing and negative stop value problem Chris Rebert <clp2@rebertia.com> - 2011-08-21 15:16 -0700

csiph-web