python修炼——CodeWars_2!

codewars 刷题第二道:comp.py

题目

"""
Given two arrays a and b write a function comp(a, b) (compSame(a, b) in Clojure) that checks whether the two arrays have
the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a
squared, regardless of the order.

给定两个数组a和b编写一个函数comp(a, b)(compSame(a, b)在Clojure中),检查两个数组是否具有“相同”元素,具有相同的多重性。
“相同”在这里表示,无论顺序如何,b元素都是a平方元素。

Examples   例子
Valid arrays    有效数组
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]

comp(a, b) returns true because in b 121 is the square of 11, 14641 is the square of 121, 20736 the square of 144, 361
 the square of 19, 25921 the square of 161, and so on. It gets obvious if we write b's elements in terms of squares:

comp(a, b)返回true因为b 121 是 11 的平方,14641是121的平方,20736的平方是198,361的平方是19,25921的平方是161,依此类推。
如果我们用b正方形来编写元素会很明显:

a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19]

Invalid arrays
If we change the first number to something else, comp may not return true anymore:

无效的数组
如果我们将第一个数字更改为其他数字,则comp可能不再返回true:

a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [132, 14641, 20736, 361, 25921, 361, 20736, 361]

comp(a,b) returns false because in b 132 is not the square of any number of a.
comp(a,b)返回false,因为在b 132中不是任意数量的平方a。

a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [121, 14641, 20736, 36100, 25921, 361, 20736, 361]

comp(a,b) returns false because in b 36100 is not the square of any number of a.
comp(a,b)返回false,因为在b36100中不是任意数量的平方a。

Remarks
a or b might be [] (all languages except R, Shell). a or b might be nil or null or None or nothing (except in Haskell,
Elixir, C++, Rust, R, Shell).
If a or b are nil (or null or None), the problem doesn't make sense so return false.
If a or b are empty the result is evident by itself.

备注
a或者b可能是[](除了R,Shell之外的所有语言)。 a或者b可能是nil或null或None或nothing(Haskell,Elixir,C ++,Rust,R,Shell除外)。
如果a或b有nil(或null或None),这个问题就没有意义了那么返回false。
如果a或b为空,结果本身就很明显。

"""

解决代码

def comp(array1, array2):

    for a in array1:
        if a ** 2 not in array2 or array1.count(a) != array2.count(a ** 2):
            # print("失败")
            return False
    # print("成功")
    return True


a1 = [121, 144, 19, 161, 19, 144, 19, 11]
a2 = [11 * 11, 121 * 121, 144 * 144, 19 * 19, 161 * 161, 19 * 19, 144 * 144, 19 * 19]
comp(a1, a2)

这段代码不是很成功,可以完成大部分需求,但是在进行判断执行时有一项是失败的,没有找到问题所在,没有解决。

猜你喜欢

转载自blog.csdn.net/qyf__123/article/details/82388595