请帮我简化这段代码(Python)

1 投票
7 回答
1108 浏览
提问于 2025-04-16 22:55

我刚开始学习Python,都是靠自己在Google Code University上自学。我在做一个练习时遇到了问题,下面的代码解决了这个问题:

# 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的检查和逻辑完全一样,有没有人能帮忙想想?

7 个回答

3

因为如果长度是奇数,你会加1,而“奇数”的意思是 len(a)%2 == 1...

def front_back2(a, b):
    ad = (len(a) + len(a)%2) / 2
    bd = (len(b) + len(b)%2) / 2
    return a[:ad]+b[:bd]+a[ad:]+b[bd:]

当然,你甚至可以把它简化成一行代码,虽然这样会让人看起来不太容易理解:

def front_back2(a, b):
    return a[:(len(a)+len(a)%2)/2]+b[:(len(b)+len(b)%2)/2]+a[(len(a)+len(a)%2)/2:]+b[(len(b)+len(b)%2)/2:]
4

好吧,把它放在一个单独的函数里。

def front_back(string):
    offset = len(string) / 2
    if len(string) % 2 != 0:
        offset += 1
    return string[:offset], string[offset:]

def solution(a, b):
    front_a, back_a = front_back(a)
    front_b, back_b = front_back(b)
    return front_a + back_a + front_b + back_b
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:]

在代码中使用 // 来进行除法运算,这样写可以让这段代码在 Python 2.x 和 3.x 版本中都能正常运行。

撰写回答