首页 > 解决方案 > Python。我很好奇我解决这个编程问题的解决方案是否奇怪?另外,有更多经验的人可能会提供什么合适的解决方案

问题描述

我正在做一个 google python 练习,我想出了一个可行的解决方案。我觉得这个练习很有趣。我只是想知道我的解决方案是否奇怪,有经验的人是否可以通过更正常的方式解决同样的问题?我只是想改进我的编码。我都是自学的,所以只是在寻找反馈。谢谢!

# 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):
  # +++your code here+++
  lengthABack = len(a)/2
  lengthAFront = len(a)/2 + len(a)%2
  lengthBBack = len(b)/2
  lengthBFront = len(b)/2 + len(b)%2
  return a[:lengthAFront]+b[:lengthBFront]+a[-lengthABack:]+b[-lengthBBack:]

标签: python

解决方案


一个稍微短一些,也许更 Pythonic 的解决方案:

def front_back(a, b):
    a_split = (len(a) + 1) // 2
    b_split = (len(b) + 1) // 2
    return a[:a_split] + b[:b_split] + a[a_split:] + b[b_split:]

我们(len(a) + 1) // 2在这里使用是因为它在数学上给出了与 相同的结果,len(a)/2 + len(a)%2但只涉及对 的一次评估len(a)


推荐阅读