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

Резултати

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

Пребарај: #antiapartheid

当前筛选 #antiapartheid清除筛选

🕊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 7 marks the birthday of Johnny Clegg (1953–2019), South African musician, anthropologist, and anti-apartheid icon. 🎶 Known as "The White Zulu," he blended Western rock with Zulu rhythms, language, and dance in groundbreaking ways. 🎤 He co-founded the bands Juluka and Savuka, defying apartheid laws by bringing Black and white musicians together on stage. 🎵 One of his most powerful songs, Asimbonanga, was a tribute to Nelson Mandela during his imprisonment. 🔍Fun fact: Although many of his songs were banned in South Africa, Clegg gained global fame and became a symbol of cultural resistance and unity. #JohnnyClegg#Music#SouthAfrica#AntiApartheid#Birthday

🇿🇦Steve Biko — the Voice of Black Consciousness 🗓December 18 marks the birth of Steve Biko (Xhosa Steve Biko; full name Stephen Bantu Biko; 1946–1977), a prominent South African anti-apartheid activist and the founder of the Black Consciousness Movement. Biko was a committed Pan-Africanist and an advocate of African socialism. His ideas encouraged Black South Africans to reclaim their dignity, identity, and self-worth under apartheid ✊🏿 Killed as a result of police brutality, Steve Biko became a political martyr of the anti-apartheid struggle. ✍️ He wrote under the pseudonym Frank Talk — a name that can be understood both as “Frank, speak” and “honest / outspoken talk,” perfectly capturing the spirit of his writing. 🕯Steve Biko remains a lasting symbol of courage, consciousness, and the fight for human dignity. #SouthAfrica#History#SteveBiko#AntiApartheid#BlackConsciousness#HumanRights

🇿🇦🗓October 27 marks the birthday of Oliver Tambo (1917–1993) — a South African anti-apartheid activist who served for 24 years as President of the African National Congress (ANC). 🌍 He spent 30 years in exile. ✈️ In 2006, Johannesburg International Airport was renamed O. R. Tambo International Airport in his honor. 💬Quotes by Oliver Tambo: • 🇿🇦 “A country, a movement, a person that does not value its youth and children does not deserve its future.” • ⚖️ “Injustice anywhere is a threat to justice everywhere.” • 🤝 “True leaders do not seek power, they seek to empower others.” • 🚀 “Progress is not an accident; it is the result of concerted effort towards a common goal.” • 👥 “Differences should not divide us; they should be celebrated as a reflection of our shared humanity.” • 💖 “The legacy we leave behind is not measured by material wealth, but by the impact we have on the lives of others.” #History#SouthAfrica#OliverTambo#AntiApartheid#Inspiration#Leadership#Quotes

🇿🇦🎉On July 19, we remember Christopher van Wyk (1957–2014) — a South African poet, novelist, and beloved children’s author. ✊ He is widely known for his powerful poem In Detention, which exposes the suspicious deaths of political prisoners under apartheid. 📚 His writing was more than art — it was protest, memory, and truth-telling in the face of systemic injustice. 🕊 We remember. #SouthAfrica#Poetry#AntiApartheid#HumanRights#InDetention#ChristopherVanWyk#Literature#History

🇿🇦On July 21, we honor the legacy of Albert John Luthuli (1898–1967) — South African political leader, anti-apartheid activist, and president of the African National Congress (ANC). 🏆 In 1960, Luthuli became the first African recipient of the Nobel Peace Prize for his unwavering commitment to nonviolent resistance against racial oppression in apartheid South Africa. ✊ His moral leadership, courage, and commitment to equality continue to inspire generations. 💬 "I am a man of peace. My country can be free—without violence." 🕊 We remember. #AlbertLuthuli#SouthAfrica#NobelPeacePrize#HumanRights#AntiApartheid#History#Freedom#ANC