范围(n)和布尔列表的解释,onetoone映射,更简单?

2024-09-29 19:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

#!/usr/bin/python
#
# Description: bitwise factorization and then trying to find
# an elegant way to print numbers

# Source: http://forums.xkcd.com/viewtopic.php?f=11&t=61300#p2195422
# bug with large numbers such as 99, but main point in simplifying it
#
def primes(n):
    # all even numbers greater than 2 are not prime.
    s = [False]*2 + [True]*2 + [False,True]*((n-4)//2) + [False]*(n%2)
    i = 3;
    while i*i < n:
        # get rid of ** and skip even numbers.
        s[i*i : n : i*2] = [False]*(1+(n-i*i)//(i*2))
        i += 2
        # skip non-primes
        while not s[i]: i += 2
    return s


# TRIAL: can you find a simpler way to print them?
# feeling the overuse of assignments but cannot see a way to get it simpler
#
p = 49
boolPrimes = primes(p)
numbs = range(len(boolPrimes))
mydict = dict(zip(numbs, boolPrimes))

print([numb for numb in numbs if mydict[numb]])

我要找的东西,你能让TRIAL变得非常简单吗?有这样的方法吗?

^{pr2}$

Tags: andtoinfalseitfindwaybut
1条回答
网友
1楼 · 发布于 2024-09-29 19:19:51

如果你阅读Scannerdocumentation,你会发现:

public boolean hasNext()

Returns true if this scanner has another token in its input.

如果要使用hasNextLine(),需要在每个循环中读取,然后解析为String两个int,否则需要检查下一个标记的可用性,然后读取它。在这种情况下,令牌可以是intString,通过使用上述public boolean hasNext()方法

另一方面,hasNextInt()正在检查下一个int的存在,而没有检查下一个String,因此while-loop中的条件逻辑在程序中不合适

相关问题 更多 >

    热门问题