Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top