Odd Even Alternating Problem – Infytq 2019 Solve

Problem: Take a string as an input (combination of alphanumeric and special characters) from the user.

If the number of special character in the given string is even, then we have to print the first even digit and next odd digits alternatively in the same order as they are present in the string.

If the number of special character in the given string is odd, then we have to print the first odd digit and next even digits alternatively in the same order as they are present in the string.



Input format: The first line contains an integer denoting the number of testcases T. Next T lines contain a the string as input.

(NOTE: The actual problem didn’t have the number of testcases as input. But for your better convenience we have worked with testcases. Omit the testcase input line to get the actual format.)

Sample Input:

2
A5w8@k7!l23n69
#bn7856!@kn2n65jbnj482375

Sample Output:

8527639
7856523674582

Explanation: For the first string, the number of special character in the string is two (@, ! ), which is an even number, so the output will start from the even numeric character present in the string.

Here, ‘8’ is the first even number in the string, then the first odd number present is ‘5’. Then the second even number is ‘2’, the second odd number is ‘7’, and so on

Solution: We strongly recommend you to try the problem first before moving to the solution.

Python

# Code to understand Odd Even Alternating problem group in Python
# www.codewindow.in

def solve(string):
    even=[]
    odd=[]
    special_char=0
    for ch in string:
        if(ch.isalnum() == False):
            special_char+=1
        elif(ch.isdigit()):
            if int(ch)%2==0:
                even.append(ch)
            else:
                odd.append(ch)
                
    if(special_char%2!=0):
          odd, even=even, odd             
    even_len=len(even)
    odd_len=len(odd)
    m=max(even_len, odd_len)
    ev=0
    ox=0
    for i in range(m):
        if(ev!=even_len):
            print(even[ev], end='')
            ev+=1
        if(ox!=odd_len):
            print(odd[ox], end='')
            ox+=1
    print()

 # Driver code   
t=int(input())
while(t):
    s=input()
    solve(s)
    t-=1

Input:

2
A5w8@k7!l23n69
#bn7856!@kn2n65jbnj482375

Output:

8527639
7856523674582

Follow Us

You Missed


Leave a Comment

Your email address will not be published. Required fields are marked *