我已经完成了练习,但它确实有效。但我想知道是否有更聪明的方法来做到这一点。感谢。
# 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
答案 0 :(得分:2)
您可能不需要所有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'
>>>
答案 1 :(得分:1)
这是一个更清洁的代码。
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")
希望这有帮助!
答案 2 :(得分:0)
我为此写了另一个单行:
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。这就是我添加括号的原因。见Negative integer division surprising result
答案 3 :(得分:-1)
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