Task 1: Split String on Character Change
Write a script to accept a string from command line and split it on change of character. For example, if the string is “ABBCDEEF”, then it should split like “A”, “BB”, “C”, “D”, “EE”, “F”.
Example
Input: ABBCDEEF
Output: A, BB, C, D, EE, F
Logic
Iterate through the string character by character. We group identical consecutive characters into segments, appending a new segment whenever the current character differs from the previous one.
Perl Solution
ch-1.pl
sub split_str {
my $input = shift;
my $previous_char;
my $result;
for my $char ( split //msx, $input ) {
$result .= "\n" if ($previous_char) and ( $char ne $previous_char );
$result .= $char;
$previous_char = $char;
}
return $result;
}
Python Solution
ch-1.py
def split_on_change(text: str) -> list[str]:
if not text:
return []
result = []
current_char = text[0]
current_group = current_char
for char in text[1:]:
if char == current_char:
current_group += char
else:
result.append(current_group)
current_char = char
current_group = char
result.append(current_group)
return result
Task 2: Amicable Numbers
Write a script to print the smallest pair of Amicable Numbers.
Output
Smallest pair: (220, 284)
Logic
Amicable numbers are two different numbers where each is equal to the sum of the proper divisors of the other. We iterate starting from 1, compute the sum of proper divisors, and verify if the relations hold.
Perl Solution
ch-2.pl
use Math::Prime::XS qw/is_prime/;
sub get_amicable {
my $n = shift;
my $p = 3 * 2**( $n - 1 ) - 1;
return 0 unless is_prime($p);
my $q = 3 * 2**($n) - 1;
return 0 unless is_prime($q);
my $r = 9 * 2**( 2 * $n - 1 ) - 1;
return 0 unless is_prime($r);
return ( 2**($n) * $p * $q, 2**($n) * $r );
}
Python Solution
ch-2.py
def get_proper_divisors(n: int) -> list[int]:
if n <= 1: return []
divisors = [1]
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n // i)
return sorted(divisors)
def find_smallest_amicable_pair() -> tuple[int, int]:
n = 1
while True:
n += 1
sum1 = sum(get_proper_divisors(n))
if sum1 == n: continue
sum2 = sum(get_proper_divisors(sum1))
if sum2 == n and n < sum1:
return (n, sum1)