简体   繁体   English

是否有遵循模式的多个条件语句的算法

[英]Is there an algorithm for multiple conditional statements that follow a pattern

The conditional statements below have a pattern, n is multiples of 127 and P2OUT[i] is P2OUT[i-1]*2 + 1.下面的条件语句有一个模式,n 是 127 的倍数,P2OUT[i] 是 P2OUT[i-1]*2 + 1。

    if n >= 127:
            P2OUT = 0x01;  
    if n >= 254:
            P2OUT = 0x03;
    if n >= 381:
            P2OUT = 0x07;
    if n >= 508:
            P2OUT = 0x0F;
    if n >= 635:
            P2OUT = 0x1F;
    if n >= 762:
            P2OUT = 0x3F;
    if n >= 889:
            P2OUT = 0x7F;
    if n >= 1016:
            P2OUT = 0xFF;

Is there any way I can put all those conditionals inside of a python function so I put in n and get P2OUT, without explicitly writing all of them out given there is an obvious pattern.有什么办法可以将所有这些条件放在 python function 中,所以我输入 n 并得到 P2OUT,而无需明确写出所有这些条件,因为存在明显的模式。

I am aware that writing the program in general form might as well be longer than just writing out the following conditionals but I am doing is an an exercise as if there were 1000 conditionals but the pattern remains the same.我知道以一般形式编写程序可能比仅仅写出以下条件要长,但我正在做的是一个练习,好像有 1000 个条件,但模式保持不变。

You can do something like this你可以做这样的事情

def calculate_P2OUT(n):
    steps=int(n//127)
    P2OUT=0
    while steps > 0:
        P2OUT= P2OUT*2+1
        steps -= 1
    return hex(P2OUT)

print(calculate_P2OUT(889))


OUT: 0x7f

A loop isn't required for the calculation.计算不需要循环。

In [45]: def p2out(n):
    ...:     return 2**(n // 127) - 1

In [46]: [p2out(i*127) for i in range(1, 9)]
Out[46]: [1, 3, 7, 15, 31, 63, 127, 255]

In [47]: # or in hex:

In [48]: [hex(p2out(i*127)) for i in range(1, 9)]
Out[48]: ['0x1', '0x3', '0x7', '0xf', '0x1f', '0x3f', '0x7f', '0xff']

In [49]: # check range:

In [50]: [hex(p2out(i*127 + 126)) for i in range(1, 9)]
Out[50]: ['0x1', '0x3', '0x7', '0xf', '0x1f', '0x3f', '0x7f', '0xff']

In [51]: 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM