📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This module contains a code example related to12Think Python, 2nd Edition3by Allen Downey4http://thinkpython2.com56Copyright 2015 Allen Downey78License: http://creativecommons.org/licenses/by/4.0/9"""1011from __future__ import print_function, division1213import random141516def nested_sum(t):17"""Computes the total of all numbers in a list of lists.1819t: list of list of numbers2021returns: number22"""23total = 024for nested in t:25total += sum(nested)26return total272829def cumsum(t):30"""Computes the cumulative sum of the numbers in t.3132t: list of numbers3334returns: list of numbers35"""36total = 037res = []38for x in t:39total += x40res.append(total)41return res424344def middle(t):45"""Returns all but the first and last elements of t.4647t: list4849returns: new list50"""51return t[1:-1]525354def chop(t):55"""Removes the first and last elements of t.5657t: list5859returns: None60"""61del t[0]62del t[-1]636465def is_sorted(t):66"""Checks whether a list is sorted.6768t: list6970returns: boolean71"""72return t == sorted(t)737475def is_anagram(word1, word2):76"""Checks whether two words are anagrams7778word1: string or list79word2: string or list8081returns: boolean82"""83return sorted(word1) == sorted(word2)848586def has_duplicates(s):87"""Returns True if any element appears more than once in a sequence.8889s: string or list9091returns: bool92"""93# make a copy of t to avoid modifying the parameter94t = list(s)95t.sort()9697# check for adjacent elements that are equal98for i in range(len(t)-1):99if t[i] == t[i+1]:100return True101return False102103104def main():105t = [[1, 2], [3], [4, 5, 6]]106print(nested_sum(t))107108t = [1, 2, 3]109print(cumsum(t))110111t = [1, 2, 3, 4]112print(middle(t))113chop(t)114print(t)115116print(is_sorted([1, 2, 2]))117print(is_sorted(['b', 'a']))118119print(is_anagram('stop', 'pots'))120print(is_anagram('different', 'letters'))121print(is_anagram([1, 2, 2], [2, 1, 2]))122123print(has_duplicates('cba'))124print(has_duplicates('abba'))125126127if __name__ == '__main__':128main()129130131