我编写了这段代码,它对以下各项工作正常:
编写代码以检查通过input()给出的字符串是否仅包含有效字符,但是一旦到达一个无效字符,则停止。因此,如果字符串有效,则打印有效的 string 。如果字符串无效,则在该点之前打印无效的字符串。
但是现在我必须为此使用while循环,但我无法完成它,你们可以帮我还是向我解释如何在保持完全相同的功能的同时将这段代码转换为while循环。
file = input()
invalid_letter_found = False
correct_letters = []
for current_letter in file:
if current_letter in ['A', 'T', 'G', 'C']:
correct_letters.append(current_letter)
continue
elif current_letter != ['A', 'T', 'G', 'C']:
invalid_letter_found = True
break
if invalid_letter_found == True:
print(f'invalid {"".join(correct_letters)}')
else:
print(f'valid {"".join(correct_letters)}')
答案 0 :(得分:1)
file = input()
n=len(file)
lst=[]
for alp in file: # this will convert the string to list, you can use any other method if you don't want for loop
lst.append(alp) #Here the conversion ends
invalid_letter_found = False
correct_letters = []
i= 0
while i < n:
if lst[i] in ["A", "T", "G", "C"]:
correct_letters.append(lst[i])
i += 1
continue
elif lst[i] != ["A", "T", "G", "C"]:
invalid_letter_found = True
break
if invalid_letter_found == True:
print(f'invalid {"".join(correct_letters)}')
else:
print(f'valid {"".join(correct_letters)}')
答案 1 :(得分:0)
虽然您需要使用while循环的唯一原因是这是否是一项家庭作业问题,但以下是正确方向的提示:
current_letter = file[0]
file = file[1:]
while len(file):