![](/img/trans.png)
[英]My Keras CNN return the same output value, how can I fix/improve my code
[英]How to fix my output of this code to return "correct"?
我是初学者,我才刚刚开始学习如何使用 python 代码。 我在这方面遇到了麻烦。 每当我输入正确的结果时,它都会显示它仍然不正确。 我想知道我错过了什么或我做错了什么。
array1 = ([5, 10, 15, 20, 25])
print("Question 2: What is the reverse of the following array?", array1)
userAns = input("Enter your answer: ")
array1.reverse()
arrayAns = array1
if userAns == arrayAns:
print("You are correct")
else:
print("You are incorrect")
当您使用input()
时,分配的变量将默认为string
类型,因此与数组进行比较时始终返回 false。
但是,如果您计划以字符串格式返回一个列表,您应该尝试使用ast.literal_eval()来评估您作为输入function 的答案传递的字符串。
考虑:
import ast
userAns = ast.literal_eval(input("Enter your answer: "))
发送后:
[25,20,15,10,5]
你会得到这样的结果:
You are correct
因为您作为问题答案传递的字符串 ('[25,20,15,10,5]') 将被评估并识别为列表,然后在将其与其他变量进行比较时,评估结果为 True。
input
仅返回一个str
值。 您必须将“反转”数组转换为str
或将输入转换为 numpy 数组。 第一个选项似乎更容易,可能是str(array1)
。
正如已经提到的,您正在尝试将作为字符串的用户输入与数组进行比较,因此在比较时它会出现 false。
我的解决方案是:
temp = userAns.split(",")
userAns = [int(item) for item in temp]
首先将字符串拆分成一个列表。 这将创建一个字符串数组。 接下来通过将每个项目类型从字符串更改为 int 来重新创建数组。 您最终得到一个整数数组,然后可以对其进行比较。
正如其他响应者所指出的,输入返回一个 str。 如果您愿意,可以要求用户以逗号分隔的格式输入值,然后使用 split() function 将字符串分解为以逗号分隔的数组,如下所示:
array1 = ([5, 10, 15, 20, 25])
print("Question 2: What is the reverse of the following array?", array1)
userAns = input("Enter your answer (comma delimited, please): ")
array1.reverse()
arrayAns = list(map( str, array1 ) )
if userAns.split(',') == arrayAns:
print("You are correct")
else:
print("You are incorrect")
这是示例 output:
Question 2: What is the reverse of the following array? [5, 10, 15, 20, 25]
Enter your answer (comma delimited, please): 25,20,15,10,5
You are correct
又一次运行——让我们确保它在输入错误值时能正常工作:
Question 2: What is the reverse of the following array? [5, 10, 15, 20, 25]
Enter your answer (comma delimited, please): 25,20,15,10,6
You are incorrect
由于用户正在输入字符串,因此我们需要将字符串与字符串进行比较。 因此,我使用下面的 map(str, array1) 调用将 array1 中的每个 integer 转换为字符串。
您还可以看到我使用 split(',') 将 userAns 拆分为一个数组。
相反的方法也是可能的。 我们可以从 array1 构建一个字符串,然后只比较这些字符串。 在这种情况下,我可以使用 join() function 从数组构建字符串:
arrayString = ','.join( arrayAns )
因此代码可能如下所示:
array1 = ([5, 10, 15, 20, 25])
print("Question 2: What is the reverse of the following array?", array1)
userAns = input("Enter your answer (comma delimited, please): ")
array1.reverse()
arrayAns = list(map( str, array1 ) )
arrayString = ','.join(arrayAns)
if userAns == arrayString:
print("You are correct")
else:
print("You are incorrect")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.