初见Python解题之道(八)

Item

  小明同学要进行IQ测试,题目是给出一字符串,该字符串包含空格和数字,空格为每个数字单元的间隔,请找出相对于其他单元与众不同、独一无二的那个单元,并返回其位置

题目来源:Codewars(6kyu)
题目原文:Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number.

Example

例1
如果number = “1 1 1 8 1”
那么返回 4
例2:
如果number = “2 4 9 8 10”
那么返回 3
例3
如果number = “1 3 1”
那么返回 2

Knowledge

  1. 数据类型:整数型(int)
  2. 运算符:比较运算符、逻辑运算符
  3. 容器:Range()整数列表
  4. 其他:for-if结构、取余判断整数、for循环体简写

Parsing

  1. 实现这种效果,可刚可柔,此处采取“柔性”的方法;
  2. 原字符串必须简单处理成列表,去空格的方法有很多,此处个人仅使用split方法
  3. 列表有了,但是列表中的数字元素是否进一步转换成int类型,那有待下一步分析后才能确定;
  4. 观察元素,非常复杂,硬刚肯定伤肝伤肺,而这些元素终究分成两面,不妨利用一下0和1,也就是转成二进制序列;
  5. 转换成int类型,并且除以2取余,得到二进制序列;
  6. 这里就涉及到分类讨论了,根据MECE分析法第一类,那就是序列中共同有0和1的情况,第二类,仅含有0或者1的情况;
  7. 框架基本上就拿捏了,IF(1出现1次)-ELIF(0出现1次)-ELSE;
  8. 利用List count方法,统计0,1的出现次数处理第一类;
  9. 利用转换成int而非二进制序列的列表,进行循环遍历,同样的上述方法捕捉对应元素出现的次数是否为1。

Code

def iq_test(numbers):
# Go to space and turn into a digital sequence
# 去除空格,且转换成数字列表
    iq_list = [int(iIq) for iIq in numbers.split(" ")]
# Binary thinking
# “二进制思想”,处理成0或者1,核心步骤
    iql = [i%2 for i in iq_list]
# At the same time, 0 and 1
# 同时有0和1的情况
    if iql.count(0) == 1 and iql.count(1) > 1:
        return iql.index(0)+1
    elif iql.count(1) == 1 and iql.count(0) > 1:
        return iql.index(1)+1
# 仅只含0或者1的情况
    else:
        for only in iq_list:
            if iq_list.count(only) == 1:
                return iq_list.index(only)+1
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

顾平安6

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值