[Challenge] [PL,java,Py,RB,js] Shorten this code ! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

[Challenge] [PL,java,Py,RB,js] Shorten this code !

[Perl] This code has 34 char, can you shorten it under 34 char? AUTOLOAD { $p=@{$_[0]}; $p == 3 ? 0 : $p % 2 } Detail : @_ is array, and check the size. [Java] int f(int[] p) { return p.length!=3?p.length%2:0; } [Ruby] def f p y=p.size y==3?0:y%2 end [Python] def f(p): x=len(p) return 0 if x==3 else x%2 [JS] f=p=>p.length==3?0:p.length%2;

2nd Apr 2018, 6:01 AM
Momo Belia
Momo Belia - avatar
5 Answers
0
I can shorten your Python version, a little bit: [Python] def f(p): x=len(p) return x%2 - (x==3) I'm new to Perl! Does this work? If so, it's shorter. AUTOLOAD { $p == 3 ? 0 : @{$_[0]} % 2 }
2nd Apr 2018, 6:37 AM
Emma
0
how this can be work? (x!=3) * x%2
2nd Apr 2018, 7:21 AM
Momo Belia
Momo Belia - avatar
0
Apologies, my python code had a bug. It should have been x%2 - (x==3) Explanation: The result is always length % 2 (odd numbered lengths return 1, even numbered lengths, 0), except for when length is 3, which should give 0, instead of the usual 1. (x==3) either equates to 0 or 1. 1 for when x is equal to 3, and 0 at any other time. x%2 - (x==3) Table of evaluated expressions to explain: x, x%2, (x==3), x%2 - (x==3) 0, 0, 0, 0 1, 1, 0, 1 2, 0, 0, 0 3, 1, 1, 0 4, 0, 0, 0 5, 1, 0, 1 6, 0, 0, 0 7, 1, 0, 1 8, 0, 0, 0 9, 1, 0, 1
2nd Apr 2018, 9:38 AM
Emma
0
(x!=3) * x%2 also can be work in my testcase :D
2nd Apr 2018, 4:43 PM
Momo Belia
Momo Belia - avatar
- 1
bump this post
2nd Apr 2018, 6:14 AM
Momo Belia
Momo Belia - avatar