VoidProgrammer
VoidProgrammer

Reputation: 107

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

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

EDIT: All the answers were using sorted() which I felt was a bit of a cheat. But, after a little more thought, I was able to come up with a new logic that only used two lines, one of which was the input.

l=[int(input("Number: ")) for i in range(int(input("N: ")))]
[print(f'{l[j]}  ' if l[j]%2==i else '',end='') for i in range(1,-1,-1) for j in range(len(l))]

If there actually is a way of doing both input, and output in one line, without using sorted() then let me know :)

EDIT2: I came up with a way to adapt my 2 line logic into a one line code!

[print(f'{j}  ' if j%2==i else '',end='') for l in [[int(input("Number: ")) for i in range(int(input("N: ")))]] for i in range(1,-1,-1) for j in l]

Upvotes: 0

Views: 65

Answers (2)

Matthias
Matthias

Reputation: 13222

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].

Upvotes: 1

Rahul K P
Rahul K P

Reputation: 16081

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]

Upvotes: 0

Related Questions