Python – Interlist Perfect Square Pairs
有时,在数学领域工作时,我们可能会遇到一个问题,我们需要检查来自不同列表的元素的乘积是否会导致完美平方。这可以应用于许多领域,包括数学和网络开发。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
可以使用循环执行此任务。这是我们可以执行此任务的蛮力方式。在此,我们将每个元素与其他元素相乘,并检查它是否是完美的正方形。
# Python3 code to demonstrate
# Interlist Perfect Square Pairs
# using loop
# Initializing lists
test_list1 = [4, 5, 6, 7, 3, 4]
test_list2 = [6, 4, 2, 8, 9, 4]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Flatten List to individual elements
# using chain() + isinstance()
res = []
idx = 0
while(idx < len(test_list1)):
j = 0
while(j < len(test_list2)):
sub = test_list1[idx] * test_list2[j]
n = sub**0.5
temp = int(n)
if n == temp:
res.append((test_list1[idx], test_list2[j]))
j = j + 1
idx = idx + 1
# printing result
print ("The perfect square pairs are : " + str(res))
输出 :
The original list 1 is : [4, 5, 6, 7, 3, 4]
The original list 2 is : [6, 4, 2, 8, 9, 4]
The perfect square pairs are : [(4, 4), (4, 9), (4, 4), (6, 6), (4, 4), (4, 9), (4, 4)]
方法 #2:使用Counter() + set() + loop + product()
也可以使用这些功能的组合来执行此任务。在此,我们使用这样一个事实,即每个元素因子总是成对的完美正方形将是偶数。
# Python3 code to demonstrate
# Interlist Perfect Square Pairs
# using Counter() + set() + loop + product()
from itertools import product
from collections import Counter
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return Counter(factors)
# Initializing lists
test_list1 = [4, 5, 6, 7, 3, 4]
test_list2 = [6, 4, 2, 8, 9, 4]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Flatten List to individual elements
# using Counter() + set() + loop + product()
prime_fac = {idx: prime_factors(idx) for idx in set(test_list1) | set(test_list2)}
res = set()
for a, b in product(test_list1, test_list2):
combined_counts = prime_fac[a] + prime_fac[b]
if all(v % 2 == 0 for v in combined_counts.values()):
res.add(tuple(sorted([a, b])))
# printing result
print ("The perfect square pairs are : " + str(res))
输出 :
The original list 1 is : [4, 5, 6, 7, 3, 4]
The original list 2 is : [6, 4, 2, 8, 9, 4]
The perfect square pairs are : {(4, 4), (4, 9), (6, 6)}