I keep getting error messages during line six and I am not sure why. It keeps saying that not all values are being converted during string formatting. I am trying to create a program that identifies a unique number out of a string of numbers.
def iq_test(numbers):
oddlist = []
evenlist = []
numbers = numbers.split()
for x in numbers:
if x % 2 == 0:
evenlist.append(x)
if x % 2 != 0:
oddlist.append(x)
if len(evenlist) > len(oddlist):
return "".join(oddlist)
else:
return "".join(evenlist)
Python's split
function returns a list of Strings. So every x
value in your for
loop is actually a String representation of whatever number x
is. That means any arithmetic/numerical operation you perform on x
will fail because you can't perform numerical operations on a String.
Simply do int(x)
to cast any numerical String to an int
. (ie int("3") % 2 == 1
)
It looks like this function is supposed to return the shorter list of even numbers or odd numbers from an input list. After your .split()
the result is a list of strings, so the math is basically doing this:
>>> "1" % 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
Here's the fix:
def iq_test(numbers):
oddlist = []
evenlist = []
# Splitting the input strings returns a list of strings.
# Use a list comprehension to convert them to integers.
numbers = [int(x) for x in numbers.split()]
for x in numbers:
if x % 2 == 0:
evenlist.append(x)
else: # Can just use an else here
oddlist.append(x)
if len(evenlist) > len(oddlist):
return oddlist # No need for the join now
else:
return evenlist # No need for join.
data = input('Numbers? ')
result = iq_test(data)
print(result)
Output:
Numbers? 1 2 3 4 5
[2, 4]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.