Logic

逻辑符合任务之一

创建一个不使用 "or "关键字的OR函数,该函数接收一个布尔值列表并对所有的布尔值进行OR运算。

假设有1到6个变量,如果列表为空,则返回Nonepython|nil(ruby)

def alt_or(lst):
    #Please do not use the OR operator
    return True if any([c==True for c in lst]) else False if lst else None

继续精简代码

def alt_or(lst):
    return any(lst) if lst else None

逻辑符合任务之二

给定一个布尔值数组和一个逻辑运算符,根据对数组中的值依次应用运算符,返回一个布尔值结果。

例子

booleans = [True, True, False], operator = "AND"
真与真 -> 真
True AND False -> False 
最终结果返回假

booleans = [True, True, False], operator = "OR"
True OR True -> True
True OR False -> True
返回真

booleans = [True, True, False], operator = "XOR"
True XOR True -> False
False XOR False -> False
返回假

输入 一个布尔值数组(1 <= array_length <= 50) 一个指定逻辑运算符的字符串。"and", "or", "xor". 输出 一个布尔值(真或假)。

import operator

OPS = {
    "AND": operator.and_,
    "OR" : operator.or_,
    "XOR": operator.xor
}

def logical_calc(array, op):
    return reduce(OPS[op], array)

各有千秋,思路拓宽

#2nd

def logical_calc(array, op):
    res = array[0]
    for x in array[1:]:
        if op == "AND":
            res &= x
        elif op == "OR":
            res |= x
        else:
            res ^= x

    return res

#3rd

from operator import and_, or_, xor
from functools import reduce
OPERATOR = {'AND': and_, 'OR': or_, 'XOR': xor}

def logical_calc(array, op):
    return reduce(OPERATOR[op], array)

#4th

def logical_calc(array, op):
    ops = {
        "AND": lambda x, y: x & y,
        "OR": lambda x, y: x | y,
        "XOR": lambda x, y: x ^ y
    }

    from functools import reduce
    return reduce(ops[op], array)

#5th

def logical_calc(array, op):
    return reduce(eval('bool.__'+op.lower()+'__'),array)

#6th

def logical_calc(array, op):
    s = ' ' + op.lower().replace('xor''^') + ' '
    return eval(s.join(str(x) for x in array))

#7th

import operator

def logical_calc(array, op):
    op = '__{}__'.format(op.lower())
    op = getattr(operator, op)
    return reduce(op, array)

#8th

def logical_calc(array, op):
  return eval({ 'AND''&''OR''|''XOR''^' }[op].join(map(str, array)))

#9th

def logical_calc(array, op):
    out = array[0]
    for c in array[1:]:
        if op in ('AND','OR'):
            out = eval(str(out) + f" {op.lower()} " + str(c))
        elif op == 'XOR':
            out = not c == out
    return out

一道题深挖出多少语法/知识点/技巧,大力推荐自学的好方法!

本文由 mdnice 多平台发布

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值