I am trying to push my limits of making a python code as short as possible.
I left the readability part way behind.
I was attempting the K-Goodness String problem from Round A of Google Kick Start 2021.
The following was my initial solution:
def func(N, K, S):
if not S: return 0
y = 0
for i in range(N//2):
if S[i] != S[N-i-1]:
y += 1
return abs(K - y)
for i in range(int(input())):
N, K = tuple(map(int, input().split(' ')))
S = input()
y = func(N, K, S)
print(f'Case #{i+1}: {y}')
Then I shortened it down to the following:
def func(N, K, S):
if not S: return 0
for i in range(N//2): K -= S[i] != S[N-i-1]
return abs(K)
[print(f'Case #{_}: {func(*tuple(map(int, input().split())), input())}') for _ in range(1, int(input())+1)]
I seriously want to push the limits. Can anyone help me shorten the for loop part:
for i in range(N//2): K -= 1 if S[i] != S[N-i-1] else 0
so that I can make a lambda function out of func
, like:
func = lambda N, K, S: 0 if not S else ...
#something
P.S. I can do it the following way, but that is inefficient and involves redundant steps that increase time and space complexity:
func = lambda K, S: abs(K - list(map(lambda x: x[0] != x[1], list(zip(S, S[::-1])))).count(True)//2) if S else 0
[print(f'Case #{_}: {func(tuple(map(int, input().split()))[1], list(input()))}') for _ in range(1, int(input())+1)]
Please suggest a good way to do the same.
P.S. I know its not a good practice to compress a piece of code beyond readable, but I just wanted to do this for fun.
Sample Input
2
5 1
ABCAA
4 2
ABAA
Sample Output
Case #1: 0
Case #2: 1
func
is supposed to do would be helpful, as not every is familiar with that specific problem. \$\endgroup\$