Skip to content

Commit 556c42e

Browse files
committed
Added ex44
1 parent ff82fda commit 556c42e

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

exercises/ex43.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
words in them."""
77

88
from collections import defaultdict
9-
from exec_time import exec_time
109

1110
def anagram_finder(file_name):
1211

@@ -16,13 +15,13 @@ def anagram_finder(file_name):
1615
for line in f:
1716
words.append(line.rstrip())
1817

18+
# The point here is that every word that have the same letters and the
19+
# same length will be the same when they are sorted
1920
# For a good enough explanation of defaultdict, see this answer:
2021
# http://goo.gl/NbwXOv or in your Python interpreter, do:
2122
# >> help('collections.defaultdict')
2223
# If you know how defaultdict works, you should understand this
2324
# block of codes
24-
# The point here is that every word that have the same letters and the
25-
# same length will be the same when they are sorted
2625
anadict = defaultdict(list)
2726
for word in words:
2827
key = ''.join(sorted(word))

exercises/ex44.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""Your task in this exercise is as follows:
2+
3+
Generate a string with N opening brackets ("[") and N closing brackets ("]"),
4+
in some arbitrary order. Determine whether the generated string is balanced;
5+
that is, whether it consists entirely of pairs of opening/closing brackets
6+
(in that order), none of which mis-nest.
7+
Examples:
8+
9+
[] OK ][ NOT OK
10+
[][] OK ][][ NOT OK
11+
[[][]] OK []][[] NOT OK
12+
"""
13+
14+
from random import randrange
15+
import re
16+
17+
def brackets(n):
18+
i, result, brackets = 0, '', '[]'
19+
20+
# Add brackets in an arbitrary order
21+
while i < n*2:
22+
result += brackets[randrange(len(brackets))]
23+
i+=1
24+
25+
# Save our string of brackets
26+
bracket_string = result
27+
28+
# Remove all found pairs of brackets using regex
29+
while len(re.findall(r'\[\]', result)) > 0:
30+
result = re.sub(r'\[\]', '', result)
31+
32+
# If after removing all pairs of brackets the string is still not empty
33+
if len(result) > 0:
34+
print bracket_string, 'NOT OK'
35+
else:
36+
print bracket_string, 'OK'
37+
38+
#test
39+
brackets(3)

0 commit comments

Comments
 (0)