高尔夫代码:格雷码 [英] Code Golf: Gray Code

查看:115
本文介绍了高尔夫代码:格雷码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按字符数计数的最短程序,输出n位灰色代码 n 是小于 1000 100000 <的任意数字/ code>(由于用户建议),取自标准输入。格雷码将打印在标准输出中,例如在示例中。

The shortest program by character count that outputs the n-bit Gray Code. n will be an arbitrary number smaller than 1000100000 (due to user suggestions) that is taken from standard input. The gray code will be printed in standard output, like in the example.

注意:我不希望程序执行此操作在合理的时间内打印出格雷码( n = 100000 是过大的);我确实希望它能够开始打印。

Note: I don't expect the program to print the gray code in a reasonable time (n=100000 is overkill); I do expect it to start printing though.

输入

4

预期产量

0000
0001
0011
0010
0110
0111
0101
0100
1100
1101
1111
1110
1010
1011
1001
1000


推荐答案

Python-53个字符



Python - 53 chars

n=1<<input()
for x in range(n):print bin(n+x^x/2)[3:]

此54 char版本克服了Python2中范围的限制,因此n = 100000可以工作!

This 54 char version overcomes the limitation of range in Python2 so n=100000 works!

x,n=0,1<<input()
while n>x:print bin(n+x^x/2)[3:];x+=1

69个字符

G=lambda n:n and[x+y for x in'01'for y in G(n-1)[::1-2*int(x)]]or['']

75个字​​符

G=lambda n:n and['0'+x for x in G(n-1)]+['1'+x for x in G(n-1)[::-1]]or['']

这篇关于高尔夫代码:格雷码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆