首页 > 解决方案 > 为什么 range 函数的末尾有一个 -1?

问题描述

我了解整个代码,我只想知道为什么 range 函数的末尾必须有一个 -1。

我一直在用 pythontutor 检查它,但我无法弄清楚。

#Given 2 strings, a and b, return the number of the positions where they 
#contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, 
#since the "xx", "aa", and "az" substrings appear in the same place in 
#both strings.

def string_match(a, b):
  shorter = min(len(a), len(b))
  count = 0

  for i in range(shorter -1): #<<<<<<<<< This is -1 I don't understand.
    a_sub = a[i:i+2]
    b_sub = b[i:i+2]
    if a_sub == b_sub:
      count = count + 1

  return count

string_match('xxcaazz', 'xxbaaz')
string_match('abc', 'abc')
string_match('abc', 'axc')

我希望了解为什么在 range 函数的末尾必须有一个 -1 。我将感谢您的帮助和解释!

标签: python-3.7

解决方案


for 循环的值索引被计算在内,0因此最终值实际上是(size -1)


推荐阅读