2 ms·
The Python and Tcl programs don't do the same thing. The Python output is in most-common order, which requires a sort. The Tcl one is in arbitrary order. The i
by eesmith 3y ago
The Python and Tcl programs don't do the same thing. The Python output is in most-common order, which requires a sort. The Tcl one is in arbitrary order.
The idiomatic Python matching what the Tcl code does is:
#!/usr/bin/env python
import collections
import sys
for p in sys.argv[1:]:
try:
with open(p) as f:
c = collections.Counter(f)
for k, v in c.items():
if v > 1:
k = k.rstrip("\n")
print(f"{v}\t{k}")
except Exception as e:
print(f"dup: {e}")
continue
Except, even then there are three differences:
1) the Tcl code accumulates the counts across all the files, the Python code resets each time. Though the Tcl code reports the counts after each file???
2) the Tcl code has a file descriptor leak (one of the big issues I have with Tcl is in dealing with resource management. I've used an upvar with a delete trace to emulate local scope, but that makes passing the result upstream tricky).
3) the Tcl code includes the empty string "" after the final newline in the count, which doesn't make sense.
To show the issue, I've replace the Tcl code so it outputs quotes around the line:
puts "$n\t'$line'"
and set the file descriptor limit to 10 before having it read a file containing only two lines, each containing "A":
% printf "A\nA\n" > x
% limit descriptors 10
% tclsh dup.tclsh x x x x x x x x x x x
2 'A'
2 ''
4 'A'
3 ''
6 'A'
4 ''
8 'A'
5 ''
10 'A'
dup: couldn't open "x": too many open files
dup: couldn't open "x": too many open files
dup: couldn't open "x": too many open files
dup: couldn't open "x": too many open files
dup: couldn't open "x": too many open files
dup: couldn't open "x": too many open files
% python dup.py x x x x x x x x x x x
2 A
2 A
2 A
2 A
2 A
2 A
2 A
2 A
2 A
2 A
2 A