python - Need assistance on final bit of script if possible -
here prequisites script
"generate string n opening brackets ("[") , n closing brackets ("]"), in arbitrary order. need use random numbers. determine whether generated string balanced; is, whether consists entirely of pairs of opening/closing brackets (in order), none of mis-nest. examples: [] ok ][ not ok [][] ok ][][ not ok [[][]] ok []][[] not ok
"
i have come , thought done, reliased doesnt quite on line because positive result "[]]["
can me achieving part "pairs of opening/closing brackets (in order),"
#!/usr/bin/python import string import random def brackets(): count = 0 sample = [random.choice(['[', ']', '[]']) _ in range(random.randint(1, 10))] sample2 =''.join([random.choice(['[', ']', '[]']) _ in range(random.randint(1, 10))]) count1 = sample2.count('[') count2 = sample2.count(']') x in sample2: if x == "[": count +=1 if x == "]": count -=1 if count != 0 or count < 0 : print "the generated sample %s " % (sample2,) print "there %d [ in generated string" % (count1,) print "there %d ] in generated string" % (count2,) print "this string not ok" if count == 0 : print "the generated sample %s " % (sample2,) print "there %d [ in generated string" % (count1,) print "there %d ] in generated string" % (count2,) print "this string ok" print brackets()
here's funny little idea had. works seeing whether or not bracket pairs can turned individual lists:
from ast import literal_eval def valid(s): if any(c not in '[]' c in s): return false try: literal_eval(s.replace('[]', '[],')) return true except syntaxerror: return false
this (i believe) should work every time, including examples gave:
>>> valid('[]') true >>> valid('][') false >>> valid('[][]') true >>> valid('][][') false >>> valid('[[][]]') true >>> valid('[]][[]') false
Comments
Post a Comment