A+B Problem
问题描述:
Calculate a + b
输入:Two integer a,,b (0 ≤ a,b ≤ 10)
输出:Output a + b
样例输入:1 2
样例输出:3
解析:本题目取自OpenJudge第一题,题目本身不难,对输入的两个数求和,属于一道入门题
答案1:
print sum(int(x) for x in raw_input().split())
答案2:
i = raw_input()
a, b = map(int, i.split())
print a + b
知识点:
raw_input会读取控制台的输入与用户实现交互,将所有输入作为字符串看待,返回字符串类型,因此必须使用字符串的strip和split方法对字符串进行一定的处理使其可以作为输入
如下:
i = raw_input()
1 2
i
Out[10]: '1 2'
strip方法:
用于移除字符串头尾指定的字符(默认为空格)
i = raw_input()
1 2
i
Out[13]: ' 1 2 '
i.strip()
Out[14]: '1 2'
split方法:
通过指定分隔符对字符串进行切片,默认为空格
i = raw_input()
1 2
i
Out[13]: ' 1 2 '
i.strip()
Out[14]: '1 2'
i.split()
Out[15]: ['1', '2']
汉诺塔问题
问题描述:
有三根杆子A,B,C。A杆上有N个(N>1)穿孔圆盘,盘的尺寸由下到上依次变小。要求按下列规则将所有圆盘移至C杆: 每次只能移动一个圆盘; 大盘不能叠在小盘上面。 提示:可将圆盘临时置于B杆,也可将从A杆移出的圆盘重新移回A杆,但都必须遵循上述两条规则。
问:如何移?最少要移动多少次?
答案解析:
http://blog.csdn.net/geekwangminli/article/details/7981570
Python答案:
def move(n, a, b, c):
if n == 1:
print "%d:%s->%s" % (n,a,c)
return
else:
move(n-1, a, c, b)
print "%d:%s->%s" % (n,a,c)
move(n-1, b, a, c)
i = raw_input()
n, a, b, c = i.split()
n = int(n)
move(n, a, b, c)
打印水仙花数
题目描述:
打印出所有得“水仙花数”,所谓“水仙花数”是指一个3位数,其各位数字的立方和等于该数本身,例如,152是水仙花数,因为153=1×1×1+5×5×5+3×3×3。
Python答案:
for i in range(100,1000):
a = i / 100
b = i % 100 / 10
c = i % 10
if pow(a,3) + pow(b,3) + pow(c,3) == i:
print i
整数的立方和
题目描述:
给定一个正整数k,求1到k的立方和m。
Python答案:
i = raw_input()
print sum(pow(a, 3) for a in range(1,int(i)+1))
求平均年龄
题目描述:
班上有学生若干名,给出每名学生的年龄(整数),求班上所有学生的平均年龄,保留到小数点后两位
输入:第一行有一个整数n(1<= n <= 100),表示学生的人数。其后n行每行有1个整数,表示每个学生的年龄,取值为15到25。
输出:输出一行,该行包含一个浮点数,为要求的平均年龄,保留到小数点后两位。
Python答案:
i = raw_input()
a = i.split()
a1 = int(a[0])
c1 = []
while True:
j = raw_input()
b = j.split()
b1 = int(b[0])
c1.append(b1)
if a1==1:
break
a1 = a1 -1
print '%.2f' % (sum(c1)*1.0/len(c1))