Google Python入门题学习--list

写了3个函数,前2个函数基本与答案一致,只是多增加了些打印。第3个与答案差异较大,比我的答案简洁很多。主要是对sorted的用法不太熟悉,不知道key参数的含义。查了下资料。

The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. 

sorted(iterable[, cmp[, key[, reverse]]])

Return a new sorted list from the items in iterable.

The optional arguments cmpkey, and reverse have the same meaning as those for the list.sort() method (described in sectionMutable Sequence Types).

cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambdax,y: cmp(x.lower(), y.lower()). The default value is None.

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmpis called multiple times for each list element while key and reverse touch each element only once. Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

写的函数及执行输出如下。

#!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0

# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/

# Basic list exercises
# Fill in the code for the functions below. main() is already set up
# to call the functions with a few different inputs,
# printing 'OK' when each function is correct.
# The starter code for each function includes a 'return'
# which is just a placeholder for your code.
# It's ok if you do not complete all the functions, and there
# are some additional functions to try in list2.py.

# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
def match_ends(words):
    # +++your code here+++
    num_match = 0
    for str in words:
        len_str = len(str)
        print "length of |%s| is %d" % (str, len_str)
        if len_str >= 2:
            if len_str % 2 == 0:
                str_first = str[0:(len_str / 2)]
                print "str_first is %s" % str_first
                str_last = str[(len_str / 2):(len_str)]
                print "str_last is %s" % str_last
                if str_last == str_first:
                    num_match = num_match + 1
            elif len_str % 2 == 1:
                str_first = str[0:(len_str / 2)]
                print "str_first is %s" % str_first
                str_last = str[(len_str / 2 + 1):(len_str)]
                print "str_last is %s" % str_last
                if str_last == str_first:
                    num_match = num_match + 1
        print 'mactch str is %d' % num_match
    return num_match


# B. front_x
# Given a list of strings, return a list with the strings
# in sorted order, except group all the strings that begin with 'x' first.
# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
# Hint: this can be done by making 2 lists and sorting each of them
# before combining them.
def front_x(words):
    # +++your code here+++
    list_tmp_x = []
    list_tmp = []
    for list_elem in words:
        print list_elem
        if list_elem.startswith('x'):
            list_tmp_x.append(list_elem)
        else:
            list_tmp.append(list_elem)
    list_tmp_x = sorted(list_tmp_x)
    list_tmp = sorted(list_tmp)
    print 'the final list is', list_tmp_x + list_tmp
    return list_tmp_x + list_tmp


# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
    # +++your code here+++
    dict={}
    list_tmp=[]
    ret=[]
    for elem in tuples:
        print elem[-1]
        dict[elem[-1]]=elem[0:len(elem)]
        list_tmp.append(elem[-1])
    print 'list_tmp is:',list_tmp
    for key in sorted(list_tmp):
        ret.append(dict[key])
    print 'ret is',ret
    return ret


# Simple provided test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
    if got == expected:
        prefix = ' OK '
    else:
        prefix = '  X '
    print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))


# Calls the above functions with interesting inputs.
def main():
    print 'match_ends'
    test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3)
    test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2)
    test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)

    print
    print 'front_x'
    test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']),
         ['xaa', 'xzz', 'axx', 'bbb', 'ccc'])
    test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']),
         ['xaa', 'xcc', 'aaa', 'bbb', 'ccc'])
    test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']),
         ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'])

    print
    print 'sort_last'
    test(sort_last([(1, 3), (3, 2), (2, 1)]),
         [(2, 1), (3, 2), (1, 3)])
    test(sort_last([(2, 3), (1, 2), (3, 1)]),
         [(3, 1), (1, 2), (2, 3)])
    test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]),
         [(2, 2), (1, 3), (3, 4, 5), (1, 7)])


if __name__ == '__main__':
    main()

输出

C:\Python27\python.exe D:/python_test/list1.py
match_ends
length of |aba| is 3
str_first is a
str_last is a
mactch str is 1
length of |xyz| is 3
str_first is x
str_last is z
mactch str is 1
length of |aa| is 2
str_first is a
str_last is a
mactch str is 2
length of |x| is 1
mactch str is 2
length of |bbb| is 3
str_first is b
str_last is b
mactch str is 3
 OK  got: 3 expected: 3
length of || is 0
mactch str is 0
length of |x| is 1
mactch str is 0
length of |xy| is 2
str_first is x
str_last is y
mactch str is 0
length of |xyx| is 3
str_first is x
str_last is x
mactch str is 1
length of |xx| is 2
str_first is x
str_last is x
mactch str is 2
 OK  got: 2 expected: 2
length of |aaa| is 3
str_first is a
str_last is a
mactch str is 1
length of |be| is 2
str_first is b
str_last is e
mactch str is 1
length of |abc| is 3
str_first is a
str_last is c
mactch str is 1
length of |hello| is 5
str_first is he
str_last is lo
mactch str is 1
 OK  got: 1 expected: 1

front_x
bbb
ccc
axx
xzz
xaa
the final list is ['xaa', 'xzz', 'axx', 'bbb', 'ccc']
 OK  got: ['xaa', 'xzz', 'axx', 'bbb', 'ccc'] expected: ['xaa', 'xzz', 'axx', 'bbb', 'ccc']
ccc
bbb
aaa
xcc
xaa
the final list is ['xaa', 'xcc', 'aaa', 'bbb', 'ccc']
 OK  got: ['xaa', 'xcc', 'aaa', 'bbb', 'ccc'] expected: ['xaa', 'xcc', 'aaa', 'bbb', 'ccc']
mix
xyz
apple
xanadu
aardvark
the final list is ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
 OK  got: ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] expected: ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']

sort_last
3
2
1
list_tmp is: [3, 2, 1]
ret is [(2, 1), (3, 2), (1, 3)]
 OK  got: [(2, 1), (3, 2), (1, 3)] expected: [(2, 1), (3, 2), (1, 3)]
3
2
1
list_tmp is: [3, 2, 1]
ret is [(3, 1), (1, 2), (2, 3)]
 OK  got: [(3, 1), (1, 2), (2, 3)] expected: [(3, 1), (1, 2), (2, 3)]
7
3
5
2
list_tmp is: [7, 3, 5, 2]
ret is [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
 OK  got: [(2, 2), (1, 3), (3, 4, 5), (1, 7)] expected: [(2, 2), (1, 3), (3, 4, 5), (1, 7)]

进程已结束,退出代码0
 

# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
def match_ends(words):
  # +++your code here+++
  # LAB(begin solution)
  count = 0
  for word in words:
    if len(word) >= 2 and word[0] == word[-1]:
      count = count + 1
  return count
  # LAB(replace solution)
  # return
  # LAB(end solution)


# B. front_x
# Given a list of strings, return a list with the strings
# in sorted order, except group all the strings that begin with 'x' first.
# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
# Hint: this can be done by making 2 lists and sorting each of them
# before combining them.
def front_x(words):
  # +++your code here+++
  # LAB(begin solution)
  # Put each word into the x_list or the other_list.
  x_list = []
  other_list = []
  for w in words:
    if w.startswith('x'):
      x_list.append(w)
    else:
      other_list.append(w)
  return sorted(x_list) + sorted(other_list)
  # LAB(replace solution)
  # return
  # LAB(end solution)


# LAB(begin solution)
# Extract the last element from a tuple -- used for custom sorting below.
def last(a):
  return a[-1]
# LAB(end solution)

# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
  # +++your code here+++
  # LAB(begin solution)
  return sorted(tuples, key=last)
  # LAB(replace solution)
  # return
  # LAB(end solution)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值