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

0_python-sololearn[1]

Uploaded by

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

0_python-sololearn[1]

Uploaded by

emll3pd
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 165

July 26, 2023

Graph

Graphs are used to represent many real-life applications like networks, transportation
paths of a city, and social network connections.

A graph is a set of connected nodes where each node is called a Vertex and the
connection between two of them is called an Edge.

Here is an example graph:

This can represent, for example, connections on a social network, where each Vertex
represents a person and the Edges represent connections.

Tap Continue to check out the implementation of the graph in Python!


Graph in Python

Let's implement the Graph class:

G.display()

We store the matrix in a two-dimensional list, called adj.


The __init__ method creates the adj matrix with the given size (number of vertices) and
initializes all values to zeros.
The add_edge() method is used to add an edge by setting the corresponding values to
1.
Similarly, the remove_edge() method sets the values to 0.
pop()

4
July 24, 2023

Stack

A stack is a simple data structure that adds and removes elements in a particular order.
Every time an element is added, it goes on the "top" of the stack. Only an element at the top of the stack can be removed,
just like a stack of plates. This behavior is called LIFO (Last In, First Out).

Terminology
Adding a new element onto the stack is called push.
Removing an element from the stack is called pop.

Applications
Stacks can be used to create undo-redo functionalities, parsing expressions (infix to postfix/prefix conversion), and much
more.

A stack can be implemented using a list in Python.

Well if you enter data like that. The stack order will be like this 3 2 1 Because every time when we
add a new item to a stack that item will be the first item of the stack.
Let's define and implement the Stack class with its
corresponding push, pop, is_empty and print_stack methods.

We will use a list to store the data.

As you can see, it's easy to create a stack using a list.


We use a list called items to store our elements.
The push method adds an element at the beginning of the list, while the pop method
removes the first element of the list.

Play around with the code and see the Stack working in action!
Queue

A queue is similar to a stack, but defines a different way to add and remove elements.
The elements are inserted from one end, called the rear, and deleted from the other
end, called the front.
This behavior is called FIFO (First in First Out).

Terminology
The process of adding new elements into the queue is called enqueue.
The process of removal of an element from the queue is called dequeue.

Applications
Queues are used whenever we need to manage objects in order starting with the first
one in.
Scenarios include printing documents on a printer, call center systems answering people
on hold, and so on.
Python lists are the easiest way to implement a queue functionality.

Let's implement the Queue class with it's


corresponding enqueue, dequeue, is_empty and print methods.

We will use a list to store the elements.


The enqueue method adds an element at the beginning of the list, while
the dequeue method removes the last element.

queue is FiFo first in first out.. however the question was what is the element at the back i.e the
freshest element added which represent the last element added and not the one ready to go out,
hence "C"

Linked List

A linked list is a sequence of nodes where each node stores its own data and a link to
the next node.
One node links to another forming what can be thought of as a linked chain:
previous and next states. Another example would be a playlist of music, where each clip
is linked with the next one.
Linked lists can also be used to create other data structures, such
as stack, queues and graphs.
The add_at_front() method adds a new Node as the head of the list and links the
previous head to it.
The add_at_end() method iterates to the end of the list using a while loop and adds the
new node as the link of the last node.

July 2, 2023

User-Defined Data Structures

In the previous modules we have seen the built-in data structures in Python, which
include Lists, Dictionaries, Tuples and Sets.

Some applications require additional functionality when working with data, for example, word
processors have an undo-redo function, task schedulers need queuing mechanisms, maps need
to find the shortest path, etc.
In these cases we need to define our own data structures that provide the required functionality.

Some of the most popular data structures are:


- Stacks
- Queues
- Linked Lists
- Graphs

We will implement the above data structures and use them to solve popular problems.
June 28, 2023

Data Structures

As we have seen in the previous lessons, Python supports the following collection
types: Lists, Dictionaries, Tuples, Sets.

Here are some general guidelines for choosing the correct data structure:
- Use a dictionary, when you need a logical association between a key:value
- Use lists if you have a collection of data that does not need random access. Try to
choose lists when you need a simple, iterable collection that is modified frequently.
- Use a set if you need uniqueness for the elements.
- Use tuples when your data cannot/should not change.
Many times, a tuple is used in combination with a dictionary, for example, a tuple can
represent a key, because it's immutable.
dictionary can use only immutable types as keys so ans is string and tuple
June 27, 2023

Sets are collections of unordered items that are unique.

They are created using curly braces, and, due to the way they're stored, it's faster to
check whether an item is part of a set using the in operator, rather than part of a list.

Sets cannot contain duplicate elements.


1

You can use the add() function to add new items to the set, and remove() to delete a
specific element:

Duplicate elements will automatically get removed from the set.

Sets can be combined using mathematical operations.


The union operator | combines two sets to form a new one containing items in either.
The intersection operator & gets items only in both.
The difference operator - gets items in the first set but not in the second.
The symmetric difference operator ^ gets items in either set, but not both.
The & operator can only be used on numbers, not strings. You are trying to use it on two strings,
which is not possible. Mistakes happen to the best of us!
June 26, 2023

Tuple unpacking allows you to assign each item in a collection to a variable.

This can be also used to swap variables by doing a, b = b, a , since b, a on the right
hand side forms the tuple (b, a) which is then unpacked.

A variable that is prefaced with an asterisk (*) takes all values from the collection that
are left over from the other variables.
c will get assigned the values 3 to 8.
14

* for
* in

June 25, 2023

Trying to reassign a value in a tuple causes an error.

Like lists and dictionaries, tuples can be nested within each other.
An advantage of tuples over lists is that they can be used as keys for dictionaries
(because they are immutable):

Tuples are faster than lists, but they cannot be changed.

June 22, 2023


A useful dictionary function is get(). It does the same thing as indexing, but if the key is
not found in the dictionary it returns another specified value instead.
To determine how many items a dictionary has, use the len() function.
June 6, 2023
Each element in a dictionary is represented by a key:value pair.
The code above will generate an error, as it tries to use a list as the key.

May 28, 2023


May 26, 2023
May 24, 2023
Note, that the reverse() and sort() functions change the list they are called on.
[ 4, 5, 8,

May 22, 2023

The len() function can be used to return the number of elements in a list.
n will represent the current list item during each iteration.
Data ([0], [1]) - function which is x
Bec data is a list

Loops* not if*

May 20, 2023


The code above outputs the 3rd item of the 2nd row.
A matrix-like structure can be used in cases where you need to store data in row-column format.

sep *
print(Y^-1[][])

May 19, 2023

In this situation you need a " \ " befor your single quote. The backslash is a escape character.If you would print out a backslash
you need " \\ " With " \n " you text behind it is in a new line.

\' in a single quote string will escape the single quote It's preferable to use double quotes to contain your strings

Practice makes permanent


May 16, 2023

Note, that these functions return a new string with the corresponding manipulation.
May 14, 2023
1
May 10, 2023
May 9, 2023
May 8, 2023

Python Data Structures

May 8, 2023
Print(“Error”)

May 7, 2023
This ensures that the file is always closed, even if an error occurs.

Yes
The file is automatically closed at the end of the with statement, even if exceptions
occur within it.

May 6, 2023
This will create a new file called "newfile.txt" and write the content to it.
In case the file already exists, its entire content will be replaced when you open it in
write mode using "w".
This will add a new line with a new book title to the file.

Remember, \n stands for a new line.

The code above will write to the file and print the number of bytes written.
content , size, =s

May 4, 2023
This will print all of the contents of the file.

file.close()
This will read the first 5 characters of the file, then the next 7.

Calling the read() method without an argument will return the rest of the file content.

4/2 =2

If you do not need the list for each line, you can simply iterate over the file variable:
In the output, the lines are separated by blank lines, as the print function automatically adds a new line at the end of its
output.
May 3, 2023
The argument of the open function is the path to the file. If the file is in the current working directory of the program,
you can specify only its name.
May 2, 2023

2
5

3 cant be added to “2” bec diff


integer & a string

So exception is raised and 3 is added to 2


Since exception is raised, the else statement doesnt run

Print (“None”)
Try
x =0+1 = 1 no Error
x except
x except
Proceed to else:
x = 1+1 =2
Proceed to finally:
x = 2+1 = 3

May 1, 2023

Raising Exceptions

You can throw (or raise) exceptions when some condition occurs.
For example, when you take user input that needs to be in a specific format, you can throw an exception when it does not
meet the requirements.
This is done using the raise statement.

You need to specify the type of the exception raised. In the code above, we raise a ValueError.

This makes it easier for other developers to understand why you raised the exception.
April 30, 2023
The finally block is useful, for example, when working with files and resources: it can be used to make sure files or
resources are closed or released regardless of whether an exception occurs.

13

else
The else statement can also be used with try/except statements.
In this case, the code within it is only executed if no error occurs in the try statement.
4

April 29, 2023

In the code above, the except statement defines the type of exception to handle (in our case, the ZeroDivisionError).
5.0 FInished

You can handle as many exceptions in the except statement as you need.

Divided by zero

An except statement without any exception specified will catch all errors. These should be used sparingly, as they can
catch unexpected errors and hide programming mistakes.
April 28, 2023

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program.
Python has several other built-in exceptions, such as ZeroDivisionError and OSError. Third-party libraries also often
define their own exceptions.

TypeError

April 27, 2023

Properties
Properties provide a way of customizing access to instance attributes.
They are created by putting the property decorator above a method, which means when the instance attribute with the
same name as the method is accessed, the method will be called instead.
One common use of a property is to make an attribute read-only.
Run the code and see how it works!

Properties can also be set by defining setter/getter functions.


The setter function sets the corresponding property's value.
The getter gets the value.
To define a setter, you need to use a decorator of the same name as the property, followed by a dot and
the setter keyword.
The same applies to defining getter functions.
Define a decorator that
@egg.setter
April 26, 2023
new_square is a class method and is called on the class, rather than on an instance of the class. It returns a new object of
the class cls.

Technically, the parameters self and cls are just conventions; they could be changed to anything else. However, they are
universally followed, so it is wise to stick to using them.

Static Methods
Static methods are similar to class methods, except they don't receive any additional arguments; they are identical to
normal functions that belong to a class.
They are marked with the staticmethod decorator.
Static methods behave like plain functions, except for the fact that you can call them from an instance of the class.
April 25, 2023
However, there are ways to discourage people from accessing parts of a class, such as by denoting that it is an
implementation detail, and should be used at their own risk.

Weakly private methods and attributes have a single underscore at the beginning.
This signals that they are private, and shouldn't be used by external code. However, it is mostly only a convention, and
does not stop external code from accessing them.
In the code above, the attribute _hiddenlist is marked as private, but it can still be accessed in the outside code.
The __repr__ magic method is used for string representation of the instance.

Strongly private methods and attributes have a double underscore at the beginning of their names. This causes their
names to be mangled, which means that they can't be accessed from outside the class.
The purpose of this isn't to ensure that they are kept private, but to avoid bugs if there are subclasses that have methods or
attributes with the same names.
Name mangled methods can still be accessed externally, but by a different name. The method __privatemethod of
class Spam could be accessed externally with _Spam__privatemethod.

Basically, Python protects those members by internally changing the name to include the class name.
April 18, 2023

The __add__ method allows for the definition of a custom behavior for the + operator in our class.
As you can see, it adds the corresponding attributes of the objects and returns a new object, containing the result.
Once it's defined, we can add two objects of the class together.
In the example above, we defined the division operation for our class SpecialString.

As you can see, you can define any custom behavior for the overloaded operators.
We have overridden the len() function for the class VagueList to return a random number.
The indexing function also returns a random item in a range from the list, based on the expression.
April 12, 2023
In the example above, Wolf is the superclass, Dog is the subclass.

2
super().spam() calls the spam method of the superclass.
April 11, 2023

In the example above, the __init__ method takes two arguments and assigns them to the object's attributes.
The __init__ method is called the class constructor.
Fill in the blanks to create a class and its constructor, taking one argument and assigning it to the "name" attribute. Then
create an object of the class.

__ init __ 2 underscores

Methods
Classes can have other methods defined to add functionality to them.
Remember, that all methods must have self as their first parameter.
These methods are accessed using the same dot syntax as attributes.
Fill in the blanks to create a class with a method sayHi().

April 10, 2023


April 8, 2023

The parameter *args must come after the named parameters to a function.
The name args is just a convention; you can choose to use another.

‘args’ is the NAME of the tuple


*args -way to let the computer know that a function has a dynamic # of args
a and b are the names of the arguments that we passed to the function call.
The arguments returned by **kwargs are not included in *args.
April 4, 2023
The base case acts as the exit condition of the recursion.
Not adding a base case results in infinite function calls, crashing the program.
5

April 2, 2023
Now print_text corresponds to our decorated version.

This will have the same result as the above code.


A single function can have multiple decorators.
Mar 26, 2023

Yes
In the code above, we created an anonymous function on the fly and called it with an argument.
Mar 25, 2023
The function apply_twice takes another function as its argument, and calls it twice inside its body.
print(max(min(nums[:2]), abs(-42)))

nums[:2] = (55, 44)

print(max(min(55, 44), abs(-42)))


min = 44

print(max(44, abs(-42)))
abs(-42) = 42

print(max(44, 42))
Mar 23, 2023

Sets cannot contain duplicate elements.

1
Duplicate elements will automatically get removed from the set.

The len() function can be used to return the number of elements of a set.
Mar 22, 2023

This can be also used to swap variables by doing a, b = b, a , since b, a on the right hand side forms the tuple (b,
a) which is then unpacked.
Like lists and dictionaries, tuples can be nested within each other.
Mar 19, 2023
Returning is useful when you don't need to print the result of the function, but need to use it in your code. For example, a
bank account's withdraw() function could return the remaining balance of the account.

7
12
Mar 17, 2023

As you can see from the example, the argument is defined inside the parentheses and is named word.
Arguments are used to pass information to the function. This allows us to reuse the function logic for different values.
Mar 15, 2023

def test():
Print(‘A’)
Print(‘B’)
Print(‘C’)
Note, that we call a function using its name and the parentheses.
Print(“Welcome, “ + user) don’t forget space

Mar 15, 2023

Mar 14, 2023


Each argument of the format function is placed in the string at the corresponding position, which is determined using the
curly braces { }.
We used a space ' ' as the split separator to get all words of the string as a list.
o

Mar 12, 2023


1

list.count(item): Returns a count of how many times an item occurs in a list.


list.remove(item): Removes an item from a list.
list.reverse(): Reverses items in a list.
Some examples:
Mar 9, 2023
Unlike indexing items, len does not start with 0. The list above contains 5 items, meaning len will return 5.

Remember that space is also a character.


6

Note, that the function is called using the list name, followed by a dot.
The first argument is the position index, while the second parameter is the item to insert at that position.

Mar 7, 2023
For ex:
[1, 2, 3, 4, 5]

After [1: -1] Will remain [2, 3, 4]

Mar 6, 2023
Mar 5, 2023
Mar 4, 2023
5
Mar 3, 2023
The first list item's index is 0, rather than 1, as you might expect.
The code above outputs the 3rd item of the 2nd row.
This repeats the list the specified number of times.

4
In -always small let
Mar 2, 2023

Five
Feb 28, 2023
73.0

50

82
Feb 24, 2023

Command llne
Enter:
// operator

It is used to divide the operands and will not give the output in float or decimal value even if required. It only gives
integer value as output.

https://brainly.in/question/20278365

You might also like