将eval(target[i9:i9+9])改为list(target[i9:i9+9])即可,因为eval会将字符串解析为变量名,但是这里的字符串不是变量名,所以会报错。而list函数则可以将字符串转换为列表。修改后的代码如下:

定义魔方初始状态和目标状态

start = "WWWBBBBBBGGGGGGYYYGGGWWWWWWBBBYYYYYYOOOOOOOOORRRRRRRRR" target = "WWWWWWWWWBBBBBBGGGGGGYYYRRRRRRRRROOOOOOOOOGGGGGGYYYYYBBB"

定义每个面的颜色索引

front = [0, 1, 2, 9, 10, 11, 18, 19, 20] back = [6, 7, 8, 15, 16, 17, 24, 25, 26] left = [0, 3, 6, 9, 12, 15, 18, 21, 24] right = [2, 5, 8, 11, 14, 17, 20, 23, 26] top = [0, 1, 2, 3, 4, 5, 6, 7, 8] bottom = [18, 19, 20, 21, 22, 23, 24, 25, 26]

定义旋转函数

def rotate(face, direction): # 根据旋转方向生成旋转后的面 if direction == "clockwise": new_face = [face[i] for i in [6, 3, 0, 7, 4, 1, 8, 5, 2]] else: new_face = [face[i] for i in [2, 5, 8, 1, 4, 7, 0, 3, 6]] return new_face

计算从初始状态到目标状态需要的步数和操作指令

steps = 0 instructions = [] for i in range(6): # 获取当前面的颜色索引和目标面的颜色索引 start_face = eval(['front', 'back', 'left', 'right', 'top', 'bottom'][i]) target_face = list(target[i9:i9+9]) # 如果当前面不是目标面,进行旋转操作 if start_face != target_face: # 选择旋转方向 if start_face[0] == target_face[2] and target_face[0] == start_face[2]: direction = "anticlockwise" else: direction = "clockwise" # 执行旋转操作 start_face = rotate(start_face, direction) faces = {'front': 0, 'back': 1, 'left': 2, 'right': 3, 'top': 4, 'bottom': 5} globals()[list(faces.keys())[list(faces.values()).index(i)]] = start_face # 记录操作指令 instructions.append([['front', 'back', 'left', 'right', 'top', 'bottom'][i], direction]) steps +=

# 定义魔方初始状态和目标状态start = WWWBBBBBBGGGGGGYYYGGGWWWWWWBBBYYYYYYOOOOOOOOORRRRRRRRRtarget = WWWWWWWWWBBBBBBGGGGGGYYYRRRRRRRRROOOOOOOOOGGGGGGYYYYYBBB# 定义每个面的颜色索引front = 0 1 2 9 10 11 18 19 20back = 6 7 8 15

原文地址: https://www.cveoy.top/t/topic/fFZz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录