Home > Software engineering >  How to implement list comprehensions when there are multiple nested if conditions
How to implement list comprehensions when there are multiple nested if conditions

Time:11-23

I am always confused when it comes to list comprehensions especially with these nested if-else. How can I implement this part of the code using list comprehension

for i in range(len(s1)):
   if i % 2 == 0:
      if ord(s1[i]) == 122:
         s3  = chr(97)
      else:
         s3  = chr(ord(s1[i]) 1)
   else:
      if ord(s2[i]) == 122:
          s3  = chr(97)
      else:
          s3  = chr(ord(s2[i]) 1)

this is the full code for reference

s1 = input()
s2 = input()
n = int(input())
lst = []
for i in range(n):
    s3 = ''
    for i in range(len(s1)):
        if i % 2 == 0:
            if ord(s1[i]) == 122:
                s3  = chr(97)
            else:
                s3  = chr(ord(s1[i]) 1)
        else:
            if ord(s2[i]) == 122:
                s3  = chr(97)
            else:
                s3  = chr(ord(s2[i]) 1)
    lst.append(s3)
    s1 = s2
    s2 = s3
print(lst[n-3])

CodePudding user response:

Although I have no clue why you're doing it, rewriting that code as a comprehension is fairly straightforward:

s3 = ''.join(
    chr(97) if ord(t[i % 2]) == 122 else chr(ord(t[i % 2]) 1) 
    for i, t in enumerate(zip(s1, s2))
)

CodePudding user response:

Writing comprehensions basically means that you move the append line, in this case string concatenation, to the front and everything else stays in the same order. I think Grismar's answer is better, but here is how you do it specifically as you asked.

''.join(
    chr(97) if ord(s1[i]) == 122 else chr(ord(s1[i]) 1) if i % 2 == 0
    else chr(97) if ord(s2[i]) == 122 else chr(ord(s2[i]) 1)
    for i in range(len(s1))
)

See below:

>>> def f(s1, s2):
...     s3 = ''
...     for i in range(len(s1)):
...         if i % 2 == 0:
...             if ord(s1[i]) == 122:
...                 s3  = chr(97)
...             else:
...                 s3  = chr(ord(s1[i]) 1)
...         else:
...             if ord(s2[i]) == 122:
...                 s3  = chr(97)
...             else:
...                 s3  = chr(ord(s2[i]) 1)
...     return s3
... 
>>> f('123', '456')
'264'
>>> def g(s1, s2):
...     return ''.join(
...         chr(97) if ord(s1[i]) == 122 else chr(ord(s1[i]) 1) if i % 2 == 0
...         else chr(97) if ord(s2[i]) == 122 else chr(ord(s2[i]) 1)
...         for i in range(len(s1))
...     )
... 
>>> g('123', '456')
'264'

P.S. this level of nested if statements is way too complicated to include in code you share with other people (including your future self). Simplify, simplify, simplify!

  • Related