Stock Recommendations from Yahoo Finance Using ML Models in Python.
Строим модель рекомендации по акциям от Yahoo Finance с использованием ML-моделей на Python.
@pythonl
Строим модель рекомендации по акциям от Yahoo Finance с использованием ML-моделей на Python.
import yfinance as yf
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import matplotlib.pyplot as plt
symbol = 'AAPL'
stock_data = yf.download(symbol, start='2022-01-05', end='2023-01-06')
df = pd.DataFrame(stock_data)
df['DailyReturn'] = df['Close'].pct_change()
df['Target'] = df['DailyReturn'].apply(lambda x: 1 if x > 0 else 0)
df = df.dropna()
X = df[['Open', 'High', 'Low', 'Close', 'Volume']]
y = df['Target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
predictions_df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
plt.figure(figsize=(10, 6))
plt.plot(predictions_df.index, predictions_df['Actual'], label='Actual')
plt.plot(predictions_df.index, predictions_df['Predicted'], label='Predicted')
plt.xlabel('Date')
plt.ylabel('Target')
plt.title('Actual vs. Predicted Stock Recommendations')
plt.legend()
plt.show()
@pythonl
В посте мы рассмотрим, как использовать PyWhatKit для создания отложенных сообщений WhatsApp с помощью Python. 🐍
pip install pywhatkit
import pywhatkit
phone_num = '+123456789'
message = 'hello'
hour = 17
minute = 25
try:
pywhatkit.sendwhatmsg(phone_num, message, hour, minute)
print(f'Message sent to {phone_num} successfully!')
except Exception as e:
print(f'Error: {str(e)}')
▪Github
▪Docs
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Введение в алгоритмы: Примеры алгоритмов на Python для новичков.
▪Bubble Sort
def bubble_sort(list):
for i in range(len(list)):
for j in range(len(list) - 1):
if list[j] > list[j + 1]:
list[j], list[j + 1] = list[j + 1], list[j] # swap
return list
▪Selection Sort
def selection_sort(list):
for i in range(len(list)):
min_index = i
for j in range(i + 1, len(list)):
if list[min_index] > list[j]:
min_index = j
list[i], list[min_index] = list[min_index], list[i] # swap
return list
▪Insertion Sort
def insertion_sort(list):
for i in range(1, len(list)):
key = list[i]
j = i - 1
while j >=0 and key < list[j] :
list[j+1] = list[j]
j -= 1
list[j+1] = key
return list
▪Quick Sortdef partition(array, low, high):
i = (low-1)
pivot = array[high]
for j in range(low, high):
if array[j] <= pivot:
i = i+1
array[i], array[j] = array[j], array[i]
array[i+1], array[high] = array[high], array[i+1]
return (i+1)
def quick_sort(array, low, high):
if len(array) == 1:
return array
if low < high:
partition_index = partition(array, low, high)
quick_sort(array, low, partition_index-1)
quick_sort(array, partition_index+1, high)
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
YAPF
A formatter for Python files.
YAPF - это форматировщик Python, основанный на clang-format. По сути, алгоритм анализирует код и вычисляет наилучшее форматирование, соответствующее заданному стилю. Это избавляет от хлопот, связанных с поддержкой кода.
Example:
reformat:
🖥 Github
@pythonl
A formatter for Python files.
YAPF - это форматировщик Python, основанный на clang-format. По сути, алгоритм анализирует код и вычисляет наилучшее форматирование, соответствующее заданному стилю. Это избавляет от хлопот, связанных с поддержкой кода.
$ pip install yapf
Example:
x = { 'a':37,'b':42,
'c':927}
y = 'hello ''world'
z = 'hello '+'world'
a = 'hello {}'.format('world')
class foo ( object ):
def f (self ):
return 37*-+2
def g(self, x,y=42):
return y
def f ( a ) :
return 37+-+a[42-x : y**3]
reformat:
x = {'a': 37, 'b': 42, 'c': 927}
y = 'hello ' 'world'
z = 'hello ' + 'world'
a = 'hello {}'.format('world')
class foo(object):
def f(self):
return 37 * -+2
def g(self, x, y=42):
return y
def f(a):
return 37 + -+a[42 - x:y**3]
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🔥 Подборка каналов для Python разработчиков
🖥 Machine learning
ai_ml – крупнейши канал по ии, нейросетям и науке о данных.
datasc - дата сайнс обучение самой востребованной профессии.
@bigdatai - Big Data
@machinelearning_ru – гайды по машинному обучению
@machinelearning_interview – подготовка к собеседованию мл.
@datascienceiot – бесплатные книги ds
@ArtificialIntelligencedl – ИИ
@machinee_learning – чат о машинном обучении
@datascienceml_jobs - вакансии ds, ml
@Machinelearning_Jobs - чат с вакансиями
🖥 Python
@pythonl - главный канал самого популярного языка программирования.
@pro_python_code – учим python с ментором.
@python_job_interview – подготовка к Python собеседованию.
@python_testit - проверочные тесты на python
@pythonlbooks - современные книги Python
@python_djangojobs - работа для Python программистов
@python_django_work - чат обсуждения вакансий
#️⃣ c# c++
C# - погружение в C#
@csharp_cplus чат
@csharp_1001_notes - инструменты C#
🖥 Machine learning
ai_ml – крупнейши канал по ии, нейросетям и науке о данных.
datasc - дата сайнс обучение самой востребованной профессии.
@bigdatai - Big Data
@machinelearning_ru – гайды по машинному обучению
@machinelearning_interview – подготовка к собеседованию мл.
@datascienceiot – бесплатные книги ds
@ArtificialIntelligencedl – ИИ
@machinee_learning – чат о машинном обучении
@datascienceml_jobs - вакансии ds, ml
@Machinelearning_Jobs - чат с вакансиями
🖥 SQL базы данных
@sqlhub - Повышение эффективности кода с грамотным использованием бд.
@chat_sql - чат изучения бд.
👣 Golang
@Golang_google - восхитительный язык от Google, мощный и перспективный.
@golang_interview - вопросы и ответы с собеседований по Go. Для всех уровней разработчиков.
@golangtests - интересные тесты и задачи GO
@golangl - чат изучающих Go
@GolangJobsit - отборные вакансии и работа GO
@golang_jobsgo - чат для ищущих работу.
@golang_books - полезные книги Golang
@golang_speak - обсуждение языка Go
@golangnewss - новости go
🖥 Linux
linux - kali linux ос для хакинга
linux chat - чат linux для обучения и помощи.
@linux_read - бесплатные книги linux
🖥 Javascript / front
@react_tg - - 40,14% разработчиков сайтов использовали React в 2022 году - это самая популярная библиотека для создания сайтов.
@javascript -канал для JS и FrontEnd разработчиков. Лучшие практики и примеры кода. Туториалы и фишки JS
@Js Tests - каверзные тесты JS
@hashdev - погружение в web разработку.
@javascriptjobjs - отборные вакансии и работа FrontEnd.
@jsspeak - чат поиска FrontEnd работы.
🖥 Java
@javatg - выучить Java с senior разработчиком на практике
@javachats - чат для ответов на вопросы по Java
@java_library - библиотека книг Java
@android_its - Android разработка
@java_quizes - тесты Java
@Java_workit - работа Java
@progersit - шпаргалки ит
👷♂️ IT работа
https://yangx.top/addlist/_zyy_jQ_QUsyM2Vi -ит каналы по яп с вакансиями
🤡It memes
@memes_prog - ит-мемы
⚙️ Rust
@rust_code - Rust избавлен от болевых точек, которые есть во многих современных яп
@rust_chats - чат rust
📓 Книги
https://yangx.top/addlist/HwywK4fErd8wYzQy - актуальные книги по всем яп
⭐️ Нейронные сети
@vistehno - chatgpt ведет блог, решает любые задачи и отвечает на любые ваши вопросы.
@aigen - сети для генерации картинок. видео, музыки и многого другого.
@neural – погружение в нейросети.
📢 English for coders
@english_forprogrammers - Английский для программистов
🖥 Devops
Devops - канал для DevOps специалистов.
ai_ml – крупнейши канал по ии, нейросетям и науке о данных.
datasc - дата сайнс обучение самой востребованной профессии.
@bigdatai - Big Data
@machinelearning_ru – гайды по машинному обучению
@machinelearning_interview – подготовка к собеседованию мл.
@datascienceiot – бесплатные книги ds
@ArtificialIntelligencedl – ИИ
@machinee_learning – чат о машинном обучении
@datascienceml_jobs - вакансии ds, ml
@Machinelearning_Jobs - чат с вакансиями
@pythonl - главный канал самого популярного языка программирования.
@pro_python_code – учим python с ментором.
@python_job_interview – подготовка к Python собеседованию.
@python_testit - проверочные тесты на python
@pythonlbooks - современные книги Python
@python_djangojobs - работа для Python программистов
@python_django_work - чат обсуждения вакансий
#️⃣ c# c++
C# - погружение в C#
@csharp_cplus чат
@csharp_1001_notes - инструменты C#
ai_ml – крупнейши канал по ии, нейросетям и науке о данных.
datasc - дата сайнс обучение самой востребованной профессии.
@bigdatai - Big Data
@machinelearning_ru – гайды по машинному обучению
@machinelearning_interview – подготовка к собеседованию мл.
@datascienceiot – бесплатные книги ds
@ArtificialIntelligencedl – ИИ
@machinee_learning – чат о машинном обучении
@datascienceml_jobs - вакансии ds, ml
@Machinelearning_Jobs - чат с вакансиями
@sqlhub - Повышение эффективности кода с грамотным использованием бд.
@chat_sql - чат изучения бд.
@Golang_google - восхитительный язык от Google, мощный и перспективный.
@golang_interview - вопросы и ответы с собеседований по Go. Для всех уровней разработчиков.
@golangtests - интересные тесты и задачи GO
@golangl - чат изучающих Go
@GolangJobsit - отборные вакансии и работа GO
@golang_jobsgo - чат для ищущих работу.
@golang_books - полезные книги Golang
@golang_speak - обсуждение языка Go
@golangnewss - новости go
linux - kali linux ос для хакинга
linux chat - чат linux для обучения и помощи.
@linux_read - бесплатные книги linux
@react_tg - - 40,14% разработчиков сайтов использовали React в 2022 году - это самая популярная библиотека для создания сайтов.
@javascript -канал для JS и FrontEnd разработчиков. Лучшие практики и примеры кода. Туториалы и фишки JS
@Js Tests - каверзные тесты JS
@hashdev - погружение в web разработку.
@javascriptjobjs - отборные вакансии и работа FrontEnd.
@jsspeak - чат поиска FrontEnd работы.
@javatg - выучить Java с senior разработчиком на практике
@javachats - чат для ответов на вопросы по Java
@java_library - библиотека книг Java
@android_its - Android разработка
@java_quizes - тесты Java
@Java_workit - работа Java
@progersit - шпаргалки ит
👷♂️ IT работа
https://yangx.top/addlist/_zyy_jQ_QUsyM2Vi -ит каналы по яп с вакансиями
🤡It memes
@memes_prog - ит-мемы
⚙️ Rust
@rust_code - Rust избавлен от болевых точек, которые есть во многих современных яп
@rust_chats - чат rust
📓 Книги
https://yangx.top/addlist/HwywK4fErd8wYzQy - актуальные книги по всем яп
@vistehno - chatgpt ведет блог, решает любые задачи и отвечает на любые ваши вопросы.
@aigen - сети для генерации картинок. видео, музыки и многого другого.
@neural – погружение в нейросети.
@english_forprogrammers - Английский для программистов
Devops - канал для DevOps специалистов.
Please open Telegram to view this post
VIEW IN TELEGRAM
👩❤👨Creating a Tinder bot in Python
Создание бота для Tinder на Python
💻Для этого проекта нужно скачать и установить Chromedriver.
▪ Video
@pythonl
Создание бота для Tinder на Python
💻Для этого проекта нужно скачать и установить Chromedriver.
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import time
opening_line = "Hi!"
number_of_swipes = 10
path = # paste your chromedriver path here
service = Service(executable_path=path)
web = 'https://tinder.com/'
options = Options()
options.add_experimental_option("debuggerAddress", "localhost:9222")
driver = webdriver.Chrome(service=service, options=options)
driver.get(web)
time.sleep(3)
for i in range(number_of_swipes):
try:
like_button = driver.find_element(by='xpath', value='//button//span[text()="Like"]')
driver.execute_script("arguments[0].click();", like_button)
time.sleep(2)
its_match_window = driver.find_element(by='xpath', value='//textarea[@placeholder="Say something nice!"]')
its_match_window.send_keys(opening_line)
time.sleep(1)
send_message_button = driver.find_element(by='xpath', value='//button/span[text()="Send"]')
send_message_button.click()
time.sleep(1)
close_its_match_window = driver.find_element(by='xpath', value='//button[@title="Back to Tinder"]')
close_its_match_window.click()
except:
try:
box = driver.find_element(by='xpath', value='//button/span[text()="Maybe Later"] | //button/span[text()="Not interested"] | //button/span[text()="No Thanks"]')
box.click()
except:
pass
▪ Video
@pythonl
Создание собственного генератора RANDOM.
import datetime
import pytz # Required library for time zone support
def randomnum(time_zone):
# Getting the current time in the specified time zone
time_now = datetime.datetime.now(pytz.timezone(time_zone))
# Getting time in terms of microseconds
random_seed = time_now.microsecond
# An equation which returns a number between 0 and 10
seed = random_seed * 8 % 11
# Making random number somewhat unpredictable
random_micro_secs = []
for i in range(seed):
random_micro_secs.append(time_now.second**seed)
seed_2 = sum(random_micro_secs)
# Generating the final random number
truly_random_num = (seed_2 * 8 % 11)
return truly_random_num
# Example usage
time_zone = 'America/New_York' # Specify the desired time zone
random_number = randomnum(time_zone)
print(random_number)
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Math for Devs - Cosine Similarity in Python
Математика для разработчиков - Косинусное сходство на Python
Функция Python cosine_similarity(vector1: list[float], vector2: list[float]) -> float: принимает на вход два вектора и вычисляет их косинусное сходство.
@pythonl
Математика для разработчиков - Косинусное сходство на Python
Функция Python cosine_similarity(vector1: list[float], vector2: list[float]) -> float: принимает на вход два вектора и вычисляет их косинусное сходство.
from math import sqrt, pow
def cosine_similarity(vector1: list[float], vector2: list[float]) -> float:
"""Returns the cosine of the angle between two vectors."""
# the cosine similarity between two vectors is the dot product of the two vectors divided by the magnitude of each vector
dot_product = 0
magnitude_vector1 = 0
magnitude_vector2 = 0
vector1_length = len(vector1)
vector2_length = len(vector2)
if vector1_length > vector2_length:
# fill vector2 with 0s until it is the same length as vector1 (required for dot product)
vector2 = vector2 + [0] * (vector1_length - vector2_length)
elif vector2_length > vector1_length:
# fill vector1 with 0s until it is the same length as vector2 (required for dot product)
vector1 = vector1 + [0] * (vector2_length - vector1_length)
# dot product calculation
for i in range(len(vector1)):
dot_product += vector1[i] * vector2[i]
# vector1 magnitude calculation
for i in range(len(vector1)):
magnitude_vector1 += pow(vector1[i], 2)
# vector2 magnitude calculation
for i in range(len(vector2)):
magnitude_vector2 += pow(vector2[i], 2)
# final magnitude calculation
magnitude = sqrt(magnitude_vector1) * sqrt(magnitude_vector2)
# return cosine similarity
return dot_product / magnitude
vector1 = [1, 2, 3]
vector2 = [2, 3, 4]
similarity = cosine_similarity(vector1, vector2)
print("The cosine similarity between vector1 and vector2 is: ", similarity
)@pythonl
How to Create Fake Access Points using Scapy in Python
Как создать поддельные точки доступа с помощью Scapy в Python
Мы генерируем случайный MAC-адрес, задаем имя точки доступа, которую хотим создать, а затем создаем фрейм 802.11.
@pythonl
Как создать поддельные точки доступа с помощью Scapy в Python
$ pip3 install faker scapy
from scapy.all import *
from threading import Thread
from faker import Faker
def send_beacon(ssid, mac, infinite=True):
dot11 = Dot11(type=0, subtype=8, addr1="ff:ff:ff:ff:ff:ff", addr2=mac, addr3=mac)
# ESS+privacy to appear as secured on some devices
beacon = Dot11Beacon(cap="ESS+privacy")
essid = Dot11Elt(ID="SSID", info=ssid, len=len(ssid))
frame = RadioTap()/dot11/beacon/essid
sendp(frame, inter=0.1, loop=1, iface=iface, verbose=0)
if __name__ == "__main__":
# number of access points
n_ap = 5
iface = "wlan0mon"
# generate random SSIDs and MACs
faker = Faker()
ssids_macs = [ (faker.name(), faker.mac_address()) for i in range(n_ap) ]
for ssid, mac in ssids_macs:
Thread(target=send_beacon, args=(ssid, mac)).start()
Мы генерируем случайный MAC-адрес, задаем имя точки доступа, которую хотим создать, а затем создаем фрейм 802.11.
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
pgAdmin 4 is a rewrite of the popular pgAdmin3 management tool for the PostgreSQL (http://www.postgresql.org) database.
Cамая популярная и многофункциональная платформа администрирования и разработки с открытым исходным кодом для PostgreSQL.
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Реализация шаблона Singleton в Python. Шаблон Singleton (Одиночка) один из самых часто используемых шаблонов. Его можно встретить во множестве проектов и он относительно прост для обучения. Его обязательно нужно знать и уметь его использовать.
▪Modify the new class method
▪Using the Metaclass approach
▪Using the decorator approach
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
A Minimal Example of Machine Learning (with scikit-learn)
Минимальный пример кода машинного обучения (с помощью scikit-learn)
@pythonl
Минимальный пример кода машинного обучения (с помощью scikit-learn)
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
data = [{'humidity': 80, 'wind': 20, 'temp': 15, 'clouds': 90, 'raining?': 'yes'},
{'humidity': 40, 'wind': 5, 'temp': 25, 'clouds': 15, 'raining?': 'no'},
{'humidity': 20, 'wind': 30, 'temp': 35, 'clouds': 50, 'raining?': 'no'},
{'humidity': 90, 'wind': 3, 'temp': 18, 'clouds': 100, 'raining?': 'yes'},
{'humidity': 70, 'wind': 13, 'temp': 22, 'clouds': 75, 'raining?': 'no'},
{'humidity': 85, 'wind': 10, 'temp': 17, 'clouds': 90, 'raining?': 'yes'},
{'humidity': 90, 'wind': 20, 'temp': 20, 'clouds': 80, 'raining?': 'yes'},
{'humidity': 60, 'wind': 5, 'temp': 23, 'clouds': 30, 'raining?': 'no'},
{'humidity': 95, 'wind': 25, 'temp': 13, 'clouds': 100, 'raining?': 'yes'},
{'humidity': 70, 'wind': 2, 'temp': 30, 'clouds': 100, 'raining?': 'no'},
]
df = pd.DataFrame(data, columns=['humidity', 'wind', 'temp', 'clouds', 'raining?'])
print(df)
X, y = df.to_numpy()[:8, :4], df.to_numpy()[:8, 4]
model = RandomForestClassifier()
model.fit(X, y)
model.predict([[95, 25, 13, 100],[70, 2, 30, 100]]).reshape(1, -1)
@pythonl
5 полезных скриптов автоматизации Python
1. Download Youtube videos
pip install pytube
from pytube import YouTube
# Specify the URL of the YouTube video
video_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
# Create a YouTube object
yt = YouTube(video_url)
# Select the highest resolution stream
stream = yt.streams.get_highest_resolution()
# Define the output path for the downloaded video
output_path = "path/to/output/directory/"
# Download the video
stream.download(output_path)
print("Video downloaded successfully!")
2. Automate WhatsApp messages
pip install pywhatkit
import pywhatkit
# Set the target phone number (with country code) and the message
phone_number = "+1234567890"
message = "Hello, this is an automated WhatsApp message!"
# Schedule the message to be sent at a specific time (24-hour format)
hour = 13
minute = 30
# Send the scheduled message
pywhatkit.sendwhatmsg(phone_number, message, hour, minute)
3. Google search with Python
pip install googlesearch-python
from googlesearch import search
# Define the query you want to search
query = "Python programming"
# Specify the number of search results you want to retrieve
num_results = 5
# Perform the search and retrieve the results
search_results = search(query, num_results=num_results, lang='en')
# Print the search results
for result in search_results:
print(result)
4. Download Instagram posts
pip install instaloader
import instaloader
# Create an instance of Instaloader
loader = instaloader.Instaloader()
# Define the target Instagram profile
target_profile = "instagram"
# Download posts from the profile
loader.download_profile(target_profile, profile_pic=False, fast_update=True)
print("Posts downloaded successfully!")
5. Extract audio from video files
pip install moviepy
from moviepy.editor import VideoFileClip
# Define the path to the video file
video_path = "path/to/video/file.mp4"
# Create a VideoFileClip object
video_clip = VideoFileClip(video_path)
# Extract the audio from the video
audio_clip = video_clip.audio
# Define the output audio file path
output_audio_path = "path/to/output/audio/file.mp3"
# Write the audio to the output file
audio_clip.write_audiofile(output_audio_path)
# Close the clips
video_clip.close()
audio_clip.close()
print("Audio extracted successfully!")
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
📶 Extract Saved WiFi Passwords in Python
Извлечение сохраненных паролей WiFi в Python (Linux OS)
@pythonl
Извлечение сохраненных паролей WiFi в Python (Linux OS)
import subprocess
import os
import re
from collections import namedtuple
import configparser
def get_linux_saved_wifi_passwords(verbose=1):
network_connections_path = "/etc/NetworkManager/system-connections/"
fields = ["ssid", "auth-alg", "key-mgmt", "psk"]
Profile = namedtuple("Profile", [f.replace("-", "_") for f in fields])
profiles = []
for file in os.listdir(network_connections_path):
data = { k.replace("-", "_"): None for k in fields }
config = configparser.ConfigParser()
config.read(os.path.join(network_connections_path, file))
for _, section in config.items():
for k, v in section.items():
if k in fields:
data[k.replace("-", "_")] = v
profile = Profile(**data)
if verbose >= 1:
print_linux_profile(profile)
profiles.append(profile)
return profiles
def print_linux_profiles(verbose):
"""Prints all extracted SSIDs along with Key (PSK) on Linux"""
print("SSID AUTH KEY-MGMT PSK")
print("-"*50)
get_linux_saved_wifi_passwords(verbose)
@pythonl
🔥 10 Tips And Tricks To Write Better Python Code
10 советов и приемов для написания лучшего кода на Python
1) Iterate c enumerate() вместо range(len())
2) list comprehension вместо for-loops
3) sorted() method
4) Хранение данных в Sets
5) Экономьте память с помощью генераторов
6) Определение значений по умолчанию в словарях с помощью .get() и .setdefault()
7) Подсчет хэшируемых объектов с помощью collections.Counter
8 ) Форматирование строк с помощью f-Strings
9) Конкатенация строк с помощью .join()
list_of_strings = ["Hello", "my", "friend"]
my_string = " ".join(list_of_strings)
10) Слияние словарей с синтаксисом двойной звездочки **.
10 советов и приемов для написания лучшего кода на Python
1) Iterate c enumerate() вместо range(len())
data = [1, 2, -3, -4]
# плохо:
for i in range(len(data)):
if data[i] < 0:
data[i] = 0
# хорошо:
data = [1, 2, -3, -4]
for idx, num in enumerate(data):
if num < 0:
data[idx] = 0
2) list comprehension вместо for-loops
#плохо:
squares = []
for i in range(10):
squares.append(i*i)
# хорошо:
squares = [i*i for i in range(10)]
3) sorted() method
data = (3, 5, 1, 10, 9)
sorted_data = sorted(data, reverse=True) # [10, 9, 5, 3, 1]
data = [{"name": "Max", "age": 6},
{"name": "Lisa", "age": 20},
{"name": "Ben", "age": 9}
]
sorted_data = sorted(data, key=lambda x: x["age"])
4) Хранение данных в Sets
my_list = [1,2,3,4,5,6,7,7,7]
my_set = set(my_list) # removes duplicates
primes = {2,3,5,7,11,13,17,19}
5) Экономьте память с помощью генераторов
# list comprehension
my_list = [i for i in range(10000)]
print(sum(my_list)) # 49995000
# generator comprehension
my_gen = (i for i in range(10000))
print(sum(my_gen)) # 49995000
import sys
my_list = [i for i in range(10000)]
print(sys.getsizeof(my_list), 'bytes') # 87616 bytes
my_gen = (i for i in range(10000))
print(sys.getsizeof(my_gen), 'bytes') # 128 bytes
6) Определение значений по умолчанию в словарях с помощью .get() и .setdefault()
my_dict = {'item': 'football', 'price': 10.00}
count = my_dict['count'] # KeyError!
# лучше:
count = my_dict.get('count', 0) # optional default value
count = my_dict.setdefault('count', 0)
print(count) # 0
print(my_dict) # {'item': 'football', 'price': 10.00, 'count': 0}
7) Подсчет хэшируемых объектов с помощью collections.Counter
from collections import Counter
my_list = [10, 10, 10, 5, 5, 2, 9, 9, 9, 9, 9, 9]
counter = Counter(my_list)
print(counter) # Counter({9: 6, 10: 3, 5: 2, 2: 1})
print(counter[10]) # 3
from collections import Counter
my_list = [10, 10, 10, 5, 5, 2, 9, 9, 9, 9, 9, 9]
counter = Counter(my_list)
most_common = counter.most_common(2)
print(most_common) # [(9, 6), (10, 3)]
print(most_common[0]) # (9, 6)
print(most_common[0][0]) # 9
8 ) Форматирование строк с помощью f-Strings
name = "Alex"
my_string = f"Hello {name}"
print(my_string) # Hello Alex
i = 10
print(f"{i} squared is {i*i}") # 10 squared is 100
9) Конкатенация строк с помощью .join()
list_of_strings = ["Hello", "my", "friend"]
#плохо:
my_string = ""
for i in list_of_strings:
my_string += i + " "
#хорошо
list_of_strings = ["Hello", "my", "friend"]
my_string = " ".join(list_of_strings)
10) Слияние словарей с синтаксисом двойной звездочки **.
d1 = {'name': 'Alex', 'age': 25}
d2 = {'name': 'Alex', 'city': 'New York'}
merged_dict = {**d1, **d2}
@pythonl