Math
average
Math
average
statistics.mean. statistics.mean takes an array as an argument whereas this function takes variadic arguments.
Returns the average of two or more numbers.
-Takes the sum of all the args and divides it by len(args). The second argument 0.0 in sum is to handle floating point division in python2.
Takes the sum of all the args and divides it by len(args). The second argument 0.0 in sum is to handle floating point division in python3.
def average(*args):
return sum(args, 0.0) / len(args)
@@ -306,6 +306,19 @@ bubble_sort(lst)
print("sorted %s" %lst) # [17,20,26,31,44,54,55,77,91]
has_duplicates
Checks a flat list for duplicate values. Returns True if duplicate values exist and False if values are all unique.
+This function compares the length of the list with length of the set() of the list. set() removes duplicate values from the list.
+ +def has_duplicates(lst): + return len(lst) != len(set(lst))+ +
x = [1,2,3,4,5,5] +y = [1,2,3,4,5] +has_duplicates(x) # True +has_duplicates(y) # False+
String
count_vowels
Retuns number of vowels in provided string.
Use a regular expression to count the number of vowels (A, E, I, O, U) in a string.
Object
keys_only
Function which accepts a dictionary of key value pairs and returns a new flat list of only the keys.
+Uses the .items() function with a for loop on the dictionary to track both the key and value and returns a new list by appending the keys to it. Best used on 1 level-deep key:value pair dictionaries (a flat dictionary) and not nested data-structures which are also commonly used with dictionaries. (a flat dictionary resembles a json and a flat list an array for javascript people).
+ +def keys_only(flat_dict): + lst = [] + for k, v in flat_dict.items(): + lst.append(k) + return lst+ +
ages = {
+ "Peter": 10,
+ "Isabel": 11,
+ "Anna": 9,
+}
+keys_only(ages) # ['Peter', 'Isabel', 'Anna']
+values_only
Function which accepts a dictionary of key value pairs and returns a new flat list of only the values.
+Uses the .items() function with a for loop on the dictionary to track both the key and value of the iteration and returns a new list by appending the values to it. Best used on 1 level-deep key:value pair dictionaries and not nested data-structures.
+ +def values_only(dict): + lst = [] + for k, v in dict.items(): + lst.append(v) + return lst+ +
ages = {
+ "Peter": 10,
+ "Isabel": 11,
+ "Anna": 9,
+}
+values_only(ages) # [10, 11, 9]
+all_unique
Checks a flat list for all unique values. Returns True if list values are all unique and False if list values aren't all unique.
+This function compares the length of the list with length of the set() of the list. set() removes duplicate values from the list.
+ +def all_unique(lst): + return len(lst) == len(set(lst))+ +
x = [1,2,3,4,5,6] +y = [1,2,2,3,4,5] +all_unique(x) # True +all_unique(y) # False+