rpiboy
Posts: 82
Joined: Mon Mar 20, 2017 8:39 pm

Noob lost been reading this code for hours

Wed Aug 09, 2017 2:32 am

Hi, Please, Hoping for a kind person that can help me understand this code. I've been trying to understand this code for hours on end. I understand what it is trying to do when I run it, but still would appreciate someone who will explain it thanks!

Code: Select all

import random
from urllib.request import urlopen
import sys

WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []

PHRASES = {
    "class %%%(%%%):":
     "Make a class named %%% that is-a %%%.",
    "class %%%(object):\n\tdef __init__(self, ***)" :
     "class %%% has-a __init__ that takes self and *** params.",
    "class %%% (object):\ntdef ***(self, @@@)":
     "class %%% has-a function *** that takes self and @@@ params.",
    "*** = %%%()":
     "Set *** to an instance of class %%%.",
    "***.***(@@@)":
     "From *** get the *** function, call it with params self, @@@.",
    "***.*** = '***'":
     "From *** get the *** attribute and set it to '***'."
}

if len(sys.argv) == 2 and sys.argv[1] == "english":
    PHRASE_FIRST =True
else:
    PHRASE_FIRST = False

for word in urlopen(WORD_URL).readlines():
    WORDS.append(str(word.strip(), encoding="utf-8"))

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[:]

        for word in class_names:
            result = result.replace("%%%", word, 1)

        for word in other_names:
            result = result.replace("***", word, 1)

        for word in param_names:
            result = result.replace("@@@", word, 1)

        results.append(result)

    return results

try:
    while True:
        snippets = list(PHRASES.keys())
        random.shuffle(snippets)

        for snippet in snippets:
            phrase = PHRASES[snippet]
            question, answer = convert(snippet, phrase)
            if PHRASE_FIRST:
                question, answer = answer, question
            print(question)
            input("> ")
            print("ANSWER: {}\n\n".format(answer))
except EOFError:
    print("\nBye")

bensimmo
Posts: 1739
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Noob lost been reading this code for hours

Wed Aug 09, 2017 7:12 am

Run it using Thonny (the new Python3 IDE for Raspbian) and follow it step by step seeing what happens as you go.
See if that helps.

rpiboy
Posts: 82
Joined: Mon Mar 20, 2017 8:39 pm

Re: Noob lost been reading this code for hours

Wed Aug 09, 2017 6:59 pm

OK, so I am trying to debug it.
I have this

Code: Select all

snippets = list(PHRASES.keys())
for snippet in snippets:
    phrase = PHRASES[snippet]
     print(phrase)
Now what I don't understand is this I see that it is printing out the key values but how is that doing it?

I know in a dict you get the values by doing variable[key] but isn't it converting it to a list? I thought a list gets it value by variable[number]. :?

User avatar
rpdom
Posts: 11521
Joined: Sun May 06, 2012 5:17 am
Location: Essex, UK

Re: Noob lost been reading this code for hours

Wed Aug 09, 2017 7:13 pm

Look at what the "for" statement is doing.

bensimmo
Posts: 1739
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Noob lost been reading this code for hours

Thu Aug 10, 2017 5:24 am

It's early, pre-coffee and so not check completely but see if it's doing this ?

Code: Select all

variable={"stuff":"things", }

list_of_keys = list(variable.keys())

for key in list_of_keys:
    phrase = variable[key]
    print(phrase)

User avatar
elParaguayo
Posts: 1876
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Noob lost been reading this code for hours

Thu Aug 10, 2017 9:35 am

I'm not sure the "list" line is necessary. Have a look at this:

Code: Select all

my_dict = {"key1": "value1", "key2": "value2"}
list_of_keys = list(my_dict.keys())
for key in list_of_keys: 
    print(my_dict[key])
outputs

Code: Select all

value2
value1
Simpler version:

Code: Select all

for key in my_dict: 
    print(my_dict[key])
outputs

Code: Select all

value2
value1
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

bensimmo
Posts: 1739
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Noob lost been reading this code for hours

Thu Aug 10, 2017 11:00 am

I think it's used as they shuffle the keys before proceeding in the full code in the original post.

User avatar
elParaguayo
Posts: 1876
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Noob lost been reading this code for hours

Thu Aug 10, 2017 11:03 am

Fair enough.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

Return to “Python”

Who is online

Users browsing this forum: paddyg and 13 guests