## 2016年7月11日月曜日

### Python - Lists(nested list, cumsum, middle, chop, sorted, anagrams, duplicates)

Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 10.(Lists)のExercises 10-1, 2, 3, 4, 5, 6, 7.(No. 2339)を取り組んでみる。

Exercises 10-1、 2、 3、 4、 5、 6、 7.(No. 2339)

コード(Emacs)

``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- def nested_sum(nested_list): result = 0 for nums in nested_list: result += sum(nums) return result def cumsum(nums): result = [] for i, num in enumerate(nums): if i == 0: result.append(num) else: result.append(result[i - 1] + num) return result def middle(items): t = items[1:-1] return t def chop(items): items.pop(0) items.pop() def is_sorted(items): return sorted(items) == items def is_anagram(s1, s2): return sorted(s1) == sorted(s2) def has_duplicates(l): return len(l) != len(set(l)) if __name__ == '__main__': print('10-1.') t = [[1, 2], [3], [4, 5, 6]] print(nested_sum(t)) print('10-2.') t = [1, 2, 3] print(cumsum(t)) print('10-3.') t = [1, 2, 3, 4] print(middle(t)) print(t) print('10-4.') t = [1, 2, 3, 4] print(chop(t)) print(t) print('10-5.') print(is_sorted([1, 2, 2])) print(is_sorted(['b', 'a'])) print('10-6.') print(is_anagram('cinema', 'iceman')) print(is_anagram('cinemaa', 'icemana')) print(is_anagram('cinemaa', 'iceman')) print('10-7.') print(has_duplicates([1, 2, 1, 3, 4, 5, ])) print(has_duplicates([1, 2, 3, 4, 5])) ```

```\$ ./sample1.py
10-1.
21
10-2.
[1, 3, 6]
10-3.
[2, 3]
[1, 2, 3, 4]
10-4.
None
[2, 3]
10-5.
True
False
10-6.
True
True
False
10-7.
True
False
\$
```