PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 16, 2022

[FIXED] How to test programs related to linked lists in Python

 August 16, 2022     input, linked-list, output, python, tree     No comments   

Issue

For example, merge 2 sorted linked lists. I understand the code for solving the problem. However, how to create two linked lists and see the output? I have the same problem with trees. If I know how to test the input, it will be very helpful.

Input: l1 = [1,2,4], l2 = [1,3,4] Output: [1,1,2,3,4,4]

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:


Solution

For testing solutions with linked lists it helps to have functions (or methods) which translate linked lists to lists and vice versa. So define these:

def to_linked_list(iterable):
    head = None
    for val in reversed(iterable):
        head = ListNode(val, head)
    return head

def to_native_list(head):
    lst = []
    while head:
        lst.append(head.val)
        head = head.next
    return lst

Now you can more easily test your solution:

l1 = to_linked_list([1,2,4])
l2 = to_linked_list([1,3,4])
result = Solution().mergeTwoLists(l1, l2)
print(to_native_list(result))


Answered By - trincot
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing