35.8k views
3 votes
The function below takes a single parameter, a list of numbers called number_list. Complete the function to return a string of the provided numbers as a series of comma separate values (CSV). For example, if the function was provided the argument [22, 33, 44], the function should return '22,33,44'. Hint: in order to use the join function you need to first convert the numbers into strings, which you can do by looping over the number list to create a new list (via append) of strings of each number.

1 Answer

5 votes

Answer:

The solution code is written in Python:

  1. def convertCSV(number_list):
  2. str_list = []
  3. for num in number_list:
  4. str_list.append(str(num))
  5. return ",".join(str_list)
  6. result = convertCSV([22,33,44])
  7. print(result)

Step-by-step explanation:

Firstly, create a function "convertCSV" with one parameter "number_list". (Line 1)

Next, create an empty list and assign it to a new variable str_list. (Line 2)

Use for-loop to iterate through all the number in the number_list.(Line 4). Within the loop, each number is converted to a string using the Python built-in function str() and then use the list append method to add the string version of the number to str_list.

Use Python string join() method to join all the elements in the str_list as a single string. The "," is used as a separator between the elements (Line 7) . At the end return the string as an output.

We can test the function by calling the function and passing [22,33,34] as an argument and we shall see "22,33,44" is printed as an output. (Line 9 - 10)

User Rashomon
by
5.4k points