teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

追記を受けて

2018/06/28 07:25

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -21,4 +21,65 @@
21
21
  """
22
22
  ```
23
23
 
24
- まずこれが出来ないと、アルファベットなんてとても太刀打ちできないでしょう。
24
+ まずこれが出来ないと、アルファベットなんてとても太刀打ちできないでしょう。
25
+
26
+ 追記を受けて
27
+ ---
28
+ 例えばこんなクラスを組むと、『加算』をカスタムできます。
29
+ ```Python
30
+ class Elem:
31
+ def __init__(self, chr, num=None):
32
+ if num is not None:
33
+ self._chr = chr
34
+ self._num = num
35
+ return
36
+
37
+ if chr in [0, '0']:
38
+ self._chr = None
39
+ self._num = 0
40
+ return
41
+
42
+ if isinstance(chr, str):
43
+ self._chr = chr[0]
44
+ self._num = int(chr[1:])
45
+ return
46
+
47
+ raise ValueError
48
+
49
+ def is_zero(self):
50
+ return self._chr is None
51
+
52
+ def __add__(self, other):
53
+ if self.is_zero():
54
+ return other
55
+
56
+ if other.is_zero():
57
+ return self
58
+
59
+ if self._chr == other._chr:
60
+ return Elem(
61
+ self._chr,
62
+ self._num + other._num
63
+ )
64
+
65
+ return Elem(
66
+ self._chr if self._num > other._num else other._chr,
67
+ abs(self._num - other._num)
68
+ )
69
+
70
+ def __repr__(self):
71
+ if self._chr is None:
72
+ return '0'
73
+
74
+ return f'{self._chr}{self._num}'
75
+
76
+
77
+ print(
78
+ Elem('A3') + Elem('B2')
79
+ )
80
+ ```
81
+
82
+ **実行結果** [Wandbox](https://wandbox.org/permlink/YZbfo8mODZtiJTLX)
83
+ ```plain
84
+ A1
85
+ ```