Discuss / Python / 作业

作业

Topic source

行云流水

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

练习1

def normalize(word):      
    word = word[0].upper() + word[1:].lower()
    return word

#测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)

练习2

from functools import reduce

def prod(L):
    return reduce(lambda x, y:x * y, L)

#测试
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('测试成功!')
else:
    print('测试失败!')

练习3

from functools import reduce

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,'10': 10}

def str2float(s):
    i = s.index('.')
    s1 = s[:i]
    s2 = s[i+1:]
    def char2num(x):
        return DIGITS[x]
    def str2int(s):
        return reduce(lambda x, y: x * 10 + y, map(char2num,s))
    result = str2int(s1) + str2int(s2) * pow(10, -i)
    return result

#测试
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')

ksahgfiwhi

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

#第一题:利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:

def normalize(name):

    name = name[0].upper() + name[1:].lower()

    return name

#第二题:Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积:

from functools import reduce

def prod(L):

    def f1(x, y):

        return x*y

    return reduce(f1, L)

#第三题:利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:

from functools import reduce

def str2float(s):

    def fn(x, y):

        if y == '.':

            return x

        else:

            return x*10 + y

    DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.':'.'}

    def char2num(s):

        return DIGITS[s]

    return reduce(fn, map(char2num, s))/(10 ** (len(s) - s.index('.')-1))

ksahgfiwhi

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

不好意思哈哈哈,发错地方了

Love Yourz

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

练习三result那里不对吧,我稍稍改了一下

from functools import reduce

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def char2num(s):

    return DIGITS[s]

def str2int(s):

    return reduce(lambda x,y:x*10+y,map(char2num,s))

def str2float(s):

    i=s.index('.')

    s1=s[:i]

    s2=s[i+1:]

    result=str2int(s1)+str2int(s2)*pow(10,-len(s2))

    return result


  • 1

Reply