Take a Ten Minute Walk - 步行十分钟

我的个人博客

更多内容,请跳转我的个人博客

题目

Take a Ten Minute Walk

步行十分钟

描述

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.

Note: you will always receive a valid array containing a random assortment of direction letters (‘n’, ‘s’, ‘e’, or ‘w’ only). It will never give you an empty array (that’s not a walk, that’s standing still!).

你生活在卡特西亚市,那里所有的道路都以完美的网格布局。你提前十分钟到达,没有预约,所以你决定趁机去散散步。该市为市民的手机上提供了一个步行生成应用程序——每次你按下按钮,它都会向你发送一组表示步行方向的单字母字符串(如[n]、[s]、[w]、[e])。你总是只为每个字母(方向)走一个街区,你知道穿过一个城市街区需要一分钟,所以创建一个函数,如果应用程序给你的步行正好需要十分钟(你不想早或晚!),那么该函数将返回真值,当然,它会让你回到起点。否则返回false。

注意:您将始终收到一个包含随机方向字母组合的有效数组(“仅限n”、“s”、“e”或“w”)。它永远不会给你一个空数组(那不是散步,那是静止不动的!)。

例子

test.expect(is_valid_walk([‘n’,‘s’,‘n’,‘s’,‘n’,‘s’,‘n’,‘s’,‘n’,‘s’]), ‘should return True’);

test.expect(not is_valid_walk([‘w’,‘e’,‘w’,‘e’,‘w’,‘e’,‘w’,‘e’,‘w’,‘e’,‘w’,‘e’]), ‘should return False’);

test.expect(not is_valid_walk([‘w’]), ‘should return False’);

test.expect(not is_valid_walk([‘n’,‘n’,‘n’,‘s’,‘n’,‘s’,‘n’,‘s’,‘n’,‘s’]), ‘should return False’);

思路

其实本题的思路很简单,因为只要东 = 西,南 = 北,那么一定是能走到原点的,所以只要遍历列表,记录东西南北出现的次数即可,然后判断是否相等,就可以判断能否回到原点了

##完整代码

def is_valid_walk(walk):
    #determine if walk is valid
    # 东:e
    # 西:w
    # 南:s
    # 北:n
    # 如果长度不等于10,返回false
    if len(walk) != 10:
        return False
    # 创建一个列表,用来保存东西南北分别出现的次数
    record = [0] * 4
    # 遍历
    for val in walk:
        if val == "e":
            record[0] += 1
        elif val == "w":
            record[1] += 1
        elif val == "s":
            record[2] += 1
        elif val == "n":
            record[3] += 1
    # 判断此时e == w和s == n:
    if (record[0] == record[1]) and (record[2] == record[3]):
        return True
    else:
        return False
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值