原题:
I always thought that my old friend John was rather richer than he looked, but I never knew exactly how much money he actually had. One day (as I was plying him with questions) he said:
- "Imagine I have between
m
andn
Zloty..." (or did he say Quetzal? I can't remember!) - "If I were to buy 9 cars costing
c
each, I'd only have 1 Zloty (or was it Meticals?) left." - "And if I were to buy 7 boats at
b
each, I'd only have 2 Ringglets (or was it Zloty?) left."
Could you tell me in each possible case:
- how much money
f
he could possibly have ? - the cost
c
of a car? - the cost
b
of a boat?
So, I will have a better idea about his fortune. Note that if m-n
is big enough, you might have a lot of possible answers.
Each answer should be given as ["M: f", "B: b", "C: c"]
and all the answers as [ ["M: f", "B: b", "C: c"], ... ]
. "M" stands for money, "B" for boats, "C" for cars.
Note: m, n, f, b, c
are positive integers, where 0 <= m <= n
or m >= n >= 0
. m
and n
are inclusive.
Examples:
howmuch(1, 100) => [["M: 37", "B: 5", "C: 4"], ["M: 100", "B: 14", "C: 11"]]
howmuch(1000, 1100) => [["M: 1045", "B: 149", "C: 116"]]
howmuch(10000, 9950) => [["M: 9991", "B: 1427", "C: 1110"]]
howmuch(0, 200) => [["M: 37", "B: 5", "C: 4"], ["M: 100", "B: 14", "C: 11"], ["M: 163", "B: 23", "C: 18"]]
Explanation of the results for howmuch(1, 100)
:
In the first answer his possible fortune is 37:
-
- so he can buy 7 boats each worth 5:
37 - 7 * 5 = 2
- or he can buy 9 cars worth 4 each:
37 - 9 * 4 = 1
- so he can buy 7 boats each worth 5:
- The second possible answer is 100:
- he can buy 7 boats each worth 14:
100 - 7 * 14 = 2
- or he can buy 9 cars worth 11:
100 - 9 * 11 = 1
- he can buy 7 boats each worth 14:
-------------------------------------------------------------------------------------------------------------------
题目大意为给出一个数的范围,在此范围中找出数字,满足公式(这个整数-7*某个整数)=2以及满足(这个整数-9*某个整数)=1,然后返回这个数以及符合条件的“某个整数”的值
解题办法:
看一下我的解题办法,重复代码好多,,,,
def howmuch(m, n): # your code L = [] if n >= m: for i in range(m, n+1): L1 = [] b = (i-2) % 7 c = (i-1) % 9 if b == 0 and c == 0: L1 = ["M: "+str(i), "B: "+str(int((i-2)/7)), "C: "+str(int((i-1)/9))] L.append(L1) else: for i in range(n, m+1): L1 = [] b = (i-2) % 7 c = (i-1) % 9 if b == 0 and c == 0: L1 = ["M: "+str(i), "B: "+str(int((i-2)/7)), "C: "+str(int((i-1)/9))] L.append(L1) return L
再看看网友优秀的思路:
def howmuch(m, n): return [['M: %d'%i, 'B: %d'%(i/7), 'C: %d'%(i/9)] for i in range(min(m,n), max(m,n)+1) if i%7 == 2 and i%9 == 1]
简洁到令人发指,,,羡慕啊!!!
知识点:
1、取两个数的最大值和最小值,可以使用min()和max()函数来取出最大值和最小值;也可以使用n, m = m, n if m>n:
2、i = 1; (["M: %s"])%i -------->这是一种错误的办法