def fold_paper(length, width, times): if times == 0: return length, width half_length = length // 2 half_width = width // 2 if length % 2 == 1: half_length += 1 if width % 2 == 1: half_width += 1 return fold_paper(half_length, width, times - 1), fold_paper(length, half_width, times - 1) if __name__ == '__main__': length = int(input("请输入长方形的长度:")) width = int(input("请输入长方形的宽度:")) times = int(input("请输入对折的次数:")) final_length, final_width = fold_paper(length, width, times) print("最终的长和宽分别为:{}, {}".format(final_length, final_width)) if final_length > final_width: print("从大到小输出:{}, {}".format(final_length, final_width)) else: print("从大到小输出:{}, {}".format(final_width, final_length))简化代码
时间: 2024-03-13 16:48:24 浏览: 59
可以将递归函数中的两个返回值改为一个元组类型,来简化程序:
```python
def fold_paper(length, width, times):
if times == 0:
return length, width
half_length = (length + 1) // 2
half_width = (width + 1) // 2
return fold_paper(half_length, width, times - 1)[0], fold_paper(length, half_width, times - 1)[1]
if __name__ == '__main__':
length = int(input("请输入长方形的长度:"))
width = int(input("请输入长方形的宽度:"))
times = int(input("请输入对折的次数:"))
final_length, final_width = fold_paper(length, width, times)
print("最终的长和宽分别为:{}, {}".format(final_length, final_width))
if final_length > final_width:
print("从大到小输出:{}, {}".format(final_length, final_width))
else:
print("从大到小输出:{}, {}".format(final_width, final_length))
```
这样程序更加简洁。
阅读全文