Skip to content

Commit

Permalink
Add dfa.py (keon#606)
Browse files Browse the repository at this point in the history
* fix the comment on line 33 (left->right)

* add DFA.py

* Update README.md

* Update merge_sort.py

* Create test_automata.py

* Update test_automata.py

* Update DFA.py

* Update test_automata.py

* Update test_automata.py

* Create __init__.py

* Update DFA.py

* Update test_automata.py

* Update test_automata.py

* Update test_automata.py
  • Loading branch information
ahnhyunjun417 authored and keon committed Dec 11, 2019
1 parent bbad761 commit cd4f9c7
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ If you want to uninstall algorithms, it is as simple as:
- [two_sum](algorithms/arrays/two_sum.py)
- [move_zeros](algorithms/arrays/move_zeros.py)
- [n_sum](algorithms/arrays/n_sum.py)
- [automata](algorithms/automata)
- [DFA](algorithms/automata/DFA.py)
- [backtrack](algorithms/backtrack)
- [general_solution.md](algorithms/backtrack/)
- [add_operators](algorithms/backtrack/add_operators.py)
Expand Down
18 changes: 18 additions & 0 deletions algorithms/automata/DFA.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
def DFA(transitions, start, final, string):

num = len(string)
num_final = len(final)
cur = start

for i in range (num):

if transitions[cur][string[i]] == None:
return False
else:
cur = transitions[cur][string[i]]

for i in range (num_final):
if cur == final[i]:
return True
return False

1 change: 1 addition & 0 deletions algorithms/automata/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .DFA import *
48 changes: 48 additions & 0 deletions tests/test_automata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from algorithms.automata import DFA


import unittest


class TestDFA(unittest.TestCase):
def test_DFA(self):

transitions = {
'a': {'1': 'a', '0': 'b'},
'b': {'1': 'b', '0': 'a'}
}

final=['a']
start = 'a'

self.assertEqual(False, DFA(transitions, start, final, "000111100"))
self.assertEqual(True, DFA(transitions, start, final, "111000011"))

transitions1 = {
'0': {'0': '1', '1': '0'},
'1': {'0': '2', '1': '0'},
'2': {'0': '2', '1': '3'},
'3': {'0': '3', '1': '3'}
}

final1 = ['0', '1', '2']
start1 = '0'

self.assertEqual(False, DFA(transitions1, start1, final1, "0001111"))
self.assertEqual(True, DFA(transitions1, start1, final1, "01010101"))

transitions2 = {
'0': {'a': '0', 'b': '1'},
'1': {'a': '0', 'b': '2'},
'2': {'a': '3', 'b': '2'},
'3': {'a': '3', 'b': '3'}
}

final2=['3']
start2 = '0'

self.assertEqual(False, DFA(transitions2, start2, final2, "aaabbb"))
self.assertEqual(True, DFA(transitions2, start2, final2, "baabba"))

if __name__ == '__main__':
unittest.main()

0 comments on commit cd4f9c7

Please sign in to comment.