In: Computer Science
Design a Python script that accepts as input a user-provided list and transforms it into a different list in preparation for data analysis, the transformed list replaces each numeric element in the original list with its base-10 order of magnitude and replaces string elements with blanks.
Example:
This script accepts as input a user-provided list expected to contain non-zero numbers and strings. It then prints a transformed list replacing numbers with their order of magnitude, and strings as blanks.
Type list here, separated by commas, but without any brackets or parentheses: 45,0,"",,hfe8r34, 12.0,0.3744,3489,d3
Transformed list is [1, '', '', '', '', 1, 0, 3, '']
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
import math
#method to transform a value into base-10 order of magnitude if
it is numeric
#else return an empty string
def transform(value):
#using try except block, converting value to
float and finding order_magnitude using
#log10 function
try:
order_magnitude=math.log10(float(value))
#if no exception
occurred, returning integer value of order_magnitude
return int(order_magnitude)
except:
#exception occurred,
returning empty string
return ''
#asking and reading input
print('Type list here, separated by commas, but without any
brackets or parentheses:')
str_array=input().split(',') #reads a line of
text, splits by ',' to create a list
transformed_list=[] #empty list to store transformed
elements
#ooping through each element in str_array
for i in str_array:
#tranforming i and assigning to value
value=transform(i)
#appending to transformed_list
transformed_list.append(value)
#printing transformed_list
print('Transformed list is',transformed_list)
#OUTPUT
Type list here, separated by commas, but without any brackets or parentheses:
45,0,"",,hfe8r34, 12.0,0.3744,3489,d3
Transformed list is [1, '', '', '', '', 1, 0, 3, '']