-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathapi.py
89 lines (76 loc) · 2.16 KB
/
api.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
import enchant
from itertools import permutations
from flask_cors import CORS
from flask import Flask,jsonify,request
app = Flask(__name__)
CORS(app)
language = enchant.Dict("en_US")
@app.errorhandler(Exception)
def handle_error(error):
message = [str(x) for x in error.args]
response = {
'error': {
'msg': message
}
}
return jsonify(response)
@app.route('/', methods=['GET', 'POST'])
def get_inputs():
if request.method == 'GET':
return "Hi! Thank you for hitting me. Please try hitting using POST method with args letters and size."
data = request.get_json()
letters = data.get("letters")
if not letters:
raise Exception("Letters not provided")
letters = letters.strip()
size = data.get("size")
if len(letters) > 20:
raise Exception("Too long letters. Pheww...")
if not size:
size = len(letters)
else:
size = int(size)
return get_permutation(letters, size)
def get_permutation(letter_list, length=None):
permutation = permutations(letter_list, length)
words = permutation_processor(permutation)
counter = 0
word_set = set()
for word in words:
if word:
counter += 1
word_set.add(word)
if counter != 0:
return jsonify({
"msg": "Here are the results. Bingo!",
"result": list(word_set)
})
else:
return jsonify({
"msg": "Oops! No words found. You just broke the English language 😟",
"result":[]
})
def permutation_processor(permutation):
for i in permutation:
joined_word = "".join(i)
word = check_words(joined_word)
yield word
def check_words(word):
if language.check(word):
return word
@app.route('/word-checker', methods=['POST'])
def word_receiver():
data = request.get_json()
word = data.get("word")
checked_word = check_words(word)
if checked_word is not None:
return jsonify({
"isValidWord": True
})
else:
return jsonify({
"isValidWord": False
})
# Uncomment if necessary
if __name__ == "__main__":
app.run()