python之简单题目(2)

6、题目:暂停一秒输出,并格式化当前时间。

程序分析:无。

import time
print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
time.sleep(1)
print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())

7、题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

程序分析:兔子的规律为数列1,1,2,3,5,8,13,21....

 

rabbit_dict={'month_1':1,'month_2':1}
#month=3
for month in xrange(3,10):
    month_str='month_'+str(month)#create the str to save the month
    month_str_pre='month_'+str(month-1)
    month_str_pre_pre='month_'+str(month-1-1)
    rabbit_dict.setdefault(month_str,rabbit_dict[month_str_pre]+\
                           rabbit_dict[month_str_pre_pre])
    #calculate the rabbit number and save it into the
print rabbit_dict

 

8、题目:判断101-200之间有多少个素数,并输出所有素数。

程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数。   

import math
count=0 #the number to save the number which is not prime
for i in xrange(101,201):
    for j in xrange(2,int(math.sqrt(i))+1):
        if i%j==0: #if i%j==0,then i is not a prime
            count+=1
            break
    else:#then i is a prime ,print it
        print str(i)+'\n'
print 100-count

 

9、题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。

程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。

import math

for x in range(100,1000):

    single_digit=x%10

    tens_digit=(x%100)/10

    hundreds_digit=x/100

    If x==pow(single_digit,3)+pow(tens_digit,3)+pow(hundreds_digit,3):

        print x

 

10、题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。

程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:
(1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。
(2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数你n,重复执行第一步。
(3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。

import math

#search_for_min_prime bigger than input_last_prime
def search_for_min_prime(input_last_prime):
    for i in xrange(input_last_prime+1,99999):
        for j in xrange(2,int(math.sqrt(i))+1):
            if i%j==0: #if i%j==0,then i is not a prime
                break
        else:#then i is a prime ,print it
            return i

def search_for_k(input_x):
    global prime_temp
    if input_x==prime_temp:
        print str(input_x) #'it it over'
    elif prime_temp<input_x and input_x%prime_temp==0:
        quotient=input_x/prime_temp #save the quotient
        print '%d *' %prime_temp,  #the prime_temp is one of the factors
        prime_temp=2    #reset the prime_temp
        search_for_k(quotient)# call search_for_k with quotient
    else:
        prime_temp=search_for_min_prime(prime_temp)#search next prime
        search_for_k(input_x) #recall the func search_for_k

prime_temp=2 #set the min prime_temp
inputx=int(raw_input('please enter a number:'))
print str(inputx)+'=',
search_for_k(inputx)   

猜你喜欢

转载自blog.csdn.net/dieju8330/article/details/81490519
今日推荐