我是Python的新手,目前正在阅读“潜入Python”中的字符串操作章节。
我想知道有哪些最佳(或最聪明/最有创意)的方法可以做到以下几点:
1)从这个字符串中提取:“stackoverflow.com/questions/ask”这个词'问题'。我做了string.split(/)[0] - 但这不是很聪明。
2)找到给定数字或字符串中最长的回文
3)从一个给定的单词(即“cat”)开始 - 找到所有可能的方法从那里获得另一个三个字母的单词(“dog”),一次更改一个字母,以便每次更改字母形成一个新的有效词。
例如 - 猫,婴儿床,点,狗
答案 0 :(得分: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)))
讨论结束后,如果它发生了,我很抱歉。我已经编写了另一个回文搜索器的实现,如果sberry2A可以,我想知道一些基准测试的结果!
请注意,关于指针和硬“+1 -1”问题存在很多错误(我猜),但这个想法很清楚。从中间开始,然后展开,直到可以。
以下是代码:
#!/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)
答案 1 :(得分:0)
No 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 :(得分:0)