TCS DIGITAL| Advanced Coding
Question 1 (Even-Odd
series): Given a string and it contains the
digits as well as non-digits. We have to find the count of non-digits. If it is
odd then remove all the non-digits and print the string as in even-odd order.If
it is even then print the string as in odd-even order.
E.g. The
given string is */24#5%7&9*3@. We have to count
the non-digit. It’s 7, odd. Then remove all the digits from the string and
output will become (in a string) 254739. In the problem, we have only 2 even
and 4 odd numbers then after the even number of completion print the remaining
odd numbers.
Solution: This
is a basic question and the time complexity is O(n)
·
Python
string = input()
characters = []
even = []
odd = []
for i in string:
if i.isdigit():
if int(i)%2==0: even.append(i) else: odd.append(i) else: characters.append(i) charlen = len(characters)
minlen = min(len(odd),len(even))
result = []
if charlen%2 == 0: for i in range(minlen):
result.append(odd.pop(0)) result.append(even.pop(0)) result.extend(even)
result.extend(odd)
else: for i in range(minlen):
result.append(even.pop(0)) result.append(odd.pop(0)) result.extend(even)
result.extend(odd)
print("".join(result)) |
Comments
Post a Comment