初学者一枚,最近在巩固python基础,故今天找来了CodingBat进行python编程练习,有一些习题比较有趣。我的代码写的不太好,经常会冗余,写一篇笔记记录一下。
题目1
logic 2—Long-sum问题
Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum.
参考代码
def lone_sum(a, b, c):
sum = 0
if a != b and a != c: sum += a
if b != a and b != c: sum += b
if c != a and c != b: sum += c
return sum
我的答案(明显要麻烦许多):
def lone_sum(a, b, c):
if a!=b and b!=c and c!=a:
return a+b+c
else:
if a==b==c:
return 0
elif a==b:
return c
elif a==c:
return b
elif b==c:
return a
题目2
logic 2 lucky_sum
Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. So for example, if b is 13, then both b and c do not count.
lucky_sum(1, 2, 3) → 6
lucky_sum(1, 2, 13) → 3
lucky_sum(1, 13, 3) → 1
我的答案(没有看到标准答案,感觉还是有点冗余)
def lucky_sum(a, b, c):
if a==13:
return 0
elif b==13:
return a
elif c==13:
return a+b
else:
return a+b+c
logic 2 Make Chocolate
We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can’t be done.
make_chocolate(4, 1, 9) → 4
make_chocolate(4, 1, 10) → -1
make_chocolate(4, 1, 7) → 2
def make_chocolate(small, big, goal):
if big*5<goal:
if goal-big*5>small:
return -1
else:
return goal-big*5
else:
if goal%5<=small:
return goal%5
else:
return -1
logic 2 round sum
For this problem, we’ll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a separate helper “def round10(num):” and call it 3 times. Write the helper entirely below and at the same indent level as round_sum().round_sum(16, 17, 18) → 60
round_sum(12, 13, 14) → 30
round_sum(6, 4, 4) → 10
我的答案
def round_sum(a, b, c):
l=[]
for i in a,b,c:
if i%10>4:
l.append((i/10+1)*10)
else:
l.append(i/10*10)
return sum(l)
参考答案
def round_sum(a, b, c):
return round10(a) + round10(b) + round10(c)
def round10(num):
mod = num % 10
num -= mod
if mod >= 5: num += 10
return num