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

Резултати

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

Пребарај: #mandela

当前筛选 #mandela清除筛选

🕊November 7: The Woman Who Said “No” to Apartheid 🇿🇦🗓 November 7 marks the birthday of Helen Suzman (née Gavronsky; 1917–2009) — a South African activist and politician who bravely stood against apartheid. She was the only member of Parliament to consistently and unequivocally oppose all apartheid legislation. Suzman played a crucial role in improving prison conditions for members of the banned African National Congress (ANC), including Nelson Mandela, and she used her parliamentary privilege to bypass government censorship and share reports on the worst abuses of apartheid. She was nominated twice for the Nobel Peace Prize. 🕊 💬Quotes by Helen Suzman: • “I was the only one who said ‘no’ to apartheid, but that was no reason to keep quiet.” • “It is not my questions that embarrass South Africa—it is your answers.” (Addressed to the apartheid government during her time in Parliament.) • “The test of civilization is the way that it cares for its helpless members.” 📸 Photo: Wikipedia #SouthAfrica#History#HumanRights#AntiApartheid#Mandela

🗓 June 18 – Thabo Mbeki turns 83 On this day in 1942, Thabo Mvuyelwa Mbeki, the second President of South Africa (1999–2008) after Nelson Mandela, was born. As a young man, he studied in the Soviet Union and played a key role in the anti-apartheid movement. 🎓 Mbeki has long emphasized the power of education in transforming Africa. Here are some of his most compelling quotes: 💬 “We must prioritize education and invest in our young people. They are the future leaders and the driving force of our continent's development.” 💬 “Education is the key to unlocking the potential of our people. It’s the tool that will help us overcome challenges and build a brighter future.” 💬 “Education is not just about acquiring knowledge. It’s about developing critical thinking and a lifelong thirst for learning.” #Education#Mbeki#Birthday#SouthAfrica#Mandela

🗓🎉October 7 — Birthday of Archbishop Desmond Tutu (1931–2021) A fearless anti-apartheid activist, theologian, and the first Black South African Anglican bishop, Desmond Tutu received the Nobel Peace Prize in 1984 for his unwavering fight for justice and equality. ✝️✨ 🕊🇿🇦 After South Africa’s first democratic elections in 1994, President Nelson Mandela appointed him to chair the Truth and Reconciliation Commission (TRC) — a crucial step toward national healing after decades of apartheid. 💬Quotes by Desmond Tutu: • “If you want peace, you don’t talk to your friends. You talk to your enemies.” • “Hope is being able to see that there is light despite all of the darkness.” • “Without forgiveness, there is no future.” • “If you are neutral in situations of injustice, you have chosen the side of the oppressor.” • “Children are a wonderful gift. They have an extraordinary capacity to see into the heart of things and to expose sham and humbug for what they are.” #DesmondTutu#SouthAfrica#History#NobelPeacePrize#HumanRights#Mandela

🇿🇦 The Office of the Honorary Consul of South Africa met with Tatyana Mohamed — a Yekaterinburg native who has lived in South Africa for more than 30 years. 🌍✨ 📸 Her husband is a renowned photographer who used to work with Nelson Mandela. During the meeting, we shared insights about the activities of the Honorary Consul, Sergey Mazurkevich, and discussed opportunities for future cooperation and potential joint projects. 🤝 #SouthAfrica#Yekaterinburg#Diplomacy#Cooperation#Culture#Mandela#Photography#HonoraryConsul

NELSON MANDELA STATUE IN PRETORIA 🕊 The nine-meter statue of Nelson Mandela stands on the grounds of the Union Buildings in Pretoria. 🗓 It was officially unveiled on December 16, 2013, one day after the end of South Africa’s 10-day national mourning period, which followed Mandela’s passing on 5 December. 📍 The unveiling took place on Reconciliation Day, a symbolic moment marking a new chapter in the nation’s journey. With outstretched arms, the statue represents unity, reconciliation, and the spirit of Ubuntu — values Mandela championed throughout his life. More on Ubuntu in an upcoming post. #SouthAfrica#Mandela#Pretoria#UnionBuildings#Ubuntu#MandelaLegacy#ReconciliationDay#History#Architecture