This is the "translation" of earlier JavaScript post about Counting Same Occurrences.
Here, I have Python 2.7.7.
The concept
The main idea of this function is the same as the JavaScript version (link above - so that I don't have to re-explain it[I'm quite lazy that way]).
In this snippet, I typed a function that generates a
dictionary
(in JavaScript: object
) output from a list
(in JavaScript: array
) input.The output consists of
list element: {"index": [array of indexes], "length": array of indexes length}pairs.
The "confusing" part was when I tried to initialize the
list
type for the non-existing dictionary
key.The "solution" is using
try-except
block, with KeyError
exception.
Let's take a look
Accessing the output
To print the list of indexes, do this:
print occurrence(your_list)["the_element"]["index"]And to print the list length (of a particular element):
print occurrence(your_list)["the_element"]["length"]You can always store it as a variable and do further process.
List of keywords
-
def
A (custom) function declaration in Python: more info -
isinstance(the_object, class_info)
It is a built-in function to test whetherthe_object
is an instance ofclass_info
argument. Likeinstanceof
operator in JavaScript (also in PHP and Java, Ruby has some methods you can choose).
Thethe_object
in the snippet above is denoted byv
(an item froma
list) andclass_info
islist
: more info -
for index, value in enumerate(iterable_input)
A looping block which iterates over theiterable_input
. With this modification, we can also access the index of a particular value. LikeforEach
in JavaScript orforeach
in PHP (and Java has the funkiest form for that): -
if
statement
Just like JavaScript or any other programming languages conditional statement block: more info not
operator
Used in Boolean operation. In JavaScript, it is an exclamation mark (!). It negates an argument: more info-
str(the_input)
function
Convertthe_input
into string object. In JavaScript, it's liketoString()
: more info -
append(an_item)
method
A method to appendan_item
into a list (which is declared in front of the method). In JavaScript, it is equivalent topush()
: more info -
try-except
block
It is liketry-catch-[finally]
error block handling in JavaScript: -
Other than those...
are custom variable/parameter keywords.
They are:occurrence
(the name of the function).result
(output).v
(item value).i
(index).a
(received list input).
No comments:
Post a Comment
Tell me what you think...