File: split-numbers

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (45 lines) | stat: -rwxr-xr-x 1,249 bytes parent folder | download
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
#!/usr/bin/env python3


import errno
import sys

def write_data_to_path_if_changed(data, path):
    # See if the file contents are identical.
    try:
        with open(path) as f:
            if f.read() == data:
                print("note: %s: file contents unchanged" % (
                    path,), file=sys.stderr)
                return
    except IOError as e:
        if e.errno != errno.ENOENT:
            raise

    # Otherwise, write the data.
    with open(path, 'wb') as f:
        f.write(data)
    print("note: %s: updated file" % (path,), file=sys.stderr)

# Split the input into even and odd numbers.
even = []
odd = []
for line in sys.stdin:
    for number in line.split():
        if number.isdigit():
            value = int(number)
            if value % 2:
                odd.append(value)
            else:
                even.append(value)

if len(sys.argv) != 3:
    raise SystemExit("error: invalid number of arguments")

odd_data = '\n'.join(map(str, sorted(odd))) + '\n'
even_data = '\n'.join(map(str, sorted(even))) + '\n'
_, odd_out_path, even_out_path = sys.argv
        
# Write the files, if changed.
write_data_to_path_if_changed(odd_data, odd_out_path)
write_data_to_path_if_changed(even_data, even_out_path)