0
点赞
收藏
分享

微信扫一扫

Take a Ten Minutes Walk--codewar刷题总结

_鱼与渔_ 2022-04-29 阅读 47
python

You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. ['n', 's', 'w', 'e']). You always walk only a single block for each letter (direction) and you know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.

 首先得明白解题的思路,先把所有大于十的列表都排除掉,一个计一分钟,这个肯定超时了。然后,我们可以设置两个都为零的变量,如果往北走一次,变量加一,往南走一次,这个变量减一,另一个变量是用来记录东和西的行走过程。最后如果两个变量都成为了零,说明我们回到了起点。

看一下我的解决方案

def is_valid_walk(walk):
    x,y=0,0
    if len(walk)==10:
        for i in walk:
            if i=='n':
                x+=1
            elif i=='s':
                x-=1
            elif i=='w':
                y+=1
            elif i=='e':
                y-=1
        if x==0 and y==0:
            return True
        else:
            return False
    else:
        return False

 再看一下别人的解决方案

def isValidWalk(walk):
    if (walk.count('n') == walk.count('s') and 
        walk.count('e') == walk.count('w') and
        len(walk) == 10):
            return True
    return False
举报

相关推荐

0 条评论