1636957060
Numerical analysis and methods | Math for AI - ML - Engineering, we talk about the bisection method and give an intuitive explanation on why it works. MATLAB implementation of bisection method is also given along the way. This lecture is outlined as follows:
Chapters
00:00 Intro
00:23 Bisection Method Requirements
03:07 Bisection Method
06:55 Convergence Speed of Bisection Method
07:17 Bisection Method on MATLAB
17:34 Bisection Method Validation on MATLAB
25:41 Outro
Note: The MATLAB code could easily be used in Python. Minimal changes could be done. The code is open-source with detailed explanation found within the shared link. Bisection method is a popular recursive techniques to estimate zeros or roots to almost any given equation, with linear convergence.
Lecture notes with detailed MATLAB code are on my website 👉 https://bazziahmad.com/2021/11/14/bisectionmethod
Instructor: Dr. Ahmad Bazzi
Subscribe: https://www.youtube.com/c/AhmadBazzi/featured
1604008800
Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.
Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.
“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”
We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.
We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.
Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast
module, and wide adoption of the language itself.
Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:
As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:
The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.
A token might consist of either a single character, like (
, or literals (like integers, strings, e.g., 7
, Bob
, etc.), or reserved keywords of that language (e.g, def
in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.
Python provides the tokenize
module in its standard library to let you play around with tokens:
Python
1
import io
2
import tokenize
3
4
code = b"color = input('Enter your favourite color: ')"
5
6
for token in tokenize.tokenize(io.BytesIO(code).readline):
7
print(token)
Python
1
TokenInfo(type=62 (ENCODING), string='utf-8')
2
TokenInfo(type=1 (NAME), string='color')
3
TokenInfo(type=54 (OP), string='=')
4
TokenInfo(type=1 (NAME), string='input')
5
TokenInfo(type=54 (OP), string='(')
6
TokenInfo(type=3 (STRING), string="'Enter your favourite color: '")
7
TokenInfo(type=54 (OP), string=')')
8
TokenInfo(type=4 (NEWLINE), string='')
9
TokenInfo(type=0 (ENDMARKER), string='')
(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)
#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer
1623856080
Have you ever visited a restaurant or movie theatre, only to be asked to participate in a survey? What about providing your email address in exchange for coupons? Do you ever wonder why you get ads for something you just searched for online? It all comes down to data collection and analysis. Indeed, everywhere you look today, there’s some form of data to be collected and analyzed. As you navigate running your business, you’ll need to create a data analytics plan for yourself. Data helps you solve problems , find new customers, and re-assess your marketing strategies. Automated business analysis tools provide key insights into your data. Below are a few of the many valuable benefits of using such a system for your organization’s data analysis needs.
…
#big data #latest news #data analysis #streamline your data analysis #automated business analysis #streamline your data analysis with automated business analysis
1623292080
Time series analysis is the backbone for many companies since most businesses work by analyzing their past data to predict their future decisions. Analyzing such data can be tricky but Python, as a programming language, can help to deal with such data. Python has both inbuilt tools and external libraries, making the whole analysis process both seamless and easy. Python’s Panda s library is frequently used to import, manage, and analyze datasets in various formats. However, in this article, we’ll use it to analyze stock prices and perform some basic time-series operations.
#data-analysis #time-series-analysis #exploratory-data-analysis #stock-market-analysis #financial-analysis #getting started with time series using pandas
1621628640
Python has a set of magic methods that can be used to enrich data classes; they are special in the way they are invoked. These methods are also called “dunder methods” because they start and end with double underscores. Dunder methods allow developers to emulate built-in methods, and it’s also how operator overloading is implemented in Python. For example, when we add two integers together, 4 + 2
, and when we add two strings together, “machine” + “learning”
, the behaviour is different. The strings get concatenated while the integers are actually added together.
If you have ever created a class of your own, you already know one of the dunder methods, __init__()
. Although it’s often referred to as the constructor, it’s not the real constructor; the __new__()
method is the constructor. The superclass’s __new__()
, super().__new__(cls[, ...])
, method is invoked, which creates an instance of the class, which is then passed to the __init__()
along with other arguments. Why go through the ordeal of creating the __new__()
method? You don’t need to; the __new__()
method was created mainly to facilitate the creation of subclasses of immutable types (such as int, str, list) and metaclasses.
#developers corner #uncategorized #dunder methods #magic methods #operator overriding #python dunder methods #python magic methods
1662358320
В любом языке программирования нам нужно иметь дело с данными. Теперь одной из самых фундаментальных вещей, которые нам нужны для работы с данными, является эффективное хранение, управление и доступ к ним организованным образом, чтобы их можно было использовать всякий раз, когда это необходимо для наших целей. Структуры данных используются для удовлетворения всех наших потребностей.
Структуры данных являются фундаментальными строительными блоками языка программирования. Он направлен на обеспечение системного подхода для выполнения всех требований, упомянутых ранее в статье. Структуры данных в Python — это List, Tuple, Dictionary и Set . Они считаются неявными или встроенными структурами данных в Python . Мы можем использовать эти структуры данных и применять к ним многочисленные методы для управления, связывания, манипулирования и использования наших данных.
У нас также есть пользовательские структуры данных, определяемые пользователем, а именно Stack , Queue , Tree , Linked List и Graph . Они позволяют пользователям полностью контролировать их функциональность и использовать их для расширенных целей программирования. Однако в этой статье мы сосредоточимся на встроенных структурах данных.
Неявные структуры данных Python
Списки помогают нам хранить наши данные последовательно с несколькими типами данных. Они сопоставимы с массивами за исключением того, что они могут одновременно хранить разные типы данных, такие как строки и числа. Каждый элемент или элемент в списке имеет назначенный индекс. Поскольку Python использует индексацию на основе 0, первый элемент имеет индекс 0, и подсчет продолжается. Последний элемент списка начинается с -1, что можно использовать для доступа к элементам от последнего к первому. Чтобы создать список, мы должны написать элементы внутри квадратных скобок .
Одна из самых важных вещей, которые нужно помнить о списках , это то, что они изменяемы . Это просто означает, что мы можем изменить элемент в списке, обратившись к нему напрямую как часть оператора присваивания с помощью оператора индексации. Мы также можем выполнять операции в нашем списке, чтобы получить желаемый результат. Давайте рассмотрим код, чтобы лучше понять список и операции со списками.
1. Создание списка
#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)
Выход
['p', 'r', 'o', 'b', 'e']
2. Доступ к элементам из списка
#accessing the list
#accessing the first item of the list
my_list[0]
Выход
'p'
#accessing the third item of the list
my_list[2]
'o'
3. Добавление новых элементов в список
#adding item to the list
my_list + ['k']
Выход
['p', 'r', 'o', 'b', 'e', 'k']
4. Удаление элементов
#removing item from the list
#Method 1:
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
# delete one item
del my_list[2]
print(my_list)
# delete multiple items
del my_list[1:5]
print(my_list)
Выход
['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
print(my_list)
#Method 3:
#with pop function
print(my_list.pop(1))
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)
Выход
['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']
5. Список сортировки
#sorting of list in ascending order
my_list.sort()
print(my_list)
Выход
['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
my_list.sort(reverse=True)
print(my_list)
Выход
['y', 'r', 'm', 'l', 'k']
6. Нахождение длины списка
#finding the length of list
len(my_list)
Выход
5
Кортежи очень похожи на списки с той ключевой разницей, что кортеж является IMMUTABLE , в отличие от списка. Как только мы создаем кортеж или имеем кортеж, нам не разрешается изменять элементы внутри него. Однако если у нас есть элемент внутри кортежа, который сам является списком, только тогда мы можем получить доступ к этому списку или изменить его. Чтобы создать кортеж, мы должны написать элементы внутри круглых скобок . Как и со списками, у нас есть аналогичные методы, которые можно использовать с кортежами. Давайте рассмотрим некоторые фрагменты кода, чтобы понять, как использовать кортежи.
1. Создание кортежа
#creating of tuple
my_tuple = ("apple", "banana", "guava")
print(my_tuple)
Выход
('apple', 'banana', 'guava')
2. Доступ к элементам из кортежа
#accessing first element in tuple
my_tuple[1]
Выход
'banana'
3. Длина кортежа
#for finding the lenght of tuple
len(my_tuple)
Выход
3
4. Преобразование кортежа в список
#converting tuple into a list
my_tuple_list = list(my_tuple)
type(my_tuple_list)
Выход
list
5. Реверс кортежа
#Reversing a tuple
tuple(sorted(my_tuple, reverse=True))
Выход
('guava', 'banana', 'apple')
6. Сортировка кортежа
#sorting tuple in ascending order
tuple(sorted(my_tuple))
Выход
('apple', 'banana', 'guava')
7. Удаление элементов из кортежа
Для удаления элементов из кортежа мы сначала преобразовали кортеж в список, как мы сделали в одном из наших методов выше (пункт № 4), затем следовали тому же процессу списка и явно удалили весь кортеж, просто используя del заявление .
Словарь — это коллекция, которая просто означает, что она используется для хранения значения с некоторым ключом и извлечения значения по данному ключу. Мы можем думать об этом как о наборе пар ключ: значение, и каждый ключ в словаре должен быть уникальным , чтобы мы могли получить соответствующий доступ к соответствующим значениям .
Словарь обозначается фигурными скобками { } , содержащими пары ключ: значение. Каждая из пар в словаре разделена запятой. Элементы в словаре неупорядочены , последовательность не имеет значения, пока мы обращаемся к ним или сохраняем их.
Они ИЗМЕНЯЕМЫ , что означает, что мы можем добавлять, удалять или обновлять элементы в словаре. Вот несколько примеров кода, чтобы лучше понять словарь в Python.
Важно отметить, что мы не можем использовать изменяемый объект в качестве ключа в словаре. Таким образом, список не допускается в качестве ключа в словаре.
1. Создание словаря
#creating a dictionary
my_dict = {
1:'Delhi',
2:'Patna',
3:'Bangalore'
}
print(my_dict)
Выход
{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
Здесь целые числа — это ключи словаря, а название города, связанное с целыми числами, — это значения словаря.
2. Доступ к элементам из словаря
#access an item
print(my_dict[1])
Выход
'Delhi'
3. Длина словаря
#length of the dictionary
len(my_dict)
Выход
3
4. Сортировка словаря
#sorting based on the key
Print(sorted(my_dict.items()))
#sorting based on the values of dictionary
print(sorted(my_dict.values()))
Выход
[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
['Bangalore', 'Delhi', 'Patna']
5. Добавление элементов в Словарь
#adding a new item in dictionary
my_dict[4] = 'Lucknow'
print(my_dict)
Выход
{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}
6. Удаление элементов из словаря
#for deleting an item from dict using the specific key
my_dict.pop(4)
print(my_dict)
#for deleting last item from the list
my_dict.popitem()
#for clearing the dictionary
my_dict.clear()
print(my_dict)
Выход
{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}
Set — это еще один тип данных в python, представляющий собой неупорядоченную коллекцию без повторяющихся элементов. Общие варианты использования набора — удаление повторяющихся значений и проверка принадлежности. Фигурные скобки или set()функция могут использоваться для создания наборов. Следует иметь в виду, что при создании пустого набора мы должны использовать set(), и . Последний создает пустой словарь. not { }
Вот несколько примеров кода, чтобы лучше понять наборы в python.
1. Создание набора
#creating set
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)
Выход
{'apple', 'strawberry', 'mango'}
2. Доступ к элементам из набора
#to test for an element inside the set
"apple" in my_set
Выход
True
3. Длина набора
print(len(my_set))
Выход
3
4. Сортировка набора
print(sorted(my_set))
Выход
['apple', 'mango', 'strawberry']
5. Добавление элементов в Set
my_set.add("guava")
print(my_set)
Выход
{'apple', 'guava', 'mango', 'strawberry'}
6. Удаление элементов из Set
my_set.remove("mango")
print(my_set)
Выход
{'apple', 'guava', 'strawberry'}
В этой статье мы рассмотрели наиболее часто используемые структуры данных в Python, а также рассмотрели различные связанные с ними методы.
Ссылка: https://www.askpython.com/python/data
#python #datastructures