In: Computer Science
Write a Python program that calls a function to sum all the numbers in a list and returns the result to the caller. The main program creates a list (with hard-coded or user input) and passes the list as an argument to the function. You may not use the built-in function, sum.
The program calls a second function to multiply all the numbers in a list passed to it by main and returns the product back to the caller.
List can be created with user input or hard-coded elements.
The program calls a third function that takes the list of words (below) passed to it from main and determines which elements are palindromes without changing the original list.
['racecar', 'Python', 'mom', 'java','level', 'DNA','101101' ]
If true, the function appends the word to a new list and returns it to the caller. The main program prints the list of palindromes returned from the function. The function should not modify the original list passed to it from the main (no side effect).
A palindrome is a word, phrase, number or sequence of words that reads the same backward as forward
"""
Python version : 3.6
Python program to create and test functions
"""
def sum_list(lst):
"""
function to calculate and return sum of all the
numbers in the given list, lst
"""
# initialize result to 0
result = 0
# loop over the list elements adding the elements to
result
for num in lst:
result += num
return result
def product_list(lst):
"""
function to calculate and return the product of all
numebrs in the given list, lst
"""
# initialize result to 1
result = 1
# loop over the list elements multiplying the elements
to result
for num in lst:
result *= num
return result
def palindromes_list(lst):
"""
function that accepts a list of words as input and
returns a list of all the strings
that are palindrome without changing the input
list
"""
# create an empty list
palindrome_list = []
# loop over input list
for s in lst:
# if reverse of s = s, then it is a
palindrome, hence append s to palindrome_list
if s == s[-1::-1]:
palindrome_list.append(s)
return palindrome_list
# test the functions
numbers = [12, 8, 10, 6, 7.3, 22]
print(sum_list(numbers))
print(product_list(numbers))
words = ['racecar', 'Python', 'mom', 'java','level', 'DNA','101101'
]
print(palindromes_list(words))
#end of program
Code Screenshot:
Output: