在 Python 中从给定的方程 a + b = c 中找出缺失值

pythonserver side programmingprogramming更新于 2025/10/15 17:48:17

假设我们有一个这种形式的方程:a + b = c,现在 a、b 或 c 中的任何一个项都缺失了。我们必须找到缺失的那个。

那么,如果输入是这样的? + 4 = 9,则输出为 5

为了解决这个问题,我们将遵循以下步骤 −

  • 从字符串中删除所有空格并将 (+ 和 = 更改为逗号 ',')

  • 元素 := 元素列表,通过用逗号分隔的字符串进行拆分

  • idx := 0

  • 对于 i,范围从 0 到元素大小,执行

    • 如果 elements[i] 不是数字,则

      • idx := i

      • 退出循环

  • 如果最后一个元素缺失,则

    • 返回第一个元素 + 第二个元素

  • 否则当第二个元素缺失时,则

    • 返回最后一个元素 - 第一个元素

  • 否则当第一个元素缺失时,则

    • 返回最后一个元素 - 第二个元素

示例

让我们看看下面的实现以便更好地理解 −

def find_missing(string):
   string = string.strip().replace(' ', '')
   string = string.replace('=',',')
   string = string.replace('+',',')
   elements = string.split(',')
   idx = 0
   for i in range(len(elements)):
      if not elements[i].isnumeric():
         idx = i
         break
   if idx == 2:
      return int(elements[0]) + int(elements[1])
   elif idx == 1:
      return int(elements[2]) - int(elements[0])
   elif idx == 0:
      return int(elements[2]) - int(elements[1])

print(find_missing('6 + 8 = ?'))
print(find_missing('? + 8 = 20'))
print(find_missing('5 + ? = 15'))

输入

'6 + 8 = ?'
'? + 8 = 20'
'5 + ? = 15'

输出

14
12
10

相关文章


有用资源