2

I'm new to Python and am currently reading a chapter on String manipulation in "Dive into Python."

I was wondering what are some of the best (or most clever/creative) ways to do the following:

1) Extract from this string: "stackoverflow.com/questions/ask" the word 'questions.' I did string.split(/)[0]-- but that isn't very clever.

2) Find the longest palindrome in a given number or string

3) Starting with a given word (i.e. "cat")-- find all possible ways to get from that to another three- letter word ("dog"), changing one letter at a time such that each change in letters forms a new, valid word.

For example-- cat, cot, dot, dog

Parseltongue
  • 11,157
  • 30
  • 95
  • 160
  • 3
    these are three separate question, having nothing in common. And in general, you don't seem to have a problem. – SilentGhost Jan 19 '11 at 16:25
  • 8
    the problem is he's new to the language and already looking for the 'craziest way' :-D.. btw, why is string.split('/')[1] not clever? – Marco Mariani Jan 19 '11 at 16:28
  • @Parsetongue what do you have already? – OscarRyz Jan 19 '11 at 16:40
  • @SilentGhost-- The above three questions were all projects I assigned myself to learn about strings. To be honest, the text I'm using isn't very instructive and people on StackOverflow always post creative solutions to problems. I was hoping to glean insight from those solutions to learn more about Python. – Parseltongue Jan 19 '11 at 16:43
  • clever/craziest is not the same thing as best in my opinion. – jaydel Jan 19 '11 at 16:44
  • @jaydel: Indeed. Or as Alex Martelli put it: "To describe something as clever is NOT considered a compliment in the Python culture." Do it smart - correctly and in a way that makes the correctness (and what it ought to do in the first place) as obvious as possible to the reader. –  Jan 19 '11 at 16:53
  • @Marco - that's how you know he is practically born to be a python programmer. :) – James Jan 19 '11 at 16:56
  • For #1, couldn't you just return `'questions'`? You don't need to extract it from a larger string if you already know what you're looking for :) – Brian Goldman Jan 19 '11 at 17:13
  • Not only am I confused as to how this is a gamedev question, but the last question is not physically possible without some kind of english dictionary. – PrettyPrincessKitty FS Jan 19 '11 at 17:39

3 Answers3

2

As personal exercise, here's to you, (hopefully) well commented code with some hints.

#!/usr/bin/env python2

# Let's take this string:
a = "palindnilddafa"
# I surround with a try/catch block, explanation following
try:
  # In this loop I go from length of a minus 1 to 0.
  # range can take 3 params: start, end, increment
  # This way I start from the thow longest subsring,
  # the one without the first char and without the last
  # and go on this way
  for i in range(len(a)-1, 0, -1):
    # In this loop I want to know how many 
    # Palidnrome of i length I can do, that
    # is len(a) - i, and I take all
    # I start from the end to find the largest first
    for j in range(len(a) - i):
      # this is a little triky.
      # string[start:end] is the slice operator
      # as string are like arrays (but unmutable).
      # So I take from j to j+i, all the offsets 
      # The result of "foo"[1:3] is "oo", to be clear.
      # with string[::-1] you take all elements but in the
      # reverse order
      # The check string1 in string2 checks if string1 is a 
      # substring of string2
      if a[j:j+i][::-1] in a:
        # If it is I cannot break, 'couse I'll go on on the first
        # cycle, so I rise an exception passing as argument the substring
        # found
        raise Exception(a[j:j+i][::-1])

# And then I catch the exception, carrying the message
# Which is the palindrome, and I print some info
except Exception as e:
  # You can pass many things comma-separated to print (this is python2!)
  print e, "is the longest palindrome of", a
  # Or you can use printf formatting style
  print "It's %d long and start from %d" % (len(str(e)), a.index(str(e)))

After the discussion, and I'm little sorry if it goes ot. I've written another implementation of palindrome-searcher, and if sberry2A can, I'd like to know the result of some benchmark tests!

Be aware, there are a lot of bugs (i guess) about pointers and the hard "+1 -1"-problem, but the idea is clear. Start from the middle and then expand until you can.

Here's the code:

#!/usr/bin/env python2


def check(s, i):
  mid = s[i]
  j = 1
  try:
    while s[i-j] == s[i+j]:
      j += 1
  except:
    pass
  return s[i-j+1:i+j]

def do_all(a):
  pals = []
  mlen = 0
  for i in range(len(a)/2):
    #print "check for", i
    left = check(a, len(a)/2 + i)
    mlen = max(mlen, len(left))
    pals.append(left)

    right = check(a, len(a)/2 - i)
    mlen = max(mlen, len(right))
    pals.append(right)

    if mlen > max(2, i*2-1):
      return left if len(left) > len(right) else right

string = "palindnilddafa"

print do_all(string)
Enrico Carlesso
  • 6,818
  • 4
  • 34
  • 42
0

No 3:

If your string is s:

max((j-i,s[i:j]) for i in range(len(s)-1) for j in range(i+2,len(s)+1) if s[i:j]==s[j-1:i-1:-1])[1]

will return the answer.

neil
  • 3,387
  • 1
  • 14
  • 11
0

For #2 - How to find the longest palindrome in a given string?

Community
  • 1
  • 1
kefeizhou
  • 6,234
  • 10
  • 42
  • 55