Category Archives: Programming Language

LeetCode problem 167

Back online after quite some time. Lately I’ve been playing with leetcode, so below is solution to problem 167. This problem is an easy one and no complex structures are needed in order to solve it.

#!/usr/bin/env python

''' LeetCode problem 167 
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, 
find two numbers such that they add up to a specific target number. 
Let these two numbers be numbers[index1] and numbers[index2] where 1 <= first < second <= numbers.length.
2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers is sorted in non-decreasing order.
-1000 <= target <= 1000
The tests are generated such that there is exactly one solution. '''

def twoSum(numbers, target):
	for i in numbers:
		if (target - i) in numbers[numbers.index(i)+1:]:
			return [numbers.index(i), numbers.index(i) + numbers[numbers.index(i)+1:].index(target - i)+1]


#twoSum([-5, -3, -1, 0, 10], -1)
print(f"{twoSum([-5, -3, -1, 0, 10], -1)}")
#twoSum([2, 7, 11, 15], 9)
print(f"{twoSum([2,7,11,15], 9)}")
#twoSum([2, 3, 4], 6)
print(f"{twoSum([2, 3, 4], 6)}")
#twoSum([5, 25, 75], 100)
print(f"{twoSum([5, 25,75], 100)}")
#twoSum([0, 0, 3, 4], 0)
print(f"{twoSum([0, 0, 3, 4], 0)}")

I'll try to post more often from now on. I'll try to make it at least once a week.

Create csv file ordered with highest yield dividend paying stock

For this script to work Yahoo Finance is needed. It can be easily installed with pip. Stock tickers are taken from a file called tickers.txt.

#!/usr/bin/env python

import time
from yahoo_finance import Share

dict = {}
f = open("tickers.txt", "r")
for ticker in f.readlines():
        dividend = Share(ticker).get_dividend_yield()
        if dividend is not None:
                print ticker.rstrip()+": "+dividend
                if float(dividend) > 0:
                        dict[float(dividend)] = ticker.rstrip()
f.close()

filename = "dividends-"+time.strftime("%Y%m%d")+".csv"
f = open(filename, "a")
f.write("Ticker, Dividend Yield, Dividend Share, Stock Price\n")
print "Ticker; Dividend Yield; Dividend Share; Stock Price\n"
for k in reversed(sorted(dict.keys())):
        escribir = dict[k]+","+str(k)+","+str(float(Share(dict[k]).get_dividend_share()))+","+str(float(Share(dict[k]).get_price()))+"\n"
        print dict[k]+";"+str(k)+";"+Share(dict[k]).get_dividend_share()+";"+Share(dict[k]).get_price()
        f.write(escribir)
f.close()

When done it creates a csv (named dividends-YYYYMMDD.csv) file ordered by highest dividend yield paying stocks.

00:55:40 [me@server Finance]$ head -5 dividends-20160414.csv
Ticker, Dividend Yield, Dividend Share, Stock Price
GLBL,44.0,1.1,2.64
CLM,29.7,4.42,15.624
XRDC,22.99,0.6,2.65
CRF,22.1,3.98,16.75
00:55:49 [me@server Finance]$

Python mechanize to automate WordPress login

I had to play around with Mechanize lib to automate wordpress login. Proved out to be pretty handy.

#!/usr/bin/env python

from mechanize import Browser #pip install mechanize

br = Browser()
br.set_handle_robots(False)
br.addheaders = [("User-agent","Python Script using mechanize")]

sign_in = br.open("https://www.wordpress.com/wp-login.php")  #the login url

br.select_form(nr = 0) #accessing form by their index. Since we have only one form in this example, nr =0.
br["log"] = "user@domain" #the key "username" is the variable that takes the username/email value
br["pwd"] = "passwd"    #the key "password" is the variable that takes the password value

logged_in = br.submit()   #submitting the login credentials

logincheck = logged_in.read()  #reading the page body that is redirected after successful login

print logged_in.code   #print HTTP status code(200, 404...)
print logged_in.info() #print server info
#print logincheck #printing the body of the redirected url after login

Execution:

user@server: ~/Python $ python wordpress-login.py 
200
Server: nginx
Date: Fri, 04 Mar 2016 16:45:40 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 5762
Connection: close
Vary: Accept-Encoding
X-Frame-Options: SAMEORIGIN
X-ac: 1.ams _dfw
Strict-Transport-Security: max-age=15552000
X-UA-Compatible: IE=Edge

user@server: ~/Python $

If you uncomment the last line in the script above it would print out the HTML code of the logged in page.

Python script to download all NASDAQ and NYSE ticker symbols

Below is a short python script to get all NASDAQ and NYSE common stock tickers. You can then use the resulting file to get a lot of info using yahoofinance library.

#!/usr/bin/env python

import ftplib
import os
import re

# Connect to ftp.nasdaqtrader.com
ftp = ftplib.FTP('ftp.nasdaqtrader.com', 'anonymous', 'anonymous@debian.org')

# Download files nasdaqlisted.txt and otherlisted.txt from ftp.nasdaqtrader.com
for ficheiro in ["nasdaqlisted.txt", "otherlisted.txt"]:
        ftp.cwd("/SymbolDirectory")
        localfile = open(ficheiro, 'wb')
        ftp.retrbinary('RETR ' + ficheiro, localfile.write)
        localfile.close()
ftp.quit()

# Grep for common stock in nasdaqlisted.txt and otherlisted.txt
for ficheiro in ["nasdaqlisted.txt", "otherlisted.txt"]:
        localfile = open(ficheiro, 'r')
        for line in localfile:
                if re.search("Common Stock", line):
                        ticker = line.split("|")[0]
                        # Append tickers to file tickers.txt
                        open("tickers.txt","a+").write(ticker + "\n")

Project Euler number 11

Below is my solution to Poject Euler number eleven. I created back ordered array with the number and its positions on a 2D 20×20 array. The 4 corners 4×4 array products only the vertical and horizontal products where calculated since the diagonal products are calculated previously with the 16×16 array.

#!/usr/bin/env python

import time

start = time.time()
f = open("grid.txt", "r")
i = 0
j = 0
newList = []
List = []

# Create and array 20x20 converting members to int
for line in f:
        List.append(line.split())
        List[i] = map(int, List[i])
        i = i + 1

# Create an ordered array starting by highest number and writing also position
i = 0
j = 0
for i in range(len(List[i])):
        for j in range(len(List[i])):
                newList.append([List[i][j],[i,j]])
sortedList = sorted(newList)
# backorderdList is an array containing an ordered number with its positions in array second entry.
backorderedList = sortedList[::-1]

max = 0
for member in backorderedList:
        if ((member[1][0] == 0) and (member[1][1] == 0)):
                # Multiply upper corner first four lines
                for x in range(4):
                        # Line multiplication
                        newmax = List[x][0]*List[x][1]*List[x][2]*List[x][3]
                        if (newmax > max):
                                max = newmax
                        # Column multiplication
                        newmax = List[0][x]*List[1][x]*List[2][x]*List[3][x]
                        if (newmax > max):
                                max = newmax

        elif ((member[1][0] == 0) and (member[1][1] == 16)):
                # Multiply upper right corner
                for x in range(4):
                        # Line multiplication
                        newmax = List[x][16]*List[x][17]*List[x][18]*List[x][19]
                        if (newmax > max):
                                max = newmax
                        # Column multiplication
                        newmax = List[0][x+16]*List[1][x+16]*List[2][x+16]*List[3][x+16]
                        if (newmax > max):
                                max = newmax

        elif ((member[1][0] == 16) and (member[1][1] == 0)):
                # Multiply lower left corner
                for x in range(4):
                        # Line multiplication
                        newmax = List[x+16][0]*List[x+16][1]*List[x+16][2]*List[x+16][3]
                        if (newmax > max):
                                max = newmax
                        # Column multiplication
                        newmax = List[16][x]*List[17][x]*List[18][x]*List[19][x]
                        if (newmax > max):
                                print max

        elif ((member[1][0] == 16) and (member[1][1] == 16)):
                # Multiply lower right corner
                for x in range(4):
                        # Line multiplication
                        newmax = List[x+16][16]*List[x+16][17]*List[x+16][18]*List[x+16][19]
                        if (newmax > max):
                                max = newmax
                        # Column multiplication
                        newmax = List[16][x+16]*List[17][x+16]*List[18][x+16]*List[19][x+16]
                        if (newmax > max):
                                max = newmax

        elif ((member[1][0] >= 3) and (member[1][0] <= 16) and (member&#91;1&#93;&#91;1&#93; >= 3) and (member[1][1] <= 16)):
                # column numbers from numbers not on edges
                newmax = List&#91;member&#91;1&#93;&#91;0&#93;-3&#93;&#91;member&#91;1&#93;&#91;1&#93;&#93;*List&#91;member&#91;1&#93;&#91;0&#93;-2&#93;&#91;member&#91;1&#93;&#91;1&#93;&#93;*List&#91;member&#91;1&#93;&#91;0&#93;-1&#93;&#91;member&#91;1&#93;&#91;1&#93;&#93;*List&#91;member&#91;1&#93;&#91;0&#93;&#93;&#91;member&#91;1&#93;&#91;1&#93;&#93;
                if (newmax > max):
                        max = newmax
                newmax = List[member[1][0]+3][member[1][1]]*List[member[1][0]+2][member[1][1]]*List[member[1][0]+1][member[1][1]]*List[member[1][0]][member[1][1]]
                if (newmax > max):
                        max = newmax
                # line numbers
                newmax = List[member[1][0]][member[1][1]-3]*List[member[1][0]][member[1][1]-2]*List[member[1][0]][member[1][1]-1]*List[member[1][0]][member[1][1]]
                if (newmax > max):
                        max = newmax
                newmax = List[member[1][0]][member[1][1]+3]*List[member[1][0]][member[1][1]+2]*List[member[1][0]][member[1][1]+1]*List[member[1][0]][member[1][1]]
                if (newmax > max):
                        max = newmax
                # diagonal numbers
                newmax = List[member[1][0]-3][member[1][1]-3]*List[member[1][0]-2][member[1][1]-2]*List[member[1][0]-1][member[1][1]-1]*List[member[1][0]][member[1][1]]
                if (newmax > max):
                        max = newmax
                newmax = List[member[1][0]+3][member[1][1]+3]*List[member[1][0]+2][member[1][1]+2]*List[member[1][0]+1][member[1][1]+1]*List[member[1][0]][member[1][1]]
                if (newmax > max):
                        max = newmax
                newmax = List[member[1][0]-3][member[1][1]+3]*List[member[1][0]-2][member[1][1]+2]*List[member[1][0]-1][member[1][1]+1]*List[member[1][0]][member[1][1]]
                if (newmax > max):
                        max = newmax
                newmax = List[member[1][0]+3][member[1][1]-3]*List[member[1][0]+2][member[1][1]-2]*List[member[1][0]+1][member[1][1]-1]*List[member[1][0]][member[1][1]]
                if (newmax > max):
                        max = newmax

print "Max is: %d." % (max)
elapsed = (time.time() - start)
print "Elapsed time: %s seconds." % (elapsed)

f.close()

Took the execution time idea from here.

Execution:

user@server1: ~ $ python euler_11.py ; uname -a
Max is: 70600674.
Elapsed time: 0.0441608428955 seconds.
Linux server1 2.6.32-042stab106.4 #1 SMP Fri Mar 27 15:19:28 MSK 2015 x86_64 GNU/Linux
user@server1: ~ $