Skip to content

Instantly share code, notes, and snippets.

@Hiromi-nee
Created September 1, 2021 16:11
Show Gist options
  • Save Hiromi-nee/ce0efd7aa5082ade392e7a6e009e8d4b to your computer and use it in GitHub Desktop.
Save Hiromi-nee/ce0efd7aa5082ade392e7a6e009e8d4b to your computer and use it in GitHub Desktop.
#### Function Examples ####
## New Function Introduction: isinstance(variable, type)
## Given a variable (e.g.: a,b,c) and a specific type (int, float, bool, str, list, dict, etc)
## isinstance(variable, type) checks if variable is of the specified type and returns True or False
## e.g.:
## a = 1
## isinstance(a, int) --returns--> True
## isinstance(a, str) --returns--> False
## Note the following:
## a = True
## isinstance(a, int) --returns--> True
## isinstance(a, bool) --returns--> True
## Retains only numbers in a given list, numbers must be converted to float type
def keep_numbers(my_list):
my_new_list = list()
for idx, item in enumerate(my_list):
if isinstance(item, int) or isinstance(item, float): # check if its any numerical type, incl boolean
my_new_list.append( float(item) )
elif isinstance(item, str): # is string
if item.isdigit():
my_new_list.append( float(item) )
# all other types will be ignored e.g. list, dict, tuple, etc
# done loop checking
return my_new_list
def sum_all_items(my_list):
pass
# TODO: Sum all items in a cleaned list
## TODO
## 1. Implement keep_strings function
a = [1,2,'123', '123a', 'abcde', True, False, 'can i has cake']
b = [234, 567, "five", "six", "seven", ['abc','def'], False, 888]
cleaned_list_a = keep_numbers(a)
cleaned_list_b = keep_numbers(b)
print(cleaned_list_a)
print(cleaned_list_b)
## The following will not run correctly if sum_all_items() is not implemented
# sum_a = sum_all_items(cleaned_list_a)
# sum_b = sum_all_items(cleaned_list_b)
# print(f'Sum of list a: {sum_a}')
# print(f'Sum of list b: {sum_b}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment