Question

In: Computer Science

Given: You are given a Python Class template. In this class there is a class variable...

Given: You are given a Python Class template. In this class there is a
class variable vector, is a list of N non-negative integers and are
stored (in positions 0, 1, 2, ... (N-1)), where at least one integer
is 0.

Task: Write a recursive function "findAllPaths" to find all possible
path through V starting at position 0, and ending at
the location of 0, in accordance with the Rule below.
If no such path exists, "paths" should be an empty list. You also
have to write functions called "getShortest" and "getLongest" which
return respectively the shortest and longest paths as lists.

Rule: From position i, the next position in the path must be either i+x,
or i-x, where x is the non-negative integer stored in position i.
There is no path possible from position i to position i+x if
either of these 2 conditions hold:
position i+x is beyond the end of V.
position i+x is already on the path.
There is no path possible from position i to position i-x if
either of these 2 conditions hold:
position i-x is beyond the start of V.
position i-x is already on the path.

Example:
Suppose V contained the following:
Position: 0 1 2 3 4 5 6 7 8 9 10 11
Integer: 2 8 3 2 7 2 2 3 2 1 3 0
Then one path is:
0 2 5 7 4 11

Recursive Algorithm
-------------------
Your solution MUST use a recursive function to identify the paths.

You must implement the recursive function, as follows:

def findAllPaths(self, position, solution):

"findAllPaths" takes the initial part of a solution Path, and
a potential next solution position in the Vector. It explores
paths with the given position appended to the given solution
path so far.

The class variable paths is a list of lists and the function

Example Run:
------------
Example vector: [2, 8, 3, 2, 7, 2, 2, 3, 2, 1, 3, 0]
Valid paths:
0 2 5 7 4 11
0 2 5 3 1 9 10 7 4 11
0 2 5 3 1 9 8 10 7 4 11
0 2 5 3 1 9 8 6 4 11

No Solution example:
3 1 1 1 3 4 2 5 3 0

The following template is given:

def getName():
# Use the name displayed on D2L (easier for us to find)
   return "Haque, Mohammad"
  
class Pathfinder():
def __init__(self, vector):
# Initialize the Pathfinder object
self.vector = vector
self.paths = []
self.findAllPaths(0,[])

def findAllPaths(self, position, solution):
# Recursively explore the possible paths and store valid paths
# This method will not be tested, so you can modify the parameters as needed
print("hi")
pass

def getLongest(self):
# Return the longest of all paths found or [] if no paths exist
# If multiple paths with the longest length exist, return one of them
pass

def getShortest(self):
# Return the shortest of all paths found or [] if no paths exist
# If multiple paths with the shortest length exist, return one of them
pass

Any help will very much appreciated

Solutions

Expert Solution

Complete code of Solution:-

# Path finder class
class Pathfinder:

   # constructor of Path finder class.
   def __init__(self, vector):
       self.vector = vector
       self.paths = []

   # Recursive method to find all possible paths
   # 'self' is for refering current object, same as 'this' of java and c++
   # 'pos' is the index of element in 'self.vector' list where am I currently at.
   # 'path' is current path
   # 'idx' is for indexing in 'path' list.
   def findAllPaths(self, pos, path):

       # place 'pos' at index where -1 appeared first time in 'path'.
       path[path.index(-1)] = pos

       # if value at position denoting by 'pos' in 'self.vector' list is equal to 0
       # list elements in the range 0 to idx(inclusive) is representing one possible path.
       if self.vector[pos] == 0:

           # Appending one possible path into our 'paths' list.
           self.paths.append(path[0:path.index(-1)])

           # removing current position from 'path'
           path[path.index(-1)-1] = -1
           return

       # if we can move one step ahead (pos+x) from this position then make recursive call.
       if (pos+self.vector[pos]) not in path and (pos+self.vector[pos]) < len(self.vector):
           self.findAllPaths((pos+self.vector[pos]), path)

       # if we can move one step back (pos-x) from this position then make recursive call.
       if (pos-self.vector[pos]) not in path and (pos-self.vector[pos]) > -1:
           self.findAllPaths((pos-self.vector[pos]), path)

       # removing current position from 'path'
       path[path.index(-1)-1] = -1

   # This method will return one of the shortest paths.
   def shortesPath(self):
       ans = []
       for path in self.paths:
           if len(ans) == 0 or len(path) < len(ans):
               ans.clear()
               ans = path
       return ans

   # This method will return one of the longest paths.
   def longestPath(self):
       ans = []
       for path in self.paths:
           if len(ans) == 0 or len(path) > len(ans):
               ans.clear()
               ans = path
       return ans

# Creating object of 'Pathfinder' class.
Path = Pathfinder([3, 1, 1, 1, 3, 4, 2, 5, 3, 0])

# Initializing path will all '-1', denoting that path is empty now.
path = [-1 for i in range(len(Path.vector)+2)]
Path.findAllPaths(0, path)

# printing all paths.
print("All Paths-------------")
for path in Path.paths:
   print(path)

print("\nShortest path")
print(Path.shortesPath())
print("\nLongest path")
print(Path.longestPath())

Screenshot of Output:-

For first output, input list is [3, 1, 1, 1, 3, 4, 2, 5, 3, 0], so there won't be any possible path.

For second output, input list is [2, 8, 3, 2, 7, 2, 2, 3, 2, 1, 3, 0].


Related Solutions

Write a template class Number with the following features Overload following operators for the template class...
Write a template class Number with the following features Overload following operators for the template class + - < > Overload << and >> operators for the ostream and istream against this class. Write a main function to demonstrate the functionality of each operator.
Write a template class Number with the following features Overload following operators for the template class...
Write a template class Number with the following features Overload following operators for the template class + - < > Overload << and >> operators for the ostream and istream against this class. Write a main function to demonstrate the functionality of each operator.
1.) A class template can be derived from a non-template class True or False 2.) Inaccessible...
1.) A class template can be derived from a non-template class True or False 2.) Inaccessible pointer is a potential problem on simple linked list True or False 3.) Array based lists are faster in term of acing data True or False 4.) Simple linked lists use less space than double linked lists True or False 5.) For large lists "array based lists" are more efficient for insertion and deleting operational True or False 6.) We can remove data only...
A header file contains a class template, and in that class there is a C++ string...
A header file contains a class template, and in that class there is a C++ string object. Group of answer choices(Pick one) 1)There should be a #include for the string library AND a using namespace std; in the header file. 2)There should be a #include for the string library. 3)There should be a #include for the string library AND a using namespace std; in the main program's CPP file, written before the H file's include.
Python Explain Code #Python program class TreeNode:
Python Explain Code   #Python program class TreeNode:    def __init__(self, key):        self.key = key        self.left = None        self.right = Nonedef findMaxDifference(root, diff=float('-inf')):    if root is None:        return float('inf'), diff    leftVal, diff = findMaxDifference(root.left, diff)    rightVal, diff = findMaxDifference(root.right, diff)    currentDiff = root.key - min(leftVal, rightVal)    diff = max(diff, currentDiff)     return min(min(leftVal, rightVal), root.key), diff root = TreeNode(6)root.left = TreeNode(3)root.right = TreeNode(8)root.right.left = TreeNode(2)root.right.right = TreeNode(4)root.right.left.left = TreeNode(1)root.right.left.right = TreeNode(7)print(findMaxDifference(root)[1])
Given an unordered list (defined using the UnorderedList class above), transform it into a Python list.When...
Given an unordered list (defined using the UnorderedList class above), transform it into a Python list.When the input list is empty, the output Python list should be empty as well.Example: When the input unordered list is [1,2,3], the output Python list should be [1,2,3] . Use the following codes: class Node: def __init__(self, data): self.data = data self.next = None def getData(self): return self.data def getNext(self): return self.next def setData(self, data): self.data = data def setNext(self, node): self.next = node...
Explain this python program as if you were going to present it to a class in...
Explain this python program as if you were going to present it to a class in a power point presentation. How would you explain it? I am having a hard time with this. I have my outputs and code displayed throughout 9 slides. #Guess My Number Program # Python Code is modified to discard duplicate guesses by the computer import random #function for getting the user input on what they want to do. def menu(): #print the options print("\n\n1. You...
C++ Please write a exmaple of class template RedBlackTree.h.(It must be template!). I do not mind...
C++ Please write a exmaple of class template RedBlackTree.h.(It must be template!). I do not mind about details but please include the basic functions that are necessary for a RedBlackTree.
C++ Static Stack Template In this chapter you studied IntStack, a class that implements a static...
C++ Static Stack Template In this chapter you studied IntStack, a class that implements a static stack of integers. Write a template that will create a static stack of any data type. Demonstrate the class with a driver program. Dynamic Stack Template In this chapter you studied DynIntStack, a class that implements a dynamic stack of integers. Write a template that will create a dynamic stack of any data type. Demonstrate the class with a driver program. Static Queue Template...
Redo Program 1 so that you have a template class, that works with a char, string,...
Redo Program 1 so that you have a template class, that works with a char, string, int, or double data type. Program 1 is below: #include <iostream> #include <string> #define CAPACITY 12 using namespace std; class queue { private: string strArray[CAPACITY]; int frontIndex, endIndex; int queueSize; public: queue() { frontIndex = endIndex = -1; queueSize = 0; } void enqueue(string); string dequeue(); int size() { return queueSize; } int front() { return frontIndex; } int end() { return endIndex; }...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT