Home > OS >  Is there a way for me to make this code even shorter
Is there a way for me to make this code even shorter

Time:10-20

My code has the basic aim. Sort a list so that all the odd numbers are to the left and the even numbers are to the right. For example, [1,2,3,4,5] becomes [1,3,5,2,4] However, I kept myself an extra challenge. Make the code as short as possible.

I was able to get it down to this.

l=[int(input("Number: ")) for i in range(int(input("N: ")))]
[l.append((l.pop(l.count(''))) if l[l.count('')]%2==0 else '') for i in range(len(l))]
for i in l: print(f'{i}  ' if i!='' else f'{i}',end='')

Forgetting readability and efficiency, is there any way to get this down even further, without using exec()?

I thought of adding an else statement to the for loop inside the list comprehension, but apparently, you cannot add for-else statements in list comprehension without Python throwing you a syntax error.

l=[int(input("Number: ")) for i in range(int(input("N: ")))]
[l.append((l.pop(l.count(''))) if l[l.count('')]%2==0 else '') for i in range(len(l)) else for i in l: print(f'{i}  ' if i!='' else f'{i}',end='')]

If anyone else has any other ideas, I would love to hear them

CodePudding user response:

sorted accepts a key function. If we calculate the value of the modulus of 2 and negate the result, we get what we want.

data = [1, 2, 3, 4, 5]
print(sorted(data, key=lambda i: -(i%2)))

The result is [1, 3, 5, 2, 4].

CodePudding user response:

You can try this,

In [1]: l = [1,2,3,4,5]

In [2]: sorted([i for i in l if i%2 == 1])   sorted([i for i in l if i%2 == 0])
Out[2]: [1, 3, 5, 2, 4]
  • Related