首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Identicon发电机

Identicon发电机
EN

Code Review用户
提问于 2015-06-10 17:27:30
回答 1查看 521关注 0票数 6

我只是在玩Python,尝试重新熟悉它,因为我已经几年没有使用它了。我正在使用Python3,但据我所知,只要更改print语句,就很容易成为Python2。我正在生成类似于GitHub标识符的东西。

我知道两个可能的问题,一个是我不考虑一个奇怪的宽度,另一个是我的填充字符串将在对称的一半上反转,所以我不能使用类似[ ]的东西。

代码语言:javascript
复制
import random

def generateConnectedAvatar(fill="XX", empty="  ", height=10, width=10, fillpercent=0.4):
    halfwidth = int(width/2)
    painted = 0
    maxPainted = height*halfwidth*fillpercent
    adjacent = [(-1,-1), (-1,0), (-1,1), (0,1), (0,-1), (1,-1), (1,0), (1,1)]
    # initialize a blank avatar                                                                                         
    avatar = [[empty for w in range(halfwidth)] for h in range(height)]
    # 'paint' a single cell and add it to the stack                                                                     
    y, x = random.randint(0,height-1), random.randint(0,halfwidth-1)
    lst = [(y,x)]
    while (len(lst) != 0):
        # Take the first element off the list                                                                           
        y, x = lst.pop()
        # Determine if we should paint it                                                                               
        if painted <= maxPainted:
            avatar[y][x] = fill
            painted += 1
            # Find all available neighbors and add them to the list (in a random order)                                 
            # shuffle our adjacent positions table                                                                      
            random.shuffle(adjacent)
            for posy, posx in adjacent:
                tmpy, tmpx = y + posy, x + posx
                if tmpx >= 0 and tmpx < halfwidth:
                    if tmpy >= 0 and tmpy < height:
                        # Make sure we haven't already painted it                                                       
                        if avatar[tmpy][tmpx] is not fill:
                            lst.append((tmpy,tmpx))
    # output the result (symmetrically)                                                                                 
    #   (in our case, just printing to console)                                                                         
    for h in range(height):
        half = ""
        for w in range(halfwidth):
            half += avatar[h][w]
        print(half + half[::-1])

输出有时看起来很整洁,但是它经常是块的,所以我可能想找出某种类型的间隔算法。

一些样本输出:

XX XXXX XX XX

EN

回答 1

Code Review用户

回答已采纳

发布于 2015-06-10 21:13:16

这很整齐。不过,我建议做一些改进。

该方法做了两件事:它生成一个同功点,然后打印它。最好将这两个操作分开,这样您就可以拥有遵循单一责任原则的功能。

while循环条件可以简化为更多的pythonic:

代码语言:javascript
复制
while lst:

范围条件也可以简化:

代码语言:javascript
复制
if 0 <= tmpx < halfwidth:

您的命名和间距应该遵循PEP8 ( python样式指南)。

票数 3
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/93245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档