155k views
4 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.

User Pantsgolem
by
6.3k points

1 Answer

3 votes

Answer:

The solution code is written in Python 3.

  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(), that take one input which is a list of number, number_list. (Line 1)

Next, declare a new string list, str_list. (Line 2)

Use a for-loop to traverse the individual number in the number_list (Line 4) and add each of the number into the str_list. Please note, the individual number is converted to string type using Python str() method. (Line 5)

By now, the str_list should have a list of string type number. We can use join() method to join all the string element in the str_list into a single string and return it as an output. (Line 7) The "," acts as a separator between the element in the str_list.

We can test the function by passing a random list of number, (e.g. [22,33,44]) and the output shall be '22,33,44'. (Line 9 - 10)

User Sanjay Zalke
by
5.9k points