How to write and run more than one code in Python

2019-03-02 19:59发布

问题:

How do you get that code, see below, run in IDLE? I am stuck in my course right now and I could not find an explanation. I know how to run in IDLE just one "def" or code, pressing F5, write e.g. hash_string('udacity', 3) in the shell, "Enter", result. In that code, with more than one code it will not work, of course. For a deeper understanding I want to run it in the Python Online Tutor, condition is that it will work in IDLE or vice versa. Further I would like to know, why the input #print hashtable_get_bucket(table, "Zoe") results in: #>>> [['Bill', 17], ['Zoe', 14]] Why does 'Bill', 17, appear in the list?

# Define a procedure, hashtable_get_bucket,
# that takes two inputs - a hashtable, and
# a keyword, and returns the bucket where the
# keyword could occur.

def hashtable_get_bucket(htable,keyword):
     return htable[hash_string(keyword,len(htable))]


def hash_string(keyword,buckets):
     out = 0
     for s in keyword:
        out = (out + ord(s)) % buckets
     return out

def make_hashtable(nbuckets):
     table = []
     for unused in range(0,nbuckets):
        table.append([])
     return table


#table = [[['Francis', 13], ['Ellis', 11]], [], [['Bill', 17],
#['Zoe', 14]], [['Coach', 4]], [['Louis', 29], ['Rochelle', 4], ['Nick', 2]]]

#print hashtable_get_bucket(table, "Zoe")
#>>> [['Bill', 17], ['Zoe', 14]]

#print hashtable_get_bucket(table, "Brick")
#>>> []

#print hashtable_get_bucket(table, "Lilith")
#>>> [['Louis', 29], ['Rochelle', 4], ['Nick', 2]]

Thanks for taking the time reading that post and for your suggestions, too!

回答1:

To answer your last question first: table is a triple list, so a list of lists containing lists. One of those lists is [['Bill', 17], ['Zoe', 14]]. Since hash_string returns an index, it retrieves one list out of table, which happens to be the one with Bill and Zoe.

Further, to run more than one function from within IDLE, you will have to create a new function (a new def my_assignment or something) that calls the other functions.

Hope this helps.