Question
Normalize a list of numbers so the sum of all numbers in the list is equal to 1. I suppose to Debug this code so
Normalize a list of numbers so the sum of all numbers in the list is equal to 1.
I suppose to Debug this code so it works for the test cases:
def normalize(lst):
s = sum(lst)
return list(map(lambda v: v / s, lst))
This code works correctly for normalize([1, 2, 5, 4]) but fails for normalize([1, 2, -7, 4]). What causes the second test case to fail? Find out the error message and keep the list as it is when the error occurs by simply return the list. So without modifying the normalize function, implement this strategy in the safe_normalize function. Complete safe_normalize. You may assume that the normalize function has already been defined for you.
What I came up with(can only pass one test case):
def safe_normalize(lst): def normalize(lst): s = sum(lst) if s == 0: return s elif s!= 0: new_s = s return list(map(lambda v: v / new_s, lst)) return normalize(lst)
Please help!!
test cases:
safe_normalize([1, 2, 2, 3]) | [0.125, 0.25, 0.25, 0.375] | ||
safe_normalize([1, 2, -5, 2]) | [1, 2, -5, 2] |
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started