Files
  • main.py
main.py
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
# http://www.blopig.com/blog/2016/08/processing-large-files-using-python/

dat1 ='allotment', 'amortization', 'ampules', 'antitheses', 'aquiline', 'barnacle', 'barraged', 'bayonet', 'beechnut', 'bereavements', 'billow', 'boardinghouses', 'broadcasted', 'cheeseburgers', 'civil', 'concourse', 'coy', 'cranach', 'cratered', 'creameries', 'cubbyholes', 'cues', 'dawdle', 'director', 'disallowed', 'disgorged', 'disguise', 'dowries', 'emissions', 'epilogs', 'evict', 'expands', 'extortion', 'festoons', 'flexible', 'flukey', 'flynn',
'folksier', 'gave', 'geological', 'gigglier', 'glowered', 'grievous', 'grimm', 'hazards', 'heliotropes', 'holds', 'infliction', 'ingres', 'innocently', 'inquiries', 'intensification', 'jewelries', 'juicier', 'kathiawar', 'kicker', 'kiel', 'kinswomen', 'kit', 'kneecaps', 'kristie', 'laggards', 'libel', 'loggerhead', 'mailman', 'materials', 'menorahs', 'meringues', 'milquetoasts', 'mishap', 'mitered', 'mope', 'mortgagers', 'mumps', 'newscasters', 'niggling', 'nowhere', 'obtainable', 'organization', 'outlet', 'owes', 'paunches', 'peanuts', 'pie', 'plea', 'plug', 'predators', 'priestly', 'publish', 'quested', 'rallied', 'recumbent', 'reminiscence', 'reveal', 'reversals', 'ripples', 'sacked', 'safest', 'samoset', 'satisfy', 'saucing', 'scare', 'schoolmasters', 'scoundrels', 'scuzziest', 'shoeshine', 'shopping', 'sideboards', 'slate', 'sleeps', 'soaping', 'southwesters', 'stubbly', 'subscribers', 'sulfides', 'taxies', 'tillable', 'toastiest', 'tombstone', 'train', 'truculent', 'underlie', 'unsatisfying', 'uptight', 'wannabe', 'waugh', 'workbooks',
'allotment', 'amortization', 'ampules', 'antitheses', 'aquiline', 'barnacle', 'barraged', 'bayonet', 'beechnut', 'bereavements', 'billow', 'boardinghouses', 'broadcasted', 'cheeseburgers', 'civil', 'concourse', 'coy', 'cranach', 'cratered', 'creameries', 'cubbyholes', 'cues', 'dawdle', 'director', 'disallowed', 'disgorged', 'disguise', 'dowries', 'emissions', 'epilogs', 'evict', 'expands', 'extortion', 'festoons', 'flexible', 'flukey', 'flynn',
'folksier', 'gave', 'geological', 'gigglier', 'glowered', 'grievous', 'grimm', 'hazards', 'heliotropes', 'holds', 'infliction', 'ingres', 'innocently', 'inquiries', 'intensification', 'jewelries', 'juicier', 'kathiawar', 'kicker', 'kiel', 'kinswomen', 'kit', 'kneecaps', 'kristie', 'laggards', 'libel', 'loggerhead', 'mailman', 'materials', 'menorahs', 'meringues', 'milquetoasts', 'mishap', 'mitered', 'mope', 'mortgagers', 'mumps', 'newscasters', 'niggling', 'nowhere', 'obtainable', 'organization', 'outlet', 'owes', 'paunches', 'peanuts', 'pie', 'plea', 'plug', 'predators', 'priestly', 'publish', 'quested', 'rallied', 'recumbent', 'reminiscence', 'reveal', 'reversals', 'ripples', 'sacked', 'safest', 'samoset', 'satisfy', 'saucing', 'scare', 'schoolmasters', 'scoundrels', 'scuzziest', 'shoeshine', 'shopping', 'sideboards', 'slate', 'sleeps', 'soaping', 'southwesters', 'stubbly', 'subscribers', 'sulfides', 'taxies', 'tillable', 'toastiest', 'tombstone', 'train', 'truculent', 'underlie', 'unsatisfying', 'uptight', 'wannabe', 'waugh', 'workbooks'

dat2 = 'abut', 'actuators', 'advert', 'altitude', 'animals', 'aquaplaned', 'battlement', 'bedside', 'bludgeoning', 'boeing', 'bubblier', 'calendaring', 'callie', 'cardiology', 'caryatides', 'chechnya', 'coffey', 'collage', 'commandos', 'defensive', 'diagnosed', 'doctor', 'elaborate', 'elbow', 'enlarged', 'evening', 'flawed', 'glowers', 'guested', 'handel', 'homogenized', 'husbands', 'hypermarket', 'inge', 'inhibits', 'interloper', 'iowan', 'junco', 'junipers', 'keen', 'logjam', 'lonnie', 'louver', 'low', 'marcelo', 'marginalia', 'matchmaker', 'mold', 'monmouth', 'nautilus', 'noblest', 'north', 'novelist', 'oblations', 'official', 'omnipresent', 'orators', 'overproduce', 'passbooks', 'penalizes', 'pisses', 'precipitating', 'primness', 'quantity', 'quechua', 'rama', 'recruiters', 'recurrent', 'remembrance', 'rumple', 'saguaro', 'sailboard', 'salty', 'scherzo', 'seafarer', 'settles', 'sheryl', 'shoplifter', 'slavs', 'snoring', 'southern', 'spottiest', 'squawk', 'squawks', 'thievish', 'tightest', 'tires', 'tobacconist', 'tripling', 'trouper', 'tyros', 'unmistakably', 'unrepresentative', 'waviest'

dat3 = 'administrated', 'aggressively', 'albee', 'amble', 'announcers', 'answers', 'arequipa', 'artichoke', 'awed', 'bacillus', 'backslider', 'bandier', 'bellow', 'beset', 'billfolds', 'boneless', 'braziers', 'brick', 'budge', 'cadiz', 'calligrapher', 'clip', 'confining', 'coronets', 'crispier', 'dardanelles', 'daubed', 'deadline', 'declassifying', 'delegating', 'despairs', 'disembodying', 'dumbly', 'dynamically', 'eisenhower', 'encryption', 'estes', 'etiologies', 'evenness', 'evillest', 'expansions', 'fireproofed', 'florence', 'forcing', 'ghostwritten', 'hakluyt', 'headboards', 'hegel', 'hibernate', 'honeyed', 'hope', 'horus', 'inedible', 'inflammation', 'insincerity', 'intuitions', 'ironclads', 'jeffrey', 'knobby', 'lassoing', 'loewi', 'madwoman', 'maurois', 'mechanistic', 'metropolises', 'modified', 'modishly', 'mongols', 'motivation', 'mudslides', 'negev', 'northward', 'outperforms', 'overseer', 'passport', 'pathway', 'physiognomy', 'pi', 'platforming', 'plodder', 'pools', 'poussin', 'pragmatically', 'premeditation', 'punchier', 'puncture', 'raul', 'readjusted', 'reflectors', 'reformat', 'rein', 'relives', 'reproduces', 'restraining', 'resurrection', 'revving', 'rosily', 'sadr', 'scolloped', 'shrubbery', 'side', 'simulations', 'slashing', 'speculating', 'subsidization', 'teaser', 'tourism', 'transfers', 'transnationals', 'triple', 'undermining', 'upheavals', 'vagina', 'victims', 'weird', 'whereabouts', 'wordiness'

import datetime
from functools import wraps
from time import time

datetme = datetime.datetime.now()
date = datetme.strftime('%d %b %Y %H:%M:%S ').upper()

results = []

log = () #TUPLE

combined_file_name = 'combinedfile'

file_type = '.dat'

# tuples are used to read in the data to save cost of memory usage
combined_dat = dat1, dat2, dat3 #* 100000

# reading the data in line by line, so that only a single line is stored in the RAM at any given time.

# with open(combined_file_name + file_type, 'r') as f:
#     for line in f:
#         process(line)


# decorator for speed test.
def speed_test(f):
    @wraps(f)
    def wrapper(*a, **kw):
        start = time()
        result = f(*a, **kw)
        end = time()
        print('Elapsed time: {} s'.format(round(end - start, 8)))
        return result
    return wrapper
    
@speed_test
def merge_sort_lists(list_of_lists, *a, **kw):
    """takes in a list of lists/tuples and returns a sorted list"""
    try:
        for f in list_of_lists:
            try:
                for c in f:
                    # recursion for lists in the list of lists... 
                    if isinstance(c, tuple):
                        merge_sort_lists([c])
                    else:
                        results.append(c)
            except:
                datetme, ":: Item: {} not added".format(c)
                # Logging
                    # log.append("file {} not found".format(f))
    except:
        datetme, "file {} not found".format(f)
        # Logging
        # log.append("file {} not found".format(f))

    # [Timsort] (Used in python sort() ) Has good aspects: It's stable (items that compare equal retain their relative order, so, e.g., if you sort first on postal code, and a second time on  name, people with the same name still appear in order of increasing postal code; this is important in apps that, e.g., refine the results of queries based on user input)
    
    # It has no bad cases (O(N log N) is worst case; N−1 compares is best).
    
    # https://en.wikipedia.org/wiki/Timsort
    
    results.sort()
    
    # with open('log.txt', 'a') as f:
    #     for line in log:
    #         f.write(line)

merge_sort_lists(combined_dat)

for i in results:
    print(i)

# Tests

def combined_length(combined):
    """calculates the length of a list of lists"""
    com_len = 0
    
    for i in combined:
        # if isinstance(i, tuple):
        #     combined_length(((i)))
        # else:
            com_len += int(len(i))
    return com_len

com_length = (combined_length(combined_dat))

res_len = len(results)
print('\nResult Length: ', res_len, '\nCombined Lists: ', com_length)
assert(res_len == com_length)


# import glob
# import os
# import datetime
# from functools import wraps
# from time import time

# # first define the  directory and file type. Keeping the at the top and also as their own variables enables the code to be reused easily with differrent names and filetypes..
# os.chdir("./20k/")

# # init datetime stamps for logging
# datetme = datetime.datetime.now()
# date = datetme.strftime('%d %b %Y %H:%M:%S ').upper()

# log = []

# combined_file_name = 'combinedfile'
# file_type = '.dat'

# # init the combined list of lists of file data
# files_in_dir = []

# # create a list of files in the directory
# for f in glob.glob('*' + file_type):
#     files_in_dir.append(f)


# # decorator for speed test.  rounded to 8 decimal places to catch the quickest calculations
# def speed_test(f):
#     @wraps(f)
#     def wrapper(*a, **kw):
#         start = time()
#         result = f(*a, **kw)
#         end = time()
#         print('Elapsed time: {} s'.format(round(end - start, 8)))
#         return result
#     return wrapper

# # init the results of the sorted data, Keep the results outside of the function in order to run assertion tests later..
# #  Also this will stop the tests from writing the files again
# results = []
# # file_count = 0

# @speed_test
# def merge_sort_lists(files_to_process, *a, **kw):
#     """takes in a list of lists/tuples and returns a sorted list"""
#     # break if the lenght of the list is 1and return the first item
#     if len(files_to_process) == 1:
#         results.append(files_to_process[0])        

#     for f in files_to_process:
#         try:
#             f1 = open(f).read().splitlines()
           
#             for c in f1:
#                 try:
#                     # file_count += 1  # uncomment this to cause errors and write to log.txt
#                     # recursion in case of lists/tuples in the list of lists..I camer across this when reading from lists instead of files so thought i owuld keep it here..
#                     if isinstance(c, list):
#                         merge_sort_lists([c])
#                     else:                        
#                         results.append(c)                                                
#                 except:
#                     bad_add = datetme, ":: Item: {} was not added".format(c)
#                     # Logging
#                     log.append(bad_add)
#         except:
#             bad_file = datetme, "file {} had a problem!".format(f)
#             # Logging
#             log.append(bad_file)

#     # [Timsort] (Used in python sort() ) Has good aspects: It's stable (items that compare equal retain their relative order, so, e.g., if you sort first on postal code, and a second time on  name, people with the same name still appear in order of increasing postal code; this is important in apps that, e.g., refine the results of queries based on user input)
#     # It has no bad cases (O(N log N) is worst case; N−1 compares is best).
#     # https://en.wikipedia.org/wiki/Timsort
#     results.sort()

#     # Save the logs
#     with open('log.txt', 'a') as l:
#         for line in log:
#             l.write(str(line))

#     # Save the sorted data
#     with open('combined.dat', 'a') as l:
#         for line in results:
#             l.write(line + '\n')

# merge_sort_lists(files_in_dir)

# # Tests
# def testing(test_list, test_file_name):
#     """ Takes in a test_list and output file name.
#         Runs tests and asserts length.
#         saves an output txt file
#     """
#     com_length = len(files_in_dir)
#     res_len = len(results)
#     avg_words_in_file = res_len // com_length

#     res = str(datetme)[:19] + '\n\tResult Length: {} \n\tNumber of files: {}\n\tAvg no. words per file: {}\n'.format(res_len, com_length, avg_words_in_file)

#     test_list.append(res)

#     with open(test_file_name, 'a') as l:
#         for line in test_list:
#             l.write(line)
    
#     print('\n', res)
#     # assert(res_len == com_length)
    

# log_st = []    
# testing(log_st, 'speed_test_log.txt')

# # # Stress Testing
# # results = []
# # stress_test = []

# # for i in range(5):
# #     files_in_dir = []

# #     for f in glob.glob('*' + file_type):
# #         dat_content = open(f).read().splitlines()
# #         files_in_dir.append(dat_content)
# #     merge_sort_lists(files_in_dir)
# #     testing(stress_test, 'stress_test_log.txt')