GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — ThinkPython2/code/list_exercises.py at master · AllenDowney/ThinkPython2 Expand file tree/ Copy pathlist_exercises.pyMore file actions 129 lines (86 loc) · 2.17 KB / Copy pathlist_exercises.pyFile metadata and controls129 lines (86 loc) · 2.17 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 """This module contains a code example related to Think Python, 2nd Edition by Allen Downey https://greenteapress.com/wp/think-python-2e/ Copyright 2015 Allen Downey License: http://creativecommons.org/licenses/by/4.0/ """ from __future__ import print_function, division import random def nested_sum(t): """Computes the total of all numbers in a list of lists. t: list of list of numbers returns: number """ total = 0 for nested in t: total += sum(nested) return total def cumsum(t): """Computes the cumulative sum of the numbers in t. t: list of numbers returns: list of numbers """ total = 0 res = [] for x in t: total += x res.append(total) return res def middle(t): """Returns all but the first and last elements of t. t: list returns: new list """ return t[1:-1] def chop(t): """Removes the first and last elements of t. t: list returns: None """ del t[0] del t[-1] def is_sorted(t): """Checks whether a list is sorted. t: list returns: boolean """ return t == sorted(t) def is_anagram(word1, word2): """Checks whether two words are anagrams word1: string or list word2: string or list returns: boolean """ return sorted(word1) == sorted(word2) def has_duplicates(s): """Returns True if any element appears more than once in a sequence. s: string or list returns: bool """ # make a copy of t to avoid modifying the parameter t = list(s) t.sort() # check for adjacent elements that are equal for i in range(len(t)-1): if t[i] == t[i+1]: return True return False def main(): t = [[1, 2], [3], [4, 5, 6]] print(nested_sum(t)) t = [1, 2, 3] print(cumsum(t)) t = [1, 2, 3, 4] print(middle(t)) chop(t) print(t) print(is_sorted([1, 2, 2])) print(is_sorted(['b', 'a'])) print(is_anagram('stop', 'pots')) print(is_anagram('different', 'letters')) print(is_anagram([1, 2, 2], [2, 1, 2])) print(has_duplicates('cba')) print(has_duplicates('abba')) if __name__ == '__main__': main() |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |