一些Python经典案例题
1:判断年份是否为闰年
import java.util.Scanner;
/*
有一个年份,判断是否是闰年,
输出不同的提示是闰年或不是闰年
(直接使用逻辑运算符实现)
*/
public class LeapYear {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个年份:");
int year =sc.nextInt();
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
System.out.println(year + "是闰年");
} else {
System.out.println(year + "不是闰年");
}
sc.close();
}
}
2:水仙花
打印出100-999所有的水仙花数,所谓水仙花数是指一个三位数,其各位数字立方和等于该数本身
如:153是一个’水仙花数’,因为153=1的三次方+5的三次方+3的三次方
n = []
for i in range(100,1000):
i = str(i)
a = pow(int(i[0]),3)
b = pow(int(i[1]),3)
c = pow(int(i[2]),3)
if a+b+c == int(i):
n.append(i)
else:
continue
print(n)
3:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if( i != k ) and (i != j) and (j != k):
print (i,j,k)
4:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
程序分析:
假设该数为 x。
1、则:x + 100 = n2, x + 100 + 168 = m2
2、计算等式:m2 - n2 = (m + n)(m - n) = 168
3、设置: m + n = i,m - n = j,i * j =168,i 和 j 至少一个是偶数
4、可得: m = (i + j) / 2, n = (i - j) / 2,i 和 j 要么都是偶数,要么都是奇数。
5、从 3 和 4 推导可知道,i 与 j 均是大于等于 2 的偶数。
6、由于 i * j = 168, j>=2,则 1 < i < 168 / 2 + 1。
7、接下来将 i 的所有数字循环计算即可。
for i in range(1,85):
if 168 % i == 0:
j = 168 / i;
if i > j and (i + j) % 2 == 0 and (i - j) % 2 == 0 :
m = (i + j) / 2
n = (i - j) / 2
x = n * n - 100
print(x)
5:题目:输入某年某月某日,判断这一天是这一年的第几天?
year = int(input('year:\n'))
month = int(input('month:\n'))
day = int(input('day:\n'))
months = (0,31,59,90,120,151,181,212,243,273,304,334)
if 0 < month <= 12:
sum = months[month - 1]
else:
print ('data error')
sum += day
leap = 0
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
leap = 1
if (leap == 1) and (month > 2):
sum += 1
print ('it is the %dth day.' % sum)
6:输入三个整数x,y,z,请把这三个数由小到大输出。
l = []
for i in range(3):
x = int(raw_input('integer:\n'))
l.append(x)
l.sort()
print l
7:斐波那契数列。
def fib(n):
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
# 输出了第10个斐波那契数列
print (fib(10))
8:将一个列表的数据复制到另一个列表中。
a = [1, 2, 3]
b = a[:]
print (b)
9:输出 9*9 乘法口诀表。
for i in range(1, 10):
print
for j in range(1, i+1):
print "%d*%d=%d" % (i, j, i*j),
10:生兔子
程序分析:兔子的规律为数列1,1,2,3,5,8,13,21…
f1 = 1
f2 = 1
for i in range(1,22):
print '%12ld %12ld' % (f1,f2),
if (i % 3) == 0:
print ''
f1 = f1 + f2
f2 = f1 + f2