2011-01-19 9 views
2

私はPythonを初めて使い、現在「Dive into Python」の文字列操作に関する章を読んでいます。Python:文字列操作時の巧妙な方法

1)は、この文字列から抽出します:「stackoverflow.com/questions/ask」言葉「質問

私は最高の(または最も賢い/創造的な)方法をいくつかあると思いましては、以下を実行します。私はstring.split(/)[0]でしたが、それはあまり巧妙ではありません。

2)(すなわち、「猫」)を与えられた単語で始まる)与えられた数または文字列

3で最長の回文を探す - (別の3文字の単語にそれから得るためにすべての可能な方法を見つけます"犬")、文字の各変更が新しい有効な単語を形成するように、一度に1つの文字を変更する。 example--猫、ベビーベッド、ドット、犬

+3

は、ここでは、コードです。そして、一般的に、あなたは問題を抱えていないようです。 – SilentGhost

+8

問題は彼が言語に慣れていないことと、すでに「狂った方法」を探していることです:-D .. btw、なぜstring.split( '/')[1]は巧妙ではないのですか? –

+0

@ Parsetongueあなたはすでに何を持っていますか? – OscarRyz

答えて

2

は、ここでは(たぶん)だけでなく、いくつかのヒントを使用してコードをコメントし、あなたにあります。

#!/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))) 

議論の後、私は少しお悔やみ申し上げます。私はpalindrome-searcherの別の実装を書いています。もしsberry2Aができるなら、私はいくつかのベンチマークテストの結果を知りたいと思います!

ポインタとハードな「+1 -1」問題については、多くのバグがありますが、そのアイデアははっきりしています。真ん中から始めてできるだけ早く展開してください。これらは共通で何を持っていない、3つの独立した質問です

#!/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) 
+0

うわー!どうもありがとう。これは非常に有用です。私は勉強しなければならない。 – Parseltongue

+0

私はこれを書くことができるすべてのものを手に入れようとしましたが、少しのものがあります。喜んで助けてください。 –

+0

良い答え。私のソリューション(確かに最適なソリューションではありません)より約5倍速いですが、@kefeizhouのソリューションよりも2倍遅いです。 – sberry

0

ありません3については

あなたの文字列が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]

は答えを返します。 #2のために

+2

これはperl-vomitのように見えます – Aphex

+0

私はこの回答の正確に0%を理解しています。驚くばかり。 – Parseltongue

+0

しかし、それは失敗します。文字列 "racecar"を実行すると "aceca"が返されます – Parseltongue