我是 Python 的初学者,在 Google Code 大学自学。我有这个问题作为练习,并且能够使用下面显示的解决方案来解决它:
# F. front_back
# 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:
ad = len(a) / 2
if len(b) % 2 == 0:
bd = len(b) / 2
else:
bd = (len(b) / 2) + 1
else:
ad = (len(a) / 2) + 1
if len(b) % 2 == 0:
bd = len(b) / 2
else:
bd = (len(b) / 2) + 1
return a[:ad] + b[:bd] + a[ad:] + b[bd:]
这会产生正确的输出并解决问题。但是,我正在重复是否将字符串均匀拆分或将奇数添加到前半部分的逻辑,这似乎是多余的。必须有一种更有效的方法来做到这一点。对 a 和 b 应用相同的精确检查和逻辑。任何人?