Python 3“进化”代码

2024-04-24 00:33:51 发布

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

我想试着做一个进化的代码,你知道,看看我能不能。你知道吗

长话短说,我不能

__author__ = 'kim'
import random
import string
import fileinput
import os



#Random letter
random_letter = random.choice(string.ascii_letters)
print(random_letter)
#Other Random Letter
other_random_letter = random.choice(string.ascii_letters)
print(other_random_letter)

for line in fileinput.input("file.py", inplace=True):
    print(line.replace(other_random_letter, random_letter), end='')

os.system("python3 file.py")

我想做的是用乱七八糟的代码替换随机数量的代码。如果代码崩溃,它将从一个名为故障安全.py并替换文件文件.py你知道吗


Tags: 代码pyimportstringoslineasciirandom
1条回答
网友
1楼 · 发布于 2024-04-24 00:33:51

我会和exec一起做:

import random
import string

code = ''

for i in range(1000): #1000 iterations
    if random.randint(0, 1):
        code += random.choice(string.ascii_letters)
    else:
        code = random.choice(string.ascii_letters)

    try:
        print ('trying code: ' + code)
        exec(code)
    except:
        print('It crashed... adding another letter... it will surely work now!')

现在,让我告诉你这将永远不会工作,这几乎是不可能的,它将产生一个有意义的代码行(顺便说一句,你应该包括空间太多)随机选择). 你知道吗

我知道你想做什么,我以前也做过,但你需要一个特殊的虚拟机,有一个字节的命令,这样更容易产生有效的代码。你知道吗

相关问题 更多 >