In: Computer Science
Write a Python function that receives a stack object s, where the items in the stack are only numbers in the set {0,1} and returns the number of 1's in the stack s. The function must satisfy the following restrictions:
For example, if the stack contains 0,0,1,1,0,1,0, the function must return 3 and the stack must still contain 0,0,1,1,0,1,0.
Raw_code:
def function(stack):
# temporary variable of integer type (non-collection type)
count = 0
# for loop for iterating through each element in the stack using
membership in operator
for number in stack:
# if statement for checking whether the number is 1 or
if number == 1:
# if number is 1 incrementing the count of 1
count += 1
# after breaking of for loop returning count
else:
return count
stack1 = [0, 0, 1, 1, 0, 1, 0]
# calling the function with stack as parameter
print(function(stack1))
print(stack1)
stack2 = (0, 0, 1, 1, 0, 1, 1, 0)
print(function(stack2))
print(stack2)