Python for Coding Interviews - Everything you need to Know

NeetCode
2 Oct 202226:18

Summary

TLDRIn this coding tutorial, the host shares insights on using Python for coding interviews, highlighting its simplicity and conciseness. They discuss Python's dynamic typing, control structures, and various data structures like lists, sets, and dictionaries, emphasizing their practical use in interviews. The video also covers string manipulation, advanced data structures like heaps, and Python's syntax for functions and classes. Aimed at interview preparation, the host recommends neco.io for further resources, courses, and practice problems in multiple programming languages.

Takeaways

  • 😀 The speaker learned Python specifically for coding interviews and found it helpful for its conciseness.
  • 🔍 Python is a dynamically typed language, which allows for flexibility in variable assignment without declaring types.
  • 🚫 Python does not support the '++' operator for incrementing variables, differing from some other programming languages.
  • 💡 The 'None' keyword in Python represents null, and variables can be reassigned from other types to 'None'.
  • 🔑 Python uses indentation rather than curly braces to define code blocks, which is a syntactical difference from languages like Java or C++.
  • 🔄 The 'and' and 'or' keywords are used for logical operations instead of symbols, enhancing readability.
  • 🔢 Python performs decimal division by default, unlike many languages that default to integer division.
  • 📚 Lists (arrays) in Python are dynamic and provide various methods for manipulation, including append, pop, insert, and slice.
  • 🔤 Strings in Python are immutable, meaning they cannot be changed after creation, but new strings can be created easily.
  • 🔄 The 'zip' function is useful for iterating over multiple arrays simultaneously, combining their elements into pairs.
  • 📚 Dictionaries (hashmaps) in Python are versatile and allow for key-value pair storage with efficient search and insertion.

Q & A

  • What is the main focus of the video?

    -The main focus of the video is to cover everything one needs to know about Python for coding interviews.

  • Why did the channel creator learn Python specifically for coding interviews?

    -The channel creator learned Python specifically for coding interviews because it is easier and more concise than most languages, which was helpful throughout all his interviews at Google.

  • What are some benefits of Python mentioned in the video?

    -Python is mentioned to be beneficial for coding interviews due to its ease of use, conciseness, and dynamic typing, which allows for flexibility in variable assignments and types.

  • How does Python handle variable types differently from statically typed languages?

    -Python, being a dynamically typed language, allows variables to be assigned values without declaring their types, and types are determined at runtime, enabling variables to change types.

  • What is the significance of the 'None' keyword in Python?

    -In Python, 'None' represents the absence of a value, which is similar to 'null' in other languages, and it can be assigned to variables that are expected to hold other types of values.

  • How does Python syntax for if statements differ from other languages?

    -Python syntax for if statements does not require parentheses for the conditional and uses indentation instead of curly braces to define the block of code associated with the conditional.

  • What is the default behavior of division in Python?

    -In Python, division is decimal division by default, which means it will produce a floating-point result, unlike many other languages that use integer division by default.

  • How can one perform integer division in Python?

    -To perform integer division in Python, one can use the double slash operator '//', which will round the result towards zero.

  • What is a key difference between Python lists and arrays in other languages?

    -Python lists are dynamic arrays that can have items of different types and are easily manipulated with various built-in methods, such as append, pop, and sort.

  • How does Python handle string immutability?

    -Python strings are immutable, which means that once a string is created, its characters cannot be changed. Any operation that appears to modify a string actually creates a new string.

  • What is a unique feature of Python sets?

    -Python sets are collections of unique elements and are useful for membership testing, removing duplicates, and performing mathematical set operations.

  • How can one implement a Max Heap in Python?

    -In Python, one can implement a Max Heap by using the negative values of the elements, pushing them onto a Min Heap, and then negating them again when popping from the heap.

Outlines

00:00

🐍 Introduction to Python for Coding Interviews

The speaker begins by welcoming the audience to a coding tutorial focused on Python for coding interviews. They share their personal journey of starting the channel during the pandemic, solving coding interview questions in Python, and eventually securing a job at Google. The speaker emphasizes Python's simplicity and conciseness, which they believe is advantageous for coding interviews despite never using it professionally. They encourage viewers, whether new to Python or experienced with other languages like Java or C++, to appreciate Python's benefits. The speaker also promotes their website, neco.io, which offers free resources for coding interview preparation and mentions their advanced algorithms course and upcoming system design course.

05:01

🔍 Deep Dive into Python's Dynamic Typing and Syntax

This section delves into the dynamic typing nature of Python, where variables like 'n' can be reassigned from an integer to a string without type declaration. The speaker explains Python's syntax peculiarities, such as the lack of parentheses in conditional statements and the use of indentation to define code blocks. They discuss Python's null value 'None', the absence of '++' operator, and the use of 'and' and 'or' for logical operations. The paragraph also covers Python's for and while loops, explaining the use of 'range' and how loops are structured differently from languages like Java or C++.

10:02

🔢 Exploring Python's Numerical Operations and Data Structures

The speaker explores Python's handling of numerical operations, highlighting the default decimal division and the use of '//' for integer division. They discuss Python's approach to modulo operations with negative numbers and provide alternatives for achieving results consistent with other languages. The section continues with an overview of Python's lists, their dynamic nature, and operations like appending, popping, and inserting elements. The speaker also introduces list comprehensions and demonstrates how to create lists and multi-dimensional arrays efficiently.

15:02

📚 Advanced Python Features: Slicing, Unpacking, and More

This part of the script focuses on advanced Python list manipulation techniques like slicing and unpacking. The speaker explains how to extract sublists and assign multiple list elements to variables. They also cover iterating through lists using various methods, including simple for loops, iterating directly through values, and using 'enumerate' for index and value pairs. The paragraph extends to discussing list reversal and sorting, both in ascending and descending orders, and custom sorting using lambda functions. The speaker also touches on initializing lists using list comprehensions for more complex scenarios.

20:04

💬 Strings, Queues, and Sets in Python

The speaker transitions to discussing Python strings, their immutability, and operations like slicing and conversion between strings and integers. They introduce Python's deque for double-ended queues, explaining how to append and pop from both ends efficiently. The paragraph continues with a discussion on sets, their properties, and operations like insertion, search, and removal. The speaker also covers set comprehensions and the use of tuples as immutable sequences and hashable keys for sets and dictionaries.

25:06

🏢 Python Data Structures: Dictionaries, Heaps, and Functions

This section covers Python dictionaries, their initialization, and operations like insertion, search, and removal. The speaker explains dictionary comprehensions and iterating through dictionaries in various ways. They then move on to discuss Python's heap implementation using the 'heapq' module, explaining how to create and manipulate min and max heaps. The paragraph concludes with an introduction to Python functions, nested functions, and the use of 'nonlocal' to modify variables outside the local scope. The speaker also briefly touches on Python classes, constructors, and methods, emphasizing the use of 'self' to access member variables and methods.

🎓 Wrapping Up and Resources for Coding Interviews

In the concluding part, the speaker summarizes the key Python concepts and data structures necessary for coding interviews. They stress that while the list may seem extensive, frequent practice makes it easier to recall and use these concepts during interviews. The speaker reassures viewers that it's normal to refer back to resources for syntax or specific usage and encourages continued practice. They also promote their website, neco.io, as a platform for further learning and practice, offering video explanations and code support in multiple programming languages. The speaker thanks the audience and expresses hope to see them in future sessions.

Mindmap

Keywords

💡Python

Python is a high-level, interpreted programming language known for its readability and简洁性. In the video, it is highlighted as a language of choice for coding interviews due to its ease of use and conciseness, which allows for quicker coding and fewer lines of code compared to other languages. The speaker shares their personal experience of learning Python specifically for coding interviews, which eventually helped them secure a job at Google.

💡Coding Interviews

Coding interviews are a critical part of the hiring process for software engineering roles, where candidates are assessed on their problem-solving skills through writing code. The video focuses on preparing for such interviews using Python, emphasizing the language's utility in tackling common interview problems efficiently.

💡Dynamically Typed

A dynamically typed language, like Python, does not require explicit declaration of variable types. This is demonstrated in the script where variables can be reassigned to different data types at runtime without any type conflicts. This feature is beneficial for quick prototyping and coding interviews where the focus is on algorithmic solutions rather than type declarations.

💡None

In Python, 'None' represents the absence of a value, akin to 'null' in other languages. The video explains how 'None' can be assigned to variables that were initially holding different data types, illustrating Python's flexibility with data types. This is an important concept to understand when dealing with potential null references in Python code.

💡Indentation

Indentation in Python is used to define code blocks, unlike other languages that use braces. The video script mentions this syntactic feature, emphasizing its importance in Python's readability and structure. Proper indentation is crucial for writing valid Python code, and it plays a significant role in coding interviews where code clarity is often evaluated.

💡Data Structures

Data structures such as arrays (lists), strings, queues, sets, and hash maps (dictionaries) are fundamental in computer science and are frequently used in coding interviews. The video provides an overview of how these data structures are implemented in Python, their operations, and their time complexities, which are essential for solving problems efficiently during interviews.

💡List Comprehension

List comprehension is a Pythonic way to create lists in a concise and readable manner. The video script includes an example of using list comprehension to generate a list of numbers or to apply an operation to each element. This feature is particularly useful in coding interviews for writing concise and efficient code.

💡Recursion

Recursion, where a function calls itself to solve smaller instances of the same problem, is a common technique in coding interviews. The video touches on nested functions, which can be utilized in recursive solutions to maintain access to outer function's variables, thus simplifying the code structure.

💡Classes

Classes in Python are used to create objects and are a fundamental concept in object-oriented programming. The video script briefly covers how to define classes and their constructors, as well as how to create and access member variables and methods. Understanding classes is important for interview questions that involve designing systems or modeling real-world entities.

💡Heaps

Heaps, particularly min-heaps and max-heaps, are important data structures for efficiently retrieving the smallest or largest element. The video explains how to implement heaps in Python using lists and the 'heapq' module, and how to manipulate them to achieve the desired order. This is relevant for interview questions that require priority queue implementations or ordering algorithms.

Highlights

Introduction to Python for coding interviews

Background of the channel creator and their journey to Google

Advantages of Python in coding interviews

Python's dynamic typing and variable declaration

Differences in incrementing variables in Python

Python's handling of 'None' and its use as a null value

Conditional statements in Python without parentheses

Python's 'and' and 'or' keywords for logical operations

While loops in Python and their syntax

For loops and range functionality in Python

Negative indexing and slicing in Python lists

List comprehensions for initializing lists in Python

String immutability and operations in Python

Queue operations and deque module in Python

Set operations and their time complexities in Python

Hashmap or dictionary usage and operations in Python

Tuples as immutable sequences and their use as keys

Heap implementation and heapify function in Python

Functions in Python and nested functions for recursion

Classes in Python and their structure

Conclusion and resources for further learning

Transcripts

play00:00

hey everyone welcome back and let's

play00:01

write some more neat code today so today

play00:03

I want to cover everything you need to

play00:05

know about python for coding interviews

play00:08

if you're new here a little bit about my

play00:10

background I started the channel a

play00:12

couple years ago at the beginning of the

play00:13

pandemic I was unemployed and I made

play00:15

solutions to coding interview questions

play00:17

in python and a little over a year after

play00:19

that I eventually got a job at Google

play00:21

and I pretty much used python throughout

play00:23

all my interviews and I think it was

play00:25

really helpful because python is so much

play00:27

easier than most languages it's super

play00:30

concise I've actually never written a

play00:32

line of python code at any jobs or

play00:34

internships I've ever had I literally

play00:36

learned python just for coding

play00:38

interviews and it's definitely been

play00:39

worth it if you're already familiar with

play00:41

python I hope you learned some tips and

play00:43

tricks from this video and if you use

play00:45

other languages like Java or C plus plus

play00:46

I hope by the end of this video you see

play00:48

the benefits and then join the church of

play00:51

python I think you'll be able to learn

play00:52

it faster than you expect especially if

play00:54

you're already familiar with programming

play00:56

and by the way if you're studying for

play00:57

coding interviews check out neco.io it's

play00:59

a side I created has a bunch of free

play01:01

resources to help you prepare and I've

play01:03

also started making courses I just

play01:05

finished up the advanced algorithms

play01:06

course and I'm going to get started on

play01:08

the system design course for beginners

play01:09

so you definitely don't want to miss out

play01:11

on that okay now let's get started the

play01:13

first thing you should know about python

play01:14

is that it's a dynamically typed

play01:16

language so when we declare a variable

play01:19

like n and set it to zero we don't have

play01:20

to declare the type at all so now if we

play01:23

run the code in print and you can see

play01:24

it's equal to zero but types are

play01:26

determined at run time so we can

play01:29

reassign n to a string now and that's

play01:31

perfectly fine because n has no type the

play01:34

type is determined at run time so now we

play01:37

can run the code again and we can see

play01:39

that n was originally a zero and then it

play01:40

changed to a string ABC we can also do

play01:43

multiple assignments but it's a bit

play01:46

different than most languages if we have

play01:48

two variables we put them both on the

play01:50

left hand side and then we have our

play01:53

equal sign and then we put the two

play01:55

values on the right side it's okay to

play01:57

have multiple types in a single line

play01:59

line incrementing is a bit different of

play02:02

course we can increment a very simple

play02:04

way like this n is equal to n plus one

play02:06

we can also do the shorthand and plus

play02:09

equal to one just like most languages

play02:10

but we can't do plus plus you can see it

play02:13

even gives us a syntax error we can't do

play02:15

plus plus that's related to the python

play02:17

interpreter but it's not a big deal I

play02:19

mean this is one of the few cases where

play02:21

python is a bit less concise python also

play02:24

has null but it's called none in Python

play02:26

which is basically the absence of a

play02:28

value unlike most languages though we

play02:30

can have a value that's initially a

play02:32

number or it's supposed to store a

play02:33

number like four but then we can

play02:35

reassign It To None which means null and

play02:37

then we see it is equal to none if

play02:39

statements are pretty straightforward in

play02:41

Python at least conceptually but

play02:43

syntactically there's a couple

play02:45

differences namely that we don't need

play02:47

parentheses so if we have an if

play02:49

statement like this we don't need to put

play02:51

the conditional in parentheses and we

play02:53

don't need curly braces to represent

play02:55

what is the block that corresponds to

play02:57

this conditional we use indentation

play02:59

station for that so you can see here we

play03:01

have a tab that indicates that this code

play03:03

belongs to this statement we have a

play03:05

colon that goes after the conditional

play03:07

else if Works a bit differently we don't

play03:10

actually have both keywords else if we

play03:12

even shorten that I don't really care

play03:13

too much for this but I'm guessing it

play03:15

just has to do with the python

play03:17

interpreter because we already have two

play03:18

keywords for if and else so we have to

play03:21

create a new keyword for else if at

play03:22

least that's what I'm guessing while

play03:24

parentheses aren't required for

play03:25

conditionals in Python they are needed

play03:27

if we have multi-line conditionals and

play03:30

by the way logic and in most languages

play03:32

is the double Ampersand character but in

play03:35

Python it's just the keyword and or is

play03:37

just the keyword or so not that this is

play03:40

shorter but it just makes things a

play03:41

little bit more readable for example if

play03:43

we have an if statement that looks like

play03:44

this we use the keyword and and we use

play03:47

the keyword or to mean logic and and

play03:49

logic war and since we have a multi-line

play03:51

conditional like this these two lines

play03:53

are part of the conditional we have to

play03:55

put them inside of parentheses otherwise

play03:57

if we get a syntax error syntax

play03:59

practically while Loops are pretty

play04:01

similar for example we have a variable n

play04:03

equals zero we can create a while loop

play04:05

where the condition doesn't have to go

play04:06

in parentheses the block is followed by

play04:09

a colon and the code itself is indented

play04:11

with a tab we're printing n so running

play04:14

the code we get to print zero through

play04:16

four four Loops are pretty similar so if

play04:19

we want to do the exact same thing go

play04:20

from zero through four we create a for

play04:23

Loop where our variable I is going to go

play04:26

in the range of five that basically

play04:28

means it's going to start at zero and

play04:30

keep going until it reaches 5 and then

play04:34

stop and I is incremented implicitly so

play04:37

we don't have to tell this Loop to

play04:38

increment I I is just going to be

play04:39

incremented on every iteration of the

play04:41

loop by default so running the code

play04:43

you'll see we get pretty much the exact

play04:45

same thing zero through four so five is

play04:47

not included as the loop execute to

play04:50

better illustrate the for Loop let's

play04:52

take a look at another example where

play04:53

we're going from two through five so in

play04:56

that case we'd use the same keywords for

play04:58

I in range but we'd pass in two values

play05:01

into range we're starting at two and

play05:04

we're going up until six but not

play05:06

including six so now when we print this

play05:09

we go from two all the way up until five

play05:12

and if you want to go in reverse

play05:14

starting at five and going down to two

play05:16

it would be similar we'd start at five

play05:19

we'd go up until one but not including

play05:22

one and we'd pass in a negative one as

play05:25

the third argument because in this case

play05:27

we're decrementing if you don't pass in

play05:29

a negative one we increment the I but

play05:32

when you pass in negative one that means

play05:34

we're decrementing the I and we actually

play05:36

could have passed in a negative two here

play05:37

as well if we wanted to decrement by two

play05:39

every single time but just decrementing

play05:41

this going from five down to two and you

play05:44

can see we get what we expected I will

play05:46

admit this was one of the annoying

play05:48

things when I first learned python

play05:49

compared to most languages where you can

play05:51

do something like this explicitly

play05:53

declare the variable explicitly State

play05:55

the condition and explicitly increment

play05:57

our decrement this python syntax is

play05:59

different definitely a bit trickier but

play06:01

I think as you get used to it it's

play06:02

easier to type out than this bottom

play06:04

stuff that I have here division is also

play06:06

a bit tricky in Python it's decimal

play06:09

division by default whereas most

play06:11

languages use integer division so 5

play06:13

divided by 2 will actually give us 2.5

play06:16

whereas in most languages it'll round

play06:18

towards Zero by default if you want

play06:20

integer division you have to use double

play06:22

slash like this so printing this will

play06:25

actually round down you can see we get

play06:27

two as the result but if you caught what

play06:29

I just said you have to be careful

play06:30

because most languages will round

play06:32

towards Zero by default but in Python if

play06:35

we do integer division we're rounding

play06:37

down so you can see negative 3 divided

play06:40

by 2 will actually round down to be

play06:42

negative 2 where the decimal value would

play06:44

be negative 1.5 in most languages there

play06:47

would be negative one a workaround for

play06:50

this is to use decimal division but then

play06:52

convert the result to an integer because

play06:55

when you convert to an integer it will

play06:57

round towards zero this is kind of a

play06:59

annoying but it's just something you

play07:00

have to do you can see running this will

play07:02

give us a negative one which is what you

play07:05

might want in certain cases though I'll

play07:07

mention it's pretty rare to have to need

play07:09

to know this I'm just mentioning it in

play07:10

case you run into any issues using the

play07:13

modulo operator is pretty similar to

play07:15

most languages so 10 divided by three

play07:17

we're getting the remainder we would

play07:18

expect a one and that's exactly what we

play07:20

get except the issue is once again with

play07:23

negative values just like dividing

play07:25

negative values when we mod negative

play07:27

values we get unexpected results and

play07:29

negative 10 modded by three well the

play07:31

answer is actually two and this is

play07:33

different from most C based languages

play07:36

like Java C plus plus I think even

play07:38

JavaScript so if you want to be

play07:39

consistent with those other languages

play07:41

you can import math and then do F mods

play07:45

using this will give us negative one

play07:47

which is what you might have expected a

play07:50

few more useful math helpers we have

play07:52

floor which will explicitly round down

play07:54

we can also do the opposite which is the

play07:56

ceiling so three divided by two rounding

play07:58

up if you need to take the square root

play08:00

there's a Helper and if you need to take

play08:02

the power of a variable raised to

play08:04

another so 2 to the power of 3 would be

play08:06

this if you ever need a maximum integer

play08:08

you can use float infinity and if you

play08:10

ever need a minimum integer you can use

play08:12

float negative infinity and part of the

play08:14

reason that they come up is because

play08:16

python numbers are infinite so they

play08:18

actually never overflow so if we have a

play08:21

number like this 2 to the power of 200

play08:23

which is a very large number as you can

play08:26

see on the right after we print it it's

play08:28

so large that we can't even print it

play08:30

it's 60 additional digits but even this

play08:32

large integer is still less than

play08:35

infinity checking if this number is less

play08:38

than infinity we get true arrays which

play08:41

are called lists in Python are probably

play08:43

the most common data structure you're

play08:45

going to use next to Hash Maps so an

play08:47

array can be declared just like this but

play08:49

initializing it is pretty

play08:51

straightforward you just put the values

play08:52

inside of some brackets and printing it

play08:55

is just as simple arrays in Python are

play08:58

Dynamic arrays by Define fault so just

play09:00

like in most languages Dynamic arrays

play09:02

can be used as Stacks so you can push to

play09:04

the array AKA append and you can also

play09:07

pop from the array which will pop from

play09:10

the end of course so after we push a

play09:12

four and we push a five we can print

play09:13

that and then after we pop the last

play09:15

value you can see that we popped the

play09:17

five because this is technically an

play09:19

array and not a stack we can actually

play09:21

insert into the middle so at index one

play09:24

we can insert a value seven printing

play09:26

that you can see we indeed inserted a 7

play09:28

into the middle of the array but unlike

play09:31

pushing and popping from an array

play09:33

inserting into the middle is a big O of

play09:36

end time operation but it's not a big O

play09:39

of end time operation to index an array

play09:42

so at index 0 we can read the value and

play09:44

we can also reassign the value to zero

play09:47

in this case and we can reassign the

play09:48

value at index three and these

play09:50

operations are constant time operations

play09:52

to initialize an array of variable size

play09:55

let's say we wanted an array of size

play09:57

five and we wanted all values to be 1

play09:59

one we could do it pretty easily it

play10:01

might be kind of weird to use the

play10:02

multiplication operator here but

play10:04

syntactically it's pretty easy printing

play10:06

the array and the length of the array

play10:08

you can see we do get what we expect but

play10:10

be careful when indexing an array

play10:12

especially when you're using negative

play10:14

values because negative one is actually

play10:16

not out of bounds in Python negative one

play10:19

will actually read the last value as you

play10:22

can see on the right and to read the

play10:24

second to last value you can use

play10:25

negative two now in my opinion this

play10:27

isn't super useful but sometimes it can

play10:30

be when you want to quickly read the

play10:31

last value getting sub lists AKA slicing

play10:34

an array is one of the most useful

play10:36

features of python so here we're taking

play10:39

the values of the array from index 1 to

play10:41

index 3 but not including index three

play10:44

just like with for loops and then

play10:45

printing those values so we would expect

play10:47

two and three and that's what we get and

play10:50

we could also go from index 0 to 4 which

play10:52

is pretty much the entire array and

play10:54

that's valid as well unpacking is also a

play10:57

super useful feature basically we can

play10:59

take all the individual elements of an

play11:01

array and assign them to variables in

play11:03

this case ABC this can be super helpful

play11:06

when you want to go through a list of

play11:07

pairs for example be careful though

play11:10

because you do have to make sure that

play11:11

the number of variables on the left hand

play11:14

side does match the number that you're

play11:16

expecting from the array we can Loop

play11:18

through arrays in many different ways

play11:20

using the simple for Loop syntax we

play11:23

talked about earlier we can take the

play11:24

length of the array and then iterate

play11:26

that many times using an index I and

play11:29

then printing the individual value an

play11:32

easier way to accomplish the exact same

play11:33

thing is without using an index so we

play11:36

can actually go through every value in

play11:38

nums and then just print that individual

play11:41

value if for some reason you needed both

play11:44

the index and the value you could use

play11:46

the first for loop I have shown up here

play11:48

but another way to do it is to use the

play11:50

enumerate function in Python so a

play11:53

numerate will actually give you the

play11:54

index which will be the first value

play11:56

that's unpacked and the second value

play11:58

that's unpacked will be the number and

play12:00

then we can print both of those if for

play12:02

some reason we needed both of them and

play12:04

all three of these Loops execute as you

play12:06

would expect now if we want to iterate

play12:08

through multiple arrays simultaneously

play12:11

we can do that with unpacking and a

play12:14

helper function called Zip Zip will

play12:16

basically take both of these arrays and

play12:19

combine them into an array of pairs and

play12:22

then we can unpack those pair of values

play12:24

which are values from nums 1 and nums

play12:26

two we get pretty much what we expect

play12:28

reversing an array is as simple as

play12:31

calling the reverse method on that array

play12:33

so one two three becomes three two one

play12:36

sorting an array is just as easy taking

play12:39

this array we can call sort on it so

play12:41

this will sort it in ascending order by

play12:43

default if we want to sort it in reverse

play12:45

order we just pass in the parameter

play12:47

reverse equals true and then the array

play12:50

will be sorted in descending order we

play12:52

can also sort a list of strings by

play12:54

default they will be sorted based on

play12:56

alphabetical order as you can see on the

play12:58

right but if we want to implement a

play13:00

custom sort for example if we want to

play13:02

sort based on the length of each string

play13:04

then we can do that by passing in a

play13:06

Lambda function so in this case the key

play13:09

is equal to Lambda which is basically a

play13:11

function without a name and we're going

play13:13

to take every single value from the

play13:15

array call it X and then return from

play13:18

that the length of X and this is the key

play13:21

that's going to be used to sort the

play13:23

string so each string is going to be

play13:25

mapped to its length and then we're

play13:27

going to sort those strings based on

play13:29

their length so by default it's going to

play13:31

be in ascending order as we can confirm

play13:34

on the right another sort of advanced

play13:36

way to initialize lists is using list

play13:38

comprehension so if we wanted to go

play13:41

through every value in range 5 and to

play13:44

call that value I and we want to add

play13:47

that value to this array this is the

play13:49

shorthand so we're iterating for I in

play13:51

range 5 and then I is going here so

play13:54

we're taking that I value and adding it

play13:56

to the array and printing it you can see

play13:59

that we indeed have zero through four

play14:01

now maybe we want to go through every

play14:03

value in that range but we want to take

play14:05

I and add I plus I to the result so for

play14:09

every index we want 2 times that index

play14:11

added to the result you can see we can

play14:13

also do that pretty easily if you want

play14:16

to do something similar for a 2d list

play14:18

it's also pretty easy but maybe a bit

play14:20

different than you would expect the

play14:22

easiest way to do it is the shorthand

play14:23

that we talked about earlier where we

play14:25

take an array with zero and then

play14:27

multiply it by four this will give us an

play14:29

array of size 4 with all zeros and we

play14:32

want this array to be added to the outer

play14:36

array for time so we have an inner loop

play14:38

for I in range four we're not even using

play14:41

the variable I here but this will build

play14:44

a 4x4 grid of all zeros you might be

play14:47

thinking isn't there an easier way to do

play14:49

that well actually not you might be

play14:51

thinking can we just do this create an

play14:53

array of size 4 and then multiply that

play14:56

by four well technically this will work

play14:58

but each of the four rows of this array

play15:02

are going to be the same so if we modify

play15:04

one of the rows we're going to be

play15:06

modifying all of the other rows we're

play15:08

not actually creating four unique rows

play15:11

in this case it's a common thing that

play15:12

can throw people off if you have more

play15:14

questions about this feel free to ask in

play15:16

the comments it's something that tripped

play15:18

me up a lot when I first started strings

play15:20

are pretty similar to arrays so we can

play15:22

declare one with double quotes you can

play15:24

also use single quotes if you want and

play15:26

we can slice them the same way we do

play15:28

with arrays and printing it works the

play15:31

same but a key point is that they are

play15:33

immutable that means we can't modify

play15:35

this string that means we can't reassign

play15:38

the character at index zero we can

play15:40

however update the string but updating

play15:43

it will actually create a new string so

play15:45

adding def to the end of the string will

play15:48

create a new string so basically any

play15:51

time you modify a string it's considered

play15:53

an end time operation strings can be

play15:56

converted into integers and then those

play15:59

integers can be added integers can also

play16:01

be converted into Strings and then those

play16:04

strings can be added together so when

play16:06

you add two integers together we get an

play16:08

integer as the result adding two strings

play16:10

together appends those strings together

play16:13

so we get one two three one two three if

play16:15

for some reason you need the ASCII value

play16:18

of a character you can do that with the

play16:19

ORD function so printing this you can

play16:22

see we get 97 is the ASCII value of

play16:24

lowercase a 98 is the ASCII value of

play16:27

lowercase b you can also join a list of

play16:30

strings together with a delimiter in

play16:32

this example we have three strings and

play16:34

we're joining them with the empty string

play16:37

delimiter here so we're basically just

play16:39

appending these three strings together

play16:41

we could also have had a delimiter maybe

play16:43

a space in between all of them and

play16:45

printing the result we get all three

play16:46

strings appended cues in Python are

play16:49

double ended cues by default you can

play16:51

import them adding values to the right

play16:53

side is as easy as appending to the

play16:55

queue so at this point our queue isn't

play16:57

much different from a stack but the

play16:58

benefit is that we can actually pop from

play17:01

the left of the queue and we can do this

play17:03

operation in constant time unlike with a

play17:06

stack as you can confirm on the right

play17:08

since it's double ended we can also add

play17:10

values to the left of the queue so the

play17:12

one that we popped we can add back to

play17:14

the left side and also we can choose to

play17:16

pop from the right side if we want to so

play17:19

running this we can confirm that the one

play17:21

is added back and then we pop the two

play17:23

after that Ash sets are really useful

play17:25

because we can search them in constant

play17:28

time and we can insert values also in

play17:30

constant time of course there won't be

play17:32

any duplicates in our set of course

play17:35

unlike a list there can't be any

play17:37

duplicates in a hash set but we can just

play17:39

as easily get the length of the hash set

play17:42

to know how many elements have been

play17:43

inserted we can also search the hash set

play17:45

without a function we can use the in

play17:47

operator so if we want to know if one

play17:49

exists in the hashtag same thing with

play17:51

two same thing with three which we know

play17:53

does not exist in the hash set as we can

play17:55

confirm we can remove values also in

play17:58

constant time time and confirm that the

play18:00

value has indeed been removed to

play18:02

initialize a hash set with a bunch of

play18:04

values we can actually pass in a list

play18:06

but just like with lists we can also do

play18:08

set comprehension and manually

play18:11

initialize it with a loop inside of the

play18:13

hash set so here we're going through

play18:15

every value in the range of I and taking

play18:17

that value I adding it to the hash set

play18:20

and initializing it this way is

play18:21

identical hashmaps are probably the

play18:23

single most common data structure you're

play18:25

going to be used and this is what we

play18:26

were saving those curly braces for to

play18:28

insert we simply take some key value in

play18:31

this case a string and assign it to

play18:33

another value in this case a number 88

play18:35

and we can add a bunch more just like

play18:37

with hash sets we can't have duplicate

play18:39

keys inside of the hash map printing it

play18:42

is just as simple taking the length will

play18:44

give us the number of keys that exist in

play18:46

our hash map we can modify the value

play18:48

that's mapped to a key so we can change

play18:50

Alice from being 88 to 80. we can also

play18:53

search if a key exists in a hashmap in

play18:56

constant time and we can also remove

play18:58

that key which will also remove the

play19:00

value as we can confirm on the right to

play19:03

initialize a hashmap we can add pairs

play19:05

inside of the curly braces where each

play19:07

pair is separated by a comma and the key

play19:09

goes on the left side of the colon and

play19:11

the value goes on the right side this is

play19:13

the same as manually inserting values

play19:15

into the hash map but if you want to get

play19:17

even more fancy you can use dict

play19:19

comprehension hash maps are basically

play19:21

called dictionaries in Python and the

play19:23

syntax is pretty similar but in this

play19:25

case if our looping I in the range of 3

play19:27

we're going to have two values I in this

play19:30

case is the key then a colon and then

play19:31

the value goes after that in this case

play19:33

we're mapping I to 2 times I this is

play19:36

pretty powerful and I find that I use it

play19:38

most frequently when I'm doing graph

play19:40

problems and trying to build like an

play19:41

adjacency list looping through a map is

play19:44

pretty interesting because there's many

play19:45

ways to do it by default we iterate

play19:48

through every single key and then we can

play19:49

you know print that key and also print

play19:51

the value that that key maps to but also

play19:54

we can directly iterate through the list

play19:56

of values of that hash map if we we

play19:59

don't even need the key lastly using

play20:01

unpacking we can actually go through the

play20:03

items of that map which will give us the

play20:06

key and the value this is pretty similar

play20:08

to the first Loop that we have I guess

play20:09

it's a bit more concise to write it this

play20:11

way python also has tuples which are

play20:14

pretty similar to arrays except to

play20:16

initialize them we use parentheses

play20:18

rather than brackets and they are

play20:20

immutable so while we can index them we

play20:24

can't modify them so this won't work

play20:26

you'll mainly be using tuples as keys

play20:29

for a hash map or a hash set so in this

play20:31

case we're mapping a pair of values one

play20:33

two to three so this Tuple is basically

play20:36

our hashable key we can do the same

play20:39

thing for hash sets of course and then

play20:41

we can use that Tuple to search the hash

play20:43

set the reason we do this is because

play20:44

lists are not hashable and can't be keys

play20:47

for hash sets or hash Maps so this here

play20:50

will not work heaps are another really

play20:52

common data structure to find the Min

play20:54

and Max of a set of values frequently

play20:56

under the hood in Python they're

play20:58

implemented with array days of course so

play20:59

actually to create an empty Heap we just

play21:01

create an empty list and to push values

play21:03

to that Heap we use Heap Q dot heat push

play21:06

to that Min Heap the value three by

play21:09

default heaps in Python are Min heaps so

play21:12

we push a few more values and then to

play21:13

get the minimum value it'll always be at

play21:15

index 0. that's just how heaps are

play21:18

implemented to Loop through a heap while

play21:20

the length of the Heap is non-zero we

play21:22

can also pop values from the Heap with

play21:25

Heap Q dot heat pop from that Min heat

play21:28

and then print the corresponding value

play21:30

that we just popped since it's a Min

play21:32

Heap we'll see the values are printed

play21:33

from smallest to largest while python

play21:36

doesn't have Max heaps by default the

play21:38

workaround is basically to multiply each

play21:40

value that we push by negative one and

play21:43

then after we pop that value we also

play21:45

multiply it by negative one to negate

play21:47

the original negative one so if we

play21:49

wanted to implement a Max Heap and push

play21:50

the value 3 we would actually push

play21:52

negative three and if we wanted to push

play21:54

two we'd push negative two same thing

play21:56

with four again the max will always be

play21:58

at index 0 but we know we have to

play22:00

multiply it by negative one to negate

play22:02

the original negative one by popping

play22:04

each value and multiplying it by

play22:06

negative one we can confirm that the

play22:08

values are printed from greatest to

play22:09

smallest now if you already have the

play22:11

initial set of values that you want to

play22:13

build the Heap from you can do it in

play22:15

linear Time by calling build Heap or in

play22:17

Python it's called heapify so we can

play22:19

call Heap Q dot heapify this array and

play22:22

while that array is not empty we're

play22:23

going to keep printing the values and we

play22:25

can confirm that they're printed from

play22:26

smallest to largest functions in Python

play22:29

are pretty straightforward and concisely

play22:31

use the def keyword we name the function

play22:34

and then we pass in some parameters in

play22:36

this case n and M just like with

play22:38

conditionals and Loops we use a colon

play22:41

after the Declaration of the function

play22:42

and the body of the function is going to

play22:45

be indented so we're returning the

play22:46

multiplication of those two values and

play22:48

printing the result one functionality I

play22:51

use a lot in coding interviews is nested

play22:53

functions this can be really helpful in

play22:55

recursive problems because if you have

play22:56

an outer function that takes in a couple

play22:58

parameters and you also declare some

play23:00

values in that outer function the inner

play23:02

function will actually have access to

play23:04

all of those variables by default so

play23:06

then if we called the inner function we

play23:08

don't even have to pass in a b and c now

play23:11

this is a pretty simple example but if

play23:12

you've watched any of my graph videos

play23:14

you know how nice this can be in keeping

play23:16

our code concise one thing that trips a

play23:19

lot of people up with nested functions

play23:20

is that you can modify objects but you

play23:22

can't reassign values unless you use the

play23:25

non-local keyword so if we have a

play23:27

function that's going to double every

play23:29

value inside of an array and also double

play23:31

this value itself this is not an array

play23:34

we can have a helper function it'll have

play23:36

access to both of those outer variables

play23:38

we can modify the array pretty easily by

play23:40

going through each value in the array

play23:42

and then doubling it this works and will

play23:44

update the original array but if we

play23:47

doubled the value it'll only double the

play23:49

value in the scope of the helper

play23:51

function if you want to update the value

play23:53

outside of the helper scope you'll have

play23:55

to declare it as a non-local value and

play23:57

doing this and and then modifying the

play23:59

value will modify the original values

play24:02

and then in the outer function we can

play24:03

call the helper function without passing

play24:05

in the variables and then print the

play24:07

variables not actually called the double

play24:09

function we can create some variables

play24:10

call it run the code and we can see that

play24:13

each variable was doubled again this is

play24:15

a trivial example but if you're familiar

play24:17

with my videos you know that this can be

play24:19

helpful classes are also pretty concise

play24:22

but a bit more limited than other

play24:24

languages a Constructor is basically

play24:26

double underscore init double underscore

play24:28

after that that's kind of the name of

play24:30

the Constructor in Python self is passed

play24:32

into every method of a class it's

play24:34

basically like the this keyword in other

play24:36

languages in this case our Constructor

play24:38

is maybe taking a list of numbers to

play24:41

create member variables we also use the

play24:43

self keyword so this is creating a

play24:46

member variable called nums and

play24:47

assigning it to the nums that were

play24:49

passed in as a parameter to the

play24:51

Constructor we can also create a member

play24:53

variable for the size of nums by taking

play24:55

the length of the parameter to create a

play24:57

method for this class class for example

play24:59

get length we don't want to pass in any

play25:01

parameters to this but we have to pass

play25:03

in the self keyword always that'll give

play25:06

us access to Our member variable which

play25:07

we're going to return self.size if we

play25:10

want to call another member variable

play25:11

from a member variable in this case we

play25:14

want to call get length from this other

play25:16

function get double length we can do

play25:18

that again with the self keyword this is

play25:20

a pretty useless example but I'm mainly

play25:22

trying to explain the syntax and the

play25:24

structure of classes in Python now this

play25:27

is more or less everything I've needed

play25:28

to know for coding interviews it's

play25:30

surprisingly not a lot and you don't

play25:32

have to memorize any of this as you

play25:34

solve coding problems and as you prepare

play25:36

for interviews you might have to look up

play25:38

the syntax or how exactly do I use heaps

play25:40

how exactly do you use double ended cues

play25:42

things like that it's perfectly okay but

play25:44

after you practice enough most of this

play25:46

stuff is pretty easy to get down it

play25:48

doesn't even feel like you're writing

play25:49

code after a while python is a pretty

play25:52

big reason I was able to get a job at

play25:54

Google in my opinion now if you're

play25:55

preparing for coding interviews check

play25:57

out neco.io there's is a ton of free

play25:59

resources to help you prepare each

play26:01

practice problem listed has a thorough

play26:03

video explanation and we have code

play26:05

support for python C plus plus Java and

play26:07

JavaScript if you're new to data

play26:09

structures and algorithms I've got some

play26:11

really helpful courses not only for

play26:12

beginners but also for advanced users

play26:14

thank you so much for watching and

play26:16

hopefully I'll see you pretty soon

Rate This

5.0 / 5 (0 votes)

Ähnliche Tags
Python CodingInterview PrepGoogle JobData StructuresAlgorithmsCoding TipsPython SyntaxInterview TipsProgramming SkillsTech Tutorial
Benötigen Sie eine Zusammenfassung auf Englisch?