[codewars][Python] Are they the "same"?-- 判断一个列表中元素的平方是否是另一个列表中的元素

mac2022-08-12  28

题目:一个列表array1, 一个列表array2,如果array2中的每个元素都是array1中元素的平方,则返回true,否则返回false

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:

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:

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.

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.

My Answer:

思路: 把array1中的每个元素的平方计算出来,再判断这个平方值是否再array2中,如果在则在array2中删除这个元素,最后,判断array2是否为空,为空则返回true,否则false

def comp(array1, array2): # array2中的每个元素,都是array1中元素的平方 if array2 == None or array1 == None: return False for each in array1: if each**2 in array2: array2.remove(each**2) if len(array2) != 0: print("False") return False else: print("True") return True

 

Smart Answer:

思路: 将array1中元素每个取平方,生成一个新的列表,排序后和array2比较

重点:1. 列表推导式的使用     2. python中异常处理的使用(try, except),这样即使某个列表是None程序也不会报错

def comp(array1, array2): try: return sorted([i ** 2 for i in array1]) == sorted(array2) #用列表推导式生成列表 except: return False

或者使用高阶内置函数map()来生成新的列表:

def square(x): return x**2 def comp(array1, array2): try: return sorted(map(square, array1)) == sorted(array2) #使用map()来生成新列表 except: return False

 

最新回复(0)