Skip to content

Instantly share code, notes, and snippets.

@inesusvet
Last active November 26, 2017 18:49
Show Gist options
  • Save inesusvet/a5a5976d3cd7bafdb59b1445f2dbf7a8 to your computer and use it in GitHub Desktop.
Save inesusvet/a5a5976d3cd7bafdb59b1445f2dbf7a8 to your computer and use it in GitHub Desktop.
Проверить суммы положительных и отрицательных числе в двух столбцах во всех csv-файлах отчетов
#!/usr/bin/env python
from __future__ import print_function
import csv
import glob
import logging
import os
logging.basicConfig(
level=logging.WARNING,
format='%(levelname)s:%(message)s',
)
logger = logging.getLogger(__name__)
def find_reports(directory, mask='*.csv'):
for filename in glob.glob(mask):
yield filename
def extract(reader, columns):
"""Extract specified columns from a row"""
for row in reader:
if not row:
continue # Protection from empty lines
yield map(float, (row[index] for index in columns))
def get_sums(sequence):
"""Calculates two sums: of positive and negative numbers from sequence"""
positive, negative = (
(number for number in sequence if number >= 0),
(number for number in sequence if number < 0),
)
return sum(positive), sum(negative)
def match_sums(amounts, originals):
"""
Gets two sequenses of numbers.
Returns answer for a question:
Are sums of positive numbers in two sequences match AND
sums of negative numbers ni two sequences also match
>>> match_sums([1, 2, 3, -4, -5], [3, -5, -4, 1, 2])
True
>>> match_sums([1, 2, 3, -4], [1, 2, 3, 4])
False
"""
is_ok = True
positive, negative = get_sums(amounts)
positive_original, negative_original = get_sums(originals)
if positive != positive_original:
logger.info('Positive sums doesn\'t match for file %s', filename)
is_ok = False
if negative != negative_original:
logger.info('Negative sums doesn\'t match for file %s', filename)
is_ok = False
return is_ok, positive, negative
def main(filename):
"""Reads file and checks if sums of two columns match"""
with open(filename) as file_obj:
reader = csv.reader(file_obj, delimiter=';')
reader.next() # Skip header line
columns = (6, 11) # G & L columns
amounts, originals = zip(*extract(reader, columns=columns))
return match_sums(amounts, originals)
if __name__ == '__main__':
root = os.getcwd()
for filename in find_reports(root):
is_ok, positive, negative = main(filename)
print(filename, 'OK' if is_ok else 'Mismatch', positive, negative, sep='\t')
raw_input('Press <enter> to exit')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment