Instagram
youtube
Facebook
Twitter

Python Even Differences program Codechef solution

           Python Even Differences program Codechef solution

Problem:

You have an array consisting of N integers (a1, a2, aN).You may perform the following operation zero or more times.

  • Choose any index i (1<=i<=N) and set ai:=ai+1.

Determine the minimum number of operations you have to perform so that all pairwise differences in the resulting array are even. More formally, in the resulting array, it should hold that, for every i and j (1<=i,j<=N), aiaJ is even.

Input:

  • The first line contains a single integer T—the number of test cases. The description of each test case is as follows:
  • The first line of each test case contains a single integer N, the length of the array.
  • The second line of each test case contains N integers, a1, a2, aN —the integers in the array.

Output:

For each test case, output a new line containing a single integer—the minimum operations you must perform to make all the pairwise differences even.

Constraints:

  • 1≤T≤100
  • 1<=N<=500
  • 1<=ai<=10^5

Sample Input:

2 4 

4 1 2

Sample Output:

0

1

Explanation:

Note that an integer that is divisible by 2 is considered even. For example, 0, 4, and 6 are even, but 5 and 3 are not.

In the first test case, 22 = 0, 24 = 2, 42 = 2, and 44 = 0, all of which are even. Thus, we do not need to perform any operations.

In the second test case, we may increment 1. The pairwise differences then all become even. Thus, one operation is required.

Solution:

def count_operations(arr):

    odd_count = 0

    even_count = 0

    for num in arr:

        if num % 2 == 0:

            even_count += 1

        else:

            odd_count += 1

    return min(odd_count, even_count)

 

t = int(input(“Enter the number of terms: “))

for i in range(t):

    n = int(input(“Enter the length of array: “))

    arr = list(map(int, input(“Enter the elements in the list: “).split()))

    result = count_operations(arr)

    print(result)

 

Steps to solve this problem:

  1. Ask the user to enter the number of terms and store it in
  2. In a loop, ask the user to enter the length of an array.
  3. Ask the user to enter the elements in the list, and using the map() function, get iterator objects, and using the list() function, convert them to a list and store them in arr.
  4. Call the count_operations function, pass arr as an actual argument, and store it in the result variable.
  5. Print the value of the result.
  6. Define a function named count_operations and pass arr as an argument.
  7. Initialise odd_count and even_count with 0.
  8. In the loop, check if num modulus 2 is equal to 0, then increase the value of even_count by 1. Otherwise, increase the value of odd_count by 1.
  9. Return the minimum value between odd_count and even_count using the min() function.