Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to write this in Python?

        if(i-words < 0):
            start_point = 0
        else:
            start_point = i - words

Or is this the easiest way using min/max? This is for lists splicing.

I want start_point to always be 0 or above.

like image 398
TIMEX Avatar asked Dec 21 '25 23:12

TIMEX


2 Answers

Better is to make the limiting more obvious

start_point = max(i - words, 0)

This way, anyone reading can see that you're limiting a value.

Using any form of if has the disadvantage that you compute twice i - words. Using a temporary for this will make more code bloat.

So, use max and min in these cases.

like image 149
Mihai Maruseac Avatar answered Dec 24 '25 12:12

Mihai Maruseac


How about

start_point = 0 if i - words < 0 else i - words

or

start_point = i - words if i - words < 0 else 0

or even better, the clearest way:

start_point = max(i - words, 0)

As Mihai says in his comment, the last way is not only clearer to read and write, but evaluates the value only once, which could be important if it's a function call.

like image 45
Delan Azabani Avatar answered Dec 24 '25 12:12

Delan Azabani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!