Google python类[string2.py]练习F

Google python类[string2.py]练习F,python,Python,我做了这个练习,效果很好。但我想知道是否有更聪明的方法。谢谢 # Consider dividing a string into two halves. # If the length is even, the front and back halves are the same length. # If the length is odd, we'll say that the extra char goes in the front half. # e.g. 'abcde', the fro

我做了这个练习,效果很好。但我想知道是否有更聪明的方法。谢谢

# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
# a-front + b-front + a-back + b-back
我的代码:

def front_back(a, b):
    if len(a) % 2 == 0:
    a_front = a[0:len(a) / 2]
    else:
    a_front = a[0:(len(a) / 2) + 1]
    if len(a) % 2 == 0:
    a_back = a[len(a) / 2:]
    else:
    a_back = a[(len(a) / 2) + 1:]
    if len(b) % 2 == 0:
    b_front = b[0:len(b) / 2]
    else:
    b_front = b[0:(len(b) / 2) + 1]
    if len(b) % 2 == 0:
    b_back = b[len(b) / 2:]
    else:
    b_back = b[(len(b) / 2) + 1:]
    return a_front + b_front + a_back + b_back

您可能不需要所有的if测试。使用子字符串(正如您在python中使用切片一样),下面的Java示例可以正常工作

public static String SplitMixCombine(String a, String b) {

    return a.substring(0, (a.length()+1)/2) + 
            b.substring(0, (b.length()+1)/2) + 
            a.substring((a.length()+1)/2, a.length()) + 
            b.substring((b.length()+1)/2, b.length()); 
}
刚刚在python中实现了这一点:

>>> def mix_combine(a, b):
...     return a[0:int((len(a)+1)/2)] + b[0:int((len(b)+1)/2)] + a[int((len(a)+1)/2):] +b[int((len(b)+1)/2):]
...

>>> a = "abcd"
>>> b = "wxyz"
>>> mix_combine(a,b)
'abwxcdyz'
>>> a = "abcde"
>>> b = "vwxyz"
>>> mix_combine(a,b)
'abcvwxdeyz'
>>>

这是一个更干净的代码

def front_back(a, b):
    print a, b
    a_indx = int((len(a)+1)/2)
    b_indx = int((len(b)+1)/2)

    print a[:a_indx] + b[:b_indx] + a[a_indx:] +b[b_indx:]
    print "\n"

front_back("ab", "cd")
front_back("abc", "de")
front_back("ab", "cde")
front_back("abc", "def")

希望这有帮助

我为此写了另一行:

def front_back(a, b):
  return a[:len(a) / 2 + len(a) % 2] + b[:len(b) / 2 + len(b) % 2] + a[-(len(a) / 2):] + b[-(len(b) / 2):]

值得注意的一件有趣的事情是,在Python中,5/2产生2,但是-5/2产生-3,您可能期望得到-2。这就是我添加括号的原因。请看

这个问题在第二次会议上是合适的。非常感谢!我没有注意到一对数字+1除以2与奇数数字+1除以2(整数值)是一样的。如果你不把它们都放在一行中,代码会干净得多
def front_back(a, b):
return front_string(a)+front_string(b)+back_string(a)+back_string(b)

def front_string(s):
return  s[:int((len(s)+1)/2)]  

def back_string(s):
return  s[int((len(s)+1)/2):] 

# int((len(s)+1)/2) returns the correct index for both odd and even length strings