替代 if else python

alternative to if else python

好的,我在 python 中写了这篇文章,然后重写了,因为我不喜欢 if else 语句。 第一个版本运行良好。我的第二个失败了,最终比我的第一个版本占用了更多的行。我的问题是,我只是愚蠢吗?有没有更好的方法来做到这一点,还是我应该接受 if else 语句的需要?

抱歉代码转储,我快疯了 第一次尝试

#number we are starting with
num = 1 
#what we are going to apply equation loop to
result = num
#how many times goes through equation loop before reaching 1
count = 0
# list of numbers used in equation loop
num_in_loop = [result]
#end equation loop function. 
running = True
# equation loop
def eqation_loop(running, num_in_loop, count, num, result):
    while running == True:
        if (result % 2) == 0:
            result = result /2
            count +=1 
            num_in_loop.append(result)
        elif result == 1.0:
            print(num, "took", count ," loops to get to 1: numbers in loop = ",     num_in_loop, file=open('3x+1/result.txt','a'))
            num +=1  
            print(num)
            result = num
            num_in_loop = [result]
            count = 0
        elif num == 100:
            running = False
        elif (result % 2) != 0:        
            result = result * 3 + 1
            count +=1 
            num_in_loop.append(result)
eqation_loop(running, num_in_loop, count, num, result)

第二次尝试:

#number we are starting with
num = 1 
#what we are going to apply equation loop to
result = num
#how many times goes through equation loop before reaching 1
count = 0
# list of numbers used in equation loop
num_in_loop = [result]
limit = int(input("range you want to try: " ))
def update_var(num_in_loop,result,count):
    count +=1 
    num_in_loop.append(result)
    return equation_loop(limit,num, result)
def reset_var(num_in_loop, count, limit,num, result):
    print(num, "took", count ," loops to get to 1: numbers in loop = ", num_in_loop, file=open('3x+1/test.txt','a'))
    num +=1
    result = num
    num_in_loop = [result]
    count = 0   
    return equation_loop(limit,num, result)
def equation_loop(limit,num, result):
        if num == limit:
             return 
    elif result == 1: 
        return reset_var(num_in_loop, count, limit,num, result)    
    elif (result % 2) == 0:
        result = result /2
        return update_var(num_in_loop,result,count)        
    elif (result % 2) != 0: 
        result = result *3 +1
        return update_var(num_in_loop,result,count)
equation_loop(limit,num, result)

你不能在没有任何 if/else 语句的情况下写这篇文章(好吧,也许如果你 真的 知道你在做什么,你 技术上 可以通过严重滥用 while,但你 不应该 ),但这里有一个 simplified-down 版本,希望包含一些有用的示例,说明如何使你的代码更容易编写(和阅读!):

def equation_loop(num: int) -> list[int]:
    """
    Repeatedly applies the magic equation trying to
    reach 1.0, starting with num. Returns all the results.
    """
    nums = [num]
    while True:
        if num == 1:
            return nums
        if num % 2:
            num = num * 3 + 1
        else:
            num = num // 2
        nums.append(num)

for num in range(1, 100):
    results = equation_loop(num)
    print(f"{num} took {len(results)} loops to get to 1: {results}")

这里的关键是您不需要那么多变量!单个循环只需要它的起点 (num) 并且只需要 return 结果列表(从中你可以得到 count,因为它将是列表)。减少冗余变量的数量消除了很多不必要的代码行,这些代码行只是来回复制状态。传递一个像 running = True 这样的值是不必要的,因为它 总是 True 直到它结束循环的时候——而不是只使用 while True:returnbreak 完成后。

最重要的一点是,如果您有两个始终具有相同值的变量(或者甚至两个始终以完全相同的方式相关的值,例如列表及其长度),您可能只需要其中之一他们。

您还可以通过分离两个嵌套循环来简化代码 -- 对于给定的 num,您希望循环直到数字达到 1,因此这是一个循环。你 想遍历所有 num 直到 99(我花了一段时间才弄清楚代码正在做什么;我不得不 运行 它并查看输出以查看其中一些额外的状态片段用于在单个循环内实现嵌套循环)。在两个不同的循环中做这些很容易,你可以把其中一个放在一个很好的简洁函数中(我用你的 equation_loop 名字来做,虽然它比你的原始版本做的少)开始num 和 returns 是该起点的结果列表。然后可以在更简单的 for 循环中调用这个简单的函数,循环遍历 num 并打印每个结果。

请注意,我通过使用整数除法 (//) 将所有内容都保留为 ints -- 测试浮点数是否完全相等通常很危险,因为浮点数并不完全精确!你的等式总是用整数值运算(因为如果它是偶数你只能除以二)所以使用 int 除法更有意义,甚至不用担心浮点值。