219 views
1 1 vote

Suppose you have a list of strings representing transaction amounts, some of which contain non-numeric characters $($e.g., "$\$$"$)$. You need to clean the data, convert the valid entries to integers, and calculate the total sum.

Which of the following code snippets correctly calculates the sum of $\verb|['10', '|$\$$\verb|20', '30', '40|$\$$\verb|']|$ after removing any ' $\$$ ' characters?

  1. $\verb|sum([int(i.strip('|$\$$\verb|')) for i in data])|$
     
  2. $\verb|total = 0; for i in data: total += int(i.replace('|$\$$\verb|', ''))|$
     
  3. $\verb|sum(map(lambda} x: int(x.replace('|$\$$\verb|', '')), data))|$
     
  4. ALL OF THE ABOVE

     

1 Answer

1 1 vote

OPTION A: Uses a list comprehension and the $\verb|.strip()|$ method. Since the ' $\$$ ' is at the beginning or end of the strings in the list, $\verb|strip('|$\$$\verb|')|$ effectively removes it before the string is cast to an $\verb|int|$.

OPTION B: Uses a standard $\verb|for|$ loop and the $\verb|.replace()|$ method. This is the most readable approach for beginners and correctly accumulates the sum in the $\verb|total|$ variable.

OPTION C: Uses $\verb|map()|$ and a $\verb|lambda|$ function. This is a functional programming approach that applies the replacement and integer conversion to every element in the list before passing the result to $\verb|sum()|$.

The correct answer is D) ALL OF THE ABOVE.

Answer:
Position:
Show:

Related questions

4 4 votes
1 1 answer
219
219 views
GO Classes asked Jan 8
219 views
Consider the following two functions $f(n)$ and $g(n)$ :$f(n)=\sum_{i=1}^n \log (i)$ $g(n)$ is defined by the recurrence relation: $T(n)=8 T(n / 2)+n^2$, where $g(n)=T(n)...
1 1 vote
1 1 answer
226
226 views
GO Classes asked Jan 8
226 views
You are designing a Hash Table using Chaining (also known as "Open Hashing") to handle collisions. In this system, multiple keys that hash to the same index are stored in...
0 0 votes
1 1 answer
207
207 views
GO Classes asked Jan 8
207 views
In a Binary Search Tree, for any given node, the value of the left child must be less than the parent, and the value of the right child must be greater than the parent.If...
2 2 votes
1 1 answer
201
201 views
GO Classes asked Jan 8
201 views
In Python, the $\verb|.get()|$ method is often used to avoid $\verb|KeyError|$ exceptions. Examine the code below:counts = {"apples": 10, "bananas": 5} result = counts.ge...