python - Python 无法比较最大公约数的值
问题描述
我正在尝试解决这个hackerrank问题:
这是我的尝试:
from fractions import gcd
def connectedCities(numCities, threshold, originCities, destinationCities):
# Write your code here
output = []
for i in range(0, len(originCities)):
if gcd(originCities[i], destinationCities[i]) > threshold:
output.append(1)
else:
output.append(0)
return output
但是对于以下输入:
10
1
4
10
4
3
6
4
3
6
2
9
我的输出是:
Your Output (stdout)
0
1
0
1
Expected Output
1
1
1
1
解决方案
我绝对不知道这是否好,但它可以解决问题。
from math import gcd
def exists(a, b, t):
return gcd(a, b) > t
# find goes trough everithing it can
def find(paths, seen, start, end, true, path):
for i in paths[start]:
if i in seen or i == true:
continue
# creating shortcuts, it may backfire or help performance, it depends
for j in path:
paths[i].add(j)
path.append(i)
if i == end:
return True
seen.add(i)
if find(paths, seen, i, end, true, path):
return True
return False
def solve(nc, t, sc, ec):
ew = sc + ec
# create lookup table
paths = [None] * len(ew)
for i in range(len(ew)):
paths[i] = set()
# fill it
for i in range(len(ew)):
for j in range(i+1, len(ew)):
if exists(ew[i], ew[j], t):
paths[i].add(j)
paths[j].add(i)
# traverse paths to find a values
res = []
seen = set()
path = []
for i in range(len(sc)):
if exists(sc[i], ec[i], t) or find(paths, seen, i, i + len(sc), i, path):
res.append(1)
else:
res.append(0)
seen.clear()
path.clear()
return res
print(solve(10, 1, [4, 10, 4, 3, 6], [4, 3, 6, 2, 9]))
推荐阅读
- asynchronous - 如何安全地关闭 Trio 中的连接?
- jhipster - jhipster 的最佳 api 密钥解决方案?
- c# - 使用 docker-compose 将带有 MySQL 持久数据库的 ASP.NET Core Web 应用程序化为两个单独的容器
- build - 由于测试失败(CryptoUtilsTest 和 NodeH2SecurityTests),无法在 Ubuntu 20.04 上构建 Corda(release/os/4.6)
- azure - 自动处理将 Azure 数据资源管理器中的数据连续导出到 Azure Data Lake
- terraform - Terraform if 语句的真假
- wordpress - Wordpress 类别查询仅显示 4 个类别
- css - 处理多列布局中的分栏符
- c++ - 在定义和构造函数中初始化变量 - 使用
- ole - 使用 OLE 对象定义从 ACUCOBOL 创建 winword