我一直在這里搜索了一下,似乎沒有什么能真正封裝我的實際問題,因為我希望給定的字串(如果它的字符符合我的標準)引起不同的 if 陳述句。我的代碼的目的是讓每個字母代表我的字串的旋轉。
示例部分['rotate'] = 'Ff'
allowed = ['F', 'f', 'R', 'r', 'B', 'b', 'L', 'l', 'U', 'u', 'D', 'd']
def rotated(parms):
result = {}
if ('cube' not in parms):
result['status'] = 'error: cube is missing!'
cube = list(parms['cube'])
if ('rotate' not in parms or parms['rotate'] == ''):
return rotateF(cube)
if (parms['rotate'] == 'F'):
return rotateF(cube)
if (parms['rotate'] == 'f'):
return rotatef(cube)
if (parms['rotate'] != allowed):
result['status'] = 'error: invalid rotation'
return result
def rotateF(cube):
rotatedCube = list(cube)
.....
rotatedCube = ''.join(rotatedCube)
return rotatedCube
def rotatef(cube):
rotatedCube = list(cube)
......
rotatedCube = ''.join(rotatedCube)
return rotatedCube
所以目前,我得到的回報是 'rotate' = 'Ff' :
{'status': 'error: invalid rotation'}
我的假設是,這是因為目前,我的代碼一次只允許一個字符,而我只想確保這些是唯一允許的字符,而不是每個字串一個字符。
uj5u.com熱心網友回復:
撰寫旋轉函式的方式是與特定字串進行比較,但似乎您提供的是旋轉串列(在 python 中,字串是字串列)。嘗試引入另一個輔助函式,拆分rotated為類似do_single_rotation, 和do_all_rotations(我省略了一些錯誤處理和諸如此類的內容,因為我不確定函式回傳的確切目標是什么)
default_rotate_str = 'F'
def do_all_rotations(parms):
rotate_str = parms.get('rotate', default_rotate_str)
cube = list(parms['cube'])
for rotate_command in rotate_str:
cube = do_single_rotation(cube, rotate_command)
return cube
def do_single_rotation(cube, rotate_command):
if rotate_command == 'F':
return rotate_F(cube)
if rotate_command == 'f';
return rotate_f(cube)
# .... continue
if rotate_command == 'D':
rotate_d(cube)
raise ValueError("unrecognized rotate command")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432489.html
下一篇:如何撰寫具有特定條件的awk代碼
