Python在函数的递归调用中返回值

时间:2018-09-08 12:39:56

标签: python recursion return-value

我有一些创建数字数组的数据。有时数字可能会重复。我想为每个数字创建一个唯一的文件名。因此,我想出了一个方法,在每个数字的末尾都包含2位数字,并在出现重复的情况下将其递增

该程序在某些情况下似乎可以正常运行,并且有时无法正常运行。

numbers = [10, 20, 30, 30, 40, 50, 50, 50, 50, 60]
filenames = []


def check_name(checkFileName):
    if checkFileName in filenames:
        checkFileName += 1
        check_name(checkFileName)
        return checkFileName

    else:
        print("Def-Filename :", checkFileName)
        return checkFileName


for number in numbers:
    stringNumber = str(number)
    tempFileName = stringNumber + "00"
    tempFileInt = int(tempFileName)

    permFileName = check_name(tempFileInt)
    filenames.append(permFileName)
    print("Permanent File Name :", permFileName)
    print(filenames)

输出为

Def-Filename : 1000
Permanent File Name : 1000
[1000]
Def-Filename : 2000
Permanent File Name : 2000
[1000, 2000]
Def-Filename : 3000
Permanent File Name : 3000
[1000, 2000, 3000]
Def-Filename : 3001
Permanent File Name : 3001
[1000, 2000, 3000, 3001]
Def-Filename : 4000
Permanent File Name : 4000
[1000, 2000, 3000, 3001, 4000]
Def-Filename : 5000
Permanent File Name : 5000
[1000, 2000, 3000, 3001, 4000, 5000]
Def-Filename : 5001
Permanent File Name : 5001
[1000, 2000, 3000, 3001, 4000, 5000, 5001]
Def-Filename : 5002
Permanent File Name : 5001
[1000, 2000, 3000, 3001, 4000, 5000, 5001, 5001]
Def-Filename : 5002
Permanent File Name : 5001
[1000, 2000, 3000, 3001, 4000, 5000, 5001, 5001, 5001]
Def-Filename : 6000
Permanent File Name : 6000
[1000, 2000, 3000, 3001, 4000, 5000, 5001, 5001, 5001, 6000]   

我要去哪里错了?

1 个答案:

答案 0 :(得分:1)

问题是您要返回的是顶级函数的文件名,而不是递归函数调用返回的文件名

更改

if checkFileName in filenames:
    checkFileName += 1
    check_name(checkFileName)
    return checkFileName

对此

if checkFileName in filenames:
    checkFileName += 1
    return check_name(checkFileName)

话虽这么说,一种更简单的解决方案是使用collections.Counter

>>> from collections import Counter
>>> numbers = [10, 20, 30, 30, 40, 50, 50, 50, 50, 60]
>>> 
>>> [n*100 + i for n,cnt in Counter(numbers).items() for i in range(cnt)]
[1000, 2000, 3000, 3001, 4000, 5000, 5001, 5002, 5003, 6000]