我为我生成的Python编写了以下工作代码。这是一个基于Lindenmayer的重写系统。输出C是:+-LF+RFR+FL-F-+RF-LFL-FR+F+RF-LFL-FR+-F-LF+RFR+FL-+,我可以解释它来绘制空间填充曲线.C是起始字母,进程执行n次。
C = 'L'
n = 2
Code = {ord('L'):'+RF-LFL-FR+',
ord('R'):'-LF+RFR+FL-'}
while n:
C = C.translate(Code)
n -=1
print C现在我想要的是,代码是自动从列表中写出来的。例如,我有一个列表R=[['L', '+RF-LFL-FR+'], ['R', '-LF+RFR+FL-']],它应该自动插入到代码中,因此我可以进一步使用它。每个子列表的第一个元素应该插入到ord()方法中,第二个元素应该插入冒号之后。有什么建议吗?
我通过理解列表找到了一种方法。列表R是L=+RF-LFL-FR+, R=-LF+RFR+FL-。现在我问是否有一种更有效的方法来获取代码?
R = ['L=+RF-LFL-FR+','R=-LF+RFR+FL-']
A = 'L'
for i in range(0,len(R)):
R[i]=R[i].split('=')
print R
Start = []
Rule = []
for i in range(0,len(R)):
Start.append(R[i][0])
Rule.append(R[i][1])
#mapping via list comprehension
while n:
A=''.join([Rule[Start.index(i)] if i in Start else i for i in A])
n -=1
print A发布于 2017-11-23 11:14:11
很明显这对你有好处。代码运行在python3上。
def fun1(n):
axiom = 'L'
rules = ['L=+RF-LFL-FR+','R=-LF+RFR+FL-']
# Convert the rules into a translation table.
rules = [ r.split('=') for r in rules ]
table = dict((ord(key), value) for (key, value) in dict(rules).items())
# Expand
string = axiom
for i in range(n):
string = string.translate(table)
return string编辑:我发现了第二种使用内置map函数的方法:
def fun2(n):
axiom = 'L'
rules = ['L=+RF-LFL-FR+','R=-LF+RFR+FL-']
# Convert the rules into a translation table.
rules = [ r.split('=') for r in rules ]
table = dict(rules)
lookup = lambda c: table[c] if c in table else c
string = axiom
for i in range(n):
# Map
string = map(lookup, string)
# "Reduce": from list of strings to string
string = ''.join(string)
return stringTiming:为了检查运行时,我执行了n=10的候选项,这将导致一个字符串,该字符串的字符约为3‘500’。您的实现(当然没有打印操作)我命名为fun3(n)。我使用%timeit命令在ipython中测量结果。
%timeit fun1(n=10)
10 loops, best of 3: 143 ms per loop
%timeit fun2(n=10)
10 loops, best of 3: 195 ms per loop
%timeit fun3(n=10)
10 loops, best of 3: 152 ms per loop系统:Python3.5.2,MacBook Pro (Retina,15英寸,2015年中期),2.8 GHz英特尔核心i7。
汇总:我的第一个建议和您的实现的执行速度一样快,与我的版本相比略有优势,特别是在可读性方面。map方法没有回报。
我还尝试了第四个版本,其中的输出数组是预先分配的,但是代码正在被涉及,python的内存分配逻辑在运行时显然比我的预分配方法好2倍。我没有对此作进一步的调查。
https://stackoverflow.com/questions/47415746
复制相似问题