-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCounter.php
324 lines (232 loc) · 7.84 KB
/
Counter.php
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
<?php
//ini_set('display_startup_errors', 1);
//ini_set('display_errors', 1);
//error_reporting(-1);
trait Utils
{
public static function isAssociativeArray($a)
{
return is_array($a) && array_diff_key($a, array_keys(array_keys($a)));
}
}
/**
* Counter class is an informal porting of the Python collections.Counter class
* https://docs.python.org/3/library/collections.html#collections.Counter
*
* Example usages below, not much tested, use with care
* In some cases behavior or API slightly differ from the original
*
* Useful as a starting point for bag-of-words, TF-IDF, etc.
*
* @author https://github.com/n-gram-hub
* @version $Revision: 0.1.0 $
*
*
*/
class Counter implements ArrayAccess
{
use Utils;
private $counter = [];
/*
*
* @param string, array $mixed
*
* @throws TypeError if $mixed is not string or array. Please, God of PHP, invent constructor overloading
* @throws UnexpectedValueException if array doesn't contain valid elements
*
*/
public function __construct($mixed = [])
{
$args = func_get_args();
$argsLength = count($args);
// no argument provided, return empty counter
if ($argsLength == 0) {
return $this->counter;
}
if ($argsLength > 0) {
// if user passed associative array
if (Utils::isAssociativeArray($mixed)) {
// if keys are strings or ints && values are ints
if ($this->keysAreValid(array_keys($mixed)) && $this->valuesAreValid(array_values($mixed))) {
$a = [];
$negativeCounts = [];
foreach ($mixed as $k => $value) {
if($value>0){
for ($i = 0; $i < $value; $i++) {
$a[] = $k;
}
}else{
$negativeCounts[$k]=$value;
}
}
// for some reason Python's Counter lets you add negative counts
// since array_count_values can't do it, we need to merge them
$this->counter = array_merge(array_count_values($a),$negativeCounts);
} else {
throw new UnexpectedValueException("Each key must be string or integer, each value must be integer");
}
// if $mixed is plain array
} elseif (is_array($mixed)) {
// if elements are valid
if ($this->arrayIsValid($mixed)) {
$this->counter = array_count_values($mixed);
} else {
throw new UnexpectedValueException("Each element must be string or integer");
}
// if $mixed is string
} elseif (is_string($mixed)) {
// split
$this->counter = array_count_values(str_split($mixed));
}
// if $mixed is completely another type
else {
throw new TypeError("You can pass strings, arrays and associative arrays");
}
}
}
// return counter
public function getCounter(){
return $this->counter;
}
// ArrayAccess stuff
public function offsetSet($offset, $value)
{
if ((is_string($offset)||is_numeric($offset)) && is_int($value)) {
$this->counter[$offset] = $value;
}
}
public function offsetExists($offset)
{
return isset($this->counter[$offset]);
}
public function offsetUnset($offset)
{
unset($this->counter[$offset]);
}
public function offsetGet($offset)
{
return isset($this->counter[$offset]) ? $this->counter[$offset] : 0;
}
public function printCounter()
{
print_r($this->counter);
}
// callbacks
private function validElement_callback($n)
{
return is_int($n) || is_string($n);
}
private function validValue_callback($n)
{
return is_int($n);
}
private function elementToKeyValue_callback($n)
{
return $n = 1;
}
private function keysAreValid($array)
{
return array_product(array_map(array($this, 'validElement_callback'), $array)) == 1;
}
private function valuesAreValid($array)
{
return array_product(array_map(array($this, 'validValue_callback'), $array)) == 1;
}
private function arrayIsValid($array)
{
return $this->keysAreValid($array);
}
// Python's Counter most_common
public function mostCommon(int $n = 1)
{
$counterLength = count($this->counter);
if ($counterLength > 0) {
if ($n < 1 || $n > $counterLength) {
$n = $counterLength;
}
arsort($this->counter);
return array_slice($this->counter, 0, $n);
}
return $this->counter;
}
// validation of mixed type for subtract and update methods
// $m can be string, array of strings/ints, associative arrays of counts and Counters
private function validateMixedType($m){
if (is_string($m) || (is_array($m) && !Utils::isAssociativeArray($m))) {
$m = array_count_values(is_string($m) ? str_split($m) : $m);
} elseif (Utils::isAssociativeArray($m) || $m instanceof Counter) {
$m = $m instanceof Counter ? $m->getCounter() : $m;
if (!$this->valuesAreValid(array_values($m))) {
throw new UnexpectedValueException("Each value must be integer");
}
} else {
throw new TypeError("You can pass strings, arrays and associative arrays");
}
if (!$this->keysAreValid(array_keys($m))) {
throw new UnexpectedValueException("Each key must be string or integer");
}
return $m;
}
// Python's Counter subtract
public function subtract($mixedType)
{
try{
$assoc = $this->validateMixedType($mixedType);
}
catch (TypeError $e) {
echo "TypeError: " . $e->getMessage();
}
catch (UnexpectedValueException $e) {
echo "UnexpectedValueException: " . $e->getMessage();
}
foreach ($assoc as $k => $v) {
if (isset($this->counter[$k])) {
$this->counter[$k] -= $v;
}else{
$this->counter[$k] = 0-$v;
}
}
return $this->counter;
}
// Python's counter update
public function update($mixedType)
{
try{
$assoc = $this->validateMixedType($mixedType);
}
catch (TypeError $e) {
echo "TypeError: " . $e->getMessage();
}
catch (UnexpectedValueException $e) {
echo "UnexpectedValueException: " . $e->getMessage();
}
foreach ($assoc as $k => $v) {
if (isset($this->counter[$k])) {
$this->counter[$k] += $v;
} else {
$this->counter[$k] = $v;
}
}
return $this->counter;
}
// same as Python Counter list(elements())
public function listElements()
{
$elements = [];
foreach ($this->counter as $k => $v) {
if ($v > 0) {
for ($i = 0; $i < $v; $i++) {
$elements[] = $k;
}
}
}
return $elements;
}
// not in the original Counter API, maybe useful
public function clear(){
$this->counter = [];
}
public function sum(){
return array_sum($this->counter);
}
}