Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

IN PYTHON This function receives a list of lists as a parameter. Each element in

ID: 3677234 • Letter: I

Question

IN PYTHON

This function receives a list of lists as a parameter. Each element in the list is a list of two elements. The first is an integer indicating a value of some sort. The second (the one you are concerned with) is the index to the next element in the list you are to access. Starting with the first element in the passed-in list, you will determine the next element to visit. You will visit each element until you return to the 0th element in the passed-in list. Starting with your access to the first element as a count of 1, you will count how many hops it takes to get back to the 0th element.
Output must be identical to that presented in the check function at the bottom of the template.
There are two conditions where you will have errors. The first is if you are given a next element to visit that doesn’t exist in which case you would give the following error exactly as shown:
'No valid path.'
The second condition is if the path never returns to the 0th element – one way of which to check is if you are returned to an element you have already visited. In this case you will give the following error exactly as shown:
'No valid path. Duplicate visits.'

SAMPLE RUNS


hopCounts([[0,1],[1,3],[3,0],[4,2]])
will return this string in the following format
('Made it home in ', 4)


hopCounts([[0,3],[3,4],[1,2]])
will return this string in the following format
('No valid path.')

Explanation / Answer

python program:

#function definition
def hopCounts( listele ):
visited=[0,0,0,0,0,0,0,0,0,0,0]
count=0;
nextele=0;
visited[count]=nextele
while listele[nextele][1]!=0:
if listele[nextele][1]<len(listele):
  
for index in range(1,count):
if visited[index]==listele[nextele][1] and listele[nextele][1]!=0 :
print"No valid path Duplicate visits";
return
count=count+1
nextele=listele[nextele][1]
visited[count]=nextele
else:
print"No valid path";
return
print "'made it home in' ",count
return
#function calling
hopCounts([[0,1],[1,3],[3,4],[4,2],[2,0]])
hopCounts([[0,1],[1,3],[3,4],[4,5],[2,0]])
hopCounts([[0,1],[1,3],[3,4],[4,1],[2,0]])

output:

'made it home in' 4
No valid path
No valid path Duplicate visits