python - 为什么我得到重复的答案?
问题描述
我只是在学习 python 并且已经开始使用 if / while 语句,这个基本程序旨在确定是否可以仅使用现有的行将一块巧克力分成 x 块。
它在 99% 的时间内都有效,但偶尔我会得到 YES YES 的结果。下面的例子。(useless 只是我用来结束没有 else 的 IF 语句的占位符。)
length = int(6)
chunks = int(6)
total = row*length
row_a = total
length_a = total
useless = 0
no = 0
if chunks == total:
print("YES")
else:
useless = useless +1
while row_a != 0:
if chunks == total - row_a:
print("YES")
break
else:
row_a = row_a - row
if row_a == 0:
no = no+1
else:
useless = useless +1
while length_a != 0:
if chunks == total - length_a:
print("YES")
break
else:
length_a = length_a - length
if length_a == 0:
no = no +1
else: useless = useless +1
else: useless = useless +1
if no == 2:
print("NO")
else: useless = useless +1 ```
解决方案
我建议您从头开始检查问题,并在开始编码之前尝试解决它。您的代码对于一个简单的问题来说太复杂了。
这是可以解决问题的代码示例。
x, y = 8, 10 #length and width of the chocolate bar
p_s = 5 #pieces size
p_n = int(input('Number of pieces: '))
total=x*y #size of the chocolate bar
if total//p_s < p_n:
print('NO')
else:
print('YES')
推荐阅读
- go - 在 Go 中递归遍历文件和文件夹 - 无法理解递归是如何发生的
- excel - 使用 excel 宏更新超链接
- dialog - 织物 UI:尝试在对话框中输入一些文本时调用面板 onDismiss
- c# - 没有“IEnumerable”类型的 ViewData 项
' 具有密钥 ID - javascript - 如何使服务器中的快速路由等到它从另一个nodejs进程接收到套接字io消息,然后再向客户端返回响应?
- python - 合并值范围内的巨大数据框
- reactjs - 更改状态后,内容不会重新渲染
- python - Slack:我可以使用 Python 在 Slack 上以特定用户的身份发帖吗?
- c# - Xamarin 表单列表视图无法使用 MVVM。请我对视图模型执行此操作吗?
- javascript - 为什么我的对象数组不会从饼图数据点中删除?