Skip to content
Permalink
Fetching contributors…
Cannot retrieve contributors at this time
executable file 317 lines (252 sloc) 17.9 KB

Perl Weekly Challenge #42 Task #2: Balanced Brackets

This Task "Balanced Brackets" I solved in 3 languages: Perl5, Perl6 and Python. My personal aim here is also to learn Perl6 and Python beside the eager in solving the Tasks in Perl5.

Some highlights:

  • Perl5, Perl6 and Python solution.

  • Recursive function call.

  • do-while, do-repeat or while-if-break as DO-WHILE loop.

  • random integer number generation.

Download and References

Download File: Perl5 Solution PWC #42 Task #2 ch-2.pl
Download File: Perl6 Solution PWC #42 Task #2 ch-2.p6
Download File: Python Solution PWC #42 Task #2 ch-2.py

SYNOPSIS

# ./ch-2.pl            - Execution of program
# ./ch-2.p6            - Execution of program
# ./ch-2.py            - Execution of program
# perldoc ch-2.pod              - POD

Definition Task #2: Balanced Brackets

Write a script to generate a string with random number of ( and ) brackets. Then make the script validate the string if it has balanced brackets.

For example:
() - OK
(()) - OK
)( - NOT OK
())() - NOT OK

Perl5 and Perl6

How does the program work? Within a loop, that is left when some Balanced Brackets are found, a random number of brackets is created with the function create_brackets(). Than the bracket string is verified if it is Balanced Brackets in the function balanced_brackets(). The function balanced_brackets() is called recursively as long as a pair of brackets can be found with search/replace.

Perl Example Execution

# ./ch-2.pl
ch-2.pl (Version 1.0) PWC #42 Task #2: Balanced Brackets
(()))()))) - NOT OK
() - OK

Source Code

The code for Perl5 and Perl6 are similar, only the differences in the language. Let me mention some of the differences between Perl5 / Perl6:

  • for() / loop (), Remember the blank in Perl6.

  • .= / ~=, Assignment of a String.

  • int(rand(2)) / Int(2.rand), Create a random integer.

  • if() / if (), Again the blank after the statement, in Perl6 brackets directly after the keyword means to call a function.

  • sub balanced_brackets { my $str = shift; ... } sub balanced_brackets ($arg) { ... } Different function call syntax.

  • =~ / ~~, for applying the search/replace on a scalar.

  • do {} while() / repeat {} while (), A do-while loop becomes repeat-while.

Perl5
1 #!/usr/bin/perl 2 3 use strict; 4 use warnings; 5 6 print "ch-2.pl (Version 1.0) PWC #42 Task #2: Balanced Brackets\n"; 7 8 sub create_brackets { 9 my ($nr) = @_; 10 my $s; 11 for( my $i=0; $i<=$nr; $i++ ) { 12 my $br = int(rand(2)); 13 if($br) { $s .= ")"; } else { $s .= "("; } 14 } 15 return $s; 16 } 17 18 my $ok; 19 do { 20 my $nr = int(rand(10)); 21 my $str = create_brackets($nr); 22 $ok = balanced_brackets($str); 23 my $rs = "NOT OK"; 24 $rs = "OK" if $ok; 25 print $str, " - ", $rs, "\n"; 26 } while( ! $ok ); 27 28 sub balanced_brackets { 29 my $str = shift; 30 my $found = $str =~ s/\(\)//; 31 my $ok; 32 if($found) { 33 $ok = balanced_brackets($str); 34 return $ok; 35 } 36 else { 37 if( $str=~/\(|\)/ ) { return 0; } 38 else { return 1; } 39 } 40 }
Perl6
1 #!/home/chuck/rakudo/bin/perl6 2 3 use strict; 4 5 print "ch-2.p6 (Version 1.0) PWC #42 Task #2: Balanced Brackets\n"; 6 7 sub create_brackets { 8 my ($nr) = @_; 9 my $s; 10 loop ( my $i=0; $i <= $nr; $i++ ) { 11 my $br = Int(2.rand); 12 if ($br) { $s ~= ")"; } else { $s ~= "("; } 13 } 14 return $s; 15 } 16 17 my $ok; 18 repeat { 19 my $nr = Int(10.rand); 20 my $str = create_brackets($nr); 21 $ok = balanced_brackets($str); 22 my $rs = "NOT OK"; 23 $rs = "OK" if $ok; 24 print $str, " - ", $rs, "\n"; 25 } while ( ! $ok ); 26 27 sub balanced_brackets ($arg) { 28 my $str = $arg; # Cannot assign to a read-only. 29 my $found = ($str ~~ s/\(\)//); 30 my $ok; 31 if ($found) { 32 $ok = balanced_brackets($str); 33 return $ok; 34 } 35 else { 36 if ( $str ~~ /\(|\)/ ) { return 0; } 37 else { return 1; } 38 } 39 } 40

Python

Because the syntax is rather different, it takes some more time to convert the code to Python. But I succeeded and can publish also a Python code for this PWC Task.

Python Example Execution

# ./ch-2.py
ch-2.pl (Version 1.0) PWC #42 Task #2: Balanced Brackets

( 1)          ( = NOT OK
( 2)     (((()( = NOT OK
( 3)          ) = NOT OK
( 4)     (()))( = NOT OK
( 5)         (( = NOT OK
( 6)   ))))(()) = NOT OK
( 7)       (()( = NOT OK
( 8)        )(( = NOT OK
( 9)    ()((((( = NOT OK
(10)     )())() = NOT OK
(11)   (()())() = OK

Source Code Python

The Python source code is similar to the two Perl examples. The defined functions are the same. Because the syntax is very different to the two Perl examples, it is up to you to investigate in its details.

Beside all the other differences I want to mention the loop while True: ... if condition: break instead of the do-while or repeat-while in Perl5 or Perl6.

Python
1 #!/usr/bin/python 2 3 import array as arr 4 import re 5 import random 6 7 print "ch-2.pl (Version 1.0) PWC #42 Task #2: Balanced Brackets\n"; 8 9 def create_brackets(nr): 10 s = "" 11 for i in range(1,nr): 12 br = random.randint(0,1) 13 if br: s += ")" 14 else : s += "(" 15 return s 16 17 def balanced_brackets(brs): 18 brs, found = re.subn('\(\)','',brs); 19 ok = 0 20 if found: 21 ok = balanced_brackets(brs) 22 return ok 23 else: 24 if re.search('\(|\)',brs): return 0 25 else: return 1 26 27 loops = 0 28 while True: 29 loops = loops + 1 30 nr = random.randint(2,10) 31 brs = create_brackets(nr) 32 ok = balanced_brackets(brs) 33 rs = "NOT OK" 34 if ok: rs = "OK" 35 print("(%2d) %10s = %s" % (loops, brs, rs)) 36 if ok: break 37 if loops > 20: break

Python help

One important question as a biginner is: How do I get help? One answer is to search the net. The other is use the command line tools shipped with your Python. Below I, as a biginner, can see how to use the offline help:

In short: Start python CLI, use help() command, type the class or function you want to find, i.e. re.

# python
Python 2.7.13 (default, Sep 26 2018, 18:42:22) 
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help()

Welcome to Python 2.7!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/2.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help> re
...
/subn
...
q
help> quit

You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)".  Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
>>> quit()

AUTHOR

Chuck

You can’t perform that action at this time.