0_python-sololearn[1]
0_python-sololearn[1]
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.
This can represent, for example, connections on a social network, where each Vertex
represents a person and the Edges represent connections.
G.display()
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.
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.
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.
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
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.
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
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.
You can use the add() function to add new items to the set, and remove() to delete a
specific element:
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
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):
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
sep *
print(Y^-1[][])
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
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
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.
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
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
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
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!
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().
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.
April 2, 2023
Now print_text corresponds to our decorated version.
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)))
print(max(44, abs(-42)))
abs(-42) = 42
print(max(44, 42))
Mar 23, 2023
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
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]
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