Please write complete Python code for the question below The

Please write complete Python code for the question below

The following will go into a file called q2.py. Using Functional Programming Style (without using any control statement like if-then-else. while loop), create a function named find_product (1) where 1 is a list of digits, i.e. integers from 0 to 9. The goal is to find the 5 consecutive elements of the list 1 that has the greatest product. The function should return a tuple. (a, b), where a is the index of the greatest product and b is the greatest product value. Example: >>> find_product ([1, 2, 3, 4, 5, 6, 4, 2, 1, 3]) (2, 1440)

Solution

def comp(a, b):
    return a>b
def eq(a, b):
    return a==b

def prod(l):
    if(len(l)==5):
        prod = l[0][1]*l[1][1]*l[2][1]*l[3][1]*l[4][1]
    else:
        return 0
    return prod

def find_product(l):
    l = list(enumerate(l))
    max_index = 1
    max_prod = 1
    for i, el in enumerate(l):
        print i, comp(len(l)-1, i+5), comp(i+5, len(l)-1), eq(len(l)-1, i+5)
        last = comp(len(l)-1, i+5)*(i+5) + comp(i+5, len(l)-1)*0 + eq(len(l)-1, i+5)*(len(l)-1)
        #print last
        product = comp(last, 0)*prod(l[i:last])
        max_index = comp(product, max_prod)*i + comp(max_prod, product)*max_index
        max_prod = comp(product, max_prod)*product + comp(max_prod, product)*max_prod
    return (max_index, max_prod)
l = [1, 2, 3, 4, 5, 6, 4, 2, 1, 3]
print find_product(l)

Please write complete Python code for the question below The following will go into a file called q2.py. Using Functional Programming Style (without using any c

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site