Header Ads Widget

Ticker

6/recent/ticker-posts

Belajar Pewarnaan Wilayah dengan Python

Mari gunakan Constraint Satisfaction framework (kerangka Kepuasan Batasan) untuk menyelesaikan masalah pewarnaan wilayah.


1. Persiapkan dulu paket-paket yang dibutuhkan, yakni melakukan instalasi simpleai. Buka Terminal (Ctrl+Alt+T) lalu ketik;

pip3 -install simpleai

 2. Selanjutnya ketik kode berikut dalam text editor kamu. Klo saya pakai VSCode

from simpleai.search import CspProblem, backtrack

# Define the function that imposes the constraint
# that neighbors should be different
def constraint_func(names, values):
return values[0] != values[1]

if __name__=='__main__':
# Specify the variables
names = ('Mark', 'Julia', 'Steve', 'Amanda', 'Brian',
'Joanne', 'Derek', 'Allan', 'Michelle', 'Kelly')

# Define the possible colors
colors = dict((name, ['red', 'green', 'blue', 'gray']) for name in names)

# Define the constraints
constraints = [
(('Mark', 'Julia'), constraint_func),
(('Mark', 'Steve'), constraint_func),
(('Julia', 'Steve'), constraint_func),
(('Julia', 'Amanda'), constraint_func),
(('Julia', 'Derek'), constraint_func),
(('Julia', 'Brian'), constraint_func),
(('Steve', 'Amanda'), constraint_func),
(('Steve', 'Allan'), constraint_func),
(('Steve', 'Michelle'), constraint_func),
(('Amanda', 'Michelle'), constraint_func),
(('Amanda', 'Joanne'), constraint_func),
(('Amanda', 'Derek'), constraint_func),
(('Brian', 'Derek'), constraint_func),
(('Brian', 'Kelly'), constraint_func),
(('Joanne', 'Michelle'), constraint_func),
(('Joanne', 'Amanda'), constraint_func),
(('Joanne', 'Derek'), constraint_func),
(('Joanne', 'Kelly'), constraint_func),
(('Derek', 'Kelly'), constraint_func),
]

# Solve the problem
problem = CspProblem(names, colors, constraints)

# Print the solution
output = backtrack(problem)
print('\nColor mapping:\n')
for k, v in output.items():
print(k, '==>', v)

3. Hasil output akan nampak pada terminal;


Referensi:

  • Prateek Joshi. 2017. Artificial Intelligence with Python-Build real-world Artificial Intelligence applications with Python to intelligently interact with the world around you. Birmingham, Mumbai.

Posting Komentar

0 Komentar