samedi 7 novembre 2020

cleaner way to do a simple comparison using any?

some background

I was setting up some tests for code submitted by users for an extremely simple data science test.

coding "challenges" would be structured like so in a Jupyter Notepook:

li1 = [2,4,3,-2,-1,5,10]
li2 = [5,4,-3,7,8,-5,10,9]
def findMedian(li):
    li.sort()

    # find the median of li...
    # your code below

    listlength = len(li)
    num = listlength//2
    if listlength % 2 == 0:
        return (li[num]+li[num-1])/2
    else:
        return li[num]
if findMedian(li1) == 3:
    print("1 is correct!")
else:
    print("1 is wrong")
if findMedian(li2) == 6:
    print("2 is correct!")
else:
    print("2 is wrong")

Now while this is nice enough I decided I should probably implement something like the following to truly check many cases.

from statistics import median
import random

x = [list(range(random.randint(1,50))) for i in range(1,100)]

print(not any([False if findMedian(i) == median(i) else True for i in x]))

the thing is, using not any() feels wrong, I've been doing it for a while and I feel like I have a little gap in my knowledge...

question

Is there a cleaner way to express my comparisons?

while not any([False if findMedian(i) == median(i) else True for i in x]) does the job, is there a more efficient/pythonic way to express this?

Aucun commentaire:

Enregistrer un commentaire