rshudson February 2016

Omit a Value in a Multiple-Assignment Ternary Conditional

Scenario:

Quicksort coding challenge.

Input is two lines: Line 1 = Pivot, Line 2 is an unsorted list of integers Output is a list, with the values less than the pivot shifted to the left, followed by the pivot and the values >= to the pivot.

Example:

Input:

7
1 2 4 9 3 7 11 5 12

Output:

1 2 4 3 5 7 9 11 12

What I would like to do in Python 3 (if possible):

left,right = [ (value,DO NOT ASSIGN) for value in unsortedList if value < pivot else (DO NOT ASSIGN, value) ]

Question:

Is there a way to do what I'm trying to do? I understand how to assign the values individually, but was curious if in multiple-assignments you are required to assign a value.

'None' will not work as its a list and I need to maintain the previous values.

Answers


senshin February 2016

I mean, you could do something like this, which sort of approximates the same effect by means of filter. Note that the list(filter(...)) thing is just to materialize the filters so they print correctly.

>>> unsorted = [1, 2, 4, 9, 3, 7, 11, 5, 12]
>>> pivot = 7
>>> left, right = [list(filter(lambda n: n < pivot, unsorted)), list(filter(lambda n: n >= pivot, unsorted))]
>>> left
[1, 2, 4, 3, 5]
>>> right
[9, 7, 11, 12]

But there is no "DO NOT ASSIGN" syntactic primitive in Python.


Randy C February 2016

You can sort of fake it with None, zip and a filter at the end (though you'd also have to reposition the 7 for quicksort):

In [1]: l = map(int, "1 2 4 9 3 7 11 5 12".split())

In [2]: left, right = zip(*[(v, None) if v < 7 else (None, v) for v in l])

In [3]: left, right
Out[3]:
((1, 2, 4, None, 3, None, None, 5, None),
 (None, None, None, 9, None, 7, 11, None, 12))

In [4]: filter(lambda x: x is not None, left), filter(lambda x: x is not None, right)
Out[4]: ((1, 2, 4, 3, 5), (9, 7, 11, 12))

Post Status

Asked in February 2016
Viewed 2,734 times
Voted 6
Answered 2 times

Search




Leave an answer