Skip to content
This repository was archived by the owner on May 19, 2023. It is now read-only.

Commit 6e5e4db

Browse files
committed
Refactor modules
Some functions were moved to improve code readability and maintenance
1 parent ed8318e commit 6e5e4db

File tree

2 files changed

+37
-133
lines changed

2 files changed

+37
-133
lines changed

knapsack_problem/cli.py

Lines changed: 8 additions & 132 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,13 @@
33
"""
44

55
from typing import List
6-
from os import system
76
from sys import maxsize
8-
from threading import Thread
9-
from queue import Queue
107

118
# from PyInquirer import prompt
129
# symbols used by PyInquirer aren't showing in CMD
13-
from questionary import prompt, confirm, select, checkbox, Choice
10+
from questionary import select, checkbox, Choice
1411

1512
from validation import isPositiveNumber, isValidPercentage, delimitItems, messages
16-
from knapsack import Knapsack
17-
from file_handling import listFiles
18-
from heuristic import solveInstance
1913

2014
#! global variables
2115
# last given value in inputs
@@ -117,139 +111,21 @@ def heuristicsCheckbox():
117111
qmark='~'
118112
)
119113

120-
def validateChoices(checkbox, name) -> List[str]:
114+
def validateChoices(name, files = []) -> List[str]:
121115
'''
122116
Enters a loop until at least one element of the checkbox is chosen.
123117
124118
Returns a list of the chosen elements.
125119
'''
120+
if name == 'file':
121+
local_checkbox = filesCheckbox(files)
122+
elif name == 'heuristic':
123+
local_checkbox = heuristicsCheckbox()
124+
126125
while True:
127126
print()
128-
choices = checkbox.ask()
127+
choices = local_checkbox.ask()
129128
if len(choices) > 0:
130129
return choices
131130
else:
132131
print('Please select at least one %s.' % name)
133-
134-
def generateInstances():
135-
'''
136-
Generate instances from prompt.
137-
'''
138-
knapsacks = list()
139-
# list of threads for writing to files
140-
writing = list()
141-
142-
index = 1
143-
another = True
144-
while another:
145-
print('\n === {}° instance ==='.format(index))
146-
answers = prompt(createInstanceQuestions())
147-
148-
k = Knapsack.random(answers['n'], answers['min w'], answers['max w'], answers['min v'], answers['max v'], answers['p'])
149-
knapsacks.append(k)
150-
151-
# new thread's name
152-
name = 'w%d' % index
153-
# new thread to write last instance and start it
154-
write = Thread(target=knapsacks[-1].toFile, name=name)
155-
write.start()
156-
writing.append(write)
157-
158-
another = confirm('Do you want to add another instance?').ask()
159-
index += 1
160-
161-
heuristics = validateChoices(heuristicsCheckbox(), 'heuristic')
162-
163-
save_str = ' Saving instances to files...'
164-
size = len(writing)
165-
while size:
166-
# loop over threads list
167-
for write, k in zip(writing, knapsacks):
168-
index = int(write.name[-1])
169-
# if a thread is still running
170-
if write.is_alive():
171-
print('%s\r' % save_str , end='')
172-
continue
173-
else:
174-
# wait until the thread finishes
175-
write.join()
176-
print('%s\r' % (' ' * len(save_str)), end='')
177-
solveInstance(k, index, heuristics)
178-
size -= 1
179-
print('\n All instances have been saved to files.')
180-
181-
def loadInstances(files):
182-
'''
183-
Load instances from files.
184-
'''
185-
# if there are more than 1 available files
186-
if len(files) > 1:
187-
instances = validateChoices(filesCheckbox(files), 'file')
188-
# if there is only 1 available file
189-
else:
190-
instances = files
191-
192-
# queue for threads
193-
thread_queue = Queue(len(instances))
194-
# list of threads for reading files
195-
reading = list()
196-
for index, file_name in enumerate(instances):
197-
name = 'r%d' % index
198-
# new thread to read a file
199-
read = Thread(target=lambda q, arg: q.put(Knapsack.fromFile(arg)), args=(thread_queue, file_name), name=name, daemon=True)
200-
# start new thread and add it to list
201-
read.start()
202-
reading.append(read)
203-
204-
heuristics = validateChoices(heuristicsCheckbox(), 'heuristic')
205-
206-
# number of instances to solve
207-
size = len(instances)
208-
index = 1
209-
load_str = ' Loading instance...'
210-
# while there exist unsolved instances
211-
while size:
212-
# loop over list of threads
213-
for read in reading:
214-
# if thread is still running
215-
if read.is_alive():
216-
print('%s\r' % load_str, end='')
217-
# check next thread
218-
continue
219-
read.join()
220-
# get Knapsack object
221-
knapsack = thread_queue.get()
222-
if knapsack is not None:
223-
print('%s\r' % (' ' * len(load_str)), end='')
224-
solveInstance(knapsack, index, heuristics)
225-
size -= 1
226-
index += 1
227-
# if all instances have been solved
228-
if size <= 0:
229-
# break for
230-
break
231-
232-
def runCLI():
233-
'''
234-
Runs the options selector.
235-
'''
236-
print()
237-
238-
# list of files that contains instances, if any
239-
files = listFiles()
240-
241-
option = menu(files)
242-
# generate
243-
if option == 1:
244-
generateInstances()
245-
# load if available
246-
elif option == 2:
247-
loadInstances(files)
248-
# exit
249-
elif option == 0:
250-
return
251-
252-
print()
253-
system('pause')
254-
system('cls')
255-
return runCLI()

knapsack_problem/main.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,34 @@
11
from sys import exit
2+
from os import system
23

3-
from cli import runCLI
4+
from file_handling import listFiles
5+
from cli import menu
6+
from instance import generateInstances, loadInstances
7+
8+
def runCLI():
9+
'''
10+
Runs the options selector.
11+
'''
12+
print()
13+
14+
# list of files that contains instances, if any
15+
files = listFiles()
16+
17+
option = menu(files)
18+
# generate
19+
if option == 1:
20+
generateInstances()
21+
# load if available
22+
elif option == 2:
23+
loadInstances(files)
24+
# exit
25+
elif option == 0:
26+
return
27+
28+
print()
29+
system('pause')
30+
system('cls')
31+
return runCLI()
432

533
try:
634
runCLI()

0 commit comments

Comments
 (0)