I wrote a code to find the ugly numbers. While trying to make it faster, I found that using 3 IFs instead of an IF-ELIF-ELSE made my code faster. I tried running the code for multiple iterations of n and found that this is true most of the time.
I feel that IF-ELIF-ELSE should be faster since if one of the conditions is met, it would not go into the others. But I am unable to find any logic in what actually happened.
Here is the code:
ugly = [0]*n
ugly[0] = 1
i2, i3, i5 = 0, 0, 0
count = 1
while count<n:
n2 = ugly[i2]*2
n3 = ugly[i3]*3
n5 = ugly[i5]*5
next = min(n2, n3, n5)
if next==n2:
i2 += 1
elif next==n3:
i3 += 1
else:
i5 += 1
if next != ugly[count-1]:
ugly[count] = next
count += 1
Aucun commentaire:
Enregistrer un commentaire