#!/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
变得非常简单吗?有这样的方法吗?
如果你阅读
Scanner
的documentation,你会发现:如果要使用
hasNextLine()
,需要在每个循环中读取行,然后将解析为String
和两个int
,否则需要检查下一个标记的可用性,然后读取它。在这种情况下,令牌可以是int
或String
,通过使用上述public boolean hasNext()
方法另一方面,
hasNextInt()
正在检查下一个int
的存在,而没有检查下一个String
,因此while-loop
中的条件逻辑在程序中不合适相关问题 更多 >
编程相关推荐