Weekly Challenge 296
Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. It's a great way for us all to practice some coding.
Challenge, My solutions
Task 1: String Compression
Task
You are given a string of alphabetic characters, $chars.
Write a script to compress the string with run-length encoding, as shown in the examples.
A compressed unit can be either a single character or a count followed by a character.
BONUS: Write a decompression function.
My solution
Thanks to the power of regular expressions, this is a pretty straight forward task. Both Python and Perl allow the replacement value to be a function. Therefore I have a function called sc that will convert multiple letters into a number and the letter. For example if the input was aaa, it would return 3a.
def sc(match): m = match.group(0) return str(len(m)) + m[0]
Then it is a matter of calling this function as required.
def string_compress(s: str) -> str: return re.sub(r'(([a-z])+)', sc, s)
The decompress function (Python only) works in a similar fashion. It takes a pattern of a number followed by a letter and changes it to the letter repeated the specified number of occurrences.
def usc(match): m = match.group(0) return m[-1] * int (m[:-1]) def string_decompress(s: str) -> str: return re.sub(r'(\d+[a-z])', usc, s)
For execution from the command line, I use the argparse module to see if the --decompress option is specified.
def main(): parser = argparse.ArgumentParser() parser.add_argument("--decompress", help="decompress the input", action='store_true') parser.add_argument("str", help="the string to compress/decompress") args = parser.parse_args() if args.decompress: result = string_decompress(args.str) else: result = string_compress(args.str) print(result)
Examples
$ ./ch-1.py abbc a2bc $ ./ch-1.py aaabccc 3ab3c $ ./ch-1.py abcc ab2c $ ./ch-1.py --decompress a2bc abbc $ ./ch-1.py --decompress 3ab3c aaabccc $ ./ch-1.py --decompress ab2c abcc
Task 2: Matchstick Square
Task
You are given an array of integers, @ints.
Write a script to find if it is possible to make one square using the sticks as in the given array @ints where $ints[ì] is the length of i-th stick.
My solution
This is going to be a little long, so strap yourself in. The first thing I check is the sum of the sticks is divisible by four. If it isn't, there is no possible solution and I can return false
I can also check that no single stick is longer than one side. If this occurs, I also return false.
With these two checks, all the examples would give the correct result. However, it would erroneously report that 4 3 3 3 3 is true when in fact it is not.
Attempt two
Looking at the examples and my own thinking, I thought the solution would be to match a pair of values to match each side. So for the example 3 4 1 4 3 1 we have two pairs of 3 and 1 sticks that makes four. This would solve the 4 3 3 3 3 issue, because three doesn't have a matching one.
But this wouldn't work if the sticks were 4 4 3 1 2 1 1, as one side uses three sticks (one 2 and two 1s)
Attempt three
So my next attempt was a little more complicated, and I thought was a good solution ... until it wasn't. For this attempt, I started with the longest stick. If it wasn't the length of the side, I then took the next longest stick required to complete the side, and repeated until there was no possible solution. Using this method the following solutions were true.
- 4 4 3 1 2 1 1
- 9 5 4 3 3 3 3 3 3
- 9 6 3 5 4 3 3 3
- 9 6 3 5 4 3 3 2 1
I thought this was the solution, until I realised that 9 5 3 1 5 2 2 3 3 3 would not work. First side is 9, next side is 5 3 1, and the third side would fail with 5 3 and no 1.
Attempt four
At this point, I started to wonder if it was even possible to come up with a solution that didn't involve brute force. So I slept on it, scribbled down lots of things in on my tablet (I'm on holiday so can't use my white board), and slept on it again. My conclusion is that using a recursive function is the only solution.
Maybe I'm just overthinking all of this, or maybe there is a real simple solution that I just have thought of (as was the case last week).
The final code
Still reading? Well done :)
For this task, I have a recursive function called make_side. It takes a list (arrayref in Perl) of sticks remaining, and the length required. It then goes though the remaining sticks (highest first). Then one of three things happen:
- If the stick is longer than the required length, I skip it.
- If it is the required length, I return it.
- If it is short, I use it and call the function again to use another stick. The call removes the used stick, and reduces the required length by the length of the used stick.
The function will return a list of the sticks used, or None (undef in Perl) if no valid combination of sticks is found.
def sc(match): m = match.group(0) return str(len(m)) + m[0]
The final piece of the puzzle, I perform the checks mentioned in the first part (sum is divisible by four, no stick longer than a side), and then call the above function. If that returns None, I return false. If all the sticks are used, I return true.
def string_compress(s: str) -> str: return re.sub(r'(([a-z])+)', sc, s)
Examples
def usc(match): m = match.group(0) return m[-1] * int (m[:-1]) def string_decompress(s: str) -> str: return re.sub(r'(\d+[a-z])', usc, s)
The above is the detailed content of Matchstick compression. For more information, please follow other related articles on the PHP Chinese website!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools
