python小程序练习

1、输出斐波拉契数列

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#返回斐波那契数列的第n个数
def Fib(n):
	num = 0
	if(0 > n):
		print('input error')
	elif(0 == n):
		num = 0
	elif(1 == n):
		num = 1
	else:	
		num = Fib(n - 1) + Fib(n - 2)
	return num

	
#if __name__ == '__main__':
n = int(input('Please input the n:'))
print('The Fibonacci sequence number array is:')
for i in range(n):
	print(Fib(i))

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

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def prime_check(number):
    for i in range(2, number + 1):
        if(number % i == 0):
            break;
    #是素数
    if(i == number):
        return 1
    else:
        return 0
        
num = 0
for j in range(101, 201):
    if(1 == prime_check(j)):    
        print(j)
        num+=1
        
print('The total prime is %d' % num)

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

     这种问题的常见解法是将三位数的个十百都分解出来,如下:

     

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
for n in range(100,1000):
    i = n / 100
    j = n / 10 % 10
    k = n % 10
    if n == i ** 3 + j ** 3 + k ** 3:
        print n 

这是一种比较常见的解法,我在网络上遇到另外一种分解的方法很有意思,直接将三位数转换为字符串数组,然后再进行操作。如下:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

for i in range(100, 1000):
    s = str(i)
    if int(s[0]) ** 3 + int(s[1]) ** 3 + int(s[2]) ** 3 == i:
        print(i)

4、输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数相应的解法中应用到了字符串的库函数很有代表性,从点击打开链接摘抄过来留记。

     

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import string
s = input('input s string:\n')
letters = 0
space = 0
digit = 0
others = 0
        
for c in s:
    if c.isalpha():
        letters += 1
    elif c.isspace():
        space += 1
    elif c.isdigit():
        digit += 1
    else:
        others += 1

print('char = %d, space = %d, digit = %d, others = %d' % (letters, space, digit, others))


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值