Short Code Competition

Source: Internet
Author: User

From http://www.felix021.com/blog/read.php? 2096

P indicates that the nest is actually silently concave for three rows, but it is too ugly to do so ......



The reason for the competition is that @ tranch raised a question in segmentfault.com and asked a code to list the string "qwerty"
"." All split conditions, such as Q. werty qwe. rty Q. W. E. R. T. Y.


This problem is actually very simple. QWERTY can include up to five ". ", each place uses 1 to indicate congestion, and 0 to indicate no congestion, that is, just loop 2 ^ 5 times. (For all 0 cases, no special requirements are required ), it is also very easy to implement. Here is a C language added during this article:

# Include <stdio. h>

Int main ()
{
Char STR [] = "qwerty ";
Int I, J;
For (I = 0; I <(1 <5); I ++)
{
For (j = 0; j <5; j ++)
{
Putchar (STR [J]);
If (I> J) & 1) = 1)
Putchar ('.');
}
Printf ("Y \ n ");
}
Return 0;
}



However, I didn't want to write such code at the time. Instead, I tried to write a recursive version using Python:

Def add_dots_l (STR ):
Ret = []
For I in range (1, Len (STR )):
Left = STR [: I]
Right = STR [I:]
Ret. append (left + '.' + right)
RET + = [J + '.' + right for J in add_dots_l (left)]
RET + = [left + '.' + J for J in add_dots_l (right)]
Return set (RET)


Because 21 lines of Python code were used to implement a spelling checker some time ago, this equivalent but harder to read version was simplified on the rise:

Def add_dots (s ):
R = [s [: I] + '.' + s [I:] For I in range (1, Len (s)]
R + = [J + '.' + s [I:] For I in range (1, Len (s) for J in add_dots (s [: I])]
R + = [s [: I] + '.' + J for I in range (1, Len (s) for J in add_dots (s [I:])]
Return set (r)


Although it is very short, I still want to know if there are more simple implementations (efficiency and readability can be ignored to a certain extent), so I sent this question to the MSTC group, for simplicity, change the string to "ABCDE" and ask if there is any shorter code to give a variety of combinations.

Then @ hang Shen threw out a code and was sprayed with "can you use your phone ". This code may seem a bit confusing. The main idea is to generate ['****','***. ','**.. ','*... ','.... '], and then use zip ('abcd', p) to combine them (and then delete '*'):

From itertools import permutations as P # itertools. permutations are introduced by python2.6.
Map (lambda P :''. join (J for I in zip ('abcd', p) for J in I ). replace ('*', '') + 'E ',[''. join (y) for X
In map (lambda I: Set (P ('* (4-I) +'. '* I), range (5) for Y in X])


Then @ Xiaomei said that it is actually a Cartesian product. So I used itertools. Product to improve the syntax. I can write it like this and it looks much clearer:

From itertools import product # itertools. product is also introduced in 2.6.
Map (lambda P :''. join (I + J for I, j in zip ('abcd', p) + 'E', product (['. ', ''], repeat = 4 ))


@ Paper also provides two other wonderful codes, one of which is C. It makes full use of the parameters and recursion of the macro and main functions:

# Define z (a, B) printf (# A "% s", (x> B) & 1? ".":""),
Main (x) {z (A, 3) Z (B, 2) Z (C, 1) Z (D, 0) puts ("e "); 16-x & Main (x + 1 );}


The other is Ruby:

P ("B ".. "E "). inject (["A"]) {| A, q |. product [Q ,". "+ q]}. map &: Join

For Ruby 1.9 +, a few characters are needed:

P (? B ..? E). Inject ([? A]) {| A, q | A. Product [q ,?. + Q]}. Map &: Join


Because I don't understand the ruby syntax, I can barely look at this code, but the idea is the same as the Python code above. I use cartesian products to generate a combination sequence and then combine it with 'abcde.

As a result, ruby won (58 bytes), and Python followed closely (80 bytes, excluding import). The C language unexpectedly achieved this goal with 106 bytes of code.

This problem is of little significance from a practical point of view, but it can be compared to different languages (C/Ruby/Python) and different programming paradigm (procedural/functional) A glimpse of the charm of functional programming ~

--

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.