TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #32 · 7 фев.

Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять: from timeit import timeit def t1(): # складываем 10 строк через + из переменной t = 'text' for _ in range(1000): s = t + t + t + t + t + t + t + t + t def t2(): # склеиваем список строк через метод join arr = ['text'] * 10 for _ in range(1000): s = ''.join(arr) def t3(): # складываем через + но не из переменной а непосредственно инлайн объекты for _ in range(1000): s = 'text' + 'text' + 'text' + ... # всего 10 раз Теперь каждую строку склейки запустим по 10М раз >>> timeit(t1, number=10000) 0.21951690399964718 >>> timeit(t2, number=10000) 1.4978306379998685 >>> timeit(t3, number=10000) 0.2213820789993406 Хм, а нам говорили что через "+" это плохо и медленно ))) 😁 Тут стоит учитывать, что речь идёт о склейке множества длинных строк. Давайте изменим условия: def t4(): t = 'text'*100 for _ in range(1000): s = t + t + t + t + t + t + t + t + t def t5(): arr = ['text'*100] * 10 for _ in range(1000): s = ''.join(arr) def t6(): for _ in range(1000): s = 'text'*100 + 'text'*100 + ... # всего 10 раз >>> timeit(t4, number=10000) 12.795130728000004 >>> timeit(t5, number=10000) 2.642637542999182 >>> timeit(t6, number=10000) 0.2184546610005782 Вот, уже другой разговор, сразу видна разница, в среднем в 6 раз. Но погодите, почему последний тест t6() по скорости такой же как и t3()? Ведь строки теперь в 100 раз длиннее! Это вопросы оптимизации кода, какие простые изменения ускоряют или замедляют выполнение программы. Мы столкнулись с примером обхода обращения к переменной. Например, именно так работает директива #define в С++, во время компиляции подставляя значение переменной вместо ссылки на неё. В Python это тоже работает, но часто ли вы сможете встретить такой способ работы со строками? К сожалению, способ почти только теоретический. В целом, тесты показали то, что мы хотели. Делаем выводы самостоятельно. Полный листинг 🌍 #tricks

Резултати

Пронајдени 14 слични објави

Пребарај: #leisure

当前筛选 #leisure清除筛选

uShaka Marine World is a popular theme park that opened in 2004 in Durban, KwaZulu-Natal. The park is divided into four main sections: • uShaka Sea World – one of the largest aquariums in the world, ranked fifth globally. • uShaka Wet 'n Wild – a water park with thrilling slides and pools. • uShaka Beach – a scenic beach area perfect for relaxation and water sports. • uShaka Village Walk – a lively shopping and dining area with various stores and restaurants. The aquarium, designed to resemble a shipwreck, is home to dolphins, sharks, seals, penguins, turtles, and many species of fish, some of which are endangered. Visitors can enjoy spectacular dolphin and seal shows, dive into the aquarium with sharks in a special cage, or snorkel among colorful tropical fish. For children up to 12 years old, uShaka Kids World offers a massive play area with exciting rides, water slides, a giant sandbox, and creative activity spaces. 🌐Official Website: ushakamarine.com 🎥Video from uShaka Marine World:Watch here. #tourism#leisure

Diving in South Africa offers unforgettable adventures for everyone! From exploring the magical kelp forests with playful seals in Cape Town to thrilling close encounters with sharks along KwaZulu-Natal’s subtropical South Coast, every dive is a new discovery. Don’t miss the once-in-a-lifetime experience of the Sardine Run in Sodwana Bay—a true spectacle of nature. Discover the breathtaking beauty of South Africa both below and above the water. 🎥 Watch the video: Dive into Adventure #tourism#leisure

Henry, the world's oldest known crocodile, resides at the Crocworld Conservation Centre in Scottburgh, KwaZulu-Natal, South Africa. Born on December 16, 1900, in Botswana, Henry once gained infamy for preying on local children before being captured in 1903. Now a beloved zoo attraction, Henry has fathered over 10,000 offspring with six mates. Weighing 700 kilos and measuring 16 feet [4.9 m] in length, Henry's long life and prolific breeding highlight the resilience of Nile crocodiles and the importance of conservation. Source: Times of India http://timesofindia.indiatimes.com/articleshow/113071729.cms?utm_source=contentofinterest&utm_medium=text&utm_campaign=cppst Video: https://t.me/NationGeographic/9647 #nature#leisure

🐒Добро пожаловать в «Манкилэнд» (Monkeyland) – рай для приматов в Южной Африке!🌿 Недалеко от Плеттенберг-Бей, в 500 км к востоку от Кейптауна, находится «Манкилэнд» – первый в мире заповедник, где приматы свободно разгуливают в естественной среде. Здесь обитают спасённые обезьяны со всего мира: капуцины, лемуры, гиббоны и многие другие. Интересный факт: В «Манкилэнде» находится 128-метровый подвесной мост – самый длинный в мире! Готовы к захватывающему приключению? 🎥Видео: #туризм#отдых ___________________ 🐒Explore Monkeyland: A Primate Paradise in South Africa! 🌿 Located near Plettenberg Bay, about 500 km east of Cape Town, Monkeyland is the world’s first free-roaming primate sanctuary. Home to rescued monkeys from around the globe, visitors can stroll through a lush forest and spot capuchins, lemurs, and gibbons swinging freely. Fun fact: Monkeyland has a 128-meter suspension bridge—the longest of its kind in the world! Ready for a wild adventure? 🎥Video #tourism#leisure

Вчера мы рассказывали вам о тематическом парке «Морской мир Ушака» (uShaka Marine World). Короткое видео было снято в парке представителем русскоязычной диаспоры ЮАР. 🎥Видео из «Морского мира Ушака». #туризм#отдых ___________________ Yesterday, we posted about the uShaka Marine World theme park. The short video was made in the park by a member of the Russian-speaking community in South Africa. 🎥Video from uShaka Marine World. #tourism#leisure

💎«Завтрак у Тиффани» Завтрак морских котиков в окрестностях Кейптауна. 🦭 #Природа#Туризм#Отдых ___________________ 💎 Breakfast at Tiffany’s Seals are having breakfast not far from Cape Town. 🦭 📹https://t.me/annauar/2469 #Nature#Tourism#Leisure

В часе езды на юг от Кейптауна, в уютном Саймонстауне, находится знаменитый пляж Болдерс (Boulders Beach), где обитает колония очаровательных пингвинов. Это одно из немногих мест в мире, где можно увидеть африканских пингвинов вблизи в их естественной среде. 📹Видео #природа#туризм#отдых ___________________ Just an hour’s drive south of Cape Town, in the charming town of Simon’s Town, lies the famous Boulders Beach, home to a colony of adorable penguins. It’s one of the few places in the world where you can see African penguins up close in their natural habitat. 📹Video #nature#tourism#leisure

☕️Heaven Coffee Shop at the Cape Town Methodist Church A small coffee shop inside a large historical church is a unique and atmospheric experience. You can freely stroll around the hall, play chess, enjoy great coffee with desserts, and take beautiful photos. 📸 🕊Tip: Take your time — the space invites relaxation and admiration of the architecture. 🔗https://t.me/capetown_in_russian/1232 #CapeTown#Coffee#Leisure#Tourism#HeavenCoffeeShop

🖼Boulders Beach — Penguins on the Beach! 🌊 The beautiful Boulders Beach is one of Cape Town’s most visited and the only place in the world where you can get this close to African penguins. 🐧 The Boulders Penguin Colony in Simons Town is home to a unique and endangered land-based colony of African Penguins — one of only a few in the world. This site has become a famous international tourist destination. The Boulders section of Table Mountain National Park consists of three pristine beaches, one penguin-viewing area, and three wooden boardwalks — built to let visitors admire these wonderful birds while keeping them safe. Thanks to the huge boulders that shelter the cove from currents, wind, and waves, it’s one of the best spots in Cape Town for both penguins and people. 🌴 🎥 Watch the video: https://www.youtube.com/watch?v=yDiVyXEbiNE #SouthAfrica#CapeTown#Tourism#Leisure#Nature#Travel#Penguins

В ЮАР существует необычная профессия — наблюдатели за акулами (shark spotters). Их задача — следить за океаном и предупреждать сёрферов и отдыхающих на пляже при появлении акул вблизи побережья. Как именно они выполняют свою работу? Узнайте из видео! _____________ In South Africa, there is a job called shark spotters. They are supposed to warn surfers and swimmers if a shark is spotted in the distance. How do they do it? Watch the video. Видео / Video: https://t.me/prixodite_lyudi_vAfriku_gulyat/2498. #отдых#пляжи#туризм #leisure#beaches#tourism

🇿🇦🏔 World’s Longest Zip Line — Just Outside Cape Town! In 2024, K3 South Africa Forest Adventures launched a 3.2 km zip line — the longest in the world. It’s located in Caledon, about an hour from Cape Town, with a 500-meter drop and speeds of up to 120 km/h! 💨 📹 Video: https://www.youtube.com/watch?v=Jutf87MXLsE #SouthAfrica#CapeTown#Tourism#Adventure#Leisure#Extreme#Travel

12
ПретходнаСтраница 1 од 2Следна