user13508239
user13508239

Reputation: 35

Walking through a Directed Graph Python

I know this is not the place to ask for homework answers, but I just want some direction since I'm completely lost. I started a Python course at my college where the professor assumes no one has experience in the language. This is our first assignment:

Build on this code to create a subsequent loop that starts at W and takes a random walk of a particular maximum length specified as a variable. If there are multiple possible next states, choose one uniformly at random. If there are no next states, then you should stop the loop, even if you haven't reached your maximum length.

I understand that this code my professor provided is walking through each character of the string s, but I don't know how it's actually working. I don't get what c in enumerate(s) or next[c]=[] are doing. Any help explaining how this works or how to handle characters and strings in Python would be greatly appreciated. I've been coding in other languages for a few years and I have no idea how to even start this assignment.

next = {} # This will hold the directed graph
s = "Welcome to cs 477"
# This loops through all of the characters in s
# and keeps track of their indices
for i, c in enumerate(s): 
    if not c in next:
        # If this is the first time seeing a particular 
        # character, we need to make a new key/value pair for it
        next[c] = []
    if i < len(s)-1: # If there is a character after this
        # Record that s[i+1] is one of the following characters
        next[c].append(s[i+1])

Upvotes: 0

Views: 337

Answers (1)

E. Ferreira
E. Ferreira

Reputation: 159

enumerate(s) allows you to iterate over a list getting both the ith element in the list and the position it's in, as detailed here. In your case, the variable i holds the number of the current element starting from 0 and c the current character. If you were to print i and c inside your for loop, the result would look like this:

for i, c in enumerate(s):
    print(i, c)
# 0, W
# 1, e
# 2, l
# ...

Regarding next[c] = [], you need to first understand that next is a dictionary, which is basically a hash set. What next[c] = [] is doing, is adding the character c to the dictionary as the key, and it's value as an empty list.

Upvotes: 1

Related Questions