有什么方法可以简化此功能吗?

时间:2019-02-17 05:20:17

标签: python

此功能有效,但需要简化。有什么方程吗?

def picapp(a):
    x = (210*(a%4))
    if x == 0:
        x = 210*4
    if (a/4)%4 == 0:
        y = 275*5
    if (a/4)%4 >= 0.25  and (a/4)%4 <= 1:
        y = 275*2
    if (a/4)%4 >= 1.25  and (a/4)%4 <= 2:
        y = 275*3
    if (a/4)%4 >= 2.25  and (a/4)%4 <= 3:
        y = 275*4
    if (a/4)%4 >= 3.25  and (a/4)%4 <= 4:
        y = 275*5
    return (x, y)

picapp(32) ## Output- (840, 1375)

Visualize my problem. Screenshot

6 个答案:

答案 0 :(得分:0)

简洁性没有很大的提高,但是 elif 的可读性和正确性更高:

def picapp(a):
    x = (210*(a%4))
    z = (a/4)%4
    if x == 0:
        x = 210*4
    if z == 0:
        y = 275*5
    elif 0.25 <= z <= 1:
        y = 275*2
    elif 1.25 <= z <= 2:
        y = 275*3
    elif 2.25 <= z <= 3:
        y = 275*4
    elif 3.25 <= 4:
        y = 275*5
    return (x, y)

答案 1 :(得分:0)

是的,但这看起来毫无意义,但这是:

var query = (from p in context.Products
                         orderby p.ProductID descending
                         select p.Name ).First();

答案 2 :(得分:0)

似乎a是一个整数。一种简单的方法是使它像这样:

def picapp(a):
    x = (210*(a%4))
    if x == 0:
        x = 210*4
    if (a % 16) == 0:
        y = 275*5
    elif 1 <= (a % 16) <= 4:
        y = 275*2
    elif 5 <= (a % 16) <= 8:
        y = 275*3
    elif 9 <= (a % 16) <= 12:
        y = 275*4
    elif 13 <= (a % 16) <= 16:
        y = 275*5
    return (x, y)

但是请注意,您的范围检查非常常规,我们可以进一步这样做:

import math

def picapp(a):
    x = (210*(a%4)) or (210*4)
    multiple = 1+int(math.ceil((a % 16)/4))
    if multiple == 1:
        multiple = 5
    y = 275 * multiple
    return (x, y)

答案 3 :(得分:0)

为此任务使用bisect模块。下面是示例代码:

tesseract processed/35.0.png stdout

答案 4 :(得分:0)

我想到了在许多情况下使用范围而不是调用变量。另外,将其提取到另一个功能将使其更清洁。

def picapp(a):
    x = (210*(a%4))
    condition = (a/4)%4
    if x == 0:
        x = 210*4
    y = 210 * foo(condition)
    return (x, y)

def foo(a):
    if a == 0 or 3.25 <= a <= 4:
        return 5
    elif 0.25 <= a <= 1:
        return 2
    elif 1.25 <= a <= 2:
        return 3
    elif 2.25 <= a <= 3:
        return 4

print(picapp(32)) ## Output- (840, 1375)

答案 5 :(得分:0)

喜欢吗?

def costum_round(x):
    return round(x+0.25)

def init_x(a):
    return (210*(a%4)) if (210*(a%4)) != 0 else 210*4

def init_y(a):
    return 275*(costum_round((a/4)%4)+1) if (a/4)%4!=0 else 275*5

def picapp(a):
    return (init_x(a),init_y(a))