Skip to content

Instantly share code, notes, and snippets.

View SaraM92's full-sized avatar
🎯
Focusing

Sara Metwalli SaraM92

🎯
Focusing
View GitHub Profile
str1 = "hello"
str2 = "😀"
def str_size(s):
return len(s.encode('utf-8'))
str_size(str1)
str_size(str2)
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
#Invert the dictionary based on its content
#1- If we know all values are unique.
my_inverted_dict = dict(map(reversed, my_dict.items()))
#2- If non-unique values exist
from collections import defaultdict
#merge two or more dicts using the collections module
def merge_dicts(*dicts):
mdict = defaultdict(list)
for d in dicts:
for key in d:
mdict[key].append(d[key])
return dict(mdict)
mylist = ['blue', 'orange', 'green']
#Map the list into a dict using the map, zip and dict functions
mapped_dict = dict(zip(itr, map(fn, itr)))
a = ['blue', 'green', 'orange', 'purple', 'yellow']
b = [3, 2, 5, 4, 1]
#Use list comprehensions to sort these lists
sortedList = [val for (_, val) in sorted(zip(b, a), key=lambda x: \
x[0])]
my_list = ["blue", "red", "green"]
#1- Using sort or srted directly or with specifc keys
my_list.sort() #sorts alphabetically or in an ascending order for numeric data
my_list = sorted(my_list, key=len) #sorts the list based on the length of the strings from shortest to longest.
# You can use reverse=True to flip the order
#2- Using locale and functools
import locale
from functools import cmp_to_key
dicts_lists = [
{
"Name": "James",
"Age": 20,
},
{
"Name": "May",
"Age": 14,
},
{
def merge(*args, missing_val = None):
#missing_val will be used when one of the smaller lists is shorter tham the others.
#Get the maximum length within the smaller lists.
max_length = max([len(lst) for lst in args])
outList = []
for i in range(max_length):
result.append([args[k][i] if i < len(args[k]) else missing_val for k in range(len(args))])
return outList
keys_list = ['A', 'B', 'C']
values_list = ['blue', 'red', 'bold']
#There are 3 ways to convert these two lists into a dictionary
#1- Using Python's zip, dict functionz
dict_method_1 = dict(zip(keys_list, values_list))
#2- Using the zip function with dictionary comprehensions
dict_method_2 = {key:value for key, value in zip(keys_list, values_list)}
#for plotting in Jupyter
%pylab inline
#import needed library
from itertools import cycle
from mpl_toolkits.mplot3d import Axes3D
colors = cycle(‘bgrcmykbgrcmykbgrcmykbgrcmyk’)
# Define parameters for the walk
dims = 1
step_n = 10000
step_set = [-1, 0, 1]