1.Python for循环和if条件
def flush(hand):
.for i in range(len(hand)-1):
。..if hand[i][1] != hand[i+1][1]:
。。。return False
.return True
if __name__ == '__main__':
.print(flush([(4,'d'),(5,'d'),(3,'d')]))
2.试编写Python程序,根据哥德巴赫猜想一:任何大于6的偶数都可表
#coding=utf-8 import sys,time from math import sqrt def isprime(num): for i in range(2,int(sqrt(num))+1): if num%i==0: return False return True def gedebahe(num): for i in range(2,num//2+1): if isprime(i) and isprime(num-i): return True return Falsese def main(n): for i in range(6,n+1,2): if not gedebahe(i,L): print('fail at number {}'.format(i)) break else: tip='success: all evens in {} can be the sum of two primes.' print(tip.format(n)) if __name__=='__main__': start=time.time() n=100000 if len(sys.argv)>1: n=int(sys.argv[1]) main(n) end=time.time() print('cost {} seconds'.format(end-start))[willie@bogon pys]$ python gedebahe.py success: all evens in 100000 can be the sum of two primes. cost 24.8260421753 seconds #coding=utf-8 import sys,time from math import sqrt def primes(n): # prepair data space plist = [0, 0] + list(range(2,n+1)) for i in range(2, int(sqrt(n))+1): if plist[i]: plist[i+i::i] = [0] * len(plist[i+i::i]) return filter(None, plist) def gedebahe(n,L): for i in L: if (n-i) in L: return True elif i>n//2+1: return False def main(n): L=list(primes(n)) for i in range(6,n+1,2): if not gedebahe(i,L): print('fail at number {}'.format(i)) break else: tip='success: all evens in {} can be the sum of two primes.' print(tip.format(n)) if __name__=='__main__': start=time.time() n=100000 if len(sys.argv)>1: n=int(sys.argv[1]) main(n) end=time.time() print('cost {} seconds'.format(end-start))[willie@bogon pys]$ python gedebahe.py success: all evens in 100000 can be the sum of two primes. cost 70.5533659458 seconds。
转载请注明出处编程代码网 » pythoniffor