-1

Thanks for taking the time to ready thru my question.

At the moment I'm creating a method for a class, and below is what I've got so far.

def scramble_words_password(self, words):
    if words:
        words = words.split()
        words_count = range(len(words))

        while True:
            num = random.choice(words_count)
            del(words_count[num])
            password = [letter for letter in list(words[num])]

A few months ago i came across a tutorial, that explained how to assing functions to variables, and use something like random on them but i cant find it again...

What I want in my function/method is a way to randomly use letter.lower() and letter.upper() on the comprehension on the bottom line of my function/method, but how can i achieve that and still keep it all in the comprehension.

FYI, I know that the function ATM is an infinity loop, so no smart remarks please ;)

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Alexander
  • 88
  • 1
  • 8
  • Function names act much like variables. You can pass them into other functions as parameters or make a list of functions. – Code-Apprentice May 29 '17 at 07:13
  • I think your question is answered here: https://stackoverflow.com/questions/10354163/assigning-a-function-to-a-variable – rghome May 29 '17 at 10:17
  • 1
    Possible duplicate of [Assigning a function to a variable](https://stackoverflow.com/questions/10354163/assigning-a-function-to-a-variable) – rghome May 29 '17 at 10:18

2 Answers2

1

User random.choice over a list of methods to call:

def scramble_words_password(self, words):
    if words:
        words = words.split()
        words_count = range(len(words))
        words_funcs = [str.upper, str.lower]
        while True:
            num = random.choice(words_count)
            del(words_count[num])
            password = [random.choice(words_funcs)(letter) for letter in list(words[num])]

Main call explain, random.choice(words_funcs)(letter), will choose a random element from the list, as they are callables you can just pass the letter to them. Keep in mind that all methods from strings (also other built-in types) can be called statically, so a list with str.lower and str.upper will do.

Netwave
  • 40,134
  • 6
  • 50
  • 93
0

Function names act much like variables. You can pass them into other functions as parameters or make a list of functions. I suggest you create a list of functions and randomly select a list element.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268