Compute their Cartesian product, AxB of two lists. Each list has no more than 10 numbers.

For example, given the two input lists:
A = [1,2]
B = [3,4]

then the Cartesian product output should be:
AxB = [(1,3),(1,4),(2,3),(2,4)]

Respuesta :

Answer:

The program written in Python is as follows: (See Attachments for source file and output)

def cartesian(AB):

     if not AB:

           yield ()

     else:

           for newlist in AB[0]:

                 for product in cartesian(AB[1:]):

                       yield (newlist,)+product  

A = []

B = []

alist = int(input("Number of items in list A (10 max): "))

while(alist>10):

     alist = int(input("Number of items in list A (10 max): "))

blist = int(input("Number of items in list B (10 max): "))

while(blist>10):

     blist = int(input("Number of items in list B (10 max): "))

print("Input for List A")

for i in range(alist):

     userinput = int(input(": "))

     A.append(userinput)

print("Input for List B")  

for i in range(blist):

     userinput = int(input(": "))

     B.append(userinput)  

print(list(cartesian([A,B])))

Explanation:

The function to print the Cartesian product is defined here

def cartesian(AB):

This following if condition returns the function while without destroying lists A and B

    if not AB:

         yield ()

If otherwise

    else:

The following iteration generates and prints the Cartesian products

         for newlist in AB[0]:

              for product in cartesian(AB[1:]):

                   yield (newlist,)+product

The main method starts here

The next two lines creates two empty lists A and B

A = []

B = []

The next line prompts user for length of list A

alist = int(input("Number of items in list A (10 max): "))

The following iteration ensures that length of list A is no more than 10

while(alist>10):

    alist = int(input("Number of items in list A (10 max): "))

The next line prompts user for length of list B

blist = int(input("Number of items in list B (10 max): "))

The following iteration ensures that length of list B is no more than 10

while(blist>10):

    blist = int(input("Number of items in list B (10 max): "))

The next 4 lines prompts user for input and gets the input for List A

print("Input for List A")

for i in range(alist):

    userinput = int(input(": "))

    A.append(userinput)

The next 4 lines prompts user for input and gets the input for List B

print("Input for List B")  

for i in range(blist):

    userinput = int(input(": "))

    B.append(userinput)

This line calls the function to print the Cartesian product

print(list(cartesian([A,B])))

Ver imagen MrRoyal
Ver imagen MrRoyal