## 2017年4月23日日曜日

### Python - 数学 - ベクトル - ラボ: ドット積を用いた投票記録の比較 - ポリシーの比較(ドット積、ベクトルの比較)

コード(Emacs)

```#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import random

def create_voting_dict(strlist):
return {s.split()[0]: [int(n) for n in s.split()[3:]] for s in strlist}

def policy_compare(sen_a, sen_b,  voting_dict):
l2 = voting_dict[sen_b]
return sum([x * y for x, y in zip(voting_dict[sen_a], voting_dict[sen_b])])

def most_similar(sen, voting_dict):
l = voting_dict[sen]
names = list(voting_dict.keys())
names.remove(sen)
result = names[0]
a = policy_compare(sen, result, voting_dict)
for name in names[1:]:
t = policy_compare(sen, name, voting_dict)
if t > a:
a = t
result = name
return result

def least_similar(sen, voting_dict):
l = voting_dict[sen]
names = list(voting_dict.keys())
names.remove(sen)
result = names[0]
a = policy_compare(sen, result, voting_dict)
for name in names[1:]:
t = policy_compare(sen, name, voting_dict)
if t < a:
a = t
result = name
return result

filename = 'voting_record_dump109.txt'

with open(filename) as f:
mylist = list(f)

if __name__ == '__main__':
print('2.12.2')
voting_dict = create_voting_dict(mylist)
names = list(voting_dict.keys())
for _ in range(10):
sen_a = random.choice(names)
sen_b = random.choice(names)
print('{0}, {1}: {2}'.format(sen_a, sen_b,
policy_compare(sen_a, sen_b, voting_dict)))
print('2.12.3')
sen = random.choice(names)
name = most_similar(sen, voting_dict)
for n in [sen, name]:
print('{0:10}: {1}'.format(n, voting_dict[n]))

print('2.12.4')
name = least_similar(sen, voting_dict)
for n in [sen, name]:
print('{0:10}: {1}'.format(n, voting_dict[n]))

print('2.12.5')
print(most_similar('Lincoln', voting_dict))
print(least_similar('Santorum', voting_dict))
```

```\$ ./sample12_2.py
2.12.2
Schumer, Stevens: 24
Chafee, Hutchison: 25
Baucus, Lincoln: 34
Obama, Specter: 29
Dodd, Lincoln: 33
Ensign, Salazar: 29
Pryor, Obama: 26
Jeffords, Dorgan: 25
Isakson, Kyl: 40
Thomas, Dodd: 17
2.12.3
Crapo     : [1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Burns     : [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
2.12.4
Crapo     : [1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Feingold  : [-1, -1, 1, -1, 1, -1, -1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, 1, -1]
2.12.5
Carper
Feingold
\$
```