Professional Documents
Culture Documents
Return List of Tuples Per Criteria - Py
Return List of Tuples Per Criteria - Py
def return_list_of_matching_tuples(list_x, list_y, list_z):
"""
Given three list or arrays X, Y, Z; each of which contains same number of
non-zero integer elements. Write a program to print tuples of the form
(x,y,z) such that x belongs to X, y belongs to Y and z belongs to Z and
z-y =x.
e.g.
X = [1,2,7] , Y= [ 3,4,9], Z = [5,6,3] , output would be
(1,4,5)
(2,4,6)
(2,3,5), etc.
"""
my_list = [] # Empty list that will later hold the tuples to be returned
# Set up three loops, one inside the other.
for z_item in list_z:
for y_item in list_y:
for x_item in list_x:
# Check for the z - y = x condition in the innermost loop
if z_item - y_item == x_item:
# Create a new tuple
mytuple = (x_item, y_item, z_item)
# Add the tuple to the list if it is not already there
if mytuple not in my_list:
my_list.append(mytuple)
# Return the list of tuples that meet the criteria
return my_list
def main():
# Three different list of integers
x_list = [1, 2, 7]
y_list = [3, 4, 9]
z_list = [5, 6, 3]
# Call the function with the three lists as arguments in order to get a
# list of matching tuples
list_of_tuples = return_list_of_matching_tuples(x_list, y_list,
z_list)
# Set up Pretty Printer
pp = pprint.PrettyPrinter(indent=4)
# Pretty print the list of tuples returned
pp.pprint(list_of_tuples)
# Another set of three lists of integers
x_list_2 = [10, 6, 3]
y_list_2 = [3, 7, 10]
z_list_2 = [13, 13, 16]
# Call the function with the three lists as arguments in order to get a
# list of matching tuples
list_of_tuples_2 = return_list_of_matching_tuples(x_list_2, y_list_2,
z_list_2)
# Pretty print the list of tuples returned
pp.pprint(list_of_tuples_2)
if __name__ == '__main__':
main()