如何在python中实现元胞自动机的概念

2024-06-19 19:22:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python还是个新手(一般来说,两个月前才开始编程)。我的任务是创建一个程序,该程序使用用户的起始字符串(即“11001100”)并根据一组规则打印每一代。启动字符串时,它会在用户重复时停止。然而,我不知道从哪里开始。我对元胞自动机(cellular automata)的概念理解不清,因此不知道如何将其实现为脚本。在

理想情况下,它将使用用户输入字符串“11001100”(gen0),并查看我创建的规则集并将其转换为“00110011”(gen1),然后将其再次转换为(gen3)和(gen4),直到它返回到用户提供的原始输入(gen0)。我的规则集如下:

print("What is your starting string?")

SS = input()
gen = [SS]
while 1:
    for i in range(len(SS)):
        if gen[-1] in gen[:-2]:
            break
    for g in gen:
        print(g)


newstate = {
    #this is used to convert the string. we break up the users string into threes. i.e if user enters 11001100, we start with the left most digit "1" and look at its neighbors (x-1 and x+1) or in this case "0" and "1". Using these three numbers we compare it to the chart below:
    '000': 1 ,
    '001': 1 ,
    '010': 0 ,
    '011': 0 ,
    '100': 1 ,
    '101': 1 ,
    '110': 0 ,
    '111': 0 ,
}

我将非常感谢任何帮助或进一步的解释/证明如何使这个工作。在


Tags: andthe字符串用户in程序forstring
2条回答

最简单的方法是re.sub公司()python regex模块中的方法,re。在

    import re

def replace_rule(string, new, pattern):
    return re.sub(pattern, new, string)

def replace_example(string):
    pattern = r"100"
    replace_with = "1"
    return re.sub(pattern, replace_with, string)

   replace_example("1009")
=> '19'
   replace_example("1009100")
=> '191'

Regex是一种将字符串与某些正则模式匹配的方法,并对它们执行某些操作,如sub,它查找并替换字符串中的模式。这里有一个链接:https://docs.python.org/3/library/re.html

假设newstate是一个有效的dict,其中键/值对对应于您的状态替换(如果您希望100转换为011newstate将具有{}),则可以对拆分字符串执行列表理解:

changed = ''.join(newstate[c] for c in prev)

其中prev是您以前的状态字符串。即:

^{pr2}$

然后,可以使用此列表组件通过在列表理解中调用自身来更改字符串本身:

>>> changed = '1010101'
>>> changed = ''.join(newstate[c] for c in changed)
>>> changed
'0101010'

原始代码中有基本的流程,但需要对其进行优化。psuedo代码看起来像:

newstate = dict with key\value mapping pairs
original = input

changed = original->after changing

while changed != original:
    changed = changed->after changing

print changed

相关问题 更多 >