#defaultdict
Explore tagged Tumblr posts
platypus-platypus-platypus · 2 months ago
Text
29/04/25
'abc' - 4 empty strings...
1st way:
import math
area = math.pi
2nd way:
From math import pi as MY_PI
random.seed(0)
no real random, same order of int every time
os - interacting with operating system
defaultdict in collection library
(must initialise counter??)
from collections import Counter
0 notes
shalu620 · 1 year ago
Text
Python Performance in Large-Scale Projects: Advanced Techniques
Python’s simplicity and flexibility make it a go-to language for developers. However, its performance can sometimes be a bottleneck, especially in large-scale projects. To tackle these challenges, we explore advanced features and techniques in Python that can optimize performance and efficiency. Considering the kind support of Learn Python Course in Hyderabad, Whatever your level of experience or reason for switching from another programming language, learning Python gets much more fun.
Tumblr media
Introduction: Addressing Performance Challenges in Python
Large-scale projects demand high performance and efficiency, areas where Python can sometimes fall short. By leveraging advanced features and techniques, you can significantly boost the performance of your Python applications, making them faster and more robust.
Leveraging Asyncio for Concurrent Programming
Asynchronous programming is a powerful way to improve performance by running tasks concurrently. Python’s asyncio module excels in handling I/O-bound operations like network requests and database access, allowing these tasks to run concurrently and reducing idle time.
Multiprocessing for Parallel Execution
For computation-heavy tasks, utilizing multiple CPU cores can dramatically enhance performance. The multiprocessing module in Python enables parallel execution by creating separate processes for different cores, making it ideal for CPU-bound tasks.
Boosting Speed with Cython
Cython bridges the gap between Python and C, allowing you to write C extensions for Python code. By converting Python code into C, Cython can significantly speed up execution, particularly for computationally intensive tasks.
Numerical Computation with NumPy
NumPy is indispensable for numerical operations in Python. It supports large arrays and matrices, and its highly optimized functions can handle large datasets efficiently, making it a cornerstone for numerical computation in large-scale projects.
Enrolling in the Best Python Certification Online can help people realise Python’s full potential and gain a deeper understanding of its complexities.
Tumblr media
Utilizing PyPy for Just-In-Time Compilation
PyPy, an alternative Python interpreter with a Just-In-Time (JIT) compiler, dynamically optimizes code during runtime. PyPy can provide substantial performance improvements, especially for long-running applications, with minimal changes to the existing codebase.
Memory Efficiency with Generators
Generators in Python are perfect for handling large datasets with minimal memory usage. By yielding items one at a time, generators reduce memory overhead, making them ideal for large-scale data processing tasks.
Specialized Data Structures from Collections Module
The collections module offers specialized data structures such as deque, Counter, and defaultdict that are more efficient for certain operations than built-in types. Using these structures can lead to faster operations and lower memory usage.
Buffered I/O for Faster File Handling
Buffered I/O streams, available through Python’s io module, can enhance file operation performance by minimizing the number of I/O operations. Buffered readers and writers reduce disk access frequency, speeding up read and write tasks.
Profiling Tools for Performance Analysis
Profiling tools are essential for identifying and addressing performance bottlenecks. Tools like cProfile, line_profiler, and memory_profiler help you measure execution time and memory usage, enabling targeted optimizations.
Selecting Efficient Algorithms and Data Structures
Choosing the right algorithms and data structures is critical for optimizing performance. Understanding their time and space complexities allows you to select the most efficient approach for your problem, leading to significant performance improvements.
Conclusion
Optimizing performance in large-scale Python projects requires a strategic approach, leveraging advanced features and techniques. By using concurrency with asyncio, parallelism with multiprocessing, Cython, NumPy, and PyPy, along with efficient memory management and profiling tools, you can enhance the performance of your Python applications. These optimizations not only improve speed but also scalability and maintainability, ensuring your large-scale projects run efficiently.
By continuously refining and optimizing your code, you can maintain high performance standards as your project evolves. These advanced techniques provide a robust toolkit for overcoming Python’s performance limitations, enabling you to build efficient and scalable applications.
0 notes
edcater · 1 year ago
Text
Building Bridges: Intermediate Python Programming Tips and Tricks
Python, a versatile and powerful programming language, serves as a gateway for developers to create robust and scalable applications. If you've already mastered the basics, it's time to build bridges to the next level of expertise with intermediate Python programming. In this article, we'll explore essential tips and tricks that will help you elevate your Python skills and enhance your ability to tackle more complex projects.
1. Diving Deeper into Functions
Functions are the building blocks of any Python program, and understanding them thoroughly is crucial for intermediate programmers. Explore advanced concepts such as lambda functions, closures, and decorators. Lambda functions allow you to create concise anonymous functions, closures enable data encapsulation, and decorators add a layer of functionality to existing functions. Mastering these concepts empowers you to write more modular and efficient code.
2. Embracing Object-Oriented Programming (OOP)
Take your Python programming to the next level by delving into the world of Object-Oriented Programming. Learn how to create classes and objects, encapsulate data, and implement inheritance and polymorphism. Understanding OOP principles enhances code organization, promotes reusability, and facilitates the development of large-scale applications. This section will guide you through the fundamentals of OOP and its practical applications in Python.
3. Handling Exceptions Gracefully
Error handling is a crucial aspect of programming, and Python provides a robust mechanism for dealing with exceptions. Explore the 'try', 'except', 'else', and 'finally' blocks to gracefully handle errors and prevent your programs from crashing. Learn to raise custom exceptions to provide meaningful error messages, making it easier to debug and maintain your code. This section will guide you through the art of effective error handling in Python.
4. Exploring Advanced Data Structures
While lists and dictionaries are fundamental data structures in Python, intermediate programmers should expand their repertoire. Explore advanced data structures such as sets, tuples, and collections like defaultdict and namedtuple. Understanding when and how to use these structures can significantly improve the efficiency and readability of your code. This section will provide practical examples to illustrate the benefits of these advanced data structures.
5. Mastering File Handling
Efficient file handling is a crucial skill for any intermediate Python programmer. Learn how to read and write different file formats, including text files, CSV, JSON, and more. Dive into file handling best practices, such as using the 'with' statement for automatic resource management and error handling. This section will equip you with the knowledge to manipulate files seamlessly within your Python programs.
6. Harnessing the Power of Libraries and Modules
Python's strength lies in its extensive collection of libraries and modules. Explore popular libraries like NumPy, pandas, and Matplotlib for data manipulation, analysis, and visualization. Learn how to install and import external libraries, and understand the basics of virtual environments to manage dependencies effectively. This section will guide you through leveraging third-party tools to enhance the functionality of your Python programs.
7. Conquering Regular Expressions
Regular expressions are powerful tools for string manipulation and pattern matching. As an intermediate Python programmer, it's essential to master the art of regex. Explore the 're' module and learn how to create complex patterns, validate input, and extract information from strings efficiently. This section will provide hands-on examples to help you become proficient in using regular expressions in Python.
8. Optimizing Code for Performance
Efficiency is paramount when it comes to writing production-ready code. In this section, delve into techniques for optimizing Python code for better performance. Explore concepts such as list comprehensions, generator expressions, and profiling tools. Learn when to use these techniques to achieve faster execution and lower memory consumption. This knowledge will empower you to write code that not only works but works efficiently.
Conclusion: Building Bridges to Advanced Python Programming
By mastering the intermediate Python programming tips and tricks outlined in this article, you're well on your way to becoming a proficient Python developer. From advanced functions and OOP principles to efficient file handling and performance optimization, these skills form the foundation for tackling more complex projects and building robust applications. As you continue your Python journey, remember that practice and hands-on experience are key to solidifying your expertise. So, roll up your sleeves and start applying these tips to take your Python programming skills to new heights. Happy coding!
0 notes
y2fear · 1 year ago
Photo
Tumblr media
Defaultdict in Python - Analytics Vidhya
0 notes
pythontipsnadtricks · 2 years ago
Text
Built-in Modules in Python
Built-in modules in Python (learn python online) are pre-existing libraries that provide a wide range of functionalities to streamline and simplify various programming tasks. These modules are available as part of the standard Python library and cover a diverse array of areas, from mathematical calculations to working with files and managing dates. Here are some key built-in modules in Python:
math: This module offers mathematical functions, such as trigonometric, logarithmic, and arithmetic operations, providing access to mathematical constants like pi and e.
datetime: The datetime module allows manipulation and formatting of dates and times. It includes classes for working with dates, times, time intervals, and timezones.
random: The random module enables the generation of random numbers, providing functions for generating random integers, floating-point numbers, and random selections from sequences.
os: The os module offers a wide range of operating system-related functionalities. It provides functions for interacting with the file system, working with directories, and executing system commands.
sys: The sys module provides access to Python interpreter variables and functions, allowing interaction with the runtime environment. It's commonly used for handling command-line arguments and controlling the Python interpreter.
re: The re module is used for regular expression operations. It enables pattern matching and manipulation of strings based on specified patterns.
json: The json module facilitates encoding and decoding of JSON (JavaScript Object Notation) data, which is widely used for data interchange between applications.
collections: The collections module provides additional data structures beyond the built-in ones. It includes specialized container data types like OrderedDict, defaultdict, and namedtuple.
math: The math module contains mathematical functions and constants for more advanced calculations, including trigonometric, logarithmic, and exponential operations.
time: The time module provides functions for working with time-related tasks, including measuring execution times, setting timeouts, and creating timestamps.
csv: The csv module offers tools for reading and writing CSV (Comma-Separated Values) files, which are commonly used for tabular data storage.
heapq: The heapq module provides heap-related functions, allowing for the implementation of priority queues and heap-based algorithms.
These built-in modules save time and effort by providing pre-built solutions for common programming tasks. By utilizing these modules, developers can avoid reinventing the wheel and focus on creating more efficient and feature-rich applications.
0 notes
techhelpnotes · 3 years ago
Text
collections – Python defaultdict and lambda
I think the first line means that when I call x[k] for a nonexistent key k (such as a statement like v=x[k]), the key-value pair (k,0) will be automatically added to the dictionary, as if the statement x[k]=0 is first executed.
0 notes
webbazaar0101 · 4 years ago
Text
defaultdict() in python:
defaultdict() in python: defaultdict() is a Dictionary subclass that calls a function to supply missing values. It provides all methods provided by the dictionary but takes the first argument as a default data type....
defaultdict() is a Dictionary subclass that calls a function to supply missing values. It provides all methods provided by the dictionary but takes the first argument as a default data type. It is used to provide some default values for the key that does not exist and never raises a KeyError. But With a dict, Python will throw a KeyError when attempting to access a key that is not already in the…
View On WordPress
0 notes
triviallytrue · 2 years ago
Text
A LLM got 12th in a Leetcode coding contest (probably)
In Weekly Contest 344, a fresh account (gogogoval) solved all 4 problems in 12:13 with commented submissions and test cases that look a lot like LLM code.
This could've been faked, but I doubt it. There are a small group of people in the world (a thousand, maybe) who could solve this contest fast enough to get 12th and add comments (or solve the problems and then feed it to a LLM to add comments), but it would be a very odd thing to do on a fresh account. The code itself also looks like LLM code - it uses techniques like gets on dictionaries (instead of using defaultdicts like most competitive python programmers).
This isn't that impressive. Leetcode contests are pretty easy, and this was an unusually easy contest - all four of the problems are rated easy or medium. Leetcode contests at the top level are about speed, not depth of understanding, so it's not that shocking that a LLM could do very well.
It's still a pretty massive leap. The free version of ChatGPT can solve two of these questions with some prodding, but it's pretty helpless on the other two. In particular, the last problem (the paths through a binary tree) is not trivial - it took me about ten minutes to find and implement a solution last night, and I'm pretty good.
This isn't that big of a deal for competitive coding, but it is a big deal for both Leetcode and the online assessments companies give. I don't know how much prompting or bugfixing it took the human who submitted this code to get the LLM to a correct solution, but either way, it changes the game on how we think about easy problems. We've gone from models that were very dull to a model that could probably pass the first round of a FAANG interview for a new grad. Already, in the week after, a skilled coder used a LLM to solve the first two questions of the Leetcode contest while solving 3 and 4 manually, saving a bunch of time and getting rank 5 in the contest. Easy questions aren't useful discriminators anymore.
This is the first thing I've seen a LLM do that genuinely impressed me. We are steadily approaching a point where either the improvement will slow or these things will have massive economic impact, and I have no idea which will happen.
122 notes · View notes
prachivermablr · 5 years ago
Link
0 notes
excludedmiddle · 3 years ago
Text
Leetcode 302
Easiest competition in a while, and my first 4/4 in ages. Also my first time finishing in under half an hour (it took me 23 minutes). The overwhelming vibe of this competition was "you just do the problem." No tricks, no cleverness, just get from point A to point B as fast as possible.
1 was simple as always, and I used a counter, which is fast becoming one of my favorite python resources.
2 took a little doing, but I used a defaultdict of lists, stored numbers based on their digit sum, and then went through the values of the dict looking at every array with at least two numbers. Not bad at all.
3 was fun! I think the trick here might've been that you needed to sort in-place, otherwise you ran out of memory, but the cost bounds were so generous that I did something pretty inefficient that still worked. I think I could've saved some time here by just writing instantly instead of thinking about how I could optimize it.
Basically, I made a custom sorting key for Python's sort, and that trivialized the problem.
4 was, again, not bad at all! I think leetcode assumes no one knows any math, so problems that rely on the concept of a greatest common divisor are frequently rated Hard, despite it being a very simple concept. I found the gcd of numsDivide and then sorted nums and iterated through, checking against the gcd. Simple!
Inshallah I will gain a shitload of rating and finally crack the top 5k users on the site.
3 notes · View notes
generatour1 · 5 years ago
Text
top 10 free python programming books pdf online download 
link :https://t.co/4a4yPuVZuI?amp=1
python download python dictionary python for loop python snake python tutorial python list python range python coding python programming python array python append python argparse python assert python absolute value python append to list python add to list python anaconda a python keyword a python snake a python keyword quizlet a python interpreter is a python code a python spirit a python eating a human a python ate the president's neighbor python break python basics python bytes to string python boolean python block comment python black python beautifulsoup python built in functions b python regex b python datetime b python to dictionary b python string prefix b' python remove b' python to json b python print b python time python class python certification python compiler python command line arguments python check if file exists python csv python comment c python interface c python extension c python api c python tutor c python.h c python ipc c python download c python difference python datetime python documentation python defaultdict python delete file python data types python decorator d python format d python regex d python meaning d python string formatting d python adalah d python float d python 2 d python date format python enumerate python else if python enum python exit python exception python editor python elif python environment variables e python numpy e python for everyone 3rd edition e python import e python int e python variable e python float python e constant python e-10 python format python function python flask python format string python filter python f string python for beginners f python print f python meaning f python string format f python float f python decimal f python datetime python global python global variables python gui python glob python generator python get current directory python getattr python get current time g python string format g python sleep g python regex g python print g python 3 g python dictionary g python set g python random python hello world python heapq python hash python histogram python http server python hashmap python heap python http request h python string python.h not found python.h' file not found python.h c++ python.h windows python.h download python.h ubuntu python.h not found mac python if python ide python install python input python interview questions python interpreter python isinstance python int to string in python in python 3 in python string in python meaning in python is the exponentiation operator in python list in python what is the result of 2 5 in python what does mean python json python join python join list python jobs python json parser python join list to string python json to dict python json pretty print python j complex python j is not defined python l after number python j imaginary jdoodle python python j-link python j+=1 python j_security_check python kwargs python keyerror python keywords python keyboard python keyword arguments python kafka python keyboard input python kwargs example k python regex python k means python k means clustering python k means example python k nearest neighbor python k fold cross validation python k medoids python k means clustering code python lambda python list comprehension python logging python language python list append python list methods python logo l python number l python array python l-bfgs-b python l.append python l system python l strip python l 1 python map python main python multiprocessing python modules python modulo python max python main function python multithreading m python datetime m python time python m flag python m option python m pip install python m pip python m venv python m http server python not equal python null python not python numpy python namedtuple python next python new line python nan n python 3 n python meaning n python print n python string n python example in python what is the input() feature best described as n python not working in python what is a database cursor most like python online python open python or python open file python online compiler python operator python os python ordereddict no python interpreter configured for the project no python interpreter configured for the module no python at no python 3.8 installation was detected no python frame no python documentation found for no python application found no python at '/usr/bin python.exe' python print python pandas python projects python print format python pickle python pass python print without newline p python re p python datetime p python string while loop in python python p value python p value from z score python p value calculation python p.map python queue python queue example python quit python qt python quiz python questions python quicksort python quantile qpython 3l q python download qpython apk qpython 3l download for pc q python 3 apk qpython ol q python 3 download for pc q python 3 download python random python regex python requests python read file python round python replace python re r python string r python sql r python package r python print r python reticulate r python format r python meaning r python integration python string python set python sort python split python sleep python substring python string replace s python 3 s python string s python regex s python meaning s python format s python sql s python string replacement s python case sensitive python try except python tuple python time python ternary python threading python tutor python throw exception t python 3 t python print .t python numpy t python regex python to_csv t python scipy t python path t python function python unittest python uuid python user input python uppercase python unzip python update python unique python urllib u python string u' python remove u' python json u python3 u python decode u' python unicode u python regex u' python 2 python version python virtualenv python venv python virtual environment python vs java python visualizer python version command python variables vpython download vpython tutorial vpython examples vpython documentation vpython colors vpython vector vpython arrow vpython glowscript python while loop python write to file python with python wait python with open python web scraping python write to text file python write to csv w+ python file w+ python open w+ python write w+ python open file w3 python w pythonie python w vs wb python w r a python xml python xor python xrange python xml parser python xlrd python xml to dict python xlsxwriter python xgboost x python string x-python 2 python.3 x python decode x python 3 x python byte x python remove python x range python yield python yaml python youtube python yaml parser python yield vs return python yfinance python yaml module python yaml load python y axis range python y/n prompt python y limit python y m d python y axis log python y axis label python y axis ticks python y label python zip python zipfile python zip function python zfill python zip two lists python zlib python zeros python zip lists z python regex z python datetime z python strftime python z score python z test python z transform python z score to p value python z table python 0x python 02d python 0 index python 0 is false python 0.2f python 02x python 0 pad number python 0b 0 python meaning 0 python array 0 python list 0 python string 0 python numpy 0 python matrix 0 python index 0 python float python 101 python 1 line if python 1d array python 1 line for loop python 101 pdf python 1.0 python 10 to the power python 101 youtube 1 python path osprey florida 1 python meaning 1 python regex 1 python not found 1 python slicing 1 python 1 cat 1 python list 1 python 3 python 2.7 python 2d array python 2 vs 3 python 2.7 download python 2d list python 2.7 end of life python 2to3 python 2 download 2 python meaning 2 pythons fighting 2 pythons collapse ceiling 2 python versions on windows 2 pythons fall through ceiling 2 python versions on mac 2 pythons australia 2 python list python 3.8 python 3.7 python 3.6 python 3 download python 3.9 python 3.7 download python 3 math module python 3 print 3 python libraries 3 python ide python3 online 3 python functions 3 python matrix 3 python tkinter 3 python dictionary 3 python time python 4.0 python 4 release date python 4k python 4 everyone python 44 mag python 4 loop python 474p remote start instructions python 460hp 4 python colt 4 python automl library python 4 missile python 4 download python 4 roadmap python 4 hours python 5706p python 5e python 50 ft water changer python 5105p python 5305p python 5000 python 5706p manual python 5760p 5 python data types 5 python projects for beginners 5 python libraries 5 python projects 5 python ide with icons 5 python program with output 5 python programs 5 python keywords python 64 bit python 64 bit windows python 64 bit download python 64 bit vs 32 bit python 64 bit integer python 64 bit float python 6 decimal places python 660xp 6 python projects for beginners 6 python holster 6 python modules 6 python 357 python 6 missile python 6 malware encryption python 6 hours python 7zip python 7145p python 7754p python 7756p python 7145p manual python 7145p remote start python 7756p manual python 7154p programming 7 python tricks python3 7 tensorflow python 7 days ago python 7 segment display python 7-zip python2 7 python3 7 ssl certificate_verify_failed python3 7 install pip ubuntu python 8 bit integer python 881xp python 8601 python 80 character limit python 8 ball python 871xp python 837 parser python 8.0.20 8 python iteration skills 8 python street dakabin python3 8 tensorflow python 8 puzzle python 8 download python 8 queens python 95 confidence interval python 95 percentile python 990 python 991 python 99 bottles of beer python 90th percentile python 98-381 python 9mm python 9//2 python 9 to 09 python 3 9 python 9 subplots pythonrdd 9 at rdd at pythonrdd.scala python 9 line neural network python 2.9 killed 9 python
Tumblr media
#pythonprogramming #pythoncode #pythonlearning #pythons #pythona #pythonadvanceprojects #pythonarms #pythonautomation #pythonanchietae #apython #apythonisforever #apythonpc #apythonskin #apythons #pythonbrasil #bpython #bpythons #bpython8 #bpythonshed #pythoncodesnippets #pythoncowboy #pythoncurtus #cpython #cpythonian #cpythons #cpython3 #pythondjango #pythondev #pythondevelopers #pythondatascience #pythone #pythonexhaust #pythoneğitimi #pythoneggs #pythonessgrp #epython #epythonguru #pythonflask #pythonfordatascience #pythonforbeginners #pythonforkids #pythonfloripa #fpython #fpythons #fpythondeveloper #pythongui #pythongreen #pythongame #pythongang #pythong #gpython #pythonhub #pythonhackers #pythonhacking #pythonhd #hpythonn #hpythonn✔️ #hpython #pythonista #pythoninterview #pythoninterviewquestion #pythoninternship #ipython #ipythonnotebook #ipython_notebook #ipythonblocks #ipythondeveloper #pythonjobs #pythonjokes #pythonjobsupport #pythonjackets #jpython #jpythonreptiles #pythonkivy #pythonkeeper #pythonkz #pythonkodlama #pythonkeywords #pythonlanguage #pythonlipkit #lpython #lpythonlaque #lpythonbags #lpythonbag #lpythonprint #pythonmemes #pythonmolurusbivittatus #pythonmorphs #mpython #mpythonprogramming #mpythonrefftw #mpythontotherescue #mpython09 #pythonnalchik #pythonnotlari #pythonnails #pythonnetworking #pythonnation #pythonopencv #pythonoop #pythononline #pythononlinecourse #pythonprogrammers #ppython #ppythonwallet #ppython😘😘 #ppython3 #pythonquiz #pythonquestions #pythonquizzes #pythonquestion #pythonquizapp #qpython3 #qpython #qpythonconsole #pythonregiusmorphs #rpython #rpythonstudio #rpythonsql #pythonshawl #spython #spythoniade #spythonred #spythonredbackpack #spythonblack #pythontutorial #pythontricks #pythontips #pythontraining #pythontattoo #tpythoncreationz #tpython #pythonukraine #pythonusa #pythonuser #pythonuz #pythonurbex #üpython #upython #upythontf #pythonvl #pythonvert #pythonvertarboricole #pythonvsjava #pythonvideo #vpython #vpythonart #vpythony #pythonworld #pythonwebdevelopment #pythonweb #pythonworkshop #pythonx #pythonxmen #pythonxlanayrct #pythonxmathindo #pythonxmath #xpython #xpython2 #xpythonx #xpythonwarriorx #xpythonshq #pythonyazılım #pythonyellow #pythonyacht #pythony #pythonyerevan #ypython #ypythonproject #pythonz #pythonzena #pythonzucht #pythonzen #pythonzbasketball #python0 #python001 #python079 #python0007 #python08 #python101 #python1 #python1k #python1krc #python129 #1python #python2 #python2020 #python2018 #python2019 #python27 #2python #2pythons #2pythonsescapedfromthezoo #2pythons1gardensnake #2pythons👀 #python357 #python357magnum #python38 #python36 #3pythons #3pythonsinatree #python4kdtiys #python4 #python4climate #python4you #python4life #4python #4pythons #python50 #python5 #python500 #python500contest #python5k #5pythons #5pythonsnow #5pythonprojects #python6 #python6s #python69 #python609 #python6ft #6python #6pythonmassage #python7 #python734 #python72 #python777 #python79 #python8 #python823 #python8s #python823it #python800cc #8python #python99 #python9 #python90 #python90s #python9798
1 note · View note
kata4a · 5 years ago
Text
defaultdicts might just be my favorite container
10 notes · View notes
cognitiveprogrammer · 5 years ago
Video
youtube
Interesting Topics of Modern Python Programming - Using Python collection - defaultdict - What is it and how to use the same
In this video I've explained the concept and python collection in reference to defaultdict . Defaultdict is a dict for all practice purpose but it does help in writing out code without worrying about Key Error which we get while using python dictionary.Not only defaultdict prevent Key error but can also allow built-in containers like list, tuple, and dict as default values of the keys which are not present.Hope this video help you to understand the basics of defaultdict in a better way
1 note · View note
marekgrac · 5 years ago
Text
defaultdict : jednoduchšie vkladanie do slovníku
Vkladanie do slovníku (dict, {}) v Pythone je niečo, čo sa pri práci s dátami používa denne. V podstate potrebujeme robiť stále dokola dve veci: vytvorenie nového kľúču a operáciu nad ním. Táto operácia je obvykle jednoduchá, navýšenie počítadla alebo pridanie prvku do zoznamu.
d = dict() key = 'foo' value = 'bar' if not key in d: d[key] = [value] else: d[key].append(value)
Toto je podľa najhoršia varianta, pretože duplikujeme kód na vkladanie do poľa. (Samozrejme, že v takto prehľadnom kóde to je v podstate jedno, ale chceme mať rozumné návyky.)
if not key in d: d[key] = [] d[key].append(value)
Týmto nám vznikol kód, ktorý je kratší a jednoduchší. Existuje možnosť, ako sa zbaviť toho ```if```. Samozrejme, že áno, pretože na prístup ku kľúču v slovníku sa dá použiť metóda ```.get(key, default)``
d[key] = d.get(key, []) d[key].append(value)
Toto riešenie sa mi už celkom páči, ale stále tu je niečo lepšie. Nastavme si tú preddefinovanú hodnotu už pri vytváraní slovníku. Táto preddefinovaná hodnota by mala byť niečo, čo nám vytvára nové elementy (list|dict|int|....). Ak by sme tam totiž dali premennú, tak by sme sa dostávali stále k tej istej referencii.
from collections import defaultdict dd = defaultdict(list) key = 'foo' value = 'bar' dd[key].append(value)
1 note · View note
petaminds · 5 years ago
Text
Advanced python part 3
Advanced python part 3
In part 2, we introduced advanced python knowledge with built-in functions and other useful tools for sequence iteration, data transformation. Advanced python part 3 will continue with collections to manipulate our data.
Named tuple
Suppose we want to define a data structure to represent a geometric point on a typical x and y-axis. We could easily do this by defining a regular tuple with…
View On WordPress
0 notes
likegeeks · 3 years ago
Link
0 notes