Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a variable inside of a list comprehension

I have a python function which increments the character by 1 ascii value if the index is odd and decreases the ascii value by 1 if index is even .I want to convert it to a function which do the same increment and decrement but in the next set i want to increment by 2 and then decrement by -2 then by 3 and -3 and so on..

What Iam trying to do is to increment the counter variable by 1 each time an even index occurs after performing the ascii decrement.

I also dont want to do it with a for loop is there any way to do it in the list comprehension itself?

In my function if the input is

input :'abcd' output: is 'badc' what i want is 'baeb'

input :'cgpf' output: is 'dfqe' what i want is 'dfrd'

def changer(s):
    b=list(s)
    count=1
    d=[chr(ord(b[i])+count) if i%2==0  else chr(ord(b[i])-count) for i in range(0,len(b))]
    return ''.join(d)

I need something like count++ as show but sadly python dont support it.

def changer(s):
    b=list(s)
    count=1
    d=[chr(ord(b[i])+count) if i%2==0  else chr(ord(b[i])-count++) for i in range(0,len(b))]
    return ''.join(d)

Here is the runnable code


2 Answers

If I correctly understood what you're after, something like this (compact form) should do:

def changer(s):
    return "".join(chr(ord(c) + ((i // 2) + 1) * (-1 if i % 2 else 1))
                   for i, c in enumerate(s))

We get index and character from string by means of enumerate() and use that to feed a generator comprehension (as asked for) far of index (i) and character (c) from the string.

For each ASCII value of c, we add result of integer division of i (incremented by one as index was 0 based) by 2 and multiply it by (-1 if i % 2 else 1) which flips +/- based on even/odd number: multiply by -1 when modulo of i division by 2 is non-zero (and bool() evaluates as True), otherwise use 1.

Needless to say: such comprehension is not necessarily easy to read, so if you'd use it in your script, it would deserve a good comment for future reference. ;)

like image 138
Ondrej K. Avatar answered Jan 29 '26 13:01

Ondrej K.


Combine a stream of plus/minus with the string.

import itertools
s = 'abcdefg'

x = range(1,len(s)+1)
y = range(-1,-len(s)+1,-1)
z = itertools.chain.from_iterable(zip(x,y))
r = (n + ord(c) for (n,c) in zip(z,s))
''.join(chr(n) for n in r)

I don't think I'd try to put it all in one line. Uses generator expressions instead of list comprehensions.

like image 33
wwii Avatar answered Jan 29 '26 15:01

wwii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!