-1

我是 python 新手,我必须创建一个验证 DNA 序列的程序。(DNA 序列的背景知识非常快)为了有效: • 字符数可被 3 整除 • 前 3 个字符是 ATG • 最后 3 个字符是 TAA、TAG 或 TGA。

我的问题在于在 if 语句中使用布尔术语。

        endswith=(DNA.endswith("TAA"))
endswith2=(DNA.endswith("TAG"))
endswith3=(DNA.endswith("TGA"))
if length%3==0 and startswith==true and endswith==true or endswith2==true or endswith3==true:
    return ("true")

此代码返回错误:未定义全局名称“true”

我该如何解决这个问题,而且最后一点我真的很抱歉。这个问题的答案可能非常简单,在你看来,一个 2 岁的孩子可以编写代码:/ 我做了研究,但我一点运气都没有。所以我感谢你花时间阅读我的愚蠢问题。

4

5 回答 5

5

容易得多:

return (len(DNA) % 3 == 0 and
        DNA.startswith("ATG") and
        DNA.endswith(("TAA", "TAG", "TGA")))

将布尔值与TrueorFalse进行比较几乎总是多余的,所以每当你发现自己这样做时......做其他事情;-)

于 2014-01-24T03:27:49.827 回答
2

在 python 中,true不是关键字,而是True.

在 python 中,你不必True很明显地比较变量,只需使用

if length%3==0 and startswith and endswith or endswith2 or endswith3:
于 2014-01-24T03:24:07.823 回答
1

第一件事:True不是true

第二件事:不说endswith == True,只说endswith

第三件事:and具有比 更高的优先级or,因此您所写的内容相当于:

(length%3==0 and startswith==true and endswith==true) or ...

这不是你的意思。

第四件事:最好说:

if len(DNA) % 3 == 0 and DNA.startswith('ATG') and DNA[-3:] in ('TAA', 'TAG', 'TGA'):

正如蒂姆指出的那样,DNA.endswith(('TAA', 'TAG', 'TGA'))节拍DNA[-3:] in .... 它更简单,无需测试,我希望它也会更快。如果你有很多允许的相同长度的结尾,并且你正在做很多测试,那么构建 set一次并in测试结束切片会更快。但三种可能性并不是“很多”。

于 2014-01-24T03:29:12.107 回答
0

类型:真-->真

你最好在问问题之前参考手册。

实际上,你可以使用这个:

if length%3 and startswith and endswith or ...

不需要写

if ... startswith == True ...
于 2014-01-24T03:26:26.323 回答
0

使用True,不使用truestartswith==True此外,您可以只使用startswith(例如:)来代替if length%3==0 and startswith and endswith ...

您还应该添加括号以使您的逻辑更具可读性。尽管优先级有据可查,但许多人并不知道。即使他们这样做,他们也无法判断您是否这样做。

if (length%3==0 and (startswith and endswith) or endswith2 or endswith3):
于 2014-01-24T03:27:31.183 回答