Python script won't work with lists

@yyi is right. The problem here is that the code doesn’t accept different types of inputs (single integer or list of integers, single list of strings or nested lists, etc.)

What I would do is adapt the code to the worst case scenario for each case, being this when you have nested list of strings for the first one and a list of integers for the second. Pay attention to the if statement using isinstance().

Remove Characters

import re

inputList = IN[0]
outputList = []

def RemoveCharacters(listOfItems):
	tempList = []
	for i in lst:
	    b = re.sub('[a-zA-Z]+', '', i)
	    tempList.append(b)
	return tempList

#This will wrap the input inside a list in case the input is
#not a list of nested lists.
if not isinstance(inputList[0], list):
	inputList = [inputList]

for lst in inputList:
	processedList = RemoveCharacters(lst)
	outputList.append(processedList)

#Assign your output to the OUT variable.
OUT = outputList

Sum

inputList = IN[0]
outputList = []

def digit_sum(n):
    sum_n = 0
    while n>0:
        sum_n += (n%10)
        n=n//10
    return sum_n


#This will wrap the input  inside a list in case the input is
#not a list.
if not isinstance(inputList, list):
	inputList = [inputList]
	
	
for n in inputList:
	processed = digit_sum(n)
	outputList.append(processed)

#Assign your output to the OUT variable.
OUT = outputList

6 Likes