nac3core: fix len on range with step of different sign #129

Merged
sb10q merged 3 commits from len_range_fix into master 2021-12-13 10:44:33 +08:00
Collaborator

Previously I did not consider clearly about all the cases when the step is negative. In this PR I updated the formula to be, which I think should be fine..

def length(start, end, step != 0):
    diff = end - start
    # if diff == 0 OR `diff` and `step` are of different signs, always zero
    if diff * step <= 0:
        return 0
    else:
        return ((abs(diff) - 1) // abs(step)) + 1

previously the formula is just ((abs(diff) - 1) // abs(step)) + 1

Previously I did not consider clearly about all the cases when the step is negative. In this PR I updated the formula to be, which I think should be fine.. ```python def length(start, end, step != 0): diff = end - start # if diff == 0 OR `diff` and `step` are of different signs, always zero if diff * step <= 0: return 0 else: return ((abs(diff) - 1) // abs(step)) + 1 ``` previously the formula is just `((abs(diff) - 1) // abs(step)) + 1`
ychenfo added 1 commit 2021-12-12 06:33:39 +08:00
Owner

which I think should be fine.

You don't have to guess. Just adapt the cpython implementation:
https://github.com/python/cpython/blob/main/Objects/rangeobject.c#L182

> which I think should be fine. You don't have to guess. Just adapt the cpython implementation: https://github.com/python/cpython/blob/main/Objects/rangeobject.c#L182
Owner

And RustPython certainly has one as well. Maybe you could even get the LLVM IR out of rustc and essentially copy it.

And RustPython certainly has one as well. Maybe you could even get the LLVM IR out of rustc and essentially copy it.
ychenfo added 1 commit 2021-12-13 04:04:06 +08:00
ychenfo added 1 commit 2021-12-13 04:06:52 +08:00
Author
Collaborator

Thanks a lot for the information! I implemented again using this now.

Thanks a lot for the information! I implemented again using [this](https://github.com/python/cpython/blob/main/Objects/rangeobject.c#L889-L912) now.
sb10q merged commit ccfcba4066 into master 2021-12-13 10:44:33 +08:00
sb10q deleted branch len_range_fix 2021-12-13 10:44:34 +08:00
Owner

@ychenfo please do not use PR branches for unrelated commits like 1541188722

@ychenfo please do not use PR branches for unrelated commits like https://git.m-labs.hk/M-Labs/nac3/commit/1541188722488c82b23a84ad8ddc83a8da285be4
Sign in to join this conversation.
No reviewers
No Milestone
No Assignees
2 Participants
Notifications
Due Date
The due date is invalid or out of range. Please use the format 'yyyy-mm-dd'.

No due date set.

Dependencies

No dependencies set.

Reference: M-Labs/nac3#129
No description provided.