简体   繁体   English

不知道这个卡塔

[英]Can't figure out this Kata

I'm working on this Kata in CodeWars, and I pass all but one test, but it doesn't say what the error is. 我正在CodeWars中处理此Kata,并且我通过了除一项测试以外的所有测试,但是它没有说明错误是什么。 The description says to check both lists for multiplicities. 说明说要检查两个列表是否重复。 List a2 is a list of squares of list a1. 列表a2是列表a1的平方的列表。 I need to check a1 for the square root of all the items in a2, and return false if the array is empty, None, or the square root isn't in a1. 我需要检查a1中a2中所有项的平方根,如果数组为空,无或平方根不在a1中,则返回false。

I am hoping to get any tips you might have about not only function (make it more Pythonic), but error handling. 我希望获得关于功能(使功能更像Pythonic)以及错误处理的所有技巧。 What am I missing? 我想念什么? Why is it not passing? 为什么不过去? Thanks in advance. 提前致谢。

def comp(a1, a2):
    if a1 == [] or a2 == []:
        return False
    if a1 == None or a2 == None:
        return False
    pos_count = 0
    neg_count = 0
    for num in set(a2):
        if num**0.5 in set(a1):
            pos_count += 1
        else:
            neg_count += 1
    if neg_count > 0:
        return False
    else:
        return True

Your can improve the code you posted as a comment: 您可以改进作为注释发布的代码:

def comp(a1, a2):
    if a1 is None or a2 is None:
        return False
    num_squared = []
    for num1 in a1:
        num_squared.append(num1**2)
    if set(a2) == set(num_squared):
        return True
    else:
        return False

You can build sequences using a comprehension expression. 您可以使用理解表达式来构建序列。 You build a list by appending squares to an empty list, but you could do it like so: 您可以通过将方格添加到空列表中来构建列表,但是您可以这样做:

num_squared = [num ** 2 for num in a1]

You create a temporary set object set(num_squared) . 您创建一个临时set对象set(num_squared) However, you could build a set in the same way as the list instead: 但是,您可以按照与列表相同的方式构建集合:

num_squared = {num ** 2 for num in a1}

If you have a boolean expression and then return True else False you can replace it with the expression itself: 如果您具有布尔表达式,然后返回True否则为False ,则可以将其替换为表达式本身:

return set(a2) == set(num_squared)

Applying all these changes you can get: 应用所有这些更改,您可以获得:

def comp(a1, a2):
    if a1 is None or a2 is None:
        return False
    else:
        return set(a2) == {num ** 2 for num in a1}

edit: Just to note: 编辑:只是要注意:

Empty lists evaluate as False in boolean expressions: 空列表在布尔表达式中的值为False

>>> bool([])
False

Also, None evaluates False : 另外, None False

>>> bool(None)
False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM