aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2023-03-19 20:09:48 +0000
committerGitHub <noreply@github.com>2023-03-19 20:09:48 +0000
commitb76a63b8fa923e19be44485e2f3b27577434982f (patch)
tree5686e16d4dfa81b00d4b9b086a26c6482f6167a1
parenta657b4c4711ecde6e6177a5f3ac8c371c3783f16 (diff)
parent45fbadb9777f592fa7836287a3f62dcab4d47e97 (diff)
downloadperlweeklychallenge-club-b76a63b8fa923e19be44485e2f3b27577434982f.tar.gz
perlweeklychallenge-club-b76a63b8fa923e19be44485e2f3b27577434982f.tar.bz2
perlweeklychallenge-club-b76a63b8fa923e19be44485e2f3b27577434982f.zip
Merge pull request #7754 from LubosKolouch/master
Challenge 208 010 011
-rw-r--r--challenge-022/lubos-kolouch/perl5/ch-1.pl30
-rw-r--r--challenge-022/lubos-kolouch/perl5/ch-2.pl59
-rw-r--r--challenge-022/lubos-kolouch/python/ch-1.py34
-rw-r--r--challenge-022/lubos-kolouch/python/ch-2.py67
-rw-r--r--challenge-023/lubos-kolouch/perl/ch-1.pl28
-rw-r--r--challenge-023/lubos-kolouch/perl/ch-2.pl42
-rw-r--r--challenge-023/lubos-kolouch/python/ch-1.py74
-rw-r--r--challenge-023/lubos-kolouch/python/ch-2.py67
8 files changed, 401 insertions, 0 deletions
diff --git a/challenge-022/lubos-kolouch/perl5/ch-1.pl b/challenge-022/lubos-kolouch/perl5/ch-1.pl
new file mode 100644
index 0000000000..5c890f16fb
--- /dev/null
+++ b/challenge-022/lubos-kolouch/perl5/ch-1.pl
@@ -0,0 +1,30 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+
+sub is_prime {
+ my $n = shift;
+ return 0 if $n <= 1;
+ return 1 if $n <= 3;
+
+ return 0 if $n % 2 == 0 || $n % 3 == 0;
+
+ my $i = 5;
+ while ($i * $i <= $n) {
+ return 0 if $n % $i == 0 || $n % ($i + 2) == 0;
+ $i += 6;
+ }
+ return 1;
+}
+
+my $count = 0;
+my $num = 2;
+
+while ($count < 10) {
+ if (is_prime($num) && is_prime($num + 6)) {
+ print "($num, ", $num + 6, ")\n";
+ $count++;
+ }
+ $num++;
+}
+
diff --git a/challenge-022/lubos-kolouch/perl5/ch-2.pl b/challenge-022/lubos-kolouch/perl5/ch-2.pl
new file mode 100644
index 0000000000..e520d61522
--- /dev/null
+++ b/challenge-022/lubos-kolouch/perl5/ch-2.pl
@@ -0,0 +1,59 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+
+sub lzw_encode {
+ my ($data) = @_;
+ my %dictionary = map { chr($_) => $_ } (0..255);
+
+ my $current_string = "";
+ my @encoded_data;
+
+ foreach my $char (split //, $data) {
+ my $combined_string = $current_string . $char;
+ if (exists $dictionary{$combined_string}) {
+ $current_string = $combined_string;
+ } else {
+ push @encoded_data, $dictionary{$current_string};
+ $dictionary{$combined_string} = scalar keys %dictionary;
+ $current_string = $char;
+ }
+ }
+
+ push @encoded_data, $dictionary{$current_string} if $current_string ne "";
+ return \@encoded_data;
+}
+
+sub lzw_decode {
+ my ($encoded_data) = @_;
+ my %dictionary = map { $_ => chr($_) } (0..255);
+
+ my $current_string = chr($encoded_data->[0]);
+ my @decoded_data = ($current_string);
+
+ for my $code (@{$encoded_data}[1..$#$encoded_data]) {
+ my $entry;
+ if (exists $dictionary{$code}) {
+ $entry = $dictionary{$code};
+ } elsif ($code == scalar keys %dictionary) {
+ $entry = $current_string . substr($current_string, 0, 1);
+ } else {
+ die "Invalid code: $code";
+ }
+
+ push @decoded_data, $entry;
+
+ $dictionary{scalar keys %dictionary} = $current_string . substr($entry, 0, 1);
+ $current_string = $entry;
+ }
+
+ return join("", @decoded_data);
+}
+
+my $input_data = "ABABABABABABABAB";
+my $compressed_data = lzw_encode($input_data);
+print "Compressed data: @{$compressed_data}\n";
+
+my $decompressed_data = lzw_decode($compressed_data);
+print "Decompressed data: $decompressed_data\n";
+
diff --git a/challenge-022/lubos-kolouch/python/ch-1.py b/challenge-022/lubos-kolouch/python/ch-1.py
new file mode 100644
index 0000000000..b0e6485432
--- /dev/null
+++ b/challenge-022/lubos-kolouch/python/ch-1.py
@@ -0,0 +1,34 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from typing import Tuple
+from sympy import isprime
+
+
+def is_sexy_prime_pair(num: int) -> Tuple[int, bool]:
+ """
+ Check if the given number and the number 6 greater than it form a sexy prime pair.
+
+ :param num: An integer
+ :return: A tuple containing the number and a boolean indicating if it's part of a sexy prime pair
+ """
+ return (num, isprime(num) and isprime(num + 6))
+
+
+def main() -> None:
+ """
+ Prints the first 10 sexy prime pairs.
+ """
+ count = 0
+ num = 2
+
+ while count < 10:
+ sexy_prime = is_sexy_prime_pair(num)
+ if sexy_prime[1]:
+ print(f"({sexy_prime[0]}, {sexy_prime[0] + 6})")
+ count += 1
+ num += 1
+
+
+if __name__ == "__main__":
+ main()
diff --git a/challenge-022/lubos-kolouch/python/ch-2.py b/challenge-022/lubos-kolouch/python/ch-2.py
new file mode 100644
index 0000000000..07388527d4
--- /dev/null
+++ b/challenge-022/lubos-kolouch/python/ch-2.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+class LZW:
+
+ def encode(self, data: str) -> list[int]:
+ """Encode the input data using the LZW compression algorithm.
+
+ :param data: A string representing the data to be compressed
+ :return: A list of integers representing the compressed data
+ """
+ dictionary = {chr(i): i for i in range(256)}
+
+ current_string = ""
+ encoded_data = []
+
+ for char in data:
+ combined_string = current_string + char
+ if combined_string in dictionary:
+ current_string = combined_string
+ else:
+ encoded_data.append(dictionary[current_string])
+ dictionary[combined_string] = len(dictionary)
+ current_string = char
+
+ if current_string:
+ encoded_data.append(dictionary[current_string])
+
+ return encoded_data
+
+ def decode(self, encoded_data: list[int]) -> str:
+ """Decode the input data using the LZW compression algorithm.
+
+ :param encoded_data: A list of integers representing the compressed data
+ :return: A string representing the decompressed data
+ """
+ dictionary = {i: chr(i) for i in range(256)}
+
+ current_string = chr(encoded_data[0])
+ decoded_data = [current_string]
+
+ for code in encoded_data[1:]:
+ if code in dictionary:
+ entry = dictionary[code]
+ elif code == len(dictionary):
+ entry = current_string + current_string[0]
+ else:
+ raise ValueError(f"Invalid code: {code}")
+
+ decoded_data.append(entry)
+
+ dictionary[len(dictionary)] = current_string + entry[0]
+ current_string = entry
+
+ return "".join(decoded_data)
+
+
+if __name__ == "__main__":
+ input_data = "ABABABABABABABAB"
+
+ lzw = LZW()
+ compressed_data = lzw.encode(input_data)
+ print(f"Compressed data: {compressed_data}")
+
+ decompressed_data = lzw.decode(compressed_data)
+ print(f"Decompressed data: {decompressed_data}")
diff --git a/challenge-023/lubos-kolouch/perl/ch-1.pl b/challenge-023/lubos-kolouch/perl/ch-1.pl
new file mode 100644
index 0000000000..f7b6e7cf06
--- /dev/null
+++ b/challenge-023/lubos-kolouch/perl/ch-1.pl
@@ -0,0 +1,28 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+sub forward_difference {
+ my ($order, $nums_ref) = @_;
+
+ my @nums = @$nums_ref;
+
+ # Check if valid order is passed
+ die "Order should be a positive integer\n" if $order < 1;
+
+ my @diff = @nums;
+
+ # Calculate the nth order forward difference series
+ for (my $i = 1; $i <= $order; $i++) {
+ my @temp = ();
+ for (my $j = 0; $j < $#diff; $j++) {
+ push @temp, $diff[$j+1] - $diff[$j];
+ }
+ @diff = @temp;
+ }
+
+ # Return the final series
+ return @diff;
+}
+
diff --git a/challenge-023/lubos-kolouch/perl/ch-2.pl b/challenge-023/lubos-kolouch/perl/ch-2.pl
new file mode 100644
index 0000000000..6409948d61
--- /dev/null
+++ b/challenge-023/lubos-kolouch/perl/ch-2.pl
@@ -0,0 +1,42 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+use Test::More tests => 3;
+
+# Subroutine to compute prime factors of a number
+sub prime_decomposition {
+ my $n = shift;
+
+ # Check if number is less than 2
+ if ($n < 2) {
+ die "Number should be greater than or equal to 2\n";
+ }
+
+ my @factors = ();
+ my $d = 2;
+
+ # Divide the number by prime factors
+ while ($n > 1) {
+ while ($n % $d == 0) {
+ push @factors, $d;
+ $n /= $d;
+ }
+ $d++;
+ if ($d * $d > $n && $n > 1) {
+ push @factors, $n;
+ last;
+ }
+ }
+
+ return @factors;
+}
+
+# Test cases
+is_deeply([prime_decomposition(228)], [2, 2, 3, 19], "prime decomposition of 228");
+is_deeply([prime_decomposition(131)], [131], "prime decomposition of 131");
+is_deeply([prime_decomposition(101)], [101], "prime decomposition of 101");
+
+done_testing();
+
+
diff --git a/challenge-023/lubos-kolouch/python/ch-1.py b/challenge-023/lubos-kolouch/python/ch-1.py
new file mode 100644
index 0000000000..877379d121
--- /dev/null
+++ b/challenge-023/lubos-kolouch/python/ch-1.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+
+import unittest
+import sys
+
+
+def forward_difference(order, nums):
+ # Check if valid order is passed
+ if order < 1:
+ raise ValueError("Order should be a positive integer")
+
+ diff = nums
+
+ # Calculate the nth order forward difference series
+ for i in range(order):
+ temp = []
+ for j in range(len(diff) - 1):
+ try:
+ temp.append(diff[j + 1] - diff[j])
+ except TypeError:
+ raise TypeError(f"not a number")
+ diff = temp
+
+ # Return the final series
+ return diff
+
+
+# Main code
+if __name__ == '__main__':
+ # Parse command line arguments
+ nums = []
+ for arg in sys.argv[1:-1]:
+ try:
+ nums.append(int(arg))
+ except ValueError:
+ raise ValueError(f"Invalid argument: {arg!r}")
+ order = int(sys.argv[-1])
+
+ # Calculate the nth order forward difference series
+ diff = forward_difference(order, nums)
+
+ # Print the final series
+ print(', '.join(map(str, diff)))
+
+# Tests
+
+
+class TestForwardDifference(unittest.TestCase):
+
+ def test_first_order(self):
+ nums = [5, 9, 2, 8, 1, 6]
+ expected_diff = [4, -7, 6, -7, 5]
+ actual_diff = forward_difference(1, nums)
+ self.assertListEqual(expected_diff, actual_diff)
+
+ def test_second_order(self):
+ nums = [5, 9, 2, 8, 1, 6]
+ expected_diff = [-11, 13, -13, 12]
+ actual_diff = forward_difference(2, nums)
+ self.assertListEqual(expected_diff, actual_diff)
+
+ def test_invalid_order(self):
+ nums = [5, 9, 2, 8, 1, 6]
+ with self.assertRaises(ValueError):
+ forward_difference(-1, nums)
+
+ def test_non_numeric_parameters(self):
+ nums = [5, 9, 2, 8, "foo", 6]
+ with self.assertRaises(TypeError):
+ forward_difference(2, nums)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/challenge-023/lubos-kolouch/python/ch-2.py b/challenge-023/lubos-kolouch/python/ch-2.py
new file mode 100644
index 0000000000..87379a1b3a
--- /dev/null
+++ b/challenge-023/lubos-kolouch/python/ch-2.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import sys
+from typing import List
+
+
+def prime_decomposition(n: int) -> List[int]:
+ """
+ Compute the prime factors of a number.
+
+ Args:
+ n: An integer greater than or equal to 2.
+
+ Returns:
+ A list of prime factors of the input number.
+
+ Raises:
+ ValueError: If the input number is less than 2.
+ """
+ if n < 2:
+ raise ValueError("Number should be greater than or equal to 2")
+
+ factors = []
+ d = 2
+
+ # Divide the number by prime factors
+ while n > 1:
+ while n % d == 0:
+ factors.append(d)
+ n //= d
+ d += 1
+ if d * d > n and n > 1:
+ factors.append(n)
+ break
+
+ return factors
+
+
+# Test cases
+def test_prime_decomposition():
+ assert prime_decomposition(228) == [2, 2, 3, 19]
+ assert prime_decomposition(131) == [131]
+ assert prime_decomposition(101) == [101]
+ try:
+ prime_decomposition(1)
+ except ValueError:
+ pass
+ else:
+ assert False, "Expected ValueError for input 1"
+
+
+if __name__ == '__main__':
+ # Parse command line argument
+ if len(sys.argv) != 2:
+ print(f"Usage: {sys.argv[0]} <number>")
+ sys.exit(1)
+ n = int(sys.argv[1])
+
+ # Compute the prime decomposition
+ factors = prime_decomposition(n)
+
+ # Print the prime factors
+ print(", ".join(str(f) for f in factors))
+
+ # Run tests
+ test_prime_decomposition()