Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96169
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
import random
15
16
17
def nested_sum(t):
18
"""Computes the total of all numbers in a list of lists.
19
20
t: list of list of numbers
21
22
returns: number
23
"""
24
total = 0
25
for nested in t:
26
total += sum(nested)
27
return total
28
29
30
def cumsum(t):
31
"""Computes the cumulative sum of the numbers in t.
32
33
t: list of numbers
34
35
returns: list of numbers
36
"""
37
total = 0
38
res = []
39
for x in t:
40
total += x
41
res.append(total)
42
return res
43
44
45
def middle(t):
46
"""Returns all but the first and last elements of t.
47
48
t: list
49
50
returns: new list
51
"""
52
return t[1:-1]
53
54
55
def chop(t):
56
"""Removes the first and last elements of t.
57
58
t: list
59
60
returns: None
61
"""
62
del t[0]
63
del t[-1]
64
65
66
def is_sorted(t):
67
"""Checks whether a list is sorted.
68
69
t: list
70
71
returns: boolean
72
"""
73
return t == sorted(t)
74
75
76
def is_anagram(word1, word2):
77
"""Checks whether two words are anagrams
78
79
word1: string or list
80
word2: string or list
81
82
returns: boolean
83
"""
84
return sorted(word1) == sorted(word2)
85
86
87
def has_duplicates(s):
88
"""Returns True if any element appears more than once in a sequence.
89
90
s: string or list
91
92
returns: bool
93
"""
94
# make a copy of t to avoid modifying the parameter
95
t = list(s)
96
t.sort()
97
98
# check for adjacent elements that are equal
99
for i in range(len(t)-1):
100
if t[i] == t[i+1]:
101
return True
102
return False
103
104
105
def main():
106
t = [[1, 2], [3], [4, 5, 6]]
107
print(nested_sum(t))
108
109
t = [1, 2, 3]
110
print(cumsum(t))
111
112
t = [1, 2, 3, 4]
113
print(middle(t))
114
chop(t)
115
print(t)
116
117
print(is_sorted([1, 2, 2]))
118
print(is_sorted(['b', 'a']))
119
120
print(is_anagram('stop', 'pots'))
121
print(is_anagram('different', 'letters'))
122
print(is_anagram([1, 2, 2], [2, 1, 2]))
123
124
print(has_duplicates('cba'))
125
print(has_duplicates('abba'))
126
127
128
if __name__ == '__main__':
129
main()
130
131