LoginSignup
0
1

More than 5 years have passed since last update.

Basic data structure and Algorithms in Python

Last updated at Posted at 2019-03-14

1. Unpacking Variables

colors = ["red","green","blue"]
a,b,c = colors
print(a)
# red

2. Unpacking Group of Variables

fruits = ["orange","apple","kiwi","strawberry","grape"]
a, *b, c = fruits
print(b)
# ["apple","kiwi","strawberry"]

3. Finding the Largest/Smallest N Items

from heapq import nlargest, nsmallest
numbers = [1,2,3,4,5,6,7,8,9]
three_largest = nlargest(3,numbers)
print(three_largest)
# [7,8,9]
three_smallest = nsmallest(3,numbers)
print(three_smallest)
# [1,2,3]

4. The defaultdict

d={}
print(d["a"])
# Error

from collections import defaultdict
d = defaultdict(list)
print(d["a"])
# []

5. Keeping the Dictionaries Order

from collections import OrderedDict
d = OrderedDict()
d["a"] = 1
d["b"] = 2
d["c"] = 3
d["d"] = 4
for key in d:
    print(key,d[key])
# a 1
# b 2
# c 3
# d 4

6. Calculate with Dictionaries

prices = {"orange":2.99,"apple":3.99,"kiwi":1.99,"melon":5.99}
min_price = min(zip(prices.keys(),prices.values()))
print(min_price)
# 1.99 "kiwi"
max_price = min(zip(prices.keys(),prices.values())
print(max_price)
# 5.99 "melon"

7. Finding Commonalities in Two Dictionaries

foo = {"x":1,"y":2,"z":3}
bar = {"x":2,"y":3,"a":4}
print(foo.keys() & bar.keys())
# {"x","y"}
print(foo.keys() - b.keys())
# {"z"}

8. Store slice in Variables

fruits = ["orange","apple","kiwi","strawberry","grape"]
a = slice(1,4)
sliced_fruits = fruits(a)
print(sliced_fruits)
# ["apple","kiwi","strawberry"]

9. Count the Items Appearance in a List

from collections import Counter
numbers = [1,2,5,2,1,2,3,5,6]
numbers_count = Counter(numbers)
print(numbers_count)
# Counter({2: 3, 1: 2, 5: 2, 3: 1, 6: 1})
top_three = numbers_count.most_common(3)
print(top_three)
# [(2, 3), (1, 2), (5, 2)]

10. Extracting a Subset of a Dictionary

prices = {"orange":2.99,"apple":3.99,"kiwi":1.99,"melon":5.99}
extracted = { key:value for key,value in prices.items() if value > 3 }
print(extracted)
# {'apple': 3.99, 'melon': 5.99}

11. Named Tuple Object

from collections import namedtuple
Fruit = namedtuple("Fruit",["price","color"])
banana = Fruit("2.99","yellow")
print(banana)
# Fruit(price='2.99', color='yellow')
print(banana.price)
# 2.99

12. Combining Multiple Mappings

from collections import ChainMap
a = {"x":1,"y":2,"z":3}
b = {"x":2,"y":3,"j":4}
c = ChainMap(a,b)
print(c["x"])
# 1
print(c["y"])
# 2
print(c["j"])
# 4
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1