Task 1: Decimal to Octal
Write a script to convert a given decimal number to its octal representation.
Example Output
Input: 50
Output: 62
Logic
Using built-in formatting functions like sprintf("%o", $decimal) in Perl or oct(decimal) in Python makes this conversion extremely simple and robust.
Perl Solution
ch-1.pl
sub decimal_to_octal {
my $decimal = shift;
return sprintf( "%o", $decimal );
}
Python Solution
ch-1.py
def decimal_to_octal(decimal: int) -> str:
return oct(decimal)[2:]
Task 2: Balanced Brackets
Write a script to check if a given string of brackets ( and ) is balanced. Also implement a bracket string generator to test the validation script.
Example Output
Bracket string: (())()
Output: Balanced
Logic
To check if brackets are balanced, iterate through the string characters. Push open brackets ( onto a stack. When encountering a closing bracket ), pop from the stack (if empty, the string is unbalanced). After the iteration, the stack must be empty for the string to be balanced.
Perl Solution
ch-2.pl
sub is_balanced {
my $bracket_string = shift;
my @stack = ();
for my $bracket ( split( //, $bracket_string ) ) {
if ( $bracket eq '(' ) {
push( @stack, $bracket );
}
elsif ( $bracket eq ')' ) {
if ( @stack == 0 ) {
return 0;
}
pop(@stack);
}
}
return @stack == 0;
}
Python Solution
ch-2.py
def is_balanced(bracket_string: str) -> bool:
stack = []
for bracket in bracket_string:
if bracket == "(":
stack.append(bracket)
elif bracket == ")":
if len(stack) == 0:
return False
stack.pop()
return len(stack) == 0