回答編集履歴

1

追記を受けて

2018/06/28 07:25

投稿

LouiS0616
LouiS0616

スコア35660

test CHANGED
@@ -45,3 +45,125 @@
45
45
 
46
46
 
47
47
  まずこれが出来ないと、アルファベットなんてとても太刀打ちできないでしょう。
48
+
49
+
50
+
51
+ 追記を受けて
52
+
53
+ ---
54
+
55
+ 例えばこんなクラスを組むと、『加算』をカスタムできます。
56
+
57
+ ```Python
58
+
59
+ class Elem:
60
+
61
+ def __init__(self, chr, num=None):
62
+
63
+ if num is not None:
64
+
65
+ self._chr = chr
66
+
67
+ self._num = num
68
+
69
+ return
70
+
71
+
72
+
73
+ if chr in [0, '0']:
74
+
75
+ self._chr = None
76
+
77
+ self._num = 0
78
+
79
+ return
80
+
81
+
82
+
83
+ if isinstance(chr, str):
84
+
85
+ self._chr = chr[0]
86
+
87
+ self._num = int(chr[1:])
88
+
89
+ return
90
+
91
+
92
+
93
+ raise ValueError
94
+
95
+
96
+
97
+ def is_zero(self):
98
+
99
+ return self._chr is None
100
+
101
+
102
+
103
+ def __add__(self, other):
104
+
105
+ if self.is_zero():
106
+
107
+ return other
108
+
109
+
110
+
111
+ if other.is_zero():
112
+
113
+ return self
114
+
115
+
116
+
117
+ if self._chr == other._chr:
118
+
119
+ return Elem(
120
+
121
+ self._chr,
122
+
123
+ self._num + other._num
124
+
125
+ )
126
+
127
+
128
+
129
+ return Elem(
130
+
131
+ self._chr if self._num > other._num else other._chr,
132
+
133
+ abs(self._num - other._num)
134
+
135
+ )
136
+
137
+
138
+
139
+ def __repr__(self):
140
+
141
+ if self._chr is None:
142
+
143
+ return '0'
144
+
145
+
146
+
147
+ return f'{self._chr}{self._num}'
148
+
149
+
150
+
151
+
152
+
153
+ print(
154
+
155
+ Elem('A3') + Elem('B2')
156
+
157
+ )
158
+
159
+ ```
160
+
161
+
162
+
163
+ **実行結果** [Wandbox](https://wandbox.org/permlink/YZbfo8mODZtiJTLX)
164
+
165
+ ```plain
166
+
167
+ A1
168
+
169
+ ```