【问题标题】:Could you explain the solution to front_back google python exercise [closed]你能解释一下front_back谷歌python练习的解决方案吗?
【发布时间】: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 仅在您熟悉模运算符的情况下阅读这些词才有意义。这是一个合理的问题。

标签: python google-classroom


【解决方案1】:

您最困惑的语句似乎是if len(a) % 2 == 1:。在这种情况下,% 符号表示除以余数(模)。因此,如果字符串的长度为奇数,则将长度除以 2 的余数为 1,如果长度为偶数,则余数为 0。 if 语句检查余数是否为 1,因此长度是否为奇数。

之前将长度字符串除以 2 以找到字符串的中间位置。但是,由于len(string) 和 2 都是整数,python 会执行整数除法并将结果向下舍入为整数,这就是为什么如果长度为奇数则需要使用 if 语句添加额外的间距单位。

代码的最后一条语句然后使用切片语法根据之前找到的位置连接字符串的一半。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多