HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Comparing two partition functions in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
partitioncomparingtwopythonfunctions

Problem

I have written a partition function in Python (my_partition_adv). I have written this one after reading a similar function from a website. The version of the partition function from the website is also given below (parititon_inplace).

As I am a beginner in Python, I want to know the following things:

-
My version looks certainly more readable than the partition_in_place_with_additional_memory.

-
Are there any drawbacks for my version in terms of complexity that I am missing?

-
Are there any other drawbacks for my_partition_adv over partition_inplace?

def partition_inplace(A, start, stop, pivot_index):
    items_less_than = []
    items_greater_than_or_equal = []

    read_index = start
    while read_index <= stop:
        item = A[read_index]
        if item < pivot_value:
            items_less_than.append( item )
        else:
            items_greater_than_or_equal.append( item )
        read_index += 1

    write_index = start

    for item in items_less_than:
        A[write_index] = item
        write_index += 1

    for item in items_greater_than_or_equal:
        A[write_index] = item
        write_index += 1

    return len(items_less_than)

def my_partition_adv(A,p_val):
        less_than = []
        greater_than_or_equal = []

        for index, item in enumerate(A):
            if item < p_val:
                less_than.append(item)
            else:
                greater_than_or_equal.append(item)

        for index,item in enumerate(less_than):
            A[index] = less_than[index]

        for index,item in enumerate(greater_than_or_equal):
            A[len(less_than) + index] = greater_than_or_equal[index]

        return len(less_than)

Solution

These two functions are doing somewhat different tasks. The first one partitions a subrange of a list; the second one may only partition an entire list.

The use of enumerate is not justified in the first loop (index is not being used at all), and is quite suspicious in the second and third. Slices would achieve the same result more pythonically:

partition_point = len(less_than)
A[:partition_point] = less_than
A[partition_point:] = greater_than
return partition_point

Code Snippets

partition_point = len(less_than)
A[:partition_point] = less_than
A[partition_point:] = greater_than
return partition_point

Context

StackExchange Code Review Q#49576, answer score: 2

Revisions (0)

No revisions yet.