From 4c0cdb2f7117b9022d28b5c9c25b0dd232eeadc7 Mon Sep 17 00:00:00 2001 From: oleg20111511 Date: Thu, 28 Apr 2022 04:34:45 +0300 Subject: [PATCH] Initial commit --- .gitignore | 1 + cpp/programs/knapsack_rewritable_array.cpp | 80 +++++++++++++++ cpp/programs/quick_primes.cpp | 100 +++++++++++++++++++ cpp/programs/random.cpp | 98 ++++++++++++++++++ cpp/programs/sort_merge.cpp | 92 +++++++++++++++++ cpp/programs/sort_quick.cpp | 73 ++++++++++++++ cpp/Импортирование/main.cpp | 8 ++ cpp/Импортирование/test.cpp | 7 ++ cpp/Классы/main.cpp | 29 ++++++ cpp/Основы/ввод.cpp | 20 ++++ cpp/Основы/вывод.cpp | 33 ++++++ cpp/Основы/комментарии.cpp | 19 ++++ cpp/Основы/переменные.cpp | 25 +++++ cpp/Структуры/if.cpp | 55 ++++++++++ cpp/Структуры/switch.cpp | 41 ++++++++ cpp/Типы данных/atomic.cpp | 38 +++++++ cpp/Типы данных/hash_table.cpp | 35 +++++++ cpp/Типы данных/set.cpp | 35 +++++++ cpp/Типы данных/векторы.cpp | 37 +++++++ cpp/Типы данных/массивы.cpp | 22 ++++ cpp/Типы данных/строки.cpp | 35 +++++++ cpp/Файлы/inp.txt | 6 ++ cpp/Файлы/main.cpp | 48 +++++++++ cpp/Файлы/out.txt | 1 + cpp/Функции/main.cpp | 38 +++++++ cpp/Функции/аргументы.cpp | 72 +++++++++++++ cpp/Циклы/for.cpp | 19 ++++ cpp/Циклы/while.cpp | 27 +++++ python/sqlalchemy/core.py | 70 +++++++++++++ python/sqlalchemy/orm.py | 54 ++++++++++ 30 files changed, 1218 insertions(+) create mode 100644 .gitignore create mode 100644 cpp/programs/knapsack_rewritable_array.cpp create mode 100644 cpp/programs/quick_primes.cpp create mode 100644 cpp/programs/random.cpp create mode 100644 cpp/programs/sort_merge.cpp create mode 100644 cpp/programs/sort_quick.cpp create mode 100644 cpp/Импортирование/main.cpp create mode 100644 cpp/Импортирование/test.cpp create mode 100644 cpp/Классы/main.cpp create mode 100644 cpp/Основы/ввод.cpp create mode 100644 cpp/Основы/вывод.cpp create mode 100644 cpp/Основы/комментарии.cpp create mode 100644 cpp/Основы/переменные.cpp create mode 100644 cpp/Структуры/if.cpp create mode 100644 cpp/Структуры/switch.cpp create mode 100644 cpp/Типы данных/atomic.cpp create mode 100644 cpp/Типы данных/hash_table.cpp create mode 100644 cpp/Типы данных/set.cpp create mode 100644 cpp/Типы данных/векторы.cpp create mode 100644 cpp/Типы данных/массивы.cpp create mode 100644 cpp/Типы данных/строки.cpp create mode 100644 cpp/Файлы/inp.txt create mode 100644 cpp/Файлы/main.cpp create mode 100644 cpp/Файлы/out.txt create mode 100644 cpp/Функции/main.cpp create mode 100644 cpp/Функции/аргументы.cpp create mode 100644 cpp/Циклы/for.cpp create mode 100644 cpp/Циклы/while.cpp create mode 100644 python/sqlalchemy/core.py create mode 100644 python/sqlalchemy/orm.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f47cb20 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.out diff --git a/cpp/programs/knapsack_rewritable_array.cpp b/cpp/programs/knapsack_rewritable_array.cpp new file mode 100644 index 0000000..7af0723 --- /dev/null +++ b/cpp/programs/knapsack_rewritable_array.cpp @@ -0,0 +1,80 @@ +#include +#include +#include + +using namespace std; + +ifstream input_stream; +ofstream output_stream; + + + +int getMaxValue(int P[], int W[], int C, int N) { + int table[2][C] = {0}; + + for (int i = 0; i < 2; i++) { + for (int j = 0; j < C; j++) { + table[i][j] = 0; + } + } + + for (int i = 0; i < N; i++) { + int *topRow; + int *bottomRow; + if (i % 2 == 0) { + topRow = table[0]; + bottomRow = table[1]; + } else { + topRow = table[1]; + bottomRow = table[0]; + } + + + if (1 >= W[i]) { + bottomRow[0] = max(P[i] + topRow[1 - W[i]], bottomRow[1 - 1]); + } else { + bottomRow[0] = bottomRow[1 - 1]; + } + + for (int w = 1; w < C; w++) { + if (w + 1 > W[i]) { + bottomRow[w] = max(P[i] + topRow[(w + 1) - W[i]], topRow[w]); + } else { + bottomRow[w] = topRow[w]; + } + + for (int y = 0; y < 2; y++) { + for (int x = 0; x < C; x++) { + cout << table[y][x] << " "; + } + cout << endl; + } + // string tmp; + // cin >> tmp; + } + } + + return max(table[0][C-1], table[1][C-1]); +} + + +int main() { + input_stream.open("input.txt"); + + int N, C; + input_stream >> N; + input_stream >> C; + + int P[N]; + int W[N]; + + for (int i = 0; i < N; i++) { + input_stream >> W[i]; + input_stream >> P[i]; + } + + cout << getMaxValue(P, W, C, N) << endl; + + input_stream.close(); + return 0; +} \ No newline at end of file diff --git a/cpp/programs/quick_primes.cpp b/cpp/programs/quick_primes.cpp new file mode 100644 index 0000000..c9581f6 --- /dev/null +++ b/cpp/programs/quick_primes.cpp @@ -0,0 +1,100 @@ +#include +#include +#include +using namespace std; + + + +int main() { + int start, end; + + cin >> start; + cin >> end; + // const int start = 1; + // const int end = 1000000; + + + + list primes; + + primes.push_back(1); + primes.push_back(2); + primes.push_back(3); + primes.push_back(5); + + // Fill all numbers, excluding most obvious non-primes numbers + for (int i = 6; i <= end; i++) { + if (i % 2 == 0 || i % 3 == 0 || i % 5 == 0) { + continue; + } + primes.push_back(i); + } + + auto it = primes.begin(); + advance(it, 4); + + int stop = sqrt(end); + for (it; *it <= stop; it++) { + /* + Go through all numbers in the list that are lower than sqrt(end) + The list is modified in the loop, allowing to skip processing of some numbers + */ + int factor = *it; + + auto it2 = it; + it2++; + + auto stop2 = primes.end(); + for (it2; it2 != stop2; it2++) { + /* + Go through all numbers that are greater than the *it, + removing them if they can be divided by *it + */ + + if (*it2 % factor == 0) { + auto tmp = next(it2); + + primes.erase(it2); + + it2 = prev(tmp); + } + } + } + + // A dumb way to handle end < 5 + if (end < primes.back()) { + auto trueEnd = primes.begin(); + auto stop = primes.end(); + while (trueEnd != stop && *trueEnd <= end) { + trueEnd++; + } + primes.erase(trueEnd, stop); + } + + + auto startIt = primes.end(); + auto primesEnd = primes.end(); + + it = primes.begin(); + for (it; it != primesEnd; it++) { + if (*it >= start) { + startIt = it; + break; + } + } + + if (start == end && *startIt != start) { + // Range contains only one number and it's not prime + cout << "Absent" << endl; + } else if (it == primesEnd) { + cout << "Absent" << endl; + } else { + it = startIt; + for (it; it != primesEnd; it++) { + cout << *it << " "; + } + cout << endl; + } + + return 0; +} \ No newline at end of file diff --git a/cpp/programs/random.cpp b/cpp/programs/random.cpp new file mode 100644 index 0000000..45f7544 --- /dev/null +++ b/cpp/programs/random.cpp @@ -0,0 +1,98 @@ +#include +#include +#include + +using namespace std; + + +typedef mt19937 MyRNG; +// uint32_t seed_val; + +MyRNG rng; +bool rngInitialized = false; + +const string ALPHABET = "abcdefghijklmnopqrstuvwxyz "; +const string DESIRED_STRING = "methinks it is like a weasel"; + + +void initialize_random() { + rng.seed(time(0)); +} + + +int randint(int start, int end) { + if (!rngInitialized) { + initialize_random(); + rngInitialized = true; + } + + uniform_int_distribution myDist(start, end); + return myDist(rng); +} + + +string generate_string(string seed) { + string result; + for (int i = 0; i < DESIRED_STRING.length(); i++) { + if (seed[i] == DESIRED_STRING[i]) { + result = result + seed[i]; + } else { + result = result + ALPHABET[randint(0, 26)]; + } + } + return result; +} + + +string generate_string() { + string seed; + for (int i = 0; i < DESIRED_STRING.length(); i++) { + seed = seed + '-'; + } + return generate_string(seed); +} + + +int appraise_string(string str) { + if (str == DESIRED_STRING) { + return 100; + } + + int correct = 0; + for (int i = 0; i < str.length(); i++) { + if (str[i] == DESIRED_STRING[i]) { + correct++; + } + } + + return (correct * 100) / DESIRED_STRING.length(); +} + + +int main() { + string res = generate_string(); + int current_attempt = appraise_string(res); + int best_attempt = current_attempt; + string best_attempt_str = res; + + int counter = 0; + while(current_attempt != 100) { + res = generate_string(best_attempt_str); + current_attempt = appraise_string(res); + + if (current_attempt > best_attempt) { + best_attempt = current_attempt; + best_attempt_str = res; + } + + if (counter == 1000) { + cout << "Current best attempt with " << best_attempt << "%: " << best_attempt_str << endl; + counter = 0; + } + + counter++; + } + + cout << "Generated result with counter at " << counter << endl; + return 0; +} \ No newline at end of file diff --git a/cpp/programs/sort_merge.cpp b/cpp/programs/sort_merge.cpp new file mode 100644 index 0000000..37dbb4a --- /dev/null +++ b/cpp/programs/sort_merge.cpp @@ -0,0 +1,92 @@ +#include +using namespace std; + +void merge(int array[], int left, int mid, int right) { + int leftArrLen = mid - left + 1; + int rightArrLen = right - mid; + + // Create temp arrays + int leftArray[leftArrLen]; + int rightArray[rightArrLen]; + + // Copy data to temp arrays leftArray[] and rightArray[] + for (int i = 0; i < leftArrLen; i++) { + leftArray[i] = array[left + i]; + } + + for (auto i = 0; i < rightArrLen; i++) { + rightArray[i] = array[mid + 1 + i]; + } + + int leftArrIndex = 0; // Initial index of first sub-array + int rightArrIndex = 0; // Initial index of second sub-array + int mergedArrIndex = left; // Initial index of merged array + + // Merge the temp arrays back into array[left..right] + while (leftArrIndex < leftArrLen && rightArrIndex < rightArrLen) { + // Choose one of the two elements at current positions of left and right arrays + if (leftArray[leftArrIndex] <= rightArray[rightArrIndex]) { + array[mergedArrIndex] = leftArray[leftArrIndex]; + leftArrIndex++; + } else { + array[mergedArrIndex] = rightArray[rightArrIndex]; + rightArrIndex++; + } + mergedArrIndex++; + } + + // Copy the remaining elements of + // left[], if there are any + while (leftArrIndex < leftArrLen) { + array[mergedArrIndex] = leftArray[leftArrIndex]; + leftArrIndex++; + mergedArrIndex++; + } + + // Copy the remaining elements of + // right[], if there are any + while (rightArrIndex < rightArrLen) { + array[mergedArrIndex] = rightArray[rightArrIndex]; + rightArrIndex++; + mergedArrIndex++; + } +} + + +void mergeSort(int arr[], int left, int right) { + if (left >= right) { + return; + } + + int middle = (left + right) / 2; + mergeSort(arr, left, middle); + mergeSort(arr, middle + 1, right); + merge(arr, left, middle, right); +} + +// 4 1 3 5 2 +// 4 1 3 5 2 [4, 1] [3] +// 4 1 3 5 2 [^1, 4] [^3] +// 1 1 3 5 2 [1, ^4] [^3] +// 1 3 3 5 2 [1, ^4] [3]^ +// 1 3 4 5 2 [^5] [^2] +// 1 3 4 2 2 [^5] [2]^ +// 1 3 4 2 5 + + + +int main() { + int N = 50; + int arr[N]; + for (int i = 0; i < N; i++) { + arr[i] = N - i; + } + + mergeSort(arr, 0, N - 1); + + for (int i = 0; i < N; i++) { + cout << arr[i] << " "; + } + cout << endl; + return 0; +} \ No newline at end of file diff --git a/cpp/programs/sort_quick.cpp b/cpp/programs/sort_quick.cpp new file mode 100644 index 0000000..4f0c8c5 --- /dev/null +++ b/cpp/programs/sort_quick.cpp @@ -0,0 +1,73 @@ +#include +using namespace std; + + +int partition(int arr[], int start, int end) { + int pivot = arr[start]; + + int count = 0; + for (int i = start + 1; i <= end; i++) { + if (arr[i] <= pivot){ + count++; + } + } + + // Giving pivot element its correct position + int pivotIndex = start + count; + swap(arr[pivotIndex], arr[start]); + + // Sorting left and right parts of the pivot element + int i = start, j = end; + + while (i < pivotIndex && j > pivotIndex) { + while (arr[i] <= pivot) { + // Find index of the first element from left that is higher than pivot + i++; + } + + while (arr[j] > pivot) { + // Find index of the first element from right that is lower than pivot + j--; + } + + if (i < pivotIndex && j > pivotIndex) { + swap(arr[i], arr[j]); + i++; + j--; + } + } + + return pivotIndex; +} + + +void quickSort(int arr[], int low, int high) { + if (low < high) { + int pi = partition(arr, low, high); + + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } +} +// 4 1 3 5 2 +// 5 1 3 4 2 +// 2 1 3 4 5 +// 1 2 3 4 5 + + + +int main() { + int N = 50; + int arr[N]; + for (int i = 0; i < N; i++) { + arr[i] = N - i; + } + + quickSort(arr, 0, N - 1); + + for (int i = 0; i < N; i++) { + cout << arr[i] << " "; + } + cout << endl; + return 0; +} \ No newline at end of file diff --git a/cpp/Импортирование/main.cpp b/cpp/Импортирование/main.cpp new file mode 100644 index 0000000..15aa49b --- /dev/null +++ b/cpp/Импортирование/main.cpp @@ -0,0 +1,8 @@ +#include "test.cpp" + +using namespace std; + +int main(){ + test_func(); + return 0; +} \ No newline at end of file diff --git a/cpp/Импортирование/test.cpp b/cpp/Импортирование/test.cpp new file mode 100644 index 0000000..fad0bc6 --- /dev/null +++ b/cpp/Импортирование/test.cpp @@ -0,0 +1,7 @@ +#include + +using namespace std; + +void test_func(){ + cout << "Hello World!\n"; +} \ No newline at end of file diff --git a/cpp/Классы/main.cpp b/cpp/Классы/main.cpp new file mode 100644 index 0000000..9b264c0 --- /dev/null +++ b/cpp/Классы/main.cpp @@ -0,0 +1,29 @@ +#include + +using namespace std; + +string name = "Cat"; + +// Объявление класса +class MyClass { + public: + int myNum; + string name; + + string str() { + return name; + } +}; + +int main() { + // Создание объекта + MyClass myObj; + + // Доступ к атрибутам + myObj.myNum = 5; + myObj.name = "Vincent"; + + cout << myObj.str() << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp/Основы/ввод.cpp b/cpp/Основы/ввод.cpp new file mode 100644 index 0000000..bceb8df --- /dev/null +++ b/cpp/Основы/ввод.cpp @@ -0,0 +1,20 @@ +#include +using namespace std; + +int main(){ + /* Ввод + Синтаксис: устройство >> переменная + cin - console input - консоль как устройство ввода + >> оператор ввода + */ + float num; + cout << "Введи число: "; // *Отсутствует endl + cin >> num; + cout << "Число в квадрате: " << num * num << endl; + + printf("Введи число: "); + scanf("%f", &num); // Ввод в стиле C + printf("Число, умноженное на 5: %f\n", num * 5); + + return 0; +} diff --git a/cpp/Основы/вывод.cpp b/cpp/Основы/вывод.cpp new file mode 100644 index 0000000..7282678 --- /dev/null +++ b/cpp/Основы/вывод.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; + +int main(){ + /* Вывод + Синтаксис: устройство << данные + cout - console out - консоль как устройство вывода + << - оператор вывода. При использовании этого синтаксиса способен конкатенировать строки. + endl - '\n' + */ + cout << "Ever heard of rubber duck debugging?" << endl; + cout << " __ " << endl; + cout << " <(o )___-" << endl; + cout << " ( .__> /" << endl; + cout << " `----' " << endl; + + printf("printf output: \n"); // Вывод в стиле C + char t; + t = 'f'; + printf("printf output char: %c\n", t); + /* + %[flags][width][.precision][length]specifier + c - character, s - string, d/i - integer, + o - unsigned integer (octal), x/X - unsigned integer (hexadecimal), + u - unsigned integer (decimal), f/F - float (decimal), + e/E - float (exponential), a/A - float (hexadecimal exponent), + g/G - float (decimal/decimal exponential?), + n - number of chars written by far using this call function, + p - a pointer that points to the implementation-defined character sequence + */ + + return 0; +} diff --git a/cpp/Основы/комментарии.cpp b/cpp/Основы/комментарии.cpp new file mode 100644 index 0000000..2b5c483 --- /dev/null +++ b/cpp/Основы/комментарии.cpp @@ -0,0 +1,19 @@ +#include + +using namespace std; + +int main() { + // Это комментарий + + /* + Это + многострочный + комментарий + */ + + /** + Это комментарий для документации + */ + + return 0; +} \ No newline at end of file diff --git a/cpp/Основы/переменные.cpp b/cpp/Основы/переменные.cpp new file mode 100644 index 0000000..d828466 --- /dev/null +++ b/cpp/Основы/переменные.cpp @@ -0,0 +1,25 @@ +#include + +using namespace std; + +int main() { + /* + Синтаксис: тип имя; + или: тип имя = значение; + */ + + int myInt; + myInt = 5; + float myFloat = 6.23; + double myDouble = 6.2340282; + + // Pointers + int *myPointer; + myPointer = &myInt; // создание ссылки + cout << "Значение из указателя: " << *myPointer << endl; // Получение значения из ссылки + + // None + myPointer = nullptr; + + return 0; +} \ No newline at end of file diff --git a/cpp/Структуры/if.cpp b/cpp/Структуры/if.cpp new file mode 100644 index 0000000..fee7001 --- /dev/null +++ b/cpp/Структуры/if.cpp @@ -0,0 +1,55 @@ +#include + +using namespace std; + +int main(){ + + /* + if (condition) { + statement1; + statement2; + ... + } else if (condition2) { + statement3; + statement4; + ... + } else { + statement 5; + statement 6; + ... + } + Работает только потому, что единственное выражение не требует {} + Иначе это записывалось бы как: + if (condition) { + statement1; + statement2; + ... + } else { + if (condition2) { + statement3; + statement4; + ... + } else { + statement5; + statement6; + ... + } + } + */ + + int inp; + + cout << "Введите число: "; + cin >> inp; + cout << endl; + + if (inp > 5) { + cout << "Ваше число больше 5" << endl; + } else if (inp == 5) { + cout << "Ваше число равно 5" << endl; + } else { + cout << "Ваше число меньше 5" << endl; + } + + return 0; +} \ No newline at end of file diff --git a/cpp/Структуры/switch.cpp b/cpp/Структуры/switch.cpp new file mode 100644 index 0000000..3cc16e5 --- /dev/null +++ b/cpp/Структуры/switch.cpp @@ -0,0 +1,41 @@ +#include + +using namespace std; +int main() { + /* + Синтаксис: + switch(var:int) { + case n:int: (возможно накопление) + statement; + break; + default: + statement; + } + */ + + + int inp; + + cout << "Введите оценку: "; + cin >> inp; + cout << endl; + + switch (inp) { + case 10: + case 9: + cout << "The grade is A" << endl; + break; + case 8: + cout << "The grade is B" << endl; + break; + case 7: + cout << "The grade is C" << endl; + break; + case 6: + cout << "The grade is D" << endl; + break; + default: + cout << "The grade is F" << endl; + } + return 0; +} \ No newline at end of file diff --git a/cpp/Типы данных/atomic.cpp b/cpp/Типы данных/atomic.cpp new file mode 100644 index 0000000..3dec8ba --- /dev/null +++ b/cpp/Типы данных/atomic.cpp @@ -0,0 +1,38 @@ +#include +#include // Функция pow + +using namespace std; + +int main() { + // Фундаментальные типы данных + + // Numeric: + int myInt; + myInt = 5; + float myFloat = 6.23; + double myDouble = 6.2340282; + + myInt = float(7) / 3; // Округляет вниз + cout << "Результат myInt = float(7)/3: " << myInt << endl; // 2 + + cout << "Результат 2+3*4: " << (2+3*4) << endl; // Тип integer, 14 + cout << "Результат float(7)/3: " << float(7)/3 << endl; // Тип float, 2.33333 + cout << "Результат 7/3: " << 7/3 << endl; // In C++ this is integer division, 2 + cout << "Результат 7%3: " << 7%3 << endl; // Тип integer, 1 + cout << "Результат 2^10: " << pow(2, 10) << endl; // Тип integer, 1024 + cout << "Результат 2^100000: " << pow(2, 100000) << endl; // infinity?, inf + + // Boolean + bool myBoolean; + // and - &&; or - ||; not - !; + + // Character + char myCharacter = 'f'; // Single quotes (') for chars, double (") for strings + + // Конвертация из одного типа в другой: + int origin = 50; + double origin_transformed = double(origin); + cout << "Преобразованная переменная: " << origin_transformed << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp/Типы данных/hash_table.cpp b/cpp/Типы данных/hash_table.cpp new file mode 100644 index 0000000..7da2d13 --- /dev/null +++ b/cpp/Типы данных/hash_table.cpp @@ -0,0 +1,35 @@ +#include +#include +#include + +using namespace std; + +int main() { + /* + Синтаксис: unordered_map<тип_ключа, тип_значения> имя; + Методы: + .count(key) - true если существует ключ key, иначе false + .erase(key) - удалить запись с ключом key + .begin() - возвращает итератор к первому элементу + .end() - возвращет итератор точке после последнего элемента + */ + unordered_map spnumbers; + + spnumbers = { {"one", "uno"}, {"two", "dos"} }; + + spnumbers["three"] = "tres"; + spnumbers["four"] = "cuatro"; + + cout << "Значение с ключом 'one': "; + cout << spnumbers["one"] << endl; + + cout << "Размер таблицы: "; + cout << spnumbers.size() << endl; + + // Итерация таблицы: + for (auto i=spnumbers.begin(); i!=spnumbers.end(); i++){ + cout << i->first << ":"; + cout << i->second << endl; + } + return 0; +} \ No newline at end of file diff --git a/cpp/Типы данных/set.cpp b/cpp/Типы данных/set.cpp new file mode 100644 index 0000000..7f2aa00 --- /dev/null +++ b/cpp/Типы данных/set.cpp @@ -0,0 +1,35 @@ +#include +#include + +using namespace std; + +int main() { + /* Множества + Синтаксис: + set<тип> имя = {n1, n2, n3...}; + */ + unordered_set mySet = {1, 3, 5, 78, 90}; + unordered_set mySet2 = {4, 9}; + + // Преобразование массива в множество: + char myChArr[] = {"aaabbbccc"}; + unordered_set mySet3 = unordered_set(begin(myChArr), end(myChArr)); + + cout << "Длина множества: " << mySet3.size() << endl; + cout << "Элементы множества:" << endl; + for (auto iter = mySet3.begin(); iter != mySet3.end(); iter++) { + cout << *iter << endl; + } + + // Преобразование строки в множество: + string myStr = "zfx"; + mySet3 = unordered_set(begin(myStr), end(myStr)); + + cout << "Длина множества: " << mySet3.size() << endl; + cout << "Элементы множества:" << endl; + for (auto iter = mySet3.begin(); iter != mySet3.end(); iter++) { + cout << *iter << endl; + } + + return 0; +} \ No newline at end of file diff --git a/cpp/Типы данных/векторы.cpp b/cpp/Типы данных/векторы.cpp new file mode 100644 index 0000000..d0578e9 --- /dev/null +++ b/cpp/Типы данных/векторы.cpp @@ -0,0 +1,37 @@ +#include +#include + +using namespace std; + +int main() { + // Вектор - массив, который может расти + /* Создание вектора + Синтаксис: vector<тип> имя; + Методы: + .push_back(item) - добавить в конец (append) + .pop_back() - удалить последний элемент + .insert(i, item) - вставить элемент на индекс i + .erase(i) - удалить элемент с индексом i + .size() - возвращает размер, занимаемый элементами + .capacity() - возвращает размер выделенного места (вместимость) + .reserve(amount) - запросить изменение вместимости + */ + + cout << "Векторы:" << endl; + vector myVector; + /* + Если не зарезервировать место заранее, то при каждом выходе за пределы размеров вектора + весь массив будет копироваться в вдвое большее место в памяти + */ + // myVector.reserve(19); + + for (int i=0; i<19; i++) { + myVector.push_back(i*i); + cout << myVector[i] << endl; + // cout << "capacity: " << myVector.capacity() << endl; + } + + cout << myVector.size() << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp/Типы данных/массивы.cpp b/cpp/Типы данных/массивы.cpp new file mode 100644 index 0000000..4398cd7 --- /dev/null +++ b/cpp/Типы данных/массивы.cpp @@ -0,0 +1,22 @@ +#include + +using namespace std; + +int main() { + /* Создание смежного массива + Синтаксис: тип название[размер]; + или: тип название[] = {n1, n2, n3...}; + */ + int myArr[50]; + int myArr2[] = {1, 2, 3, 4}; + + // Функции len нет, поэтому длина массива высчитывается из занимаемого места: + cout << "Длина массива: " << sizeof(myArr2) / sizeof(myArr2[0]) << endl; + + // Для новых версий c++: + for(int item:myArr2) { + cout << item << endl; + } + + return 0; +} \ No newline at end of file diff --git a/cpp/Типы данных/строки.cpp b/cpp/Типы данных/строки.cpp new file mode 100644 index 0000000..d7fdb81 --- /dev/null +++ b/cpp/Типы данных/строки.cpp @@ -0,0 +1,35 @@ +#include + +using namespace std; + +int main() { + /* Строки + Существует 2 типа: string (стиль c++) и массив char (стиль c) + Синтаксис: + string имя = "строка"; + char имя = {"строка"}; + Методы string: + .append(string) - добавить строку в конец + .push_back(char) - добавить символ в конец + .insert(i, string) - добавить строку на индекс i + .erase(i, j) - удалить элементы стоящие между i и j + .find(item) - возвращает индекс элемента + .length() - возвращает длину + .size() - тоже возвращает длину + */ + + string myStr = "string"; + char myChArr[] = {"string"}; + + cout << myStr << endl; + cout << "Размер: " << myStr.size() << "; Длина: " << myStr.length() << endl; + cout << "Позиция подстроки 'tr': " << myStr.find("tr") << endl; + cout << "Позиция подстроки 'if': " << myStr.find("if") << endl; // Выводит неприменимое число + + cout << "Все символы строки 'string':"<< endl; + for (int i = 0; i < myStr.length(); i++) { + cout << myStr[i] << endl; + } + + return 0; +} \ No newline at end of file diff --git a/cpp/Файлы/inp.txt b/cpp/Файлы/inp.txt new file mode 100644 index 0000000..a07677d --- /dev/null +++ b/cpp/Файлы/inp.txt @@ -0,0 +1,6 @@ +554 +1 4 +2 +3 +4 +5 \ No newline at end of file diff --git a/cpp/Файлы/main.cpp b/cpp/Файлы/main.cpp new file mode 100644 index 0000000..a3ba775 --- /dev/null +++ b/cpp/Файлы/main.cpp @@ -0,0 +1,48 @@ +#include +#include + +using namespace std; + +ifstream in_stream; +ofstream out_stream; + +int main() { + in_stream.open("inp.txt"); + out_stream.open("out.txt"); + + // Чтение файла + int N; + in_stream >> N; + + cout << "Полученное число из файла: "; + cout << N << endl; + + // Чтение двух чисел с одной строки: + int x; + in_stream >> x; + cout << "Первое число второй строки: " << x << endl; + int y; + in_stream >> y; + cout << "Второе число второй строки: " << y << endl; + + // Чтение до конца файла: + int sum = 0; + int tmp; + while(!in_stream.eof()) { + in_stream >> tmp; + sum += tmp; + } + /* Аналог: + while (in_stream >> tmp) { + sum += tmp; + } + */ + cout << "Сумма оставшихся чисел в файле: " << sum << endl; + + // Вывод в файл: + out_stream << sum << endl; + + in_stream.close(); + out_stream.close(); + return 0; +} \ No newline at end of file diff --git a/cpp/Файлы/out.txt b/cpp/Файлы/out.txt new file mode 100644 index 0000000..8351c19 --- /dev/null +++ b/cpp/Файлы/out.txt @@ -0,0 +1 @@ +14 diff --git a/cpp/Функции/main.cpp b/cpp/Функции/main.cpp new file mode 100644 index 0000000..74477a9 --- /dev/null +++ b/cpp/Функции/main.cpp @@ -0,0 +1,38 @@ +#include + +using namespace std; + +/* Синтаксис: +возвращаемый_тип имя(тип_параметра параметр, ...) { + return значение; +} +*/ + +int timesTwo(int num) { + return num * 2; +} + +void printNum(int num) { + cout << num << endl; +} + +double squareroot(double n) { + /** + Метод Ньютона + */ + double root = n / 2; + + for (int i = 0; i < 20; i++) { + cout << "Guess " << i << " root " << root << endl; + root = (.5) * (root + (n / root)); + } + + return root; +} + +int main() { + int res = timesTwo(5); // Вызов функции, возвращающей значение + printNum(res); // Вызов функции, не возвращающей значение + cout << squareroot(9) << endl; + return 0; +} \ No newline at end of file diff --git a/cpp/Функции/аргументы.cpp b/cpp/Функции/аргументы.cpp new file mode 100644 index 0000000..81ec020 --- /dev/null +++ b/cpp/Функции/аргументы.cpp @@ -0,0 +1,72 @@ +#include + +using namespace std; + +void unchangingFunc(int passedVar) { + passedVar = 5; // Значение меняется только внутри функции + cout << "Новое значение passedVar внутри unchangingFunc: " << passedVar << endl; +} + + +void swap(int &num1, int &num2) { + /** + & перед именем в списке аргументов означет, что передастся ссылка на память, + с которой можно работать как со значением (обратное преобразование не нужно) + */ + int temp; + temp = num1; + num1 = num2; + num2 = temp; +} + + +void add_lists( int first[], int second[], int total[], int length ) { + /** + При передаче массива значения в изначальном массиве также меняются + Это поведение можно предотвратить используя const: + void add_lists( const int first[], const int second[], int total[], int length ) + При таком объявлении, попытка изменить значения первых двух массивов внутри функции + вызовет ошибку + */ + for( int i = 0; i < length; i++ ) { + total[i] = first[i] + second[i]; + }; +} + + +/* +Перегрузка функций позволяет создать несколько функций с одинаковыми именами, +но разными параметрами или количеством параметров +*/ +void my_func(int first_arg) { + cout << "My func called with one int argument" << endl; +} + + +void my_func(double first_arg) { + cout << "My func called with one double argument" << endl; +} + + +void my_func(int first_arg, int second_arg) { + cout << "My func called with two int arguments" << endl; +} + + +int main() { + int myVar = 3; + unchangingFunc(myVar); // Внутри main значение myVar остаётся таким же + cout << "Новое значение myVar после unchangingFunc: " << myVar << endl; + + int myOtherVar = 9; + // При вызове функции, принимающей ссылки, дополнительные преобразования не нужны + swap(myVar, myOtherVar); + cout << "После смены мест значение myVar=" << myVar << ", myOtherVar=" << myOtherVar << endl; + + // Вызов перегруженный функций + my_func(4); + my_func(double(4)); + my_func(3, 5); + + return 0; +} \ No newline at end of file diff --git a/cpp/Циклы/for.cpp b/cpp/Циклы/for.cpp new file mode 100644 index 0000000..097b0c1 --- /dev/null +++ b/cpp/Циклы/for.cpp @@ -0,0 +1,19 @@ +#include + +using namespace std; + +int main() { + /* Синтаксис: + for (создание переменной; условие; выражение) { + statement1; + statement2; + ... + } + */ + + for (int i = 1; i <= 10; i++) { + cout << "You wasted another moment. Now here lay " << i << " dead kittens..." << endl; + } + + return 0; +} \ No newline at end of file diff --git a/cpp/Циклы/while.cpp b/cpp/Циклы/while.cpp new file mode 100644 index 0000000..525e857 --- /dev/null +++ b/cpp/Циклы/while.cpp @@ -0,0 +1,27 @@ +#include + +using namespace std; +int main (){ + /* Синтаксис: + while (condition) { + statement1; + statement2; + ... + } + или + do { + statement1; + statement2; + ... + } while (condition); + */ + + int i = 0; + while (i < 5) { + cout << "Hello world " << i << "! "; + i++; + } + cout << endl; + + return 0; +} \ No newline at end of file diff --git a/python/sqlalchemy/core.py b/python/sqlalchemy/core.py new file mode 100644 index 0000000..dfbb868 --- /dev/null +++ b/python/sqlalchemy/core.py @@ -0,0 +1,70 @@ +from sqlalchemy import MetaData +from sqlalchemy import Table, Column, Integer, String +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey + +# Model declarations +metadata_obj = MetaData() + +user_table = Table( + "user_account", + metadata_obj, + Column('id', Integer, primary_key=True), + Column('name', String(30)), + Column('fullname', String) +) + +address_table = Table( + "address", + metadata_obj, + Column('id', Integer, primary_key=True), + Column('user_id', ForeignKey('user_account.id'), nullable=False), + Column('email_address', String, nullable=False) +) + +# Connection +engine = create_engine("sqlite+pysqlite:///:memory:", future=True) + +# Model migration +metadata_obj.create_all(engine) + + + +# INSERT +from sqlalchemy import insert, select + +# values method +stmt = insert(user_table).values(name='spongebob', fullname="Spongebob Squarepants") +with engine.begin() as conn: + conn.execute(stmt) + + +# autogenerate values +with engine.connect() as conn: + conn.execute( + insert(user_table), + [ + {"name": "sandy", "fullname": "Sandy Cheeks"}, + {"name": "patrick", "fullname": "Patrick Star"} + ] + ) + conn.commit() + + +# insert..select +select_stmt = select(user_table.c.id, user_table.c.name + "@aol.com") +insert_stmt = insert(address_table).from_select( + ["user_id", "email_address"], select_stmt +) +with engine.begin() as conn: + res = conn.execute(insert_stmt) + + + +# SELECT +from sqlalchemy import select + +stmt = select(user_table).where(user_table.c.name == 'spongebob') +with engine.connect() as conn: + for row in conn.execute(stmt): + print(row) diff --git a/python/sqlalchemy/orm.py b/python/sqlalchemy/orm.py new file mode 100644 index 0000000..daaf5a3 --- /dev/null +++ b/python/sqlalchemy/orm.py @@ -0,0 +1,54 @@ +from sqlalchemy import Column, Integer, String +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy.orm import Session +from sqlalchemy.orm import registry +from sqlalchemy.orm import relationship + +mapper_registry = registry() +Base = mapper_registry.generate_base() + +# from sqlalchemy.orm import declarative_base +# Base = declarative_base() + + + +class User(Base): + __tablename__ = 'user_account' + + id = Column(Integer, primary_key=True) + name = Column(String(30)) + fullname = Column(String) + + addresses = relationship("Address", back_populates="user") + + def __repr__(self): + return f"User(id={self.id!r}, name={self.name!r}, fullname={self.fullname!r})" + + + +class Address(Base): + __tablename__ = 'address' + + id = Column(Integer, primary_key=True) + email_address = Column(String, nullable=False) + user_id = Column(Integer, ForeignKey('user_account.id')) + + user = relationship("User", back_populates="addresses") + + def __repr__(self): + return f"Address(id={self.id!r}, email_address={self.email_address!r})" + + +engine = create_engine("sqlite+pysqlite:///:memory:", future=True) +Base.metadata.create_all(engine) + + + + +# SELECT +from sqlalchemy import select +stmt = select(User).where(User.name == 'spongebob') +with Session(engine) as conn: + for row in conn.execute(stmt): + print(row)