Perl Weekly Challenge 313

Broken Keys and Reverse Letters

Published: 17 Mar 2025

Solutions on GitHub

Task 1: Broken Keys

You have a broken keyboard which sometimes type a character more than once.

You are given a string and actual typed string.

Write a script to find out if the actual typed string is meant for the given string.

Logic

To check if the typed string could be produced from the name with long presses:

  1. If the typed string is shorter than the name, return false.
  2. Use two pointers, one for name (i) and one for typed (j).
  3. If the characters match, move both pointers.
  4. If they don't match, check if the current typed character is the same as the previous typed character (indicating a long press). If yes, move only the typed pointer.
  5. Otherwise, return false.
  6. At the end, if we have consumed all characters in the name, return true; otherwise, false.

Perl Solution

ch-1.pl

#!/usr/bin/env perl use v5.38; use warnings; use feature 'signatures'; no warnings 'experimental::signatures'; ## no critic (Subroutines::ProhibitSubroutinePrototypes) use Type::Params qw(compile); use Types::Standard qw(Str); =pod =head1 NAME ch-1.pl - Broken Keys =head1 SYNOPSIS perl ch-1.pl perl perrrl perl ch-1.pl # runs the embedded tests =head1 DESCRIPTION Checks whether the typed string could have been produced from the intended name when a key can be long-pressed, i.e. a character may appear repeated one or more times consecutively. =cut my $ARGS_CHECK = compile( Str, Str ); sub is_long_pressed ($name, $typed) { ( $name, $typed ) = $ARGS_CHECK->( $name, $typed ); return 0 if length($typed) < length($name); my @n = split //, $name; my @t = split //, $typed; my $i = 0; my $j = 0; while ( $j <= $#t ) { if ( $i <= $#n && $n[$i] eq $t[$j] ) { ++$i; ++$j; } elsif ( $j > 0 && $t[$j] eq $t[ $j - 1 ] ) { ++$j; } else { return 0; } } return $i == @n ? 1 : 0; } sub _run_cli (@args) { if ( !@args ) { _run_tests(); return; } die "Usage: perl $0 \n" if @args != 2; my ( $name, $typed ) = @args; my $out = is_long_pressed( $name, $typed ) ? 'true' : 'false'; say qq{Input: \$name = "$name", \$typed = "$typed"}; say "Output: $out"; } sub _run_tests { require Test::More; Test::More->import; my @cases = ( { label => 'Example 1', name => 'perl', typed => 'perrrl', expected => 1 }, { label => 'Example 2', name => 'raku', typed => 'rrakuuuu', expected => 1 }, { label => 'Example 3', name => 'python', typed => 'perl', expected => 0 }, { label => 'Example 4', name => 'coffeescript', typed => 'cofffeescccript', expected => 1 }, ); Test::More::plan( tests => scalar @cases ); for my $case (@cases) { my $got = is_long_pressed( $case->{name}, $case->{typed} ) ? 1 : 0; Test::More::is( $got, $case->{expected}, $case->{label} ); } } _run_cli(@ARGV); =pod =head1 FUNCTIONS =head2 is_long_pressed($name, $typed) Returns a boolean indicating whether C<$typed> can be produced from C<$name> using long presses. =cut

Python Solution

ch-1.py

#!/usr/bin/env python3 """Broken Keys - Perl Weekly Challenge 313 task 1.""" from __future__ import annotations from collections.abc import Sequence import sys import unittest def is_long_pressed(name: str, typed: str) -> bool: """Return True if typed could be produced from name via long-pressing keys.""" if len(typed) < len(name): return False i = 0 j = 0 while j < len(typed): if i < len(name) and name[i] == typed[j]: i += 1 j += 1 elif j > 0 and typed[j] == typed[j - 1]: j += 1 else: return False return i == len(name) class BrokenKeysExamples(unittest.TestCase): """Example-based tests from the specification.""" def test_example_1(self) -> None: self.assertTrue(is_long_pressed("perl", "perrrl")) def test_example_2(self) -> None: self.assertTrue(is_long_pressed("raku", "rrakuuuu")) def test_example_3(self) -> None: self.assertFalse(is_long_pressed("python", "perl")) def test_example_4(self) -> None: self.assertTrue(is_long_pressed("coffeescript", "cofffeescccript")) def main(argv: Sequence[str] | None = None) -> None: """Command-line interface.""" args = list(sys.argv[1:] if argv is None else argv) if not args: unittest.main(argv=[sys.argv[0]]) return if len(args) != 2: raise SystemExit("Usage: python3 ch-1.py ") name, typed = args result = "true" if is_long_pressed(name, typed) else "false" print(f'Input: $name = "{name}", $typed = "{typed}"') print(f"Output: {result}") if __name__ == "__main__": main()

Task 2: Reverse Letters

You are given a string.

Write a script to reverse only the alphabetic characters in the string.

Logic

To reverse only alphabetic characters while keeping other characters in place:

  1. Convert the string to a list of characters.
  2. Initialize two pointers: left at the start, right at the end.
  3. Move the left pointer right until it points to an alphabetic character.
  4. Move the right pointer left until it points to an alphabetic character.
  5. If left is still less than right, swap the characters at these pointers.
  6. Move both pointers inward and repeat.
  7. Join the list back into a string and return.

Perl Solution

ch-2.pl

#!/usr/bin/env perl use v5.38; use warnings; use feature 'signatures'; no warnings 'experimental::signatures'; ## no critic (Subroutines::ProhibitSubroutinePrototypes) use Type::Params qw(compile); use Types::Standard qw(Str); =pod =head1 NAME ch-2.pl - Reverse Letters =head1 SYNOPSIS perl ch-2.pl "p-er?l" perl ch-2.pl # runs the embedded tests =head1 DESCRIPTION Reverses only the alphabetic characters in the string while leaving all other characters in their original positions. =cut my $STR_CHECK = compile(Str); sub reverse_letters ($str) { ($str) = $STR_CHECK->($str); my @chars = split //, $str; my ( $l, $r ) = ( 0, $#chars ); while ( $l < $r ) { ++$l while $l < $r && $chars[$l] !~ /[A-Za-z]/; --$r while $l < $r && $chars[$r] !~ /[A-Za-z]/; ( $chars[$l], $chars[$r] ) = ( $chars[$r], $chars[$l] ) if $l < $r; ++$l; --$r; } return join '', @chars; } sub _run_cli (@args) { if ( !@args ) { _run_tests(); return; } die "Usage: perl $0 \n" if @args != 1; my $str = $args[0]; my $out = reverse_letters($str); say qq{Input: \$str = "$str"}; say qq{Output: "$out"}; } sub _run_tests { require Test::More; Test::More->import; my @cases = ( { label => 'Example 1', str => 'p-er?l', expected => 'l-re?p' }, { label => 'Example 2', str => 'wee-k!L-y', expected => 'yLk-e!e-w' }, { label => 'Example 3', str => '_c-!h_all-en!g_e', expected => '_e-!g_nel-la!h_c' }, ); Test::More::plan( tests => scalar @cases ); for my $case (@cases) { Test::More::is( reverse_letters( $case->{str} ), $case->{expected}, $case->{label} ); } } _run_cli(@ARGV); =pod =head1 FUNCTIONS =head2 reverse_letters($str) Returns the string with only alphabetic characters reversed. =cut

Python Solution

ch-2.py

#!/usr/bin/env python3 """Reverse Letters - Perl Weekly Challenge 313 task 2.""" from __future__ import annotations from collections.abc import Sequence import sys import unittest def reverse_letters(text: str) -> str: """Reverse only alphabetic characters, keeping other characters in place.""" chars = list(text) left = 0 right = len(chars) - 1 while left < right: while left < right and not chars[left].isalpha(): left += 1 while left < right and not chars[right].isalpha(): right -= 1 if left < right: chars[left], chars[right] = chars[right], chars[left] left += 1 right -= 1 return "".join(chars) class ReverseLettersExamples(unittest.TestCase): """Example-based tests from the specification.""" def test_example_1(self) -> None: self.assertEqual(reverse_letters("p-er?l"), "l-re?p") def test_example_2(self) -> None: self.assertEqual(reverse_letters("wee-k!L-y"), "yLk-e!e-w") def test_example_3(self) -> None: self.assertEqual(reverse_letters("_c-!h_all-en!g_e"), "_e-!g_nel-la!h_c") def main(argv: Sequence[str] | None = None) -> None: """Command-line interface.""" args = list(sys.argv[1:] if argv is None else argv) if not args: unittest.main(argv=[sys.argv[0]]) return if len(args) != 1: raise SystemExit("Usage: python3 ch-2.py ") text = args[0] print(f'Input: $str = "{text}"') print(f'Output: "{reverse_letters(text)}"') if __name__ == "__main__": main()