Update remaining snippets

This commit is contained in:
Angelos Chalaris
2019-08-20 11:18:55 +03:00
parent a01dae2945
commit 62581cea2f
6 changed files with 54 additions and 48 deletions

View File

@ -1,17 +1,21 @@
--- ---
title: palindrome title: palindrome
tags: string tags: string,intermediate
--- ---
Returns `True` if the given string is a palindrome, `False` otherwise. 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. Use `str.lower()` and `re.sub()` to convert to lowercase and remove non-alphanumeric characters from the given string.
Then, compare the new string with its reverse.
```py ```py
from re import sub
def palindrome(string): def palindrome(string):
from re import sub s = sub('[\W_]', '', string.lower())
s = sub('[\W_]', '', string.lower()) return s == s[::-1]
return s == s[::-1]
``` ```
```py ```py
palindrome('taco cat') # True palindrome('taco cat') # True
``` ```

View File

@ -1,8 +1,7 @@
--- ---
title: shuffle title: shuffle
tags: list tags: list,random,intermediate
--- ---
:information_source: The same algorithm is already implemented via `random.shuffle`.
Randomizes the order of the values of an list, returning a new list. Randomizes the order of the values of an list, returning a new list.
@ -12,15 +11,14 @@ Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Y
from copy import deepcopy from copy import deepcopy
from random import randint from random import randint
def shuffle(lst): def shuffle(lst):
temp_lst = deepcopy(lst) temp_lst = deepcopy(lst)
m = len(temp_lst) m = len(temp_lst)
while (m): while (m):
m -= 1 m -= 1
i = randint(0, m) i = randint(0, m)
temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m] temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
return temp_lst return temp_lst
``` ```
```py ```py

View File

@ -1,21 +1,23 @@
--- ---
title: spread title: spread
tags: list tags: list,utility,intermediate
--- ---
Implements javascript's `[].concat(...arr)`. Flattens the list(non-deep) and returns an list.
Flattens a list, by spreading its elements into a new list.
Loop over elements, use `list.extend()` if the element is a list, `list.append()` otherwise.
```py ```py
def spread(arg): def spread(arg):
ret = [] ret = []
for i in arg: for i in arg:
if isinstance(i, list): if isinstance(i, list):
ret.extend(i) ret.extend(i)
else: else:
ret.append(i) ret.append(i)
return ret return ret
``` ```
```py ```py
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9] spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]
``` ```

View File

@ -1,14 +1,15 @@
--- ---
title: unique_elements title: unique_elements
tags: list tags: list,beginner
--- ---
Returns the unique elements in a given list. 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` Create a `set` from the list to discard duplicated values, then return a `list` from it.
```py ```py
def unique_elements(li): def unique_elements(li):
return list(set(li)) return list(set(li))
``` ```
```py ```py

View File

@ -1,24 +1,23 @@
--- ---
title: values_only title: values_only
tags: object tags: object,list,beginner
--- ---
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. Returns a flat list of all the values in a flat dictionary.
Use `dict.values()` to return the values in the given dictionary.
Return a `list()` of the previous result.
```py ```py
def values_only(dict): def values_only(dict):
lst = [] return list(flat_dict.values())
for k, v in dict.items():
lst.append(v)
return lst
``` ```
```py ```py
ages = { ages = {
"Peter": 10, "Peter": 10,
"Isabel": 11, "Isabel": 11,
"Anna": 9, "Anna": 9,
} }
values_only(ages) # [10, 11, 9] values_only(ages) # [10, 11, 9]
``` ```

View File

@ -1,22 +1,24 @@
--- ---
title: zip title: zip
tags: list tags: list,math,intermediate
--- ---
:information_source: Already implemented via `itertools.zip_longest()`
Creates a list of elements, grouped based on the position in the original lists. 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`.
Use `max` combined with `list comprehension` to get the length of the longest list in the arguments.
Loop for `max_length` times grouping elements.
If lengths of `lists` vary, use `fill_value` (defaults to `None`).
```py ```py
def zip(*args, fillvalue=None): def zip(*args, fillvalue=None):
max_length = max([len(lst) for lst in args]) max_length = max([len(lst) for lst in args])
result = [] result = []
for i in range(max_length): for i in range(max_length):
result.append([ result.append([
args[k][i] if i < len(args[k]) else fillvalue for k in range(len(args)) args[k][i] if i < len(args[k]) else fillvalue for k in range(len(args))
]) ])
return result return result
``` ```
```py ```py