python-3.7 - 为什么 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 。我将感谢您的帮助和解释!
解决方案
for 循环的值索引被计算在内,0
因此最终值实际上是(size -1)
推荐阅读
- cassandra - Cassandra:需要将 cassandra 迁移到 log4j
- java - java - 如何在进程返回java时运行保证完成的后台任务?
- node.js - 如何延长node.js中相同jwt令牌的到期时间
- php - Laravel / 填充复选框
- reactjs - 谷歌图表的“仪表板不是构造函数”错误
- javascript - 为什么编辑对象后手表无法工作?
- angular - 是否可以在 Angular component.html 中解析尾随键为数字的对象?
- mercurial - 更改默认的“hg log”模板?
- java - 如何阅读书本本地 swf 文件夹?
- ajax - 带数据库的 AJAX