Skip to content

Issue in the code of algorithms/algorithms/stack/is_sorted.py #401

@anoubhav

Description

@anoubhav

Some changes need to be made in the code.
1)The first 2 return statements have to be changed to break statements. This ensures that the code after the first for loop is executed. Previously it would never execute the latter part.
2)The second append statement should add elements to stack and not storage_stack. Try the test case [3,4,7,8,5,6]. The program returns True. It should return False.

def is_sorted(stack):
    storage_stack = []
    for i in range(len(stack)):
        if len(stack) == 0:
            break    # return
        first_val = stack.pop()
        if len(stack) == 0:
            break    # return
        second_val = stack.pop()
        if first_val < second_val:
            return False
        storage_stack.append(first_val)
        stack.append(second_val)    # storage_stack.append(second_val)

    # Backup stack
    for i in range(len(storage_stack)):
        stack.append(storage_stack.pop())

    return True

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions