You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现循环获取元素前后值的优化方法咨询

Optimizing getPrevNext for a Circular Sequence of 6 Elements

Great question! Your current dummy function works perfectly, but we can make it more elegant, scalable, and concise using modular arithmetic—which is ideal for circular sequences since it handles wrap-around logic automatically without clunky conditional checks.

Approach 1: Modular Arithmetic (Best for Consecutive Sequences)

Since your sequence is a consecutive 1-based circular list of 6 elements, modulo operations let us compute previous and next values in one line each. Here's the refined function:

def getPrevNext(no):
    TOTAL_ELEMENTS = 6
    prev_no = (no - 2) % TOTAL_ELEMENTS + 1
    next_no = no % TOTAL_ELEMENTS + 1
    return [prev_no, next_no]

How this works:

  • Previous element: Subtract 2 to shift back by one and adjust for 1-based indexing, take modulo 6 to wrap around from 1 to 6, then add 1 to return to 1-based numbering.
    • For no=1: (1-2) % 6 = 5 → 5+1=6 (correct)
    • For no=6: (6-2) %6=4 →4+1=5 (correct)
  • Next element: Take modulo 6 (so 6 becomes 0), then add 1 to wrap around to 1.
    • For no=6: 6%6=0 →0+1=1 (correct)
    • For no=5: 5%6=5 →5+1=6 (note: your example had a typo here—your original dummy function returns 6 for no=5, which is the correct next element)

This approach shines because:

  • It’s scalable: Just update TOTAL_ELEMENTS if your sequence length changes (no need to rewrite conditionals)
  • No messy branches: Clean, one-line calculations replace the if/elif/else block
  • Easy to maintain: The logic stays consistent even as the sequence grows

Approach 2: Dictionary Lookup (Useful for Non-Consecutive Sequences)

If your sequence ever becomes non-consecutive (e.g., [1,3,5,7,9,11]), a dictionary lookup is a clean alternative:

def getPrevNext(no):
    sequence_map = {
        1: (6, 2),
        2: (1, 3),
        3: (2, 4),
        4: (3, 5),
        5: (4, 6),
        6: (5, 1)
    }
    return list(sequence_map[no])

This is O(1) time, but less scalable for long sequences—you’d have to manually update the dictionary. For your current consecutive sequence, the modular approach is far better.

Testing the Function

Let’s verify with your examples (correcting the typo for no=5):

print(getPrevNext(2))   # [1, 3] ✔️
print(getPrevNext(5))   # [4, 6] ✔️
print(getPrevNext(1))   # [6, 2] ✔️
print(getPrevNext(6))   # [5, 1] ✔️

All cases work as expected!

内容的提问来源于stack exchange,提问作者Shubham R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:06:17