python - 转换 C++ for 循环 python

标签 python c++ loops

尝试搜索类似的问题,但无法解决这个问题。不确定如何正确转换 C++ 循环中的某些功能。尤其是count < 20状况main()

原问题:https://rosettacode.org/wiki/Anti-primes

#include <iostream>

int countDivisors(int n) {
    if (n < 2) return 1;
    int count = 2; // 1 and n
    for (int i = 2; i <= n/2; ++i) {
        if (n%i == 0) ++count;
    }
    return count;
}

int main() {
    int maxDiv = 0, count = 0;
    std::cout << "The first 20 anti-primes are:" << std::endl;
    for (int n = 1; count < 20; ++n) {
        int d = countDivisors(n);
        if (d > maxDiv) {
            std::cout << n << " ";
            maxDiv = d;
            count++;
        }
    }
    std::cout << std::endl;
    return 0;
}

我尝试的解决方案:

def countDivisors(n):
    if (n < 2):
        return 1
    count = 2

    for i in range(2, int(n/2)-1, 1):
        print(i)    
        if(n%i == 0):
            count = count + 1
    return count

def main():
    print("The first 20 anti-primes are: ")
    n = 1
    while count < 20:    
        d = countDivisors(n)
        if(d > maxDiv):
            print(n)
            maxDiv = d
            count += 1
            n += 1
    return 0

必填答案:

1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560 

最佳答案

严格来说两者for循环:

for (int i = 2; i <= n/2; ++i)

会变成

for i in range(2,int(n/2)+1):

int(n/2)-1在你的代码中将是 i < n/2-1在C.

<小时/> 20个,

int maxDiv = 0, count = 0;    // <-- !
for (int n = 1; count < 20; ++n) {
    int d = countDivisors(n);
    if (d > maxDiv) {
        std::cout << n << " ";
        maxDiv = d;
        count++;
    }

就快到了,只是你没有maxDivcount在 Python 中初始化。

maxDiv = 0  # <-- !
count = 0   # <-- !
n = 1
while count < 20:    
    d = countDivisors(n)
    if(d > maxDiv):
        print(n)
        maxDiv = d
        count += 1
    n += 1

关于python - 转换 C++ for 循环 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59362726/

相关文章:

c++ - 无法将文件路径从 C++ 保存到数据库

python - 如何在python中循环2个函数?

javascript - 为什么数组将一个空数组插入另一个数组?

python - 函数式编程——for 和 while 循环

python - 在 PyCharm (sciview) 中本地查看远程 python 解释器的绘图

c++ - 如何访问全局类实例?

c++ - 默认写文件到桌面

javascript - 循环遍历传单要素组

python - 将最后三行python输出分配给bash中的3个变量

Python解析结构化文本文件