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

I have this code but when i run it it doesn\'t count the length. If you can help

ID: 3862016 • Letter: I

Question

I have this code but when i run it it doesn't count the length. If you can help fix length function.

This what my sample runs is:

Please enter a word (or just hit enter to end): 5
Please enter a word (or just hit enter to end): 9
Please enter a word (or just hit enter to end): 10
Please enter a word (or just hit enter to end): 1
Please enter a word (or just hit enter to end):
The structure contains 0 items: (here is supposed to count the total item and print list in ascending order.)

import sys
sys.path.append

from node import Node

def length(head):
probe = head
count = 0
if head == None:
return count
else:
probe = head
while probe.next != None:
probe = probe.next
count+=1
count+=1
return count
  
def insert(newItem, head):
newNode = Node(newItem)
if head == None:
head = newNode
else:
if newItem < head.data:
newNode.next = head
head = newNode
else:
probe = head;
while probe.next and probe.next.data<newItem:
probe = probe.next
newNode.next = probe.next;
probe.next = newNode
return head
  
def printStructure(head):
probe = head
answer = ""
while probe:
answer = answer + probe.data + " "
probe = probe.next
print (answer)
  
def main():
head = None
userInput = input('Please enter a word (or just hit enter to end): ')
while userInput != '':
head = insert(userInput, head)
userInput = input('Please enter a word (or just hit enter to end): ')
print('The structure contains', length(head), 'items:')
printStructure(head)

if __name__ == "__main__": main()

Explanation / Answer

The problem is in the method

def insert(newItem, head):
newNode = Node(newItem)
if head == None:
head = newNode
else:
if newItem < head.data:
newNode.next = head
head = newNode
else:
probe = head;
while probe.next and probe.next.data<newItem:
probe = probe.next
newNode.next = probe.next;
probe.next = newNode
return head

" return head" should be outside of outer if-else. It being inside inner IF-ELSE , nothing is being return when

head is None. Hence it always remains None and your length(head) function returns 0.

you can modify your length(head) function and remove unnecessary checks.

def length(head):
probe = head
count = 0
while probe != None:
probe = probe.next
count+=1
  
return count

PS: Double check the allignments when writting a python program

Happy Coding :)