What are “Idempotent functions” and why it is useful?

What are “Idempotent functions” and why it is useful?

        An idempotent function always returns the same value given the same set of arguments, regardless of how many times it is called. The result does not depend on non-local variables, the mutability of arguments, or data from any I/O streams.

The following add_three(number) function is idempotent:

def add_three(number):
return number + 3
view rawidompotent.py hosted with ❤ by GitHub

No matter how many times one calls add_three(7), the answer will always be 10. Here’s a different take on the function that is not idempotent:

def add_three():
“””Return 3 + the number entered by the user.”””
number = int(input(‘Enter a number: ‘))
return number + 3
view rawnon_idempotent.py hosted with ❤ by GitHub
This admittedly contrived example is not idempotent because the return value of the function depends on I/O, namely the number entered by the user. It’s clearly not true that every call to add_three() will return the same value. If it is called twice, the user could enter 3 the first time and 7 the second, making the call to add_three() return 6 and 10, respectively.
A real-world example of idem potency is hitting the “up” button in front of an elevator. The first time it’s pushed, the elevator is “notified” that you want to go up. Because the pressing the button is idempotent, pressing it over and over again is harmless. The result is always the same.

Why is idempotency important?

Testability and maintainability. Idempotent functions are easy to test because they are guaranteed to always return the same result when called with the same arguments. Testing is simply a matter of checking that the value returned by various different calls to the function return the expected value.
What’s more, these tests will be fast, an important and often overlooked issue in Unit Testing. And refactoring when dealing with idempotent functions is a breeze. No matter how you change your code outside the function, the result of calling it with the same arguments will always be the same.

Tuesday, January 21, 2020

Loop Through Python Dictionaries

Dictionary

A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.

thisdict = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
view rawdict.py hosted with ❤ by GitHub

Using .keys()

one method of iterating over the keys in a dictionary is to use the .keys() method which returns a dict_keys object that is then iterated over as we store each value in our x variable.

mock_data = {
“id”: 1,
“first_name”: “Cory”,
“last_name”: “Schimmang”,
“email”: “cschimmang0@skype.com”,
“gender”: “Female”,
“ip_address”: “186.239.104.33”
}
for x in mock_data.keys():
print(x)
“””
id
first_name
last_name
email
gender
ip_address
“””
view rawkeys.py hosted with ❤ by GitHub

Using .values()

If we want to get right at each value in the dictionary, then using the .values() method will store the term’s value in x rather than the key.

mock_data = {
“id”: 1,
“first_name”: “Cory”,
“last_name”: “Schimmang”,
“email”: “cschimmang0@skype.com”,
“gender”: “Female”,
“ip_address”: “186.239.104.33”
}
for x in mock_data.values():
print(x)
“””
1
Cory
Schimmang
cschimmang0@skype.com
Female
186.239.104.33
“””
view rawvalue.py hosted with ❤ by GitHub

Using .items()

More often than not, you will want access to both the key and the value. In this scenario, use the .items() method, which returns each key-value pair as a two-value tuple.

To pre-split the tuple, specify two variables in your for loop so that the first tuple value (the key) and the second (the value) are stored in the first and second variables respectively.

mock_data = {
“id”: 1,
“first_name”: “Cory”,
“last_name”: “Schimmang”,
“email”: “cschimmang0@skype.com”,
“gender”: “Female”,
“ip_address”: “186.239.104.33”
}
for x in mock_data.items():
print(x)
“””
(‘id’, 1)
(‘first_name’, ‘Cory’)
(‘last_name’, ‘Schimmang’)
(’email’, ‘cschimmang0@skype.com’)
(‘gender’, ‘Female’)
(‘ip_address’, ‘186.239.104.33’)
“””
for k,v in mock_data.items():
print(k,v)
“””
id 1
first_name Cory
last_name Schimmang
email cschimmang0@skype.com
gender Female
ip_address 186.239.104.33
“””
view rawitems.py hosted with ❤ by GitHub

There are many methods available, each with their own pros and cons. Once you get into larger executions you may find performance differences, however, especially at a beginner’s level, try to iterate intentionally over what is necessary.

#python #dictionary #iterations

Monday, January 20, 2020

difference between ‘/’ and ‘//’ in python

Python Operators

Operators are used to perform operations on variables and values. Python divides the operators in the following groups:

1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators

Difference between ‘/’ and ‘//’ in python

/ is regular division(returns float) and // is floor division(returns int).

Floor division was introduced in python 3.

operators

Normal Division : Divides the value on the left by the one on the right. Notice that division results in a floating-point value.

Floor Division : Divides and returns the integer value of the quotient. It neglects the digits after the decimal.

Example

# / operator
a=10/3
print(“Value of a is “,a)
# // operator
b=10//3
print(“Value of b is “,b)
view rawoperator.py hosted with ❤ by GitHub

Output is:

    Value of a is 3.3333333333333335    Value of b is 3

Sunday, January 19, 2020

Python program to count the number of occurrences of a letter in a word or in a sentence

         Suppose if we want to count the number of occurrences of a letter in a word or in a sentence, we can use the count function from python.

This is the sample code. I am assigning a string to the variable called text. Then i am counting the number of ‘e’ in the text.

text = “Hello everyone! welcome to codesimple.info”
print(text.count(‘e’)) #8
view rawlettercount.py hosted with ❤ by GitHub

This code produces an output of 8.

Python String count() 

The string count() method returns the number of occurrences of a substring in the given string. In simple words, count() method searches the substring in the given string and returns how many times the substring is present in it.

It also takes optional parameters start and end to specify the starting and ending positions in the string respectively.

The syntax of count() method is:

string.count(substring, start=…, end=…)

By providing the start value the function searches for the substring only after the start index.

If an end value is given the function searches until the end of this index.

Example

In this example there is a list consisting of different words. I will print only the words that match my condition.

condition: Print all the words that has 4 ‘r’ in it.


myArray = [‘teststring1’,‘strringrr’,‘wow’,‘strarirngr’]
letter = “r”
amount = 4
filtered = [item for item in myArray if item.count(letter) == amount]
print(filtered) # [‘strringrr’, ‘strarirngr’]
view rawexample..py hosted with ❤ by GitHub

The above program will print ‘strringrr’, ‘strarirngr’ as they have 4 ‘r’ in them.

#python #count #lettercount

Thursday, January 9, 2020

Check file, directory or path exists in python

            The OS module in python provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system.
codesimple.info

1. path.exists()

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

import os.path
os.path.exists(fname)
view rawfilexists.py hosted with ❤ by GitHub

This will check if something exists in the given name/path and not specifically check if a file exists on that name/path.

2. Check if it is file

This function will specifically check if there is a file in the given name or path.

import os
os.path.isfile(fname)
view rawfile_exists.py hosted with ❤ by GitHub

3. To check if a directory exists

The isdir() function lets you check whether a directory of a given name exists or not.

if my_file.is_dir():
# directory exists
view rawdirectory_exists.py hosted with ❤ by GitHub

4. check using Try block

You can also use resolve(strict=True) in a try block:

If the path doesn’t exist and strict is True, FileNotFoundError is raised. If strict is False, the path is resolved as far as possible and any remainder is appended without checking whether it exists. If an infinite loop is encountered along the resolution path, RuntimeError is raised.

try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn’t exist
else:
# exists
view rawtry_file.py hosted with ❤ by GitHub
#python #files #file_exists

Friday, January 3, 2020

copy text to clipboard and paste text from clipboard using python

We deal with copying and pasting text every day. But what if we could copy a text to the clipboard or paste the copied text from the clipboard to the terminal using python?
This can be achieved using a python library called pyperclip.

Installation

Pyperclip is a cross-platform Python module for copy and paste clipboard functions. It works with Python 2 and 3.

pip install pyperclip

The above command installs the pyperclip library on your device.

Usage

1. First import the package.

import pyperclip

2. Copy text to the clipboard.

 pyperclip.copy(“codesimple”)

This copies the text “codesimple” to your clipboard. If you “CTRL + V ” on your notepad, you can see that the text “codesimple” appears there.
3. Paste text from clipboard to terminal or access it in the python program.
Copy some random text using “CTRL + V”. This will be copied to our clipboard. Go to the terminal and import pyperclip package. Then enter the following command.

pyperclip.paste()

we can see that our copied text is being printed on the terminal.

#pyperclip #python #copy #paste #clipboard

Thursday, January 2, 2020

What is the difference between *p,**p, ***p in pointers?

Well, before spotting out the differences between *p, **p and ***p in pointers, I will first share what pointer is…

So, what is a pointer?

A pointer is a variable that contains the address in memory of another variable. We can have a pointer to any variable type. The unary or nomadic operator & gives the “address of a variable”. The indirection or dereference operator * gives the “contents of an object pointed to by a pointer”.

To declare a pointer to a variable do:

 int *p;

Now, *p vs **p vs ***p????

*p: *p is a pointer to a variable, as shown below. It is also called a single pointer. The single pointer has two purposes: to create an array and to allow a function to change its contents (pass by reference).

**p: **p is a pointer to a pointer variable, also called a double-pointer. It is a form of multiple indirections or a chain of pointers. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below. The double-pointer can be used in a 2D array (or array of arrays, since each “column” or “row” need not be the same length).

***p: ***p is a pointer to a double pointer, rather a pointer to a pointer to a pointer variable, as shown below. It is mostly called a triple pointer. It is an even higher level of multiple indirections or pointer chaining. A triple pointer is used to traverse an array of pointers.

Implementing *p, **p and ***p…

Output

#c #c++ #pointers

Author: Aditya Bhuyan

I am an IT Professional with close to two decades of experience. I mostly work in open source application development and cloud technologies. I have expertise in Java, Spring and Cloud Foundry.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s