Exercise 10.1. Write a function called nested_sum that takes a list of lists of integers and adds up
the elements from all of the nested lists. For example:
>>> t = [[1, 2], [3], [4, 5, 6]]
>>> nested_sum(t)
21
def lsum(ls):
acc = 0
for e in ls:
acc += e
return acc
def nsum(ns):
acc = 0
for e in ns:
acc += lsum(e)
return acc
t = [[1, 2], [3], [4, 5, 6]]
print(nsum(t))
Exercise 10.2. Write a function called cumsum that takes a list of numbers and returns the cumu-
lative sum; that is, a new list where the ith element is the sum of the first i + 1 elements from the
original list. For example:
>>> t = [1, 2, 3]
>>> cumsum(t)
[1, 3, 6]
def cumsum(t):
acc = 0
nt = []
for i in t:
acc += i
nt.append(acc)
return nt
t = [1, 2, 3]
print(cumsum(t))
Exercise 10.3. Write a function called middle that takes a list and returns a new list that contains
all but the first and last elements. For example:
>>> t = [1, 2, 3, 4]
>>> middle(t)
[2, 3]
def middle(t):
nt = t[1:-1]
return nt
t = [1, 2, 3, 4]
print(middle(t))
Exercise 10.4. Write a function called chop that takes a list, modifies it by removing the first and
last elements, and returns None. For example:
>>> t = [1, 2, 3, 4]
>>> chop(t)
>>> t
[2, 3]
def chop(t):
del t[0], t[-1]
return None
a = [1, 2, 3, 4]
print(chop(a))
print(a)
Exercise 10.5. Write a function called is_sortedthat takes a list as a parameter and returns True
if the list is sorted in ascending order and Falseotherwise. For example:
>>> is_sorted([1, 2, 2])
True
>>> is_sorted(['b', 'a'])
False
def is_sorted(t):
ref = 0
for i in range(len(t)-1):
if t[i] > t[i+1]:
return False
return True
print(is_sorted(['b', 'a']))
print(is_sorted([1, 2, 3]))
Exercise 10.6. Two words are anagrams if you can rearrange the letters from one to spell the other.
Write a function called is_anagram that takes two strings and returns True if they are anagrams.
# 这个函数数一个单词里面每个字母出现的次数,返回值是一个数列。
def abc(word):
alphabet = 'abcdefghijklmhopqrstuvwxyz'
ac = []
for i in alphabet:
count = 0
for j in word:
if i == j:
count += 1
ac.append(count)
return ac
# 这个函数检查一个词是否可以通过字母顺序重组,形成第二个词
# 方法是:比较两个词分别调用上面函数,返回的数列是否相同
def is_anagram(word1, word2):
return abc(word1) == abc(word2)
print(is_anagram('abcdef', 'defabc'))
print(is_anagram('abcabcdef', 'defabcabc'))
print(is_anagram('silent', 'listen'))
print(is_anagram('hello, ', 'world!'))
Exercise 10.7. Write a function called has_duplicates that takes a list and returns True if there
is any element that appears more than once. It should not modify the original list.
def has_duplicates(t):
for i in range(len(t)):
temp = t[:]
temp.pop(i)
for item in temp:
if item == t[i]:
return True
return False
aa = ['a', 'b', 'c']
bb = ['a', 'b', 'a']
print(has_duplicates(aa))
print(aa)
print(has_duplicates(bb))
print(bb)