[Python] Why is this floating point operation faster than integer operation in python 3.11?

Discussão em 'Python' iniciado por Stack, Fevereiro 5, 2025.

  1. Stack

    Stack Membro Participativo

    So I was solving the 'Median of Two Sorted Arrays' problem on Leetcode and I noticed that the code with integer division somehow slower is than my code with float division then converting the float to integer.

    The given cases, the inputs are the following :


    • case one : [1,3] and [2]


    • case two : [1,2] and [3,4]

    So the slower code is the following :

    def medianofarrays(array1, array2):
    mergedArray = sorted(array1 + array2)
    #median is the middle element of the list if the list has uneven amount of elements
    if len(mergedArray)%2 != 0:
    mean = mergedArray[len(mergedArray)//2]
    #median is the mean of the middle 2 elements of the list if the list has an even amount of elements
    else:
    mean = (mergedArray[len(mergedArray)//2 - 1] + mergedArray[len(mergedArray)//2]) / 2
    return mean


    And this performed better (time and space) :

    def medianofarrays(array1, array2):
    mergedArray = sorted(array1 + array2)
    #median is the middle element of the list if the list has uneven amount of elements
    if len(mergedArray)%2 != 0:
    mean = mergedArray[int((len(mergedArray)/2))]
    #median is the mean of the middle 2 elements of the list if the list has an even amount of elements
    else:
    mean = (mergedArray[int((len(mergedArray)/2)-1)] + mergedArray[int(len(mergedArray)/2)]) /2
    return mean


    Here the time it took

    I submitted multiple times to check if it was indeed this case and not some random fluctuation but it gave me the same thing every time. I did not test any further. I expected it to be the other way around, so the int division should be faster right?

    Continue reading...

Compartilhe esta Página