0% found this document useful (0 votes)
266 views

I Made A Python Cheat Sheet For Data Structures and Algorithms (Useful For Leetcode) by Abdul Malik Medium

The document provides a cheat sheet for Python data structures and algorithms. It includes descriptions and examples of commonly used data structures like lists, dictionaries, counters, and deques. It also provides time complexities for different operations on each data structure.

Uploaded by

William Vera
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
266 views

I Made A Python Cheat Sheet For Data Structures and Algorithms (Useful For Leetcode) by Abdul Malik Medium

The document provides a cheat sheet for Python data structures and algorithms. It includes descriptions and examples of commonly used data structures like lists, dictionaries, counters, and deques. It also provides time complexities for different operations on each data structure.

Uploaded by

William Vera
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

Open in app Sign up Sign in

Search

I Made A Python Cheat Sheet for Data


Structures and Algorithms (Useful for
Leetcode)
Abdul Malik · Follow
8 min read · Jun 12, 2022

Listen Share

Python Cheat Sheet

Leave a � on Github (contributions welcome)

Click here for similar Java Resource since many comments asked (not made by me)

Get a PDF of this sheet at the end of the article.

If you’d like to see similar content consider following me to be updated with other such
Cheat Sheets.

Usage Guide
• Keep this guide open beside you while solving problems and take a look as

1 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

and when necessary.

• Read through this once just to get an idea of the possibilities with Python.

• (optional) Read this guide every few days or once a week for around 1 month.
You’ll automatically have most syntax in your mind (spaced repetition).

Basics
• Data Types

• Operators and it’s precendence

2 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

Data Structures
Important data structures for Leetcode

Lists

Lists are used to store multiple items in a single variable

• Operations Time Complexities

3 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

nums = [1,2,3]

nums.index(1) # returns index


nums.append(1) # appends 1
nums.insert(0,10) # inserts 10 at 0th index
nums.remove(3) # removes all instances of 3
nums.copy(1) # returns copy of the list
nums.count(1) # returns no.of times '1' is present in the list
nums.extend(someOtherList) # ...
nums.pop() # pops last element [which element to pop can also be
given as optional argument]
nums.reverse() # reverses original list (nums in this case)
nums.sort() # sorts list [does NOT return sorted list]
#Python's default sort uses Tim Sort, which is a combination of
both merge sort and insertion sort.

It's pretty simple really:

a[start:stop] # items start through stop-1


a[start:] # items start through the rest of the array
a[:stop] # items from the beginning through stop-1

4 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

a[:] # a copy of the whole array


There is also the step value, which can be used with any of the
above:

a[start:stop:step] # start through not past stop, by step


The key point to remember is that the :stop value represents the
first value that is not in the selected slice. So, the difference
between stop and start is the number of elements selected (if step
is 1, the default).

The other feature is that start or stop may be a negative number,


which means it counts from the end of the array instead of the
beginning. So:

a[-1] # last item in the array


a[-2:] # last two items in the array
a[:-2] # everything except the last two items
Similarly, step may be a negative number:

a[::-1] # all items in the array, reversed


a[1::-1] # the first two items, reversed
a[:-3:-1] # the last two items, reversed
a[-3::-1] # everything except the last two items, reversed
Python is kind to the programmer if there are fewer items than you
ask for. For example, if you ask for a[:-2] and a only contains
one element, you get an empty list instead of an error. Sometimes
you would prefer the error, so you have to be aware that this may
happen.

Relation to slice() object


The slicing operator [] is actually being used in the above code
with a slice() object using the : notation (which is only valid
within []), i.e.:

a[start:stop:step]
is equivalent to:

a[slice(start, stop, step)]


Slice objects also behave slightly differently depending on the
number of arguments, similarly to range(), i.e. both slice(stop)
and slice(start, stop[, step]) are supported. To skip specifying a
given argument, one might use None, so that e.g. a[start:] is
equivalent to a[slice(start, None)] or a[::-1] is equivalent to
a[slice(None, None, -1)].

While the :-based notation is very helpful for simple slicing, the
explicit use of slice() objects simplifies the programmatic
generation of slicing.

Dictionary

Dictionaries are used to store data values in key:value pairs. Info about
collections.Counter() available below.

5 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

• Operations Time Complexities

dict = {'a':1,'b':2,'c':3}

dict.keys() # returns list of keys of dictionary


dict.values() # returns list of values of dictionary
dict.get('a') # returns value for any corresponding key
dict.items() # returns [('a',1),('b',2),('c',3)]
dict.copy() # returns copy of the dictionary
# NOTE : items() Returns view object that will be updated with any
future changes to dict
dict.pop(KEY) # pops key-value pair with that key
dict.popitem() # removes most recent pair added
dict.setDefault(KEY,DEFAULT_VALUE) # returns value of key, if key
exists, else default value returned
# If the key exist, this parameter(DEFAULT_VALUE) has no effect.
# If the key does not exist, DEFAULT_VALUE becomes the key's
value. 2nd argument's default is None.
dict.update({KEY:VALUE}) # inserts pair in dictionary if not
present, if present, corresponding value is overridden(not key)
# defaultdict ensures that if any element is accessed that is not
present in the dictionary
# it will be created and error will not be thrown (which happens

6 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

in normal dictionary)
# Also, the new element created will be of argument type, for
example in the below line
# an element of type 'list' will be made for a Key that does not
exist
myDictionary = defaultdict(list)

Counter

Python Counter is a container that will hold the count of each of the elements
present in the container. The counter is a sub-class available inside the
dictionary class. Specifically used for element frequencies

Pretty similar to dictionary, infact I use defaultdict(int) most of the time

from collections import Counter #(capital 'C')


# can also be used as 'collections.Counter()' in code

list1 = ['x','y','z','x','x','x','y', 'z']

# Initialization
Counter(list1) # => Counter({'x': 4, 'y': 2, 'z': 2})
Counter("Welcome to Guru99 Tutorials!") # => Counter({'o': 3, ' ':
3, 'u': 3, 'e': 2.....})

# Updating
counterObject = collections.Counter(list1)
counterObject.keys() = [ 'x' , 'y' , 'z' ]
most_common_element = counterObject.most_common(1) # [('x', 4)]
counterObject.update("some string") # => Counter({'o': 3, 'u': 3,
'e': 2, 's': 2})
counterObject['s'] += 1 # Increase/Decrease frequency

# Accessing
frequency_of_s = counterObject['s']

# Deleting
del couterObject['s']

Deque

A double-ended queue, or deque, has the feature of adding and removing


elements from either end.

• Operations Time Complexities

7 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

from collections import deque

queue = deque(['name','age','DOB'])

queue.append("append_from_right") # Append from right


queue.pop() # Pop from right

queue.appendleft("fromLeft") # Append from left


queue.popleft() # Pop from left

queue.index(element,begin_index,end_index) # Returns first index


of element b/w the 2 indices.
queue.insert(index,element)
queue.remove() # removes first occurrance
queue.count() # obvious

queue.reverse() # reverses order of queue elements

Heapq

8 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

As we know the Heap Data Structure is used to implement the Priority Queue
ADT. In python we can directly access a Priority Queue implemented using a
Heap by using the Heapq library/module.

• Operations Time Complexities

import heapq # (minHeap by Default)

nums = [5, 7, 9, 1, 3]

heapq.heapify(nums) # converts list into heap. Can be converted


back to list by list(nums).
heapq.heappush(nums,element) # Push an element into the heap
heapq.heappop(nums) # Pop an element from the heap
#heappush(heap, ele) :- This function is used to insert the
element mentioned in its arguments into heap. The order is
adjusted, so as heap structure is maintained.
#heappop(heap) :- This function is used to remove and return the
smallest element from heap. The order is adjusted, so as heap
structure is maintained.

# Other Methods Available in the Library


# Used to return the k largest elements from the iterable
specified
# The key is a function with that accepts single element from
iterable,

9 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

# and the returned value from that function is then used to rank
that element in the heap
heapq.nlargest(k, iterable, key = fun)
heapq.nsmallest(k, iterable, key = fun)

Sets

A set is a collection which is unordered, immutable, unindexed, No Duplicates.

• Operations Time Complexities

set = {1,2,3}

set.add(item)
set.remove(item)
set.discard(item) | set.remove(item) # removes item | remove will
throw error if item is not there, discard will not

10 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

set.pop() # removes random item (since unordered)

set.isdisjoint(anotherSet) # returns true if no common elements


set.issubset(anotherSet) # returns true if all elements from
anotherSet is present in original set
set.issuperset(anotherSet) # returns true if all elements from
original set is present in anotherSet

set.difference(anotherSet) # returns set containing items ONLY in


first set
set.difference_update(anotherSet) # removes common elements from
first set [no new set is created or returned]
set.intersection(anotherSet) # returns new set with common
elements
set.intersection_update(anotherSet) # modifies first set keeping
only common elements
set.symmetric_difference(anotherSet) # returns set containing all
non-common elements of both sets
set.symmetric_difference_update(anotherSet) # same as
symmetric_difference but changes are made on original set

set.union(anotherSet) # ...
set.update(anotherSet) # adds anotherSet without duplicate

Tuples

A tuple is a collection which is ordered, unchangeable and can contain duplicate


values

• Operations Time Complexities

• Similar to list

tuple = (1,2,3,1)

tuple.count(1) # returns occurence of an item


tuple.index(1) # returns index of 1 in array

Strings

# ** split Function **
#The split() method breaks up a string at the specified separator
and returns a list of strings.
text = 'Python is a fun programming language'

# split the text from space


print(text.split(' '))

11 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

#convert string to list


s="abcd"
s=list(s)

# Output: ['Python', 'is', 'a', 'fun', 'programming', 'language']

# ** count Function **
#The count() method returns the number of occurrences of a
substring in the given string.
#Example
message = 'python is popular programming language'
# number of occurrence of 'p'
print('Number of occurrence of p:', message.count('p')) # Output:
Number of occurrence of p: 4

#The isnumeric() method returns True if all characters in a string


are numeric characters. If not, it returns False.
s = '1242323'
print(s.isnumeric()) #Output: True

#The find() method returns the index of first occurrence of the


substring (if found). If not found, it returns -1.
# check the index of 'fun'
print(message.find('fun')) # Output: 12

#The isalnum() method returns True if all characters in the string


are alphanumeric (either alphabets or numbers). If not, it returns
False.

name = "M3onica Gell22er "


print(name.isalnum()) # Output : False

#The isalpha() method returns True if all characters in the string


are alphabets.
Leetcode If not, it Algorithms
Data Structures returns False
Python
name = "Monica"
print(name.isalpha()) #output true

#other imp functions


string.strip([chars]) #The strip() method returns a copy of the
string by removing both the leading and the trailing characters
(based on the string argument passed).
string.upper() #he upper() method converts all lowercase
characters in a string into uppercase characters and returns it.
string.lower() #The lower() method converts all uppercase
characters in a string into lowercase characters and returns it.
string.islower()
string.isdigit()
string.isupper()
Follow

Python integer division behaves differently with -ve numbers ex: -3//2 will give -2
Written by Abdul Malik
answer instead of -1 so always use int(-3/2) for integer division in problems
305 Followers

Resources
Love converting thoughts into code.

12 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

The Modulo Operation (%) With Negative Numbers in Python

Cheat Sheet
More from AbdulPDF
Malik
Click Here

For updated version please check GitHub repo.

If you enjoyed this experience consider being a member for more content like
this!

Please consider subscribing to be the first to receive emails for my experiences.

Abdul Malik

10 Campus Ambassador Programs you can apply for right now


Campus Ambassadors act as the connection between a company and the university they
are studying in. Oftentimes they are assigned tasks to…

2 min read · Mar 11, 2022

20

13 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

Abdul Malik

Five PRODUCTIVE Notion Templates shared by Ali Abdaal


Ali Abdaal is a Youtuber who focuses on productivity and he’s an advocate of using Notion
as a “second brain”. Regardless I've loved his…

3 min read · Jul 19, 2021

18

14 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

Abdul Malik in The Startup

Designing Data Models for Firebase


In this article we will be speaking about designing data models for Firebase to make it super
easy to store and retrieve them.

4 min read · Jul 10, 2020

200 2

Abdul Malik

Ru-Torrent Mobile — Access Your Seedbox On The Go


Ru-Torrent Mobile is an ruTorrent-based client built with Flutter.

2 min read · Aug 21, 2021

Recommended
52 from Medium

See all from Abdul Malik

15 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

Arslan Ahmad in Level Up Coding

Don’t Just LeetCode; Follow the Coding Patterns Instead


What if you don’t like to practice 100s of coding questions before the interview?

5 min read · Sep 15, 2022

6.9K 38

16 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

Ayush Thakur

Python Decorators That Can Reduce Your Code By Half


Hi there, welcome to my blog! Today I’m going to share with you some amazing Python
decorators that can reduce your code by half. Sounds…

5 min read · Nov 14

1.7K 19
Lists

Coding & Development


11 stories · 339 saves

Predictive Modeling w/ Python


20 stories · 710 saves

Practical Guides to Machine Learning


10 stories · 813 saves

ChatGPT
23 stories · 332 saves

17 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

Rohit Verma

My Interview Experience at Google [L5 Offer]


Comprehensive Insights: A Deep Dive into the Journey from Preparation Through Interviews
to Securing the Offer.

9 min read · Nov 25

5.1K 31

Naem Azam

Data Structures: Insertion Sort Algorithm using Python


Sorting and Searching algorithms like insertion sort, selection sort, merge sort are very
important to learn as a part of the preparation…

6 min read · Aug 12

11

18 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

Benoit Ruiz in Better Programming

Advice From a Software Engineer With 8 Years of Experience


Practical tips for those who want to advance in their careers

22 min read · Mar 20

12.8K 243

19 of 20 12/22/23, 11:25
I Made A Python Cheat Sheet for Data Structures and... https://buildwithmalik.medium.com/i-made-a-python-c...

Mustafa Can Sener in Stackademic

Mastering Medium-Level Algorithm Interviews: 3 Challenging


Problems and C# Solutions
Preparing for medium-level algorithm interviews often involves tackling complex problems.
In this article, we’ll explore five such…

2 min read · Nov 4

4
See more recommendations

20 of 20 12/22/23, 11:25

You might also like