簡體   English   中英

為什么使用 while 循環可以使程序工作,但我原來的 for 循環不起作用? (DNA pset6)

[英]Why does using a while loop make the program work but my original for loop doesn't work? (DNA pset6)

剛剛完成 pset6 DNA,但我很困惑。 在計算連續的 dna 序列時,如果我使用 for 循環遍歷 dna 序列文本,我的代碼將始終生成“不匹配”,如 output,但如果我將其更改為 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)

我能看到的唯一實質性區別是i += len(key)的效果。 在 for 循環中, i變量將在每個循環開始時重新實例化。 因此,這種說法沒有實際作用。 在 while 循環的情況下,重復使用相同的i變量。

考慮這個例子:

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

output 將是:

0
1
2
3
4
5
6
7
8
9

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM