python - Python 中的 IQ 测试功能未按预期工作
问题描述
我在下面的代码中遇到问题。
我的任务是创建一个函数,在给定的数字中找到一个不同的均匀度,并返回该数字的位置。数字以字符串形式给出。到目前为止,我已经设法将字符串转换为整数列表,然后使用for
循环遍历每个数字。
我遇到的问题是我设法只返回偶数中奇数的位置,我无法继续执行反之亦然的代码,因为它只返回奇数的位置数字。
这是代码:
def iq_test(numbers):
# Splitting the "numbers" string
num_split = numbers.split()
# converting the splitted strings into int
num_map = map(int, num_split)
# converting the object into list
list_num = list(num_map)
for n in list_num:
if not n%2 == 0:
return list_num.index(n) + 1
解决方案
您的问题是,您假设您正在搜索第一个偶数。你要做的,是首先决定,你在寻找什么。例如,您可以简单地首先计算偶数的数量。如果它是一个,那么你正在寻找一个偶数,否则,你正在寻找一个奇数。由于您不关心实际数字,因此我会将它们全部映射到它们的值 mod 2,如下所示:
num_map = list(map(lambda x: int(x) % 2, num_split))
然后,剩下的就很简单了。例如像这样:
def iq_test(numbers):
# Splitting the "numbers" string
num_split = numbers.split()
# converting the splitted strings into even (0) or odd (1)
num_map = list(map(lambda x: int(x) % 2, num_split))
# return the correct position based on if even or odd is in search
evens = num_map.count(0)
if evens == 1:
return num_map.index(0) + 1
else:
return num_map.index(1) + 1
推荐阅读
- machine-learning - Flux.jl:理解鸢尾花数据集下载源代码。为什么使用 SHA256 哈希?
- nunit - 在 NUnit 中调整测试名称
- python - 在 Python 中从 3D 数组创建 4D 数组
- android - 如何杀死由 NavHostFragment 创建的所有片段?
- java - 如何确定是否在十六进制字符串中设置了一个位?
- python - 使用python将pandas数据框插入actian PSQL数据库表
- xml - 使用 T-SQL 读取 XML
- python - 解析 JSON 对象时,保留字作为数据类中的属性名称
- javascript - 如何将 put 请求与 axios 连接以使其在前端工作?
- python - 我尝试在 python 中使用 tkinter 进行测验,由于某种原因,我不断收到错误消息