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,但你不应该(,但这里有一个简化的版本,希望包含一些有用的示例,说明如何使代码更容易编写(和阅读!(:

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(,并且只需要返回结果列表(从中可以获得count,因为它将是列表的长度(。减少冗余变量的数量可以消除大量不必要的代码行,这些代码行只是来回复制状态。当在结束循环之前总是True时,传递像running = True这样的值是不必要的——相反,在结束循环时只使用while True:returnbreak

最大的收获是,如果你有两个变量总是有相同的值(甚至两个值总是以完全相同的方式相关,比如列表及其长度(,你可能只需要其中一个。

您还可以通过分离两个嵌套循环来简化代码——对于给定的num,您希望循环直到数字达到1,所以这是一个循环。您希望在所有num上循环到99(我甚至花了一段时间才弄清楚代码就是这么做的;我必须运行它并查看输出,以查看其中一些额外的状态片段是否用于在单个循环中实现嵌套循环(。在两个不同的循环中执行这些操作会很容易,您可以将其中一个放在一个漂亮整洁的函数中(我使用了您的equation_loop名称,尽管它比原始版本做的工作更少(,该函数使用起始num并返回该起始点的结果列表。然后,可以在更简单的for循环中调用该简单函数,该循环遍历num并打印每个循环的结果。

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

最新更新