Open utterances-bot opened 1 year ago
Check if a List Contains All Elements of Another List:
I prefer to use self.assertEqual(set([1,2,3]) - set([1,2,3, 4])), set())
.
also you can simplify: random_str = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=10))
to: random_str = ''.join(random.choices(string.ascii_lowercase, k=10))
also you can simplify: random_str = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=10))
to: random_str = ''.join(random.choices(string.ascii_lowercase, k=10))
I’ll definitely look into this and this looks much cleaner than what I shared
thank you for the suggestion
Check if a List Contains All Elements of Another List:
I prefer to use
self.assertEqual(set([1,2,3]) - set([1,2,3, 4])), set())
.
Just out of curiosity is there any trade off using one over the other
Much more efficient one-lined way to list flattening is
outer = [[1, 4], [3, 4]]
flatten_list = [item for pair in outer for item in pair]
# [1, 4, 3, 4]
The suggestion for "Remove Duplicates from a List" list(set(my_list))
loses order though.
It's funny, Haskell has a reputation as being "hard", yet most things would be similar or sometimes even easier:
-- Reverse a String:
reverseString = reverse "Hello World"
-- Check if a Number is Even:
-- even/odd are predefined, no need to make your own
-- Find the Intersection of Two Lists:
intersection = list1 `intersect` list2 -- or intersect list1 list2
-- Remove Duplicates from a List:
noDuplicates = nub myList -- preserves order
-- Calculate the Length of a String without Using length:
lengthWithOutFunction = sum [1 | _ <- "Hello World"]
-- Check if a List Contains All Elements of Another List:
containsAll = list2 `isInfixOf` list1 -- or isInfixOf list2 list1
-- Generate a String of Random Characters:
-- Python wins here, but something like this with the System.Random package
take 10 (randomRs ('a', 'z') newStdGen)
-- Convert a List of Integers to a Single Number:
num = read . concatMap show $ [1, 2, 3, 4, 5] :: Int
-- Palindromic Check:
isPalindrome s = s == reverse s
-- List Flattening
concat [[1, 2], [3, 4], []]
-- Find the Most Frequent Element in a List:
head . maximumBy (comparing length) . group . sort $ list
-- Merge Two Maps:
mergedMap = union m1 m2 -- left-biased, so may need to flip arguments
In the Merge Two Dictionaries
example, be aware that for any keys that appear in both dicts, the values from the second will replace the first.
This approach also works with more than two dicts and duplicate keys from dicts later in the list will replace those earlier in the list.
import random;
...
That semicolon is killing me 💀
nice, but why the heck would you need to find the length without using len()
? The only thing it changes is the performance (negatively) 😅
One Liners Python Edition | Muhammad
Simple Python One liner code snippets
https://muhammadraza.me/2023/python-oneliners/