假设我们有一个翻译莫尔斯符号的函数:
. - > -.- - > ...-如果我们两次应用此函数,我们得到例如:
.- > -.- >...--.
给定输入字符串和重复次数,想知道最终字符串的长度.(佛兰芒编程竞赛 VPW中的问题1 ,取自这些在Haskell中提供解决方案的幻灯片).
对于给定的输入文件
4
. 4
.- 2
-- 2
--... 50
Run Code Online (Sandbox Code Playgroud)
我们期待解决方案
44
16
20
34028664377246354505728
Run Code Online (Sandbox Code Playgroud)
由于我不知道Haskell,这是我在Python中提出的递归解决方案:
def encode(msg, repetition, morse={'.': '-.', '-': '...-'}):
if isinstance(repetition, str):
repetition = eval(repetition)
while repetition > 0:
newmsg = ''.join(morse[c] for c in msg)
return encode(newmsg, repetition-1)
return len(msg)
def problem1(fn):
with open(fn) as f:
f.next()
for line in …Run Code Online (Sandbox Code Playgroud) 我有一组n(~1000000)字符串(DNA序列)存储在列表trans中.我必须找到列表中所有序列的最小汉明距离.我实施了一个天真的暴力算法,它运行了一天多,还没有给出解决方案.我的代码是
dmin=len(trans[0])
for i in xrange(len(trans)):
for j in xrange(i+1,len(trans)):
dist=hamdist(trans[i][:-1], trans[j][:-1])
if dist < dmin:
dmin = dist
Run Code Online (Sandbox Code Playgroud)
有没有更有效的方法来做到这一点?Hamdist是我写的一个函数,用于查找汉明距离.它是
def hamdist(str1, str2):
diffs = 0
if len(str1) != len(str2):
return max(len(str1),len(str2))
for ch1, ch2 in zip(str1, str2):
if ch1 != ch2:
diffs += 1
return diffs
Run Code Online (Sandbox Code Playgroud) 我明白,我应该使用os.urandom()或SystemRandomPython中的"安全"的伪随机数.
但是Python如何在逻辑上生成这些随机数?
还有一种方法可以在Python中生成一个比其他更"随机"的数字吗?
我有一个简单的 if-else 语句
if(this.props.params.id){
//do something
}
Run Code Online (Sandbox Code Playgroud)
现在,这在浏览器中运行良好。如果参数中有 id,则进入 if 子句;如果没有 id,则不进入 if 子句。
现在,在用 jest 编写测试时,当未定义 id 时,它会抛出错误:“无法读取未定义的属性'id'”为什么会发生这种情况,不应该将其视为 false 吗?它在浏览器中运行良好,只是在测试时会抛出错误。
我numpy从http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy下载了一个预编译的二进制文件,并尝试numpy在Windows 7上升级我当前的安装程序
pip install --upgrade "numpy-1.10.4 vanilla-cp27-none-win32.whl"
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
C:\Users\Jeroen\AppData\Local\Enthought\Canopy\User\Scripts\pip-script.py run on 04/01/16 13:20:05
Unpacking c:\users\jeroen\downloads\numpy-1.10.4 vanilla-cp27-none-win_amd64.whl
Installing collected packages: numpy
Cleaning up...
Exception:
Traceback (most recent call last):
File "C:\Users\Jeroen\AppData\Local\Enthought\Canopy\User\lib\site-packages\pip\basecommand.py", line 122, in main
status = self.run(options, args)
File "C:\Users\Jeroen\AppData\Local\Enthought\Canopy\User\lib\site-packages\pip\commands\install.py", line 283, in run
requirement_set.install(install_options, global_options, root=options.root_path)
File "C:\Users\Jeroen\AppData\Local\Enthought\Canopy\User\lib\site-packages\pip\req.py", line 1435, in install
requirement.install(install_options, global_options, *args, **kwargs)
File "C:\Users\Jeroen\AppData\Local\Enthought\Canopy\User\lib\site-packages\pip\req.py", line 671, in install
self.move_wheel_files(self.source_dir, root=root)
File "C:\Users\Jeroen\AppData\Local\Enthought\Canopy\User\lib\site-packages\pip\req.py", line 901, in move_wheel_files
pycompile=self.pycompile,
File "C:\Users\Jeroen\AppData\Local\Enthought\Canopy\User\lib\site-packages\pip\wheel.py", …Run Code Online (Sandbox Code Playgroud) 我有一个带有输入字段的Bootstrap 4表单,称为runname.我想在输入字段上执行以下验证:
runname 不能为空runname 不能包含空格runname以前不能使用我已经有一个表单的代码,如果输入字段为空,则使用自定义Bootstrap样式给出错误:
// JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})(); …Run Code Online (Sandbox Code Playgroud)我向CareerBuilder API发送GET请求:
import requests
url = "http://api.careerbuilder.com/v1/jobsearch"
payload = {'DeveloperKey': 'MY_DEVLOPER_KEY',
'JobTitle': 'Biologist'}
r = requests.get(url, params=payload)
xml = r.text
Run Code Online (Sandbox Code Playgroud)
并获得一个看起来像这样的XML .但是,我无法解析它.
使用其中之一 lxml
>>> from lxml import etree
>>> print etree.fromstring(xml)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
print etree.fromstring(xml)
File "lxml.etree.pyx", line 2992, in lxml.etree.fromstring (src\lxml\lxml.etree.c:62311)
File "parser.pxi", line 1585, in lxml.etree._parseMemoryDocument (src\lxml\lxml.etree.c:91625)
ValueError: Unicode strings with encoding declaration are not supported.
Run Code Online (Sandbox Code Playgroud)
要么 ElementTree:
Traceback (most recent call last):
File …Run Code Online (Sandbox Code Playgroud) 我有一个像这样的列表列表
matches = [[['rootrank', 'Root'], ['domain', 'Bacteria'], ['phylum', 'Firmicutes'], ['class', 'Clostridia'], ['order', 'Clostridiales'], ['family', 'Lachnospiraceae'], ['genus', 'Lachnospira']],
[['rootrank', 'Root'], ['domain', 'Bacteria'], ['phylum', '"Proteobacteria"'], ['class', 'Gammaproteobacteria'], ['order', '"Vibrionales"'], ['family', 'Vibrionaceae'], ['genus', 'Catenococcus']],
[['rootrank', 'Root'], ['domain', 'Archaea'], ['phylum', '"Euryarchaeota"'], ['class', '"Methanomicrobia"'], ['order', 'Methanomicrobiales'], ['family', 'Methanomicrobiaceae'], ['genus', 'Methanoplanus']]]
Run Code Online (Sandbox Code Playgroud)
我想从它们构建系统发育树。我写了一个像这样的节点类(部分基于此代码):
class Node(object):
"""Generic n-ary tree node object
Children are additive; no provision for deleting them."""
def __init__(self, parent, category=None, name=None):
self.parent = parent
self.category = category
self.name = name
self.childList = [] …Run Code Online (Sandbox Code Playgroud) 我有一个列表,可以包含Nones和datetime对象.我需要在连续datetime对象的子列表中拆分它,并需要datetime在原始列表中记录该子列表的第一个对象的索引.
例如,我需要能够转向
original = [None, datetime(2013, 6, 4), datetime(2014, 5, 12), None, None, datetime(2012, 5, 18), None]
Run Code Online (Sandbox Code Playgroud)
成:
(1, [datetime.datetime(2013, 6, 4, 0, 0), datetime.datetime(2014, 5, 12, 0, 0)])
(5, [datetime.datetime(2012, 5, 18, 0, 0)])
Run Code Online (Sandbox Code Playgroud)
我尝试了两种方法.一个使用find:
binary = ''.join('1' if d else '0' for d in original)
end = 0
start = binary.find('1', end)
while start > -1:
end = binary.find('0', start)
if end < 0:
end = len(binary)
dates …Run Code Online (Sandbox Code Playgroud) 我有一个自定义对象列表,我想从中删除重复项.通常情况下,你会被定义都做到这一点__eq__,并__hash__为您的对象,然后取set对象的列表中.我已经定义了__eq__,但是我无法找到一种好的方法来实现__hash__它为相等的对象返回相同的值.
更具体地说,我有一个派生自ete3工具包中的Tree类的类.如果Robinson-Foulds距离为零,我已将两个对象定义为相等.
from ete3 import Tree
class MyTree(Tree):
def __init__(self, *args, **kwargs):
super(MyTree, self).__init__(*args, **kwargs)
def __eq__(self, other):
rf = self.robinson_foulds(other, unrooted_trees=True)
return not bool(rf[0])
newicks = ['((D, C), (A, B),(E));',
'((D, B), (A, C),(E));',
'((D, A), (B, C),(E));',
'((C, D), (A, B),(E));',
'((C, B), (A, D),(E));',
'((C, A), (B, D),(E));',
'((B, D), (A, C),(E));',
'((B, C), (A, D),(E));',
'((B, A), (C, D),(E));',
'((A, …Run Code Online (Sandbox Code Playgroud) python ×8
algorithm ×2
bigdata ×1
bootstrap-4 ×1
cherrypy ×1
elementtree ×1
equality ×1
ete3 ×1
hash ×1
javascript ×1
jestjs ×1
lxml ×1
numpy ×1
phylogeny ×1
random ×1
reactjs ×1
recursion ×1
tree ×1
validation ×1
xml ×1