帮我简化这段代码(Python)

Dan*_*Dan 1 python code-formatting simplify

我是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:]
Run Code Online (Sandbox Code Playgroud)

这会产生正确的输出并解决问题.但是,我重复了是否均匀分割字符串或将奇数加到前半部分的逻辑,这似乎是多余的.必须有一种更有效的方法来做到这一点.同样的检查和逻辑正在应用于a和b.任何人?

Sve*_*ach 12

def front_back(a, b):
    ad = (len(a) + 1) // 2
    bd = (len(b) + 1) // 2
    return a[:ad] + b[:bd] + a[ad:] + b[bd:]
Run Code Online (Sandbox Code Playgroud)

使用//for division使得此代码在Python 2.x和3.x中都有效.