【发布时间】:2021-12-27 12:53:36
【问题描述】:
我正在尝试创建一个将单词转换为数字的函数,如果深度为 1,则其中一个参数是“深度”,如果深度为 2,则该函数将知道“好的,我正在翻译一个单词”该函数将知道“现在我正在翻译单词列表”......等等
问题:
如果 X == Y,有一种形式可以添加“for”循环?这是函数的当前形式:def translate(input_: Union[str, list], depth: int = 3):
if depth == 1: # Just one word
sum: int = 0
for char in input_:
sum += 17 * ord(char)
return sum
if depth == 2: # list of words
buffer: list = []
for word in input_: # for each word in list
sum: int = 0
for char in word: # the same as depth == 1
sum += 17 * ord(char)
buffer.append(sum)
if depth == 3: # list of lists of words
buffer: list = []
for lst in input_:
for word in lst: # the same as depth == 2
sum: int = 0
for char in word:
sum += 17 * ord(char)
伪代码解决方案
在 Python 中存在这样的表单吗?:
If depth > 2:
MAIN.ADDFORLOOP(for LIST in INPUT) <- We added the for loop if there's more than one list to translate
if depth > 1:
MAIN.ADDFORLOOP(for WORD in LIST) <- We added a for loop if there's more than one word
Here, if depth is 3 all for loops will be created, if depth is two, just two for loops will be created, etc
MAIN.LOADALLTHEFORLOOPS()
for char in word:
# The function goes here
【问题讨论】: