TAGRENLA 2023-07-28 14:24 采纳率: 100%
浏览 4
已结题

满足超简单需求 还有没有其他的解决方法?

满足需求 还有没有其他的解决方法?

需求如下:

i, ii 如果是一对括号 返回True,反之返回False
是否可以用 in 进行实现?

import random
i = random.choice('({[')
ii = random.choice(')}]')
print(i,ii)   # i, ii 如果是一对括号  返回True
if (i == '(' and ii == ')') or (i == '{' and ii == '}') or (i == '[' and ii == ']'):
    print(True)
else:
    print(False)
  • 写回答

5条回答 默认 最新

  • Watch the clown 2023-07-28 14:51
    关注

    两种办法,in和字典方式实现

    
    import random
    
    i = random.choice('({[')
    ii = random.choice(')}]')
    
    print(i, ii)
    
    if i+ii in ['()', '{}', '[]']:
        print(True)
    else:
        print(False)
    
    第二种办法:用字典
    import random
    
    i = random.choice('({[')
    ii = random.choice(')}]')
    
    print(i, ii)
    
    brackets = {'()': True, '{}': True, '[]': True}
    
    if i+ii in brackets:
        print(True)
    else:
        print(False)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

问题事件

  • 系统已结题 8月5日
  • 已采纳回答 7月28日
  • 创建了问题 7月28日