Discuss / Python / l1和l2得写成一样的才行,有点困惑

l1和l2得写成一样的才行,有点困惑

Topic source

脱离语言

#1 Created at ... [Delete] [Delete and Lock User]

第3题:

digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': -1}
def str2int(ch):
    return digits[ch]
def fn(x, y):
    if y < 0:
        return x
    return 10*x + y
def fn2(x, y):
    if y < 0:
        return 1
    return 10*x
l1 = map(str2int, iter(s))
l2 = map(str2int, iter(s))
s1 = reduce(fn, l1)
s2 = reduce(fn2, l2)
return s1 / s2

脱离语言

#2 Created at ... [Delete] [Delete and Lock User]

明白了,map返回值是个惰性序列导致的,可以改成这样

digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': -1}
def str2int(ch):
    return digits[ch]
def fn(x, y):
    if y < 0:
        return x
    return 10*x + y
def fn2(x, y):
    if y < 0:
        return 1
    return 10*x
l1 = list(map(str2int, iter(s)))
l2 = l1[:]
s1 = reduce(fn, l1)
s2 = reduce(fn2, l2)
return s1 / s2

  • 1

Reply