Python-입력 필터링, 가변 입력량으로 계산

Oct 09 2020

나는 파이썬을 사용하여 에어로 다이내믹스 계산기를 연구 해왔다. (내가 비교적 새로운)이 프로그램에서, 값은 여러 다른 입력을 기반으로 계산 될 수있다 . a는 b를 계산하고 b는 c를 계산하거나 c는 b를 찾을 수 있고 b는 a를 찾을 수 있습니다 .

이 프로그램의 기능에 대해 자세히 설명하기 위해 주어진 입력으로 할 수있는 모든 것을 찾을 때까지 논리를 반복합니다. 코드는 기능적으로 꽤 길기 때문에 최적화 될 수 있는지 또는 더 잘할 수 있는지 확인하고 싶습니다. 입력 방법의 경우 입력은 문자열입니다. 코드는 다음과 같습니다.

def Find_Pressure(temp):
    pressure = (101.29 * (((temp + 273.1) / 288.08) ** 5.256))
    return pressure


def Find_Temp_Alt(alt, ground_temp):
    Temp = ground_temp - (0.00649 * alt)
    return Temp


def Find_Density(pressure, temp):
    density = (pressure / (0.2869 * (temp + 273.1)))
    return density


def Find_Alt_Temp(temp, ground_temp):
    Alt = ((ground_temp - temp) / 0.00649)
    return Alt


def is_Valid(x):
    try:
        float(x)
        return True
    except ValueError:
        return False


def Parser(ground_temp, temp, alt, pressure, density):
    a = t = p = d = False
    run = True
    Alt = Temp = Pressure = Density = "N/A"
    if is_Valid(alt):
        Alt = float(alt)
        a = True
    if is_Valid(temp):
        Temp = float(temp)
        if Temp <= -273.1:
            t = False
        else:
            t = True
    if is_Valid(pressure):
        Pressure = float(pressure)
        p = True
    if is_Valid(density):
        Density = float(density)
        d = True

    if not is_Valid(ground_temp):
        print('Enter Ground Temp')
    else:
        G_T = float(ground_temp)
        while run:
            run = False
            if a and not t:
                Temp = Find_Temp_Alt(Alt, G_T)
                t = True
                run = True

            if t and not a:
                Alt = Find_Alt_Temp(Temp, G_T)
                a = True
                run = True

            if p and not t:
                Temp = ((288.08 * ((Pressure / 101.29) ** (1 / 5.256))) - 273.1)
                t = True
                run = True

            if t and not p:
                Pressure = Find_Pressure(Temp)
                p = True
                run = True

            if (p and t) and not d:
                Density = Find_Density(Pressure, Temp)
                d = True
                run = True
            if (d and t) and not p:
                Pressure = (Density * 0.2869 * (Temp + 273.1))
                p = True
                run = True

            if (d and p) and not t:
                Temp = ((Pressure / Density * 0.2869) - 273.1)
                t = True
                run = True
        return Alt, Temp, Pressure, Density

도움 / 의견을 부탁드립니다. 미리 감사드립니다!

답변

4 hjpotter92 Oct 09 2020 at 13:52

Code Review에 오신 것을 환영합니다! @Linny가 유형 힌트 및 변수 이름 지정에 대해 이미 언급 한 내용에 추가 할 것입니다. 변수 이름 지정은 Python의 PEP-8 지침의 일부입니다 (아래 참조).

매직 넘버

코드에는 실제로 변환 상수 인 많은 매직 넘버가 있지만 그러한 설명없이 나타납니다.

변수 이름

공기 역학 계산기를 작성하고 있으므로 코드에서 다양한 변수에 전체 이름을 사용하면 도움이됩니다. 예를 들어. altitude대신 alt, temperature대신들 temp( temp일반적으로 코드의 임시 변수로서 사용된다).

지상 온도

프로그램의 흐름에 따라 ground_temperature모든 계산에 필수적 이라고 생각합니다 . 아마도 처음에 그것을 확인하고 유효하지 않은 검사의 경우 일찍 중단하십시오.

선택적 인수

위에서 ground_temperature계산기를 호출하는 데만 필요합니다. 다른 모든 것은 선택 사항이며 계산할 수 있습니다. 다른 값을 기본값으로 설정하는 함수가 None더 적합 할 수 있습니다.

def aerodynamic_calculator(
    ground_temperature: float,
    temperature: float = None,
    altitude: float = None,
    pressure: float = None,
    density: float = None,
):

각 매개 변수에 대한 부울

위의 접근 방식을 사용하면 해당 값에 대한 부울을 추적하지 않고도 값 자체에 대한 유효성을 검사 할 수 있습니다.

if temperature and not altitude:
    altitude = compute_altitude_from_temperature(temperature, ground_temperature)

PEP-8

Python에서는 깨끗하고 유지 관리 가능하며 일관된 코드를 작성하기 위해 PEP-8 스타일 가이드를 따르는 것이 일반적이며 권장됩니다.

함수와 변수는 lower_snake_case, 클래스는 UpperCamelCase, 상수는 UPPER_SNAKE_CASE.

2 Linny Oct 09 2020 at 10:56

스타일에 대한 몇 가지 참고 사항

  • 변수 및 함수 이름은 snake_case
  • 허용하는 매개 변수 유형과 함수가 반환하는 값을 표시하려면 유형 힌트를 추가해야합니다.
def find_pressure(temp: float) -> float:
    return (101.29 * (((temp + 273.1) / 288.08) ** 5.256))


def find_temp_alt(alt: float, ground_temp: float) -> float:
    return ground_temp - (0.00649 * alt)


def find_density(pressure: float, temp: float) -> float:
    return (pressure / (0.2869 * (temp + 273.1)))


def Find_Alt_Temp(temp: float, ground_temp: float) -> float:
    return ((ground_temp - temp) / 0.00649)


def is_valid(x: str) -> bool:
    try:
        float(x)
        return True
    except ValueError:
        return False

계산을 반환하기 위해 계산에 대한 변수를 만들 필요가 없습니다. 표현식 자체를 반환하십시오.