Thursday, April 30, 2020

Python - How to read a file?

   In this article, we will see how to read from a file. Let us have file with content as below:
$ cat file
Unix
Linux
AIX
1.  Reading line by line:
>>> fd = open('/home/guru/file', 'r')
>>> for line in fd:
...   print(line)
... 
Unix

Linux

AIX

>>> 
         open function opens a file and returns a file object.  Arguments are filename and the mode, 'r' for reading.  When the file object is traversed, every iteration reads a line and line gets printed. Notice the blank line after every print. This is because the variable line contains a newline character read from the file and print function adds another newline.

Tuesday, April 28, 2020

bash - 10 examples to find / replace in a string

Many times when we want to replace or extract something, we immediately end up with and awk or a sed oneliner. Keep in mind, the first option should always be a internal shell option, only in the absence of which we should resort to an external command. In this article, we will see 10 different examples where instead of an awk/sed, using bash specific internal will be very beneficial:

1. Capitalize a string:  Though there are many ways to capitalize a string,  one tends to use toupper function to get it done. Instead, bash can directly handle it.
$ x='hello'
$ echo ${x^^}
HELLO
$ echo "$x" | awk '{print toupper($0)}'
HELLO
   This feature of bash(^^) is only available for bash version 4. The two carrot pattern capitalizes the entire string.

Thursday, April 23, 2020

Python - How to get the NSE daily data feed?

These are days when trading decisions are taken more by a software, and people write algorithms to get their trades executed. For all this to happen, you need to have the stock data feed with you. Data is nothing but the daily open,close,high, low and volume for the stocks. Once you have the feed, the kind of things you can do with that data is endless.  In this article, we will see how to download the data feed through a Python program.

Pre-requisites:
1. Install pandas if not present already:
pip install pandas
2. Alpha Vantage has exposed free API's for downloading data feed. Install the alpha vantage package:
pip install alpha-vantage
3. You need to register yourself in Alpha vantage and get an API key.

Saturday, April 11, 2020

Python - Get nth prime number

 Let us try to solve the 7th problem in Euler's project which is to get the 10,001st prime number. We will start with writing a function to check if a number is prime or not.

from math import sqrt

def isPrime(x):
    if x < 2:
        return False
    if x == 2 or x == 3:
        return True
    for i in range(2, int(sqrt(x)) + 1):
        if x % i == 0:
            return False

    return True