0

Is that considered recursion?

I wrote a code for a password generator function and added a condition in the function such that: If the random password is repeated (generated before): the function returns itself (return func()) I'm new to the recursion concept and that project was a good chance to try it, but I don't actually know if such a condition would be met so that I can check if the code works.

5th Feb 2020, 1:51 PM
Ali Abdelhady
Ali Abdelhady - avatar
5 Respostas
+ 6
You call your function again from the inside of the function, so formally it's recursive. However: The condition you wrote, never seems to be true, so the recursion is never actually kicked off. Try to run this version: import string, random # By: Ali Abdelhady L = [] # A random password generator def password(i): """ A function that generates a random password """ print(i) a = [i for i in (string.ascii_letters + string.digits + '@#$%^&*?></!~')] b = '' max_len = random.randint(9, 16) for char in range(max_len): c = random.choice(a) b += c if b not in L: # base case L.append(b) return b else: return password(i+1) # recursion print('here is a password suggestion:') for i in range(1000): print(password(0)) I print out an index, with each recursive call increasing by one, and call the password a thousand times. But if you look at it, index remains 0 in every case.
5th Feb 2020, 2:22 PM
HonFu
HonFu - avatar
+ 7
Hi, a recursion has the following pattern: fun recursion(value): if...... return sth else return recursion(anotherValue) your code is slightly different although it has some elements of recursion. If you run password() the first time, L is empty and your password is not in L. the recursive call will never be executed. Idea: call password() if generated pw is not in the List (I promise - you get a time out) One Idea to make it a bit recurslve is to generate exactly 10 Passwords. Changing your prog a littlebit could lead to that prog: https://code.sololearn.com/cRZPFpH56k0L/#py
5th Feb 2020, 2:36 PM
Oma Falk
Oma Falk - avatar
+ 4
Can you show us your code? Let's have a look at it!
5th Feb 2020, 2:09 PM
HonFu
HonFu - avatar
5th Feb 2020, 2:16 PM
Ali Abdelhady
Ali Abdelhady - avatar
0
HonFu Thank you So, the condition is not really needed, sometimes I have that habit of trying to make things perfect😅😅
5th Feb 2020, 2:34 PM
Ali Abdelhady
Ali Abdelhady - avatar