noviceUser
noviceUser

Reputation: 115

Python returning value inside recursive call of a function

I have some data that creates an array of numbers. Sometimes the numbers may be repeated. I want to create a unique file name for each number. So I came up with a hack to include 2 digits at the end of each number, and increment it whenever there is a repeat

The program seems to work fine in some instance and doesn't work properly some time.

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)

And the output is

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]   

Where am I going wrong?

Upvotes: 3

Views: 53

Answers (1)

Sunitha
Sunitha

Reputation: 12025

The problem is that you are returning the filename the top level function computed and not the one returned by the recursive function call

Change

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

to this

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

That being said, a much easier solution is to use 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]

Upvotes: 1

Related Questions