python - Creating a new list using for loop? -


i need write function normalizes vector (finds unit vector). vector can normalized dividing each individual component of vector magnitude.

the input function vector i.e. 1 dimensional list containing 3 integers.

the code follows:

def my_norml(my_list):     tot_sum = 0     item in my_list:         tot_sum = tot_sum + item**2     magng = tot_sum**(1/2)     norml1 = my_list[0]/magng #here want use loop      norml2 = my_list[1]/magng     norml3 = my_list[2]/magng     return [norml1, norml2,norml3] 

there's couple of things here.

initially, let me point out tot_sum = tot_sum + item**2 can written more concisely tot_sum += item**2. answer question, use loop achieve want with:

ret_list = [] in my_list:     ret_list.append(i / magng) return ret_list 

but isn't best approach. it way better utilize comprehensions achieve need; also, sum built-in function can summing instead of needing manually perform for-loop:

magng can computed in 1 line passing comprehension sum. comprehension raise each item ** 2 , divide summation sum returns:

magng = sum(item**2 item in my_list) ** (1/2) 

after this, can create new list again utilizing comprehension:

return [item/magng item in my_list] 

which creates list out of every item in my_list after dividing magng.

finally, full function reduced 2 lines (and 1 hamper readability):

def my_norml(my_list):     magng = sum(item**2 item in my_list) ** (1/2)     return [item/magng item in my_list] 

this more concise , idiomatic , pretty intuitive after you've learned comprehensions.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -