我如何编写这样的随机源代码生成器?

-4 投票
0 回答
34 浏览
提问于 2025-04-12 01:15

简单来说,我想写一个Python程序,能够生成随机的源代码。为了更好地理解这个过程,可以把编程想象成一个魔方,而源代码的各个部分就像魔方里的小方块,比如“if”、“while”、“break”、“def”等等。我们通过移动这些小方块,就能拼出源代码。这个程序的输入是一个数字数组,其中奇数代表魔方中小方块的编号,而偶数则表示这个小方块要移动的步数。最后,程序会根据数组中的所有数字,读取每个小方块的移动情况,并在最后一个偶数的移动结束时,确定魔方的某一面。然后,它会从最上面的方块开始,依次读取所有数字,最终返回一段完整的源代码,并通过exec来执行这段代码。可是我想写这样的源代码,但总是无法实现这个想法,可能你们能给我一些建议,帮助我理清思路?我试过问ChatGPT,但它并没有理解我的意思:

import random 
 
def generate_random_source_code(moves): 
  # Creating an empty list to store the source code.
  source_code = [] 
  # We get the size of the side of the Rubik's cube from the last even number.
  side_size = moves[-1] // 2 
 
  # Going through the moves.
  for i in range(0, len(moves), 2): 
    # Checking to see if we are going beyond the list of moves.
    if i + 1 >= len(moves): 
      break 

    # We get the block number and the number of its movements. 
    block_number = moves[i] 
    num_moves = moves[i + 1] // 2 
 
    # Creating a displacement string for the block.
    move_string = "" 
    for j in range(num_moves): 
      move_string += f"block{block_number + j}.move()\n" 
 
    # Adding a string of moves to the source code.
    source_code.append(move_string) 
 
  # Creating a Rubik's cube reading string.
  read_string = "" 
  for i in range(side_size): 
    for j in range(side_size): 
      read_string += f"print(block{i * side_size + j}.value)\n" 
 
  # Returning the source code.
  return "".join(source_code) + read_string 
 
 
# Generating a random list of moves.
moves = [random.choice([1, 3, 5, 7, 9]) for i in range(10)] + [random.choice([2, 4, 6, 8, 10])] 
 
# We generate the source code.
source_code = generate_random_source_code(moves) 
 
# Executing the source code.
exec(source_code)

第二段代码:

import random 
 
def generate_random_source_code(moves): 
  source_code = "" 
 
  for i in range(0, len(moves), 2): 
    block_number = moves[i] 
    direction = moves[i + 1] 

    source_code += f"move_block({block_number}, {direction})\n" 
 
  return source_code 
 
 
moves = [random.randint(1, 9) for i in range(10)] 
 
source_code = generate_random_source_code(moves) 
 
print(source_code)

也许有人能提供一些想法,如何完整地实现这个创意,怎么写这样的代码?我需要理清这个想法的核心,想想怎么去实现它?有没有人能给我一些草图或者初步的思路呢?

0 个回答

暂无回答

撰写回答