Looking for answers? Westonci.ca is your go-to Q&A platform, offering quick, trustworthy responses from a community of experts. Ask your questions and receive detailed answers from professionals with extensive experience in various fields. Get immediate and reliable solutions to your questions from a community of experienced professionals on our platform.

Q1). Write a python program to pass a list to a function and double the odd values and half even values of a list and display list elements after changing.​

Sagot :

Answer:

[tex]\textsf{\large{\underline{Solution}:}}[/tex]

The given problem is solved using language - Python.

def f(x):

   new_list=[]

   for i in x:

       if i%2==0:

           new_list.append(i//2)

       else:

           new_list.append(i*2)

   return new_list

   

my_list=list(range(1,6))

print('Original List:',my_list)

my_list=f(my_list)

print('Modified List:',my_list)

[tex]\textsf{\large{\underline{Logic}:}}[/tex]

  1. Create a new list.
  2. Iterate over the list passed into the function.
  3. Check if the element is even or not. If true, append half the value of element in the list.
  4. If false, append twice the value of the element in the list.
  5. At last, return the new list.

There is another way of doing this - By using map() function.

—————————————————————————————

def f(x):

   return list(map(lambda x:x//2 if x%2==0 else 2*x,x))

   

my_list=list(range(1,6))

print('Original List:',my_list)

my_list=f(2my_list)

print('Modified List:',my_list)

—————————————————————————————

[tex]\textsf{\large{\underline{O{u}tput}:}}[/tex]

Original List: [1, 2, 3, 4, 5]

Modified List: [2, 1, 6, 2, 10]