# 自动元代码高尔夫球

13

``````print quickSort([0,7,3,-1,8,10,57,2])
def quickSort(arr):
less = []
pivotList = []
more = []
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
for i in arr:
if i < pivot:
less.append(i)
elif i > pivot:
more.append(i)
else:
pivotList.append(i)
less = quickSort(less)
more = quickSort(more)
return less + pivotList + more
``````

``````for i in xrange(1, 101):
if i % 15 == 0:
print "FizzBuzz"
elif i % 3 == 0:
print "Fizz"
elif i % 5 == 0:
print "Buzz"
else:
print i
``````

``````from sys import argv

def randomGenerator(seed=1):
max_int32 = (1 << 31) - 1
seed = seed & max_int32

while True:
seed = (seed * 214013 + 2531011) & max_int32
yield seed >> 16

def deal(seed):
nc = 52
cards = range(nc - 1, -1, -1)
rnd = randomGenerator(seed)
for i, r in zip(range(nc), rnd):
j = (nc - 1) - r % (nc - i)
cards[i], cards[j] = cards[j], cards[i]
return cards

def show(cards):
l = ["A23456789TJQK"[c / 4] + "CDHS"[c % 4] for c in cards]
for i in range(0, len(cards), 8):
print " ", " ".join(l[i : i+8])

if __name__ == '__main__':
seed = int(argv[1]) if len(argv) == 2 else 11982
print "Hand", seed
deck = deal(seed)
show(deck)
``````

1. 您的程序不得以我专门发布的代码为目标，并且应与任何Python 2代码一起使用。我保留更改被编码的源代码的权利。您可能会假设没有多行字符串（因此您没有构建完整的解析器），并且未调用locals（）。

2. 程序的输出应以与原始源代码相同的方式运行。（即，它必须产生相同的输出。只要输出保持不变，就可以更改变量名称和语言结构）

3. 您可以使用STDIO或文件来进行源代码的输入/输出。

（上面列出的代码是根据GNU自由文档许可1.2http://rosettacode.org/ 获得的

3
KSab

3

Sp3000 2015年

4

2

2

4

# Python 2.7、794

## 结果

``````228 t1.py
128 t2.py
438 t3.py
794 total
``````

## 输出量

``````def c(a):
b=[]
d=[]
f=[]
if len(a)<=1:
return a
else:
e=a[0]
for i in a:
if i<e:
b.append(i)
elif i>e:
f.append(i)
else:
d.append(i)
b=c(b)
f=c(f)
return b+d+f
print c([0,7,3,-1,8,10,57,2])

for i in xrange(1,101):
if i%15==0:
print"FizzBuzz"
elif i%3==0:
print"Fizz"
elif i%5==0:
print"Buzz"
else:
print i

from sys import argv
def a(k=1):
b=(1<<31)-1
k=k&b
while 1:
k=(k*214013+2531011)&b
yield k>>16
def d(k):
f=52
h=range(f-1,-1,-1)
g=a(k)
for i,r in zip(range(f),g):
j=(f-1)-r%(f-i)
h[i],h[j]=h[j],h[i]
return h
def m(h):
l=["A23456789TJQK"[c/4]+"CDHS"[c%4]for c in h]
for i in range(0,len(h),8):
print" "," ".join(l[i:i+8])
if __name__=='__main__':
k=int(argv[1])if len(argv)==2 else 11982
print"Hand",k
e=d(k)
m(e)
``````

## 码

``````import sys
import re
from tokenize import generate_tokens
from token import tok_name
from keyword import iskeyword

wr = sys.stdout.write

def pyparse(text):
'Return [TYPE,TOKEN] pair list'
# Use KEYWORD,NAME,NUMBER,OP,STRING,NL,NEWLINE,COMMENT,INDENT,DEDENT
tokens = [[tok_name[n], t] for n,t,p1,p2,dx in rawtokens]
for tpair in tokens:
if tpair[0] == 'NAME' and iskeyword(tpair[1]):
tpair[0] = 'KEYWORD'

def finduservars(filename):
'Return a set of user variables that we can replace with a-zA-Z'
varset = set()
for line in open(filename):
line = line.strip()
match = re.match(r'def\s+(\w+)\s*\((.*)\)\s*:', line)
if match:
func, args = match.groups()
arglist = re.findall(r'(\w+|=)', args)
for a in arglist:
if a == '=':
break  # keyword args follow - too hard to parse
continue
match = re.match(r'(\w+)\s*=.+', line)
if match:
assigned = match.group(1)
continue
return set(v for v in list(varset) if len(v) > 1)

filename = sys.argv[1]
tokenlist = pyparse(open(filename))

# Build map for var->char conversion:
varset = finduservars(filename)
singles = [text for tok,text in tokenlist if tok=='NAME' and len(text)==1]
allvar = [chr(n) for n in range(97,123)+range(65,91)]
charvar = [c for c in allvar if c not in singles]
varreplaced = list(varset)[:len(charvar)]
varmap = dict((v, charvar.pop(0)) for v in varreplaced)

prev = 'NONE'
indent = ['']
output = []
for tok, text in tokenlist:
if tok == 'NL':
continue
elif tok == 'INDENT':
indent.append( text.replace('    ', ' ') )
output[-1] = indent[-1]
elif tok == 'DEDENT':
indent.pop(-1)
output[-1] = indent[-1]
elif tok == 'NEWLINE':
elif tok in 'KEYWORD,NAME,NUMBER':
if prev in 'KEYWORD,NAME,NUMBER':
if tok == 'NAME':
if output[-2] == 'while' and text == 'True':
else:
else:
else:
prev = tok

wr(''.join(output))
``````

4

# sed，1074（低于1390）

``````/^\$/d                  # Remove empty lines
/^[ <--TAB-->]*#/d     # Remove whole-line comments
s/    /<--TAB-->/g     # Replace 4 spaces with tabs
/^[^'"]*\$/s/ *([|&:,<>=*/%+-]) */\1/g  # Remove spaces before/after operators
``````

• 缩进在输入代码中假定为正好4个空格。

### 测试如下：

``````\$ cat qs.py fizzbuzz.py cards.py | wc -c
1390
\$ sed -rf pygolf.sed qs.py fizzbuzz.py cards.py | wc -c
1074
\$ sed -rf pygolf.sed qs.py fizzbuzz.py cards.py | python
[-1, 0, 2, 3, 7, 8, 10, 57]
1
2
Fizz
...
98
Fizz
Buzz
Hand 11982
AH AS 4H AC 2D 6S TS JS
3D 3H QS QC 8S 7H AD KS
KD 6H 5S 4D 9H JH 9S 3C
JC 5D 5C 8C 9D TD KH 7C
6C 2C TH QH 6D TC 4S 7S
JD 7D 8H 9C 2H QD 4C 5H
KC 8D 2S 3S
\$
``````

@NathanMerrill是的。运算符的前导/尾随空格现在好一点了，但是缩进一个将很难概括-这就是我获得大约2/3的增益的地方。
Digital Trauma 2015年

3

# Python 3.4、1134

``````import subprocess
from sys import argv

if 'argv' in progamtext or 'input' in progamtext or 'open' in programtext:#Make sure the program always produces the same results.
exit(0)

program = subprocess.Popen(['C:\Python27\python', argv[1]], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
program.wait()
program = subprocess.Popen(['C:\Python27\python', argv[1]], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
program.wait()
if erroroutput1 != erroroutput2 or output1 != output2:#Make sure the program always produces the same results.
exit(0)

newprog = ''
if erroroutput1:
newprog += "import sys\n" + "sys.stderr.write("+ erroroutput1 + ')'
if output1:
newprog += "\n"
if output1:
newprog += 'print ' + output1

if len(newprog) > len(progamtext):
exit(0)

open(argv[1],mode='w').write(newprog)``````

# 怎么运行的：

Sp3000的程序经过优化：

``````import sys
sys.stderr.write(b'')
print b'0.540377721372\r\n3\r\n1\r\n7\r\n99\r\nf\r\n[5, 5]\r\n53\r\n53\r\n53\r\n'``````

Sp3000的超级奖励计划，已优化：

``````import sys
sys.stderr.write(b'')
print b'B\r\n'``````

1

Martin Ender 2015年

2

Sp3000

@Martin固定（大部分）。:)
TheNumberOne 2015年

3