PLEASE REFER TO THE IMAGES FOR INSTRUCTIONS PLEASE USE STARTER CODE - CODE IN PYTHON3   ### starter  code import random def spider_web(web_map, starting_place, destination):     pass     def spider_web_rec(web_map, starting_place, destination, visited):     pass

C++ Programming: From Problem Analysis to Program Design
8th Edition
ISBN:9781337102087
Author:D. S. Malik
Publisher:D. S. Malik
Chapter18: Stacks And Queues
Section: Chapter Questions
Problem 16PE: The implementation of a queue in an array, as given in this chapter, uses the variable count to...
icon
Related questions
Question

PLEASE REFER TO THE IMAGES FOR INSTRUCTIONS

PLEASE USE STARTER CODE - CODE IN PYTHON3

 

### starter  code

import random

def spider_web(web_map, starting_place, destination):

    pass

 

 

def spider_web_rec(web_map, starting_place, destination, visited):

    pass

 

 

def make_spider_web(num_nodes, seed=0):

    if seed:

        random.seed(seed)

 

    web_map = {}

 

    for i in range(1, num_nodes + 1):

        web_map[f'Node {i}'] = []

 

    for i in range(1, num_nodes + 1):

        sample = random.sample(list(range(i, num_nodes + 1)), random.randint(1, num_nodes - i + 1))

        print('sample', i, sample)

        for x in sample:

            if i != x:

                web_map[f'Node {i}'].append(f'Node {x}')

                web_map[f'Node {x}'].append(f'Node {i}')

    return web_map

 

if __name__ == '__main__':

    num_nodes, seed = [int(x) for x in input('Input num_nodes, seed: ').split(',')]

    the_web = make_spider_web(num_nodes, seed)

    print(spider_web(the_web, 'Node 1', f'Node {num_nodes}'))

 

Allowed Built-ins/Methods/etc

  • Declaring and assigning variables, ints, floats, bools, strings, lists, dicts.
  • Using +, -, *, /, //, %, **; +=, -=, *=, /=, //=, %=, **= where appropriate
  • Comparisons ==,›, b, in
  • Logical and, or, not • if/elif/else, nested if statements
  • Casting int(x), str(x),float(x), (technically bool(x))
  • For loops, both Pori and for each type.
  • While loops

 sentinel values, boolean flags to terminate while loops

  • Lists, list(), indexing, i.e. try or myJist[3]

2d-lists if you want them/need them my_2d[i][j]

Append, remove o list slicing

  • If you have read this section, then you know the secret word is: createous.
  • String operations, concatenation +, +=, strip(), join(), upper(), lower(), isupper(), islower(), rjust(), ljust()

string slicing

  • Print, with string formatting, with end= or sep=:

'{}'format(var),' %d% some_int, f-strings

Really the point is that we don't care how you format strings in Python

Ord, chr, but you won't need them this time.

  • Input, again with string formatting in the prompt, casting the returned value.
  • Dictionaries
    • creation using dict(), or {}, copying using dict(other_dict)
    • .get(value, not_found_value) method
    • accessing, inserting elements, removing elements.
  • Using the functions provided to you in the starter code.  
  • Using import with libraries and specific functions as allowed by the project/homework.  
  • Recursion

Forbidden Built-ins/Methods/etc

 

This is not a complete listing, but it includes:

  • break, continue
  • methods outside those permitted within allowed types
    • for instance str.endswith
    • list.index, list.count, etc.
  • Keywords you definitely don't need: await, as, assert, async, class, except, finally, global, lambda, nonlocal, raise, try, yield
  • The is keyword is forbidden, not because it's necessarily bad, but because it doesn't behave as you might expect (it's not the same as ==).  
  • built in functions: any, all, breakpoint, callable, classmethod, compile, exec, delattr, divmod, enumerate, filter, map, max, min, isinstance, issubclass, iter, locals, oct, next, memoryview, property, repr, reversed, round, set, setattr, sorted, staticmethod, sum, super, type, vars, zip
  • If you have read this section, then you know the secret word is: argumentative.  
  • exit() or quit()
  • If something is not on the allowed list, not on this list, then it is probably forbidden.  
  • The forbidden list can always be overridden by a particular problem, so if a problem allows something on this list, then it is allowed for that problem.  
Whenever you visit a node, mark it as visited, and then don't go
there again.
But how do we set all this up if the function we need to call is:
def spider web (web map, starting place, destination):
Here's the next hint: Make a recursive helper function that does
most of the work that is called by the function you are required to
make.
Can the signature be the same of the recursive helper?
def spider web helper (web map, current place, destination, visited):
Note that the signature is different. The reason is because we need
to keep the visited list and pass it around all the recursive calls.
Lastly, how do we stop? Perhaps we should have considered this
first, but that's the way I wrote this so let's consider it now. We stop
in two ways. Either we exhaust all our options and everything is
visited. We never actually check if everything is visited but we will
run out of options and not find a path.
But, if we do find a path, we should return a list representing the
path. What is the first link in the chain of that path? When the
current_place is equal to the destination. That tells us that our
search is complete and we found the end of the path.
As the recursion unwinds we should add the current_place to the
path until we have reached the top of the recursion, then return that
list to the big spider_web function. Finally that function will return
that list to the caller.
Transcribed Image Text:Whenever you visit a node, mark it as visited, and then don't go there again. But how do we set all this up if the function we need to call is: def spider web (web map, starting place, destination): Here's the next hint: Make a recursive helper function that does most of the work that is called by the function you are required to make. Can the signature be the same of the recursive helper? def spider web helper (web map, current place, destination, visited): Note that the signature is different. The reason is because we need to keep the visited list and pass it around all the recursive calls. Lastly, how do we stop? Perhaps we should have considered this first, but that's the way I wrote this so let's consider it now. We stop in two ways. Either we exhaust all our options and everything is visited. We never actually check if everything is visited but we will run out of options and not find a path. But, if we do find a path, we should return a list representing the path. What is the first link in the chain of that path? When the current_place is equal to the destination. That tells us that our search is complete and we found the end of the path. As the recursion unwinds we should add the current_place to the path until we have reached the top of the recursion, then return that list to the big spider_web function. Finally that function will return that list to the caller.
Spider Webbing
Create a recursive function in a file called spider_web.py:
This is going to be a guided problem more than most of the others on this homework. This will teach you some basic
pathfinding in a network (graph) for the project. You can use this problem to build your project so l would recommend
working on this problem until you understand it.
Imagine there is a spider web:
Our goal is to find a path (not the best path, but just any path) from A to Z You see that the green path is not the
shortest but it does let us navigate from start to finish.
How can we do this?
First, we need to know A and Z, our starting and ending points. We'll pass these into our function.
I'm going to use a dictionary to represent this graph. Each node (vertex, circle) will have a name, in this case "A" and 'Z"
were the names of the nodes, but in the generated maps l'm going to use "Node 1", "Node 2", "Node 3", etc.
Here is an example web_map
web_map = {
"Node 1: ['Node 3, 'Node 2],
"Node 2: ['Node 1', 'Node 41.
"Node 3: [Node l],
Node 4: ['Node 2]
}
Nodel is connected to 2 and 3 for instance, and then also note that Node 3 is connected back to Node 1. Similariy, Node
2 is connected back to Node 1.
Then there's a connection between Node 2 and Node 4 that also goes both ways. All connections in our web will be
bi-directional.
So, in order to find the path from the start to the finish we should check if there's a path recursively through any of the
nodes connected to wherever we start.
Transcribed Image Text:Spider Webbing Create a recursive function in a file called spider_web.py: This is going to be a guided problem more than most of the others on this homework. This will teach you some basic pathfinding in a network (graph) for the project. You can use this problem to build your project so l would recommend working on this problem until you understand it. Imagine there is a spider web: Our goal is to find a path (not the best path, but just any path) from A to Z You see that the green path is not the shortest but it does let us navigate from start to finish. How can we do this? First, we need to know A and Z, our starting and ending points. We'll pass these into our function. I'm going to use a dictionary to represent this graph. Each node (vertex, circle) will have a name, in this case "A" and 'Z" were the names of the nodes, but in the generated maps l'm going to use "Node 1", "Node 2", "Node 3", etc. Here is an example web_map web_map = { "Node 1: ['Node 3, 'Node 2], "Node 2: ['Node 1', 'Node 41. "Node 3: [Node l], Node 4: ['Node 2] } Nodel is connected to 2 and 3 for instance, and then also note that Node 3 is connected back to Node 1. Similariy, Node 2 is connected back to Node 1. Then there's a connection between Node 2 and Node 4 that also goes both ways. All connections in our web will be bi-directional. So, in order to find the path from the start to the finish we should check if there's a path recursively through any of the nodes connected to wherever we start.
Expert Solution
trending now

Trending now

This is a popular solution!

steps

Step by step

Solved in 3 steps with 3 images

Blurred answer
Knowledge Booster
Image Element
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
C++ Programming: From Problem Analysis to Program…
C++ Programming: From Problem Analysis to Program…
Computer Science
ISBN:
9781337102087
Author:
D. S. Malik
Publisher:
Cengage Learning