【问题标题】:Add a for loop if X = 1如果 X = 1,则添加 for 循环
【发布时间】: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

【问题讨论】:

    标签: python loops for-loop


    【解决方案1】:

    您甚至不需要depth 来解决您的问题。您可以检查您的对象是否是列表并使用如下递归:

    def translate(input_: Union[str, list]):
        sum = 0
        for i in input_:
            if isinstance(i, list):
                sum += translate(i)
            else:
                sum += 17 * ord(i)
        return sum
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2021-06-30
      • 1970-01-01
      • 2012-09-25
      相关资源
      最近更新 更多