我是 Python 的初学者,在 Google 代码大学自学。我有这个问题作为练习,并且能够使用下面显示的解决方案解决它:
# 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 应用了相同的检查和逻辑。有人吗?
最佳答案
def front_back(a, b):
ad = (len(a) + 1) // 2
bd = (len(b) + 1) // 2
return a[:ad] + b[:bd] + a[ad:] + b[bd:]
使用 //
作为除法使得这段代码在 Python 2.x 和 3.x 中都有效。
关于python - 帮我简化这段代码(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6947214/