Question

In: Computer Science

In python I want to create a singular function that takes two parameters 'head; and 'skip'....

In python I want to create a singular function that takes two parameters 'head; and 'skip'.

Head is a linked list. Skip is a non negative value. If skip is zero it should return head unchanged. The skip amount determines the amount to skip over. I want to change the linked list accordingly.

If you have a linked list 11 -> 12 -> 18 -> 20 -> 24 -> 32 -> 38 -> 44

and skip =2, then you should return the following:

18 -> 32

If skip = 1, then you should return the following:

12 -> 20 -> 32 -> 44

Solutions

Expert Solution

class ListNode:

    """ Models a single node in a singly-linked list. Has no methods, other

        than the constructor.

    """

    def __init__(self, val):

        """ Constructs the object; caller must pass a value, which will be

            stored in the 'val' field.

        """

        self.val = val

        self.next = None

    def __str__(self):

        vals = []

        objs = set()

        curr = self

        while curr is not None:

            curr_str = str(curr.val)

            if curr in objs:

                vals.append(

                    "{} -> ... (to infinity and beyond)".format(curr_str))

                break

            else:

                vals.append(curr_str)

                objs.add(curr)

            curr = curr.next

        return " -> ".join(vals)


def accordion_n(head,skip_amt):

    if skip_amt<0:

        print("INVALID... skip amount should be non-negative")

        

    elif skip_amt==0:

        return head

    

    else:

        op=[]

        curr_skip=0

        for i in range(len(head)):

            if curr_skip==2:

                op.append(head[i])

                curr_skip=0

            else:

                curr_skip+=1

        return " -> ".join(op)


if __name__=="__main__":

    n=int(input("Enter number of nodes in linked list: "))

    l=[]

    a=int(input())

    l.append(ListNode(a))

    for i in range(1,n):

        a=int(input())

        l.append(ListNode(a))

        l[i-1].next=l[i]

    

    x=str(l[0])

    y = x.split(" -> ")

    

    #Test Case 1

    skip_amt=int(input("Enter skip amount: "))

    print("Given List:",str(l[0]))

    print("Skip amount:",skip_amt)

    ans=accordion_n(y,skip_amt)

    print("Output List:",ans)

#SAMPLE OUTPUT

PLEASE LIKE IT RAISE YOUR THUMBS UP
IF YOU ARE HAVING ANY DOUBT FEEL FREE TO ASK IN COMMENT SECTION


Related Solutions

In python I want to create a singular function that takes two parameters 'head; and 'skip'....
In python I want to create a singular function that takes two parameters 'head; and 'skip'. Head is a linked list. Skip is a non negative value. If skip is zero it should return the linked list unchanged. The skip amount determines the amount to skip over. I want to change the linked list accordingly and then return the linked list with the modifications, not a list. If you have a linked list 11 -> 12 -> 18 -> 20...
In python I have a linked list. I want to create one function that takes in...
In python I have a linked list. I want to create one function that takes in one parameter, head. In the function, cur = head and next_cur = head.next. I want to return head and next_cur, except at the end of the function they will return alternating values from head. For example, if the these are the values in the linked list: 2, 3, 5, 7, 11 after the function head should return: 2, 5, 11 and next_cur should return:...
In python I want to create a function that takes in a linked list. Using recursion...
In python I want to create a function that takes in a linked list. Using recursion only, I want to check if the linked list is sorted. How do i do this?
In python i want to create a function. The function will take in two linked lists...
In python i want to create a function. The function will take in two linked lists as the parameters. If one is shorter than the other then the shorter will be the length. I want to take the values from both linked lists and turn them into tuples. I then want these tuples to be put into a new linked list. I want to return that linked list. I want to do this using recursion and no helper functions or...
Write a Python function that takes two parameters: the first a list of strings and the...
Write a Python function that takes two parameters: the first a list of strings and the second a single string. The function should return True or False depending on whether the string is in the list or not. For example, if the list contains eggs, milk, bananas, and the second parameter is pumpkin, the function should return False. Thank you.
Write a Python function that takes two parameters: the first a list of strings and the...
Write a Python function that takes two parameters: the first a list of strings and the second a single string. The function should return True or False depending on whether the string is in the list or not. For example, if the list contains eggs, milk, bananas, and the second parameter is pumpkin, the function should return False. Thank you.
python practice! 1. Create a function that takes a user choice and one number as parameters...
python practice! 1. Create a function that takes a user choice and one number as parameters and returns the operation result. -Square: print the number square -Sqrt: print the square root of the number -Reverse: reverse the sign of the number (pos or neg) and print it Note: Detect invalid choices and throw an error message – Number can be anything. 2. Create a function that takes a user choice and two numbers (start and end) as parameters. For example,...
This is an intro to python question. #Write a function called search_for_string() that takes two #parameters,...
This is an intro to python question. #Write a function called search_for_string() that takes two #parameters, a list of strings, and a string. This function #should return a list of all the indices at which the #string is found within the list. # #You may assume that you do not need to search inside the #items in the list; for examples: # # search_for_string(["bob", "burgers", "tina", "bob"], "bob") # -> [0,3] # search_for_string(["bob", "burgers", "tina", "bob"], "bae") # -> []...
(Python) I want to use a function called level() that takes a dictionary. Here is a...
(Python) I want to use a function called level() that takes a dictionary. Here is a dictionary with people's job and skill level. dict1 = {'Jame': {'Cleaning': 5, 'Tutoring': 2, 'Baking': 1},Pam': {'Plumbing': 2, 'Cleaning': 5}) like if I called level(dict1), the output will return {'Pam', 'James'} It finds the people's average skill level like for Pam is (2+5)/2=3.5 and sorted descending. How do I do that and how do I do it in only one return statement(using comprehension or...
Challenge 1 – 2D Array Maker Create a function that takes in two parameters and returns...
Challenge 1 – 2D Array Maker Create a function that takes in two parameters and returns a created two-dimension array. var twoD = Make2D(<width>, <height>); Challenge 2 – Fill 2D Array Create a function that takes a single parameter and fills the 2D array with that parameter Use Cases: Fill2D(<twoD array>, <fill value>); //fills twoD twoD = fill2D(<twoD array>, <fill value>); //fills twoD, but also returns reference Challenge 3 – Make 2D Array Write a function that takes 3 parameters...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT