1. 罗马数字和数字的转化
下面两段代码出自
-
def to_roman(x):
-
anums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
-
rnums = "M CM D CD C XC L XL X IX V IV I".split()
-
ret=[]
-
for a,r in zip(anums,rnums):
-
n,x=divmod(x,a)
-
ret.append(r*n)
-
return "".join(ret)
-
-
def test_to_roman():
-
test=(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,25,30,40,
-
50,60,69,70,80,90,99,100,200,300,400,500,600,666,700,800,900,
-
1000,1009,1444,1666,1945,1997,1999,2000,2008,2010,2011,2500,
-
3000,3999)
-
-
for i in test:
-
print("number {} to roman is {}".format(i,to_roman(i)))
-
-
#test_to_roman()
-
def to_arabic(x):
-
decoder=dict(zip('MDCLXVI',(1000,500,100,50,10,5,1)))
-
result=0
-
for r,r1 in zip(x,x[1:]):
-
rd,rd1=decoder[r],decoder[r1]
-
if rd < rd1:
-
result+=-rd
-
else:
-
result+=rd
-
return result+decoder[x[-1]]
-
-
def test_to_arabic():
-
ll='MCMXC MMVIII MDCLXVI'.split()
-
for i in ll:
-
print(to_arabic(i))
-
-
test_to_arabic()
下面的代码是我自己写的。 和别人的比,果然是差很多了。
-
def to_arabic2(s):
-
#s: sequence
-
decoder=dict(zip('MDCLXVI',(1000,500,100,50,10,5,1)))
-
result=0
-
for i in range(len(s)-1):
-
value=decoder.get(s[i])
-
vnext=decoder.get(s[i+1])
-
if value < vnext:
-
result+=-value
-
else:
-
result+=value
-
return result+decoder.get(s[-1])
-
-
def test_to_arabic2():
-
ll='MCMXC MMVIII MDCLXVI'.split()
-
for i in ll:
-
print(to_arabic2(i))
-
-
test_to_arabic2()
2. 一个puzzle ,出自:
Puzzle:
A merchant has a 40 kg weight which he used in his shop. Once, it fell from his hands and was broken into 4 pieces. But surprisingly, now he can weigh any weight between 1 kg to 40 kg with the combination of these 4 pieces.
So question is, what are weights of those 4 pieces?
这个哥们的代码写的太通用了,还加上pieces. 即N个pieces,sum(n)==L, 同时可以表示1->L,很有趣的题目
-
import itertools as it
-
def find_weights(weight,pieces):
-
full=range(1,weight+1)
-
all_nums=set(full)
-
comb=[x for x in it.combinations(full,pieces) if sum(x)==40]
-
funcs=(lambda x: 0, lambda x: x, lambda x: -x)
-
for c in comb:
-
sums=set()
-
for fmap in it.product(funcs,repeat=pieces):
-
s=sum(f(x) for x,f in zip(c,fmap))
-
if s>0:
-
sums.add(s)
-
if sums==all_nums:
-
return c
-
-
-
print(find_weights(40,5))
阅读(1322) | 评论(0) | 转发(0) |