【问题标题】:Why does using a while loop make the program work but my original for loop doesn't work? (DNA pset6)为什么使用 while 循环可以使程序工作,但我原来的 for 循环不起作用? (DNA pset6)
【发布时间】:2020-09-05 02:28:20
【问题描述】:

刚刚完成 pset6 DNA,但我很困惑。在计算连续的 dna 序列时,如果我使用 for 循环遍历 dna 序列文本,我的代码将始终产生“不匹配”作为输出,但如果我将其更改为 while 循环以遍历 dna 序列它会工作。我不知道为什么。我在 while 循环部分下方注释掉了整个 for 循环部分。

任何帮助表示赞赏。

from sys import argv, exit
import csv

if len(argv) != 3:
    print("Usage: python dna.py data.csv sequence.txt")
    exit(1)

with open(argv[1], 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    for row in csv_reader:
        header = row
        header.pop(0)
        break

dictionary = {}

for item in header:
    dictionary[item] = 0

with open(argv[2], 'r') as dna_txt:
    dna_reader = dna_txt.read()

# This iteration using while loop works 
for key in dictionary:
    temp = 0 
    max_count = 0
    i = 0
    # This while loop works
    while i < len(dna_reader):
        if dna_reader[i : i + len(key)] == key:
            temp += 1
            if ((i + len(key)) < len(dna_reader)):
                i += len(key)
                continue
        else:
            if temp > max_count:
                max_count = temp
            temp = 0
        i += 1
    dictionary[key] = max_count

# This iteration does not work, only difference is for loop instead of while loop, why is that? Commented out so it doesn't interfere
'''for key in dictionary:
    temp = 0 
    max_count = 0

    # This for loop does not work

    for i in range(len(dna_reader)):
        if dna_reader[i : i + len(key)] == key:
            temp += 1
            if ((i + len(key)) < len(dna_reader)):
                i += len(key)
                continue
        else:
            if temp > max_count:
                max_count = temp
            temp = 0
    dictionary[key] = max_count'''

with open(argv[1], 'r') as file:
    table = csv.DictReader(file)
    for person in table:
        count = 0
        for dna in dictionary:
            if int(dictionary[dna]) == int(person[dna]):
                count += 1
            else:
                count = 0
            if count == len(header):
                print(person['name'])
                exit(1)

print('No match')
exit(0)

【问题讨论】:

标签: python cs50


【解决方案1】:

我能看到的唯一实质性区别是i += len(key) 的效果。在 for 循环中,i 变量将在每个循环开始时重新实例化。因此,这种说法没有实际效果。在while循环的情况下,相同的i变量被重用。

考虑这个例子:

for i in range(10):
    print(i)
    if i == 5:
        i += 2

这个输出将是:

0
1
2
3
4
5
6
7
8
9

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    • 2018-05-23
    • 1970-01-01
    • 2018-06-12
    相关资源
    最近更新 更多