Update syntax highlighting, update allUnique

This commit is contained in:
Angelos Chalaris
2019-08-20 10:09:53 +03:00
parent 59fd9ad9a8
commit 0f405f0da9
35 changed files with 73 additions and 72 deletions

View File

@ -1,17 +1,18 @@
---
title: all_unique
tags: list
tags: list,beginner
---
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.
Returns `True` if all the values in a flat list are unique, `False` otherwise.
``` python
Use `set()` on the given list to remove duplicates, compare its length with the length of the list.
```py
def all_unique(lst):
return len(lst) == len(set(lst))
```
``` python
```py
x = [1,2,3,4,5,6]
y = [1,2,2,3,4,5]
all_unique(x) # True

View File

@ -8,12 +8,12 @@ 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 `python3`.
```python
```py
def average(*args):
return sum(args, 0.0) / len(args)
```
``` python
```py
average(*[1, 2, 3]) # 2.0
average(1, 2, 3) # 2.0
```

View File

@ -5,7 +5,7 @@ tags: list
Bubble_sort uses the technique of comparing and swapping
```python
```py
def bubble_sort(lst):
for passnum in range(len(lst) - 1, 0, -1):
for i in range(passnum):
@ -14,7 +14,7 @@ def bubble_sort(lst):
```
```python
```py
lst = [54,26,93,17,77,31,44,55,20]
bubble_sort(lst)
print("sorted %s" %lst) # [17,20,26,31,44,54,55,77,91]

View File

@ -6,12 +6,12 @@ Returns the length of a string in bytes.
`utf-8` encodes a given string, then `len` finds the length of the encoded string.
```python
```py
def byte_size(string):
return(len(string.encode('utf-8')))
```
```python
```py
byte_size('😀') # 4
byte_size('Hello World') # 11
```

View File

@ -6,12 +6,12 @@ Capitalizes the first letter of a string.
Capitalizes the first letter of the string and then adds it with rest of the string. Omit the `lower_rest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase.
```python
```py
def capitalize(string, lower_rest=False):
return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:])
```
```python
```py
capitalize('fooBar') # 'FooBar'
capitalize('fooBar', True) # 'Foobar'
```

View File

@ -6,11 +6,11 @@ Capitalizes the first letter of every word in a string.
Uses `str.title` to capitalize first letter of every word in the string.
```python
```py
def capitalize_every_word(string):
return string.title()
```
```python
```py
capitalize_every_word('hello world!') # 'Hello World!'
```

View File

@ -6,7 +6,7 @@ Chunks an list into smaller lists of a specified size.
Uses `range` to create a list of desired size. Then use `map` on this list and fill it with splices of `lst`.
```python
```py
from math import ceil
@ -16,6 +16,6 @@ def chunk(lst, size):
list(range(0, ceil(len(lst) / size)))))
```
``` python
```py
chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]
```

View File

@ -6,11 +6,11 @@ Removes falsey values from a list.
Use `filter()` to filter out falsey values (False, None, 0, and "").
```python
```py
def compact(lst):
return list(filter(bool, lst))
```
``` python
```py
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]
```

View File

@ -8,7 +8,7 @@ Groups the elements of a list based on the given function and returns the count
Use `map()` to map the values of the list using the given function. Iterate over the map and increase the the elements count each time it occurs.
```python
```py
def count_by(arr, fn=lambda x: x):
key = {}
for el in map(fn, arr):
@ -17,7 +17,7 @@ def count_by(arr, fn=lambda x: x):
return key
```
``` python
```py
from math import floor
count_by([6.1, 4.2, 6.3], floor) # {4: 1, 6: 2}
count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}

View File

@ -8,11 +8,11 @@ Counts the occurrences of a value in a list.
Uses the list comprehension to increment a counter each time you encounter the specific value inside the list.
```python
```py
def count_occurrences(lst, val):
return len([x for x in lst if x == val and type(x) == type(val)])
```
```python
```py
count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3
```

View File

@ -6,7 +6,7 @@ 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.
```python
```py
import re
def count_vowels(str):

View File

@ -6,12 +6,12 @@ Decapitalizes the first letter of a string.
Decapitalizes the first letter of the string and then adds it with rest of the string. Omit the `upper_rest` parameter to keep the rest of the string intact, or set it to `true` to convert to uppercase.
```python
```py
def decapitalize(string, upper_rest=False):
return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:])
```
```python
```py
decapitalize('FooBar') # 'fooBar'
decapitalize('FooBar', True) # 'fOOBAR'
```

View File

@ -6,7 +6,7 @@ Deep flattens a list.
Use recursion. Use `list.extend()` with an empty list (`result`) and the spread function to flatten a list. Recursively flatten each element that is a list.
```python
```py
def spread(arg):
ret = []
for i in arg:
@ -24,6 +24,6 @@ def deep_flatten(lst):
return result
```
```python
```py
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
```

View File

@ -6,11 +6,11 @@ Returns the difference between two iterables.
Use list comprehension to only keep values not contained in `b`.
```python
```py
def difference(a, b):
_b = set(b)
return [item for item in a if item not in _b]
```
``` python
```py
difference([1, 2, 3], [1, 2, 4]) # [3]
```

View File

@ -6,13 +6,13 @@ Returns the difference between two list, after applying the provided function to
Create a `set` by applying `fn` to each element in `b`, then use list comprehension in combination with fn on a to only keep values not contained in the previously created `set`.
```python
```py
def difference_by(a, b, fn):
b = set(map(fn, b))
return [item for item in a if fn(item) not in b]
```
```python
```py
from math import floor
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]

View File

@ -6,13 +6,13 @@ Calculates the factorial of a number.
Use recursion. If `num` is less than or equal to `1`, return `1`. Otherwise, return the product of `num` and the factorial of `num - 1`. Throws an exception if `num` is a negative or a floating point number.
```python
```py
def factorial(num):
if not ((num >= 0) & (num % 1 == 0)):
raise Exception(
f"Number( {num} ) can't be floating point or negative ")
return 1 if num == 0 else num * factorial(num - 1)
```
``` python
```py
factorial(6) # 720
```

View File

@ -9,7 +9,7 @@ First, it picks the number `A` in range `1`..`(n-1)`, then it checks if `A` to t
If not, the number is not prime, else it's pseudoprime with probability 1/2. Applying this test `k `times we have probability `1/(2^k)`.
For example, if the number passes the test `10` times, we have probability `0.00098`.
``` python
```py
from random import randint
@ -24,7 +24,7 @@ def fermat_test(n, k=100):
```
``` python
```py
fermat_test(0) # False
fermat_test(1) # False
fermat_test(561) # False

View File

@ -6,7 +6,7 @@ Generates an array, containing the Fibonacci sequence, up until the nth term.
Starting with 0 and 1, adds the sum of the last two numbers of the list to the end of the list using ```list.append()``` until the length of the list reaches n. If the given nth value is 0 or less, the method will just return a list containing 0.
``` python
```py
def fibonacci(n):
if n <= 0:
return [0]
@ -20,6 +20,6 @@ def fibonacci(n):
return sequence
```
``` python
```py
fibonacci(7) # [0, 1, 1, 2, 3, 5, 8, 13]
```

View File

@ -7,14 +7,14 @@ Returns the n-th term in a Fibonnaci sequence that starts with 1
A term in a Fibonnaci sequence is the sum of the two previous terms.
This function recursively calls the function to find the n-th term.
``` python
```py
def fibonacci_until_num(n):
if n < 3:
return 1
return fibonacci_until_num(n - 2) + fibonacci_until_num(n - 1)
```
``` python
```py
fibonnaci_until_num(5) # 5
fibonnaci_until_num(15) # 610
```

View File

@ -6,7 +6,7 @@ Calculates the greatest common divisor of a list of numbers.
Uses the reduce function from the inbuilt module `functools`. Also uses the `math.gcd` function over a list.
```python
```py
from functools import reduce
import math
@ -14,6 +14,6 @@ def gcd(numbers):
return reduce(math.gcd, numbers)
```
``` python
```py
gcd([8,36,28]) # 4
```

View File

@ -6,12 +6,12 @@ Checks a flat list for duplicate values. Returns True if duplicate values exist
This function compares the length of the list with length of the set() of the list. set() removes duplicate values from the list.
``` python
```py
def has_duplicates(lst):
return len(lst) != len(set(lst))
```
``` python
```py
x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
has_duplicates(x) # True

View File

@ -4,7 +4,7 @@ tags: list
---
On a very basic level, an insertion sort algorithm contains the logic of shifting around and inserting elements in order to sort an unordered list of any size. The way that it goes about inserting elements, however, is what makes insertion sort so very interesting!
```python
```py
def insertion_sort(lst):
for i in range(1, len(lst)):
@ -16,7 +16,7 @@ def insertion_sort(lst):
lst[j + 1] = key
```
```python
```py
lst = [7,4,9,2,6,3]
insertionsort(lst)
print('Sorted %s' %lst) # sorted [2, 3, 4, 6, 7, 9]

View File

@ -7,7 +7,7 @@ Determine if 2 strings are anagrams.
Returns true if 2 strings are anagrams of each other, false otherwise.
Capital letters and whitespaces are ignored.
``` python
```py
def is_anagram(str1, str2):
str1, str2 = str1.replace(" ", ""), str2.replace(" ", "")
@ -17,6 +17,6 @@ def is_anagram(str1, str2):
return sorted(str1.lower()) == sorted(str2.lower())
```
``` python
```py
is_anagram("anagram", "Nag a ram") # True
```

View File

@ -6,12 +6,12 @@ Checks if a string is lower case.
Convert the given string to lower case, using `str.lower()` method and compare it to the original.
```python
```py
def is_lower_case(string):
return string == string.lower()
```
```python
```py
is_lower_case('abc') # True
is_lower_case('a3@$') # True
is_lower_case('Ab4') # False

View File

@ -6,12 +6,12 @@ Checks if a string is upper case.
Convert the given string to upper case, using `str.upper()` method and compare it to the original.
```python
```py
def is_upper_case(string):
return string == string.upper()
```
```python
```py
is_upper_case('ABC') # True
is_upper_case('a3@$') # False
is_upper_case('aB4') # False

View File

@ -6,12 +6,12 @@ Function which accepts a dictionary of key value pairs and returns a new flat li
Uses the .keys() method of "dict" objects. dict.keys() returns a view object that displays a list of all the keys. Then, list(dict.keys()) returns a list that stores all the keys of a dict.
``` python
```py
def keys_only(flat_dict):
return list(flat_dict.keys())
```
``` python
```py
ages = {
"Peter": 10,
"Isabel": 11,

View File

@ -8,7 +8,7 @@ Use the `greatest common divisor (GCD)` formula and the fact that `lcm(x,y) = x
Uses `reduce` function from the inbuilt module `functools`. Also defines a method `spread` for javascript like spreading of lists.
```python
```py
from functools import reduce
@ -36,7 +36,7 @@ def lcm(*args):
```
``` python
```py
lcm(12, 7) # 84
lcm([1, 3, 4], 5) # 60
```

View File

@ -6,12 +6,12 @@ Returns the `n` maximum elements from the provided list. If `n` is greater than
Use `list.sort()` combined with the `deepcopy` function from the inbuilt `copy` module to create a shallow clone of the list and sort it in ascending order and then use `list.reverse()` reverse it to make it descending order. Use `[:n]` to get the specified number of elements. Omit the second argument, `n`, to get a one-element list
```python
```py
def max_n(lst, n=1, reverse=True):
return sorted(lst, reverse=reverse)[:n]
```
```python
```py
max_n([1, 2, 3]) # [3]
max_n([1, 2, 3], 2) # [3,2]
```

View File

@ -6,7 +6,7 @@ Returns the `n` minimum elements from the provided list. If `n` is greater than
Use `list.sort()` combined with the `deepcopy` function from the inbuilt `copy` module to create a shallow clone of the list and sort it in ascending order. Use `[:n]` to get the specified number of elements. Omit the second argument, `n`, to get a one-element list
```python
```py
from copy import deepcopy
@ -16,7 +16,7 @@ def min_n(lst, n=1):
return numbers[:n]
```
```python
```py
min_n([1, 2, 3]) # [1]
min_n([1, 2, 3], 2) # [1,2]
```

View File

@ -6,12 +6,12 @@ Returns `True` if the given string is a palindrome, `False` otherwise.
Convert string `str.lower()` and use `re.sub` to remove non-alphanumeric characters from it. Then compare the new string to the reversed.
```python
```py
def palindrome(string):
from re import sub
s = sub('[\W_]', '', string.lower())
return s == s[::-1]
```
```python
```py
palindrome('taco cat') # True
```

View File

@ -8,7 +8,7 @@ Randomizes the order of the values of an list, returning a new list.
Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list.
```python
```py
from copy import deepcopy
from random import randint
@ -23,7 +23,7 @@ def shuffle(lst):
return temp_lst
```
``` python
```py
foo = [1,2,3]
shuffle(foo) # [2,3,1] , foo = [1,2,3]
```

View File

@ -4,7 +4,7 @@ tags: list
---
Implements javascript's `[].concat(...arr)`. Flattens the list(non-deep) and returns an list.
```python
```py
def spread(arg):
ret = []
for i in arg:
@ -16,6 +16,6 @@ def spread(arg):
```
```python
```py
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]
```

View File

@ -6,11 +6,11 @@ Returns the unique elements in a given list.
The given `list` is first converted to a `set` using the `set()` function. By definition, a `set` cannot have duplicate elements. So, the duplicate elements are automatically removed. Before returning, we convert it back to a `list`
``` python
```py
def unique_elements(li):
return list(set(li))
```
``` python
```py
unique_elements([1, 2, 2, 3, 4, 3]) # [1, 2, 3, 4]
```

View File

@ -6,7 +6,7 @@ Function which accepts a dictionary of key value pairs and returns a new flat li
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.
``` python
```py
def values_only(dict):
lst = []
for k, v in dict.items():
@ -14,7 +14,7 @@ def values_only(dict):
return lst
```
``` python
```py
ages = {
"Peter": 10,
"Isabel": 11,

View File

@ -8,7 +8,7 @@ Creates a list of elements, grouped based on the position in the original lists.
Use `max` combined with `list comprehension` to get the length of the longest list in the arguments. Loops for `max_length` times grouping elements. If lengths of `lists` vary `fill_value` is used. By default `fill_value` is `None`.
```python
```py
def zip(*args, fillvalue=None):
max_length = max([len(lst) for lst in args])
result = []
@ -19,7 +19,7 @@ def zip(*args, fillvalue=None):
return result
```
``` python
```py
zip(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]]
zip(['a'], [1, 2], [True, False]) # [['a', 1, True], [None, 2, False]]
zip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]]