-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
HW8 solution #17
base: main
Are you sure you want to change the base?
HW8 solution #17
Conversation
As you said in the comments, convert_and_replace() can be improved using list comprehension (and I still strongly feel that I skipped smth), but I have only this solution for now. I'm still wondering what I should change here. I'm unsure about the function's name because it's not only "convert and replace" but also its sum. |
result = [] | ||
for elem in lst: | ||
try: | ||
# Added strip() in case of unpredictable spaces | ||
result.append([int(num.strip()) for num in elem.split(',')]) | ||
except ValueError: | ||
result.append("I can't do that!") # Add msg if unable to convert |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is no need to iterate over the list twice
In direct action we return sum of list comprehension in case of error we return phrase
def convert_and_replace(lst): | ||
""" | ||
Process a list by summing sublists or replacing with a message. | ||
|
||
Args: | ||
lst (list): List of sublists or messages. | ||
Returns: | ||
list: List with either sums of integers or replacement message. | ||
""" | ||
for indx, sublist in enumerate(lst): | ||
if isinstance(sublist, list): # Check if sublist is list | ||
try: | ||
lst[indx] = sum(sublist) # Sum if list with int | ||
except TypeError: | ||
lst[indx] = "I can't do that!" | ||
return lst |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
According prev comment this function will be absolutely redundant .
It just adds complexity with additional iterations and errors handling
req_lst = ['1,2,3,4', '1,2,3,4,50', 'qwerty1,2,3'] | ||
# Call the functions | ||
result = convert_and_replace(split_and_convert(req_lst)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here you could have list comprehension with target function call for each element to get sum or text
I optimized my solution six times. I don't know; maybe it can be even shorter.