Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about a function in Learn Python the Hard Way ex41?

I got stuck on another part of this exercise. The program that is being coded allows you to drill phrases (It gives you a piece of code, you write out the English translation) and I'm confused on how the "convert" function works. Full code: http://learnpythonthehardway.org/book/ex41.html

def convert(snippet, phrase):
    class_names = [w.capitalize() for w in
                   random.sample(WORDS, snippet.count("%%%"))]
    other_names = random.sample(WORDS, snippet.count("***"))
    results = []
    param_names = []

    for i in range(0, snippet.count("@@@")):
        param_count = random.randint(1,3)
        param_names.append(', '.join(random.sample(WORDS, param_count)))

    for sentence in snippet, phrase:
        result = sentence[:]

        # fake class names
        for word in class_names:
            result = result.replace("%%%", word, 1)

        # fake other names
        for word in other_names:
            result = result.replace("***", word, 1)

        # fake parameter lists
        for word in param_names:
            result = result.replace("@@@", word, 1)

        results.append(result)

    return results

I'm pretty lost. Is "w" from w.capitalize() a file itself, or is it just referring to the objects in the list? I'm also not sure why the .count() function is in the argument for .sample() (or what .sample() really does). What is the purpose of the first for_loop?

Thank you for any and all help - I'm sorry for the barrage of questions.

like image 346
Rachel Avatar asked Oct 17 '25 01:10

Rachel


2 Answers

If it can help you,

class_names = [w.capitalize() for w in
            random.sample(WORDS, snippet.count("%%%"))]

is equivalent to

class_names = []
for w in random.sample(WORDS, snippet.count("%%%")):
    class_names.append(w.capitalize())

The .count() will return the number of occurence of "%%%" in the snippet string, so the random.sample will select a subset of N elements from the WORDS list where N is the element of "%%%" in the snippet string.

like image 63
Sébastien Bernery Avatar answered Oct 18 '25 18:10

Sébastien Bernery


w.capitalize() is like .uppercase(), but it only captilizes the first character.

like image 35
Khalid Melouka Avatar answered Oct 18 '25 18:10

Khalid Melouka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!