简体   繁体   中英

Python - How to turn an IF statement into a Function to call multiple times with other strings?

I need to check whether a permutation of a variable exists in another variable and increment a counter variable if it doesn't exist.

I've managed to create a conditional statement with for loops to make list of required permutations and check whether the variable exists in it. I need to turn it into a function so that i can make the code cleaner as i need the function to check multiple variables across multiple variables.

charList = ['A', 'B', 'C'] #actual code has other items in this list

name = "JOHN" #actual variable whose permutations are to be made for checking

checkName = "JOAN" #target variable to check against the permutations of above variable

counter = 0

if checkName is name:
    print('found1')
elif checkName in (name[:i] + c + name[i + 1:] for i in range(len(name)) for c in charList):
    print('found2')
elif checkName in ([name[:i] + c + name[i:] for i in range(len(name)) for c in charList]):
    print('found3')
elif checkName in ([name[0:i] + name[i+1] + name[i] + name[i+2:] for i in range(len(name) - 1)]):
    print('found4')
else:
    counter += 1
    print(counter)

How to make it into a function so that just by using another name variable I would directly get output of either the print statement or the increment in the counter?

I'm just a beginner so please help me understand the concept of making functions through this example. I have to deal with two variables one of which loops through a list, and being a noob i have no idea what to do.

PS I'm just learning and the above code is just a trial run so please ignore the print functions following each if statement.

You can try like this

charList = ['A', 'B', 'C'] #actual code has other items in this list

name = "JOHN" #actual variable whose permutations are to be made for checking

checkName = "JOAN" #target variable to check against the permutations of above variable

def checkName_fun(checkName, name):
    counter = 0

    if checkName is name:        
        return ('found1')
    elif checkName in (name[:i] + c + name[i + 1:] for i in range(len(name)) for c in charList):        
        return ('found2')
    elif checkName in ([name[:i] + c + name[i:] for i in range(len(name)) for c in charList]):        
        return ('found3')
    elif checkName in ([name[0:i] + name[i+1] + name[i] + name[i+2:] for i in range(len(name) - 1)]):        
        return ('found4')
    else:
        counter += 1
        return (counter)

checkName_fun(checkName, name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM