Uncategorized

programming challenge – Median of Two Sorted Arrays PYTHON



You likely obtained the problem statement from leetcode or similar.
It would be helpful to share its text and the URL.

    def findMedianSortedArrays(self, list1, list2):

PEP-8
asks that you spell this find_median_sorted_arrays.
But I suspect that a polyglot site like leetcode
is requiring you to fit a mold that makes
sense for other languages, like {JS, java, pascal},
and thus is forcing you to adopt camelCase.

class Solution(object):

Nowadays, in python3, this is just silly.
Everything inherits from object, and
you don’t need to distinguish between old style and new style classses any more.
Prefer:

class Solution:
        merged_array = list1 + list2
        merged_array.sort()

Prefer to use the
sorted()
builtin:

        merged_array = sorted(list1 + list2)

And it’s not an
array
it’s a merged list.

        medians = length % 2
        median = length / 2

These are unhelpful names.
It’s unclear why an {odd, even} flag would be plural median.
And median clearly isn’t one; it is an index that can yield a median value.

The pair of subsequent int(median) expressions
make it pretty clear that you instead intended to assign:

        median = length // 2

Introducing a temp var with an uninformative name, calculation,
does not help the Gentle Reader.

            calculation = merged_array[median] 
            return calculation
        else:
            median = int(median)
            first = merged_array[median]
            second = merged_array[median-1]
            calculation = (second+first)
            calculation = calculation/2.0
            return calculation

In the if clause, better to just return merged_array[median].

In the else clause, better to
return (merged_array[median] + merged_array[median-1]) / 2.

An index named mid, rather than median, would be conventional here.

This expression blows up if caller offered an empty list,
and that’s OK. Caller will get what they deserve.

If you really want to introduce a named temp result in
the else clause, at least call it mean.



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *