I\'ve been presented with the task of turning a string of mixed numbers (\"1 3 5 8 10\"), for example, and my goal is to put these numbers into a list as integers.
I ha
def iq_test(numbers):
nums = []
for num in numbers.split():
nums.append(int(num))
I guess ... you could(and probably should) just do a list comprehension instead
nums = [int(num) for num in numbers.split()]
You're using wrong array for iteration and also doing some wrong conversions:
def iq_test(numbers):
print(numbers)
nums = []
for number in numbers.split(" "):
nums.append(int(number))
print(nums)
You can use regular expressions:
import re
s = "1 3 5 8 10"
final_data = list(map(int, re.findall('\d+', s)))
print(final_data)
Output:
[1, 3, 5, 8, 10]
First, numbers.split(" ")
on its own isn't doing anything useful. Assign it to a variable. Also, if you give no parameters, it will always split on spaces, so you can use that.
nums = numbers.split()
With that, you should use for num in nums
to loops over the split elements rather than looping over characters of the input string.
In any case, you can shorten all of this by using a list-comprehension to apply that int function and return the list of integers.
And you've defined a function, so you should return
the value, not only print it.
nums = [int(s) for s in numbers.split()]
return nums
And then you would print(iq_test("1 2 3 10"))