python - 帮我简化这段代码(Python)

标签 python simplify code-formatting

我是 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/

相关文章:

eclipse - 如何一次性格式化Eclipse项目中的所有Java文件?

来自 CMD 输出的列表的 Python 列表

python - 浏览器附加组件生成的合法 Xpath 查询不适用于 urllib2 获取的页面

wolfram-mathematica - 在 Mathematica 中简化一个系列

Pydev,自动代码格式化Eclipse项目中的所有文件

Eclipse "align fields in columns"随火星变化

python - 如何使用 Python 合并 2 个不同工作簿中的 2 个同名文件

python - 优化 Pandas 多索引查找

z3 - 简化 CNF 公式,同时保留某些变量的所有解决方案

jquery - 简化冗余的 jQuery 代码