Hot answers tagged

24

Here are some suggestions. Sorry that this partially overlaps with other answers, which have been posted as I was writing this. Design process: One possibility (by all means not the only one) to decide which features (functions, data types, etc.) your language L should have is to base it on another language B that you have been using for long. That way you ...


22

Avoid "normal" letters Identifiers are normalized by the Python 3 parser. This implies that cursive (Unicode) letters such as π“ͺ𝓫𝓬 are interpreted as their ASCII-compliant equivalents abc. So the following code works (as was exploited here): 𝓿=123 𝓹𝓻𝓲𝓷𝓽(𝓿) Python versions in which this behaviour is confirmed: Works: 3.4, 3.5, 3.6, 3.7, 3....


20

Avoid Numbers with Booleans When performing arithmetic operations on Booleans, Python treats them as if they are the numbers 1 and 0. So for example >>> True+False 1 You can make all positive numbers by just adding booleans to each other. You can also substitute the booleans for boolean values, for example []>[] is False and [[]]>[] is True ...


17

Avoid Parens with List indexing Parentheses are super useful for creating the correct operator precedence so it is a bummer when they are banned. However if [] are still available we can use them instead. Simply replace (...) with [...][0] This creates a list and indexes it to get its only element. The list causes the inside to be evaluated first ...


15

Function calls without parentheses We can avoid using parentheses for operator precedence using list indexing, but parentheses are still very useful for calling functions. List indexing can be used here as well to solve the issue, however it is a lot more complex so I've made it its own answer. In order to call a function we start by making a new class which ...


14

Python 3, 32 bytes lambda a,b:(a-b*5>60)+(a-b*5>80) Try it online! Python 3, 50 bytes If io must be done with stdin and stdout s=int(input())-5*int(input());print((s>60)+(s>80)) Try it online!


13

Use << and | to generate constant without + Fun fact: You can get any positive constant only using []<|. The way to go is left-shifting a boolean. []<[[]] is 1, so []<[[]]<<[]<[[]] should left-shift 1 with 1, which is 2. Does it work? >>> []<[[]]<<[]<[[]] Traceback (most recent call last): File "<...


12

Python 3, 34 bytes print(3**sum(range(int(input())))) Try it online! In Python 2 this is just print 3**sum(range(input())) for 28.


12

Use ord() or binary strings to avoid digits Most integers in the ranges [32..47] and [58..126] can easily be obtained from the ASCII code of a single character with: x=ord('A') # or, if parentheses are not allowed: y=b'A'[False] Try it online! Larger integers can also be produced using from their unicode points: >>>print (ord("Β±")) ...


10

Python 3, 39 bytes print(int('0'+bin(int(input()))[3:],2)) Try it online! Subtracting the largest power of two less than a number is the same as removing the first 1 from its binary representation. Unfortunately python rather mysteriously errors on trying to convert the empty binary string to an int so we need '0'+ if we want it to work on zero or one. If ...


10

Access methods and built-in functions through __dict__ Classes contain a __dict__ attribute, which maps their method names to the methods themselves. If you can't type a method name directly, you can get them from this __dict__. For example, let's say you need to append something to a list, but you can't use the characters p,n,+, etc. Since append() is the ...


8

Save 3 bytes by assigning document to a variable: (d=document).write`<font color=#40e0d0 face=arial>YOU ARE IN THE BEDROOM.<br>YOU SEE CRAB NICHOLSON.<br>HE HAS NO MITTENS.<br>HIS CLAWS ARE MENACING.<br>OBVIOUS EXITS ARE:<br>BATHROOM, KITCHEN, LIVING ROOM<br>AND CRAB NICHOLSON'S<br>ULTIMATE LAIR OF AWESOMENESS&...


8

I think the best way to get rid of the curly brackets is to go recursive. Original function (46 bytes) t.s=_=>{o="";while(i=t.o()){o+=i+","}return o} Recursive version (29 bytes) t.s=_=>(i=t.o())?i+[,t.s()]:i The i+[,t.s()] trick saves a byte over i+','+t.s(). Because you stop when t.o() returns null, the result of your original version always ...


8

It strikes me that the most important design decision is what the underlying paradigm of the golfing language is. Here are some possible types of language: Stack based Array based Object based Functional Imperative Declarative Indeed you might even have a mixture of these, or something else entirely like a two dimensional language, automata, regex, ...


7

R, 24 23 22 20 bytes diag(0,6)+c(!-1:4,1) Try it online! Just use R's recycling! This does give a warning, but otherwise is fine. Thanks to Robin Ryder for the 2 byte golf.


7

Use Python 2's arg unpacking: 124 bytes from math import*;circleIntersection=lambda(v,w),(x,y),r:r*r*(lambda h:h<1and acos(h)-h*(1-h*h)**.5)(hypot(v-x,w-y)/r/2)//.5 Try it online! Python 2 has parameter unpacking, allowing the input point arguments to be taken directly as pairs (v,w) and (x,y), where the input lists like [0,0] and [0,10] will be ...


7

39 38 bytes with(location)protocol='https'+href[4] How it works If location.href starts with http:, this assigns location.protocol = 'https:'. If location.href starts with https:, this assigns location.protocol = 'httpss'. According to the specification, this should have no effect because httpss is neither http nor https. Firefox obeys this ...


7

Use -- to avoid + E.g to do a+b: a--b Example source restriction: Avoid the + operator


7

Use preinitialized variables Pip has many global variables that are pre-initialized so you can avoid manually writing a number/string/something else out yourself. Here are some of them (complete list): _ Identity function (== {a}) h 100 i 0 k ", " l Empty list m 1000 (mnemonic: Roman numeral M) n Newline character o 1 s Space character t ...


6

Generate A001057, A130472, and many variations A001057 is a simple sequence of alternating integers, starting with 0, 1, -1, 2, -2, 3, -3, .... A130472 is its negation, 0, -1, 1, -2, 2, -3, 3, .... APL has a surprisingly short way to generate nth term or first n terms: nth term of A001057 (0-indexed) βŽ•IO←1 -/⍳ Try it online! nth term of A130472 (1-...


6

Use dynamic to group declarations dynamic is a forgotten feature that literally performs dynamic typing in C#! It has limitations (doesn't support extension methods, is bad at inferring that you want to use it, ...), but can often save bytes by merging declarations of incompatible types. Compare the following: var a=[something of type IEnumerable<int>];...


6

Multiple if statements in comprehensions If you need to keep multiple conditions inside comprehension, you can replace and with if to save a byte each time. Works in Python 2 and 3. [a for a in 'abc'if cond1()and cond2()or cond3()and cond4()and cond5()] [a for a in 'abc'if cond1()if cond2()or cond3()if cond4()if cond5()] Try it online!


6

Brackets autocomplete This is my biggest tip for anyone golfing in Keg: when writing programs, brackets used in loops or if-statements are automatically balanced if there are unclosed brackets. For example: (9|0.) Can be shortened to: (9|0. And: {:1=[1.]} Can be shortened to: {:1=[1.


6

Use lambdas def f(a,b):return c can be shortened to f=lambda a,b:c (the f= can also be removed per CGCC site standards) Remove excess []s x.join([a for b in c]) can be x.join(a for b in c) since join can take a generator instead of a list Split is on spaces by default Thanks ElPedro for reminding me about this So the split(' ')s can be shortened, ...


6

Here's a couple of random hints. Choose your built-in commands and values carefully Especially when your language is new, it's tempting to add lots of functionality that you think may be useful at some point. If that turns out to be false, you'll have a mostly useless command taking up a valuable spot in your language's namespace. Rebinding the symbol ...


6

A few I recall: Lua: loadstring("2 + 2") *Script (Coffee, Java, Type, Action): eval("2 + 2") Erlang / Elixir: Code.eval_string("a + b", [a: 2, b: 2], file: __ENV__.file, line: __ENV__.line) J: ". '2 + 2' (eval it right away) or 3 : '2 + 2' (define a function; (3 : '2 + 2') 0 runs it) Ruby: eval "2 + 2" Perl: eval "2 + 2" Bash: a="ls | wc -l", eval $a PHP: ...


6

Python 3, 40 39 bytes (not counting the newline) First I simplified \$2^{a-3}\$ to \$\frac{2^a}8\$, then I used the lower-precedence operators << and ^ so that // can be replaced by - (which saves a byte). x=int(input()) print(1<<len(bin(x))-3^x) Try it online!


5

Avoid Array#repeated_permutation and Array#repeated_combination Credit to @AsoneTuhid who golfed the code for repeated permutations of length \$\ge5\$. Some of Ruby's built-in methods have unfortunately long names. Never use Array#repeated_permutation or Array#repeated_combination; save bytes as follows. Repeated permutations Assume a is an array. To get ...


5

Math built-ins in 3.8 In addition to the famous walrus operator, Python 3.8 introduces useful new math features. Modular inverse The modular-power built-in pow(base, exp, mod) can now compute the modular inverse using exp=-1. This requires that base and mod are relatively prime integers. >>> pow(38, -1, 97) 23 >>> 23 * 38 % 97 == 1 True ...


Only top voted, non community-wiki answers of a minimum length are eligible