You are given a positive integer, $n. Write a script to return true if the given integer is a power of three otherwise return false.
Handle 0 explicitly as true (per Example 2, 0 = 0 ^ 3) and return false for any integer less than 1. For positive integers, repeatedly divide n by 3 while it is divisible by 3. If the remaining value equals 1, the original number is a power of three. This avoids floating-point precision issues and runs in O(log3 n) time and O(1) space.
ch-1.pl)#!/usr/bin/env perl
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(Int);
use Test::More;
signature_for is_power_of_three => (
method => 0,
positional => [Int],
);
sub is_power_of_three ($n) {
return 1 if $n == 0;
return 0 if $n < 1;
while ( $n % 3 == 0 ) {
$n /= 3;
}
return $n == 1 ? 1 : 0;
}
ch-1.py)def is_power_of_three(n: int) -> bool:
"""Return True if n is a power of three (or 0 = 0^3), False otherwise."""
if n == 0:
return True
if n < 1:
return False
while n % 3 == 0:
n //= 3
return n == 1
You are given a string, $s. Write a script to reverse all the vowels (a, e, i, o, u) in the given string.
Extract all vowels (a, e, i, o, u, case-insensitive) from the string and reverse their order. Then iterate through the characters of the original string: consonants and other characters remain untouched, while each vowel position takes the next vowel from the reversed list, adjusted to match the uppercase or lowercase casing of the original position (so "Uiua" becomes "Auiu"). This runs in O(n) time and O(n) space.
ch-2.pl)#!/usr/bin/env perl
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(Str);
use Test::More;
signature_for reverse_vowels => (
method => 0,
positional => [Str],
);
sub reverse_vowels ($s) {
my @vowels = reverse( $s =~ /[aeiou]/ig );
my @chars = split //, $s;
for my $i ( 0 .. $#chars ) {
if ( $chars[$i] =~ /[aeiouAEIOU]/ ) {
my $replacement = shift @vowels;
$chars[$i] = ( $chars[$i] =~ /[AEIOU]/ ) ? uc($replacement) : lc($replacement);
}
}
return join '', @chars;
}
ch-2.py)def reverse_vowels(s: str) -> str:
"""Return s with all vowels reversed while preserving original vowel case."""
vowels = set("aeiouAEIOU")
reversed_vowels: list[str] = [char for char in s if char in vowels][::-1]
reversed_iter = iter(reversed_vowels)
result: list[str] = []
for char in s:
if char in vowels:
replacement = next(reversed_iter)
result.append(replacement.upper() if char.isupper() else replacement.lower())
else:
result.append(char)
return "".join(result)