【发布时间】:2017-06-26 22:21:26
【问题描述】:
我正在寻找对 front_back google python 练习的解决方案的解释。具体来说,我不明白为什么使用 % 符号(占位符?)。我也不明白为什么字符串的长度要除以 2。尤其是因为 2 不等于 1 (2==1??)
问题/解决方案如下:
# 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+++
# LAB(begin solution)
# Figure out the middle position of each string.
a_middle = len(a) / 2
b_middle = len(b) / 2
if len(a) % 2 == 1: # add 1 if length is odd
a_middle = a_middle + 1
if len(b) % 2 == 1:
b_middle = b_middle + 1
return a[:a_middle] + b[:b_middle] + a[a_middle:] + b[b_middle:]
# LAB(replace solution)
# return
# LAB(end solution)
谢谢!
【问题讨论】:
-
% 不是占位符。这是模运算符。第一次使用上面的注释告诉您该行在做什么。 cmets 会准确地告诉您为什么要进行 2 除法。我建议您找到 Python 的教程之一。在 python.org 上有一个它们的列表。 (至少,您应该阅读您发布的代码中的 cmets。它们解释得很清楚,但您必须实际阅读其中的文字。)
-
@KenWhite 仅在您熟悉模运算符的情况下阅读这些词才有意义。这是一个合理的问题。