Author: Anirudh

  • Consecutive Prime Sum — Project Euler (Problem 50)

    Consecutive Prime Sum — Project Euler (Problem 50)

    Many problems in Project Euler relate to working with primes. I use primesieve-python to help solve such problems. It consists of Python bindings for the primesieve C++ library. Generates primes orders of magnitude faster than any pure Python code. Features:

    • Generate a list of primes
    • Count primes and prime k-tuplets
    • Print primes and prime k-tuplets
    • Find the nth prime
    • Iterate over primes using little memory

    Anyway, here’s Problem 50 from Project Euler:

    ProjectEuler50

    Here’s how I did it:

    # Question: Which prime, below one-million, can be written as the sum of the most consecutive primes
    from primesieve import *
    from math import *
    # Generate list of primes under a million
    primes_under_million = generate_primes(10**6)
    # Sum of consecutive primes is of order 0.5(n^2)(logn)
    # Calculate 'n' so that sum of consecutive primes is less than a million (and not necessarily prime)
    nsum = 1
    n = 1
    while nsum < 10**6:
    nsum = 0.5*(n**2)*(log(n, e))
    n += 1
    # Calculate index so that sum of first 'index' consecutive primes is under a million and also prime
    primes_subset = primes_under_million[:n]
    nsum = sum(primes_under_million[:n])
    while nsum > 10**6:
    n -= 1
    nsum = sum(primes_under_million[:n])
    primes_sum = 0
    index = 0
    for i in range(len(primes_subset)):
    if i % 2 == 1:
    pass
    else:
    sumprimes = sum(primes_subset[:i])
    if sumprimes > primes_sum and sumprimes < 10**6 and sumprimes in primes_under_million:
    primes_sum = sumprimes
    index = i
    # Print out sum of consecutive primes till 'index', index, n
    # print primes_sum, index, n
    # Check consecutive primes within a range (index to n) such that their number is greater than index and maximum
    j = index + 1
    start = 0
    while j <= n:
    while (j-start) >= (n-index):
    sumprimes = sum(primes_subset[start:j])
    if sumprimes > primes_sum and sumprimes in primes_under_million:
    primes_sum = sumprimes
    start += 1
    j += 1
    start = 0
    print primes_sum
    view raw euler50.py hosted with ❤ by GitHub

    Answer: 997651

  • Largest Product in a Grid — Project Euler (Problem 11)

    Largest Product in a Grid — Project Euler (Problem 11)

    I started solving Project Euler problems this month. Check out the Project Euler tab of this blog for a list of the problems I’ve solved (with solutions) till date. Here’s a problem you might find interesting:

    ProjectEuler11

    Here’s my solution using Python (I basically search through the entire matrix which is of O() complexity):

    I first copy the maxtrix into a text file euler11.txt so that it can be later read into Python

    08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
    49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
    81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
    52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
    22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
    24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
    32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
    67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
    24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
    21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
    78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
    16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
    86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
    19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
    04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
    88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
    04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
    20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
    20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
    01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
    view raw euler11.txt hosted with ❤ by GitHub

    I then execute the following code from the same working directory as euler11.txt
    # import numpy module for matrix operations
    from numpy import *
    # read the file with the matrix of numbers
    filename = 'euler11.txt'
    # store each line of the file into an array
    with open(filename, "r") as ins:
    array = []
    for line in ins:
    array.append(line)
    print array
    # create a new array that converts the number strings into number integers
    newArray = []
    for i in array:
    j = i.split(' ')
    k = [int(n) for n in j]
    newArray.append(k)
    print newArray
    # convert the array of integers into a matrix of integers
    problemMatrix = matrix(newArray)
    print problemMatrix
    # set initial maximum product to be a dummy number, say 1
    maxProd = 1
    # search all combinations for maximum product
    for i in range(16):
    for j in range(16):
    prod1 = problemMatrix[i,j]*problemMatrix[i+1,j]*problemMatrix[i+2,j]*problemMatrix[i+3,j]
    if prod1 > maxProd:
    maxProd = prod1
    prod2 = problemMatrix[i,j]*problemMatrix[i,j+1]*problemMatrix[i,j+2]*problemMatrix[i,j+3]
    if prod2 > maxProd:
    maxProd = prod2
    prod3 = problemMatrix[i,j]*problemMatrix[i+1,j+1]*problemMatrix[i+2,j+2]*problemMatrix[i+3,j+3]
    if prod3 > maxProd:
    maxProd = prod3
    prod4 = problemMatrix[19-i,j]*problemMatrix[18-i,j+1]*problemMatrix[17-i,j+2]*problemMatrix[16-i,j+3]
    if prod4 > maxProd:
    maxProd = prod4
    print maxProd
    view raw euler11.py hosted with ❤ by GitHub

    Answer: 70600674

  • MOOC Review: Introduction to Computer Science and Programming Using Python (6.00.1x)

    MOOC Review: Introduction to Computer Science and Programming Using Python (6.00.1x)

    I enrolled in Introduction to Computer Science and Programming Using Python with the primary objective of learning to code using Python. This course, as the name suggests, is more than just about Python. It uses Python as a tool to teach computational thinking and serves as an introduction to computer science. The fact that it is a course offered by MIT, makes it special.

    As a matter of fact, this course is aimed at students with little or no prior programming experience who feel the need to understand computational approaches to problem solving. Eric Grimson is an excellent teacher (also Chancellor of MIT) and he delves into the subject matter to a surprising amount of detail.

    The video lectures are based on select chapters from an excellent book by John Guttag. While the book isn’t mandatory for the course (the video lectures do a great job of explaining the material on their own), I benefited greatly from reading the textbook. There are a couple of instances where the code isn’t presented properly in the slides (typos or indentation gone wrong when pasting code to the slides), but the correct code / study material can be found in the textbook. Also, for explanations that are more in-depth, the book comes in handy.

    Introduction to Computation and Programming Using Python

    MIT offers this course in 2 parts via edX. While 6.00.1x is is an introduction to computer science as a tool to solve real-world analytical problems, 6.00.2x is an introduction to computation in data science. For a general look and feel of the course, this OCW link may be a good starting point. It contains material including video lectures and problem sets that are closely related to 6.00.1x and 6.00.2x.

    Each week’s material of 6.00.1x consists of 2 topics, followed by a Problem Set. Problem Sets account for 40% of your grade. Video lectures are followed by finger exercises that can be attempted any number of times. Finger exercises account for 10% of your grade. The Quiz (kind of like a mid-term exam) and the Final Exam account for 25% each. The course is of 8 weeks duration and covers the following topics (along with corresponding readings from John Guttag’s textbook).

    course_structure_till_quiz

    course_structure_till_final

    From the questions posted on forums, it was apparent that the section of this course that most people found challenging, was efficiency and orders of growth – and in particular, the Big-O asymptotic notation and problems on algorithmic complexity.

    Lectures on Classes, Inheritance and Object Oriented Programming (OOP) were covered really well in over 100 minutes of video time. I enjoyed the problem set that followed, requiring the student to build an Internet news filter alerting the user when it noticed a news story that matched that user’s interests.

    The final week had lectures on the concept of Trees, which were done hurriedly when compared to the depth of detail the instructor had earlier gone to, while explaining concepts from previous weeks. However, this material was covered quite well in Guttag’s textbook and the code for tree search algorithms was provided for perusal as part of the courseware.

    At the end of the course, there were some interesting add-on videos to tickle the curiosity of the learner on the applications of computation in diverse fields such as medicine, robotics, databases and 3D graphics.

    The Wiki tab for this course (in the edX platform) is laden with useful links to complement each week of lectures. I never got around to reading those, but I’m going through them now, and they’re quite interesting. It’s a section that nerds would love to skim through.

    I learnt a great deal from this course (scored well too) putting in close to 6-hours-a-week of study. It is being offered again on August 26, 2015. In the mean time, I’m keeping my eyes open for MIT’s data science course (6.00.2x) which is likely to be offered in October, in continuation to 6.00.1x.

  • Which Programming Languages Get Used Most At Hackathons?

    Which Programming Languages Get Used Most At Hackathons?

    For a quick peek into the list:

    The Top 10 Languages At Devpost’s Hackathons:

    1. HTML/CSS (see note below)
    2. JavaScript
    3. Python
    4. Java
    5. C/C++
    6. PHP
    7. Objective-C
    8. C#
    9. Swift
    10. JSON (which isn’t … really a programming language, but is on their list for some reason, so I’m including #11 too)
    11. Ruby

    Read the full Techcrunch article to know why.

    In stark contrast:

    The Top 10 Languages according to IEEE Spectrum’s 2015 Rankings:

    1. Java
    2. C
    3. C++
    4. Python
    5. C#
    6. R
    7. PHP
    8. JavaScript
    9. Ruby
    10. Matlab

    Note: HTML isn’t quite a “programming” language — it’s a markup language, meaning it’s a means of laying out the elements of a document. But it’s a “language” none the less, and one that pretty much every web developer taps endlessly, so we’ll let the semantic stuff slide

  • R — The Big Mover in IEEE Spectrum’s 2015 Rankings for Top 10 Programming Languages

    R — The Big Mover in IEEE Spectrum’s 2015 Rankings for Top 10 Programming Languages

    The column on the left is the 2015 ranking; the column on the right is the 2014 ranking for comparison:

    top-tech-rankings

    source: The 2015 Top Ten Programming Languages

    The thing to note is that the top 5 languages haven’t budged from their positions. R has pushed past PHP, JavaScirpt and Ruby, which have maintained their relative positions.  So this year’s rankings have been about R moving forward.

  • Object Oriented Programing with Python – Particle Diffusion Simulation

    Object Oriented Programing with Python – Particle Diffusion Simulation

    I’m a newbie to the programming world. I first started programming in Python in May this year, a month after I started this blog, so I still haven’t learnt enough to contribute to economics as is the stated goal of this blog. But I know I’ll get there in a year or less.

    This blog was also meant to document my learning. In May, I would have called myself Newb v0.0. Today, 3 months later, I’d like to call myself Newb v0.3 and the goal is to be at least Expert v1.0 by January 2016.

    With the help of Rice University’s awesome classes on Python programming I created a cool simulation of particles diffusing into space, using the concept of Classes, which I learnt just yesterday!

    Click to check out the code !

    Screenshot from 2015-07-23 11:49:00

    Screenshot from 2015-07-23 11:49:10

    Screenshot from 2015-07-23 11:49:39

  • Number of Inversions in an Unsorted Array: Python Code

    Number of Inversions in an Unsorted Array: Python Code

    This is my solution to the first programming assignment of Tim Roughgarden’s course on Algorithms  that was due 12:30 PM IST today. Here’s the question quoted as it is:

    Programming Question-1
    Download the text file here. (Right click and save link as) This file contains all of the 100,000 integers between 1 and 100,000 (inclusive) in some order, with no integer repeated.

    Your task is to compute the number of inversions in the file given, where the ith row of the file indicates the ith entry of an array.
    Because of the large size of this array, you should implement the fast divide-and-conquer algorithm covered in the video lectures. The numeric answer for the given input file should be typed in the space below.
    So if your answer is 1198233847, then just type 1198233847 in the space provided without any space / commas / any other punctuation marks. You can make up to 5 attempts, and we’ll use the best one for grading.
    (We do not require you to submit your code, so feel free to use any programming language you want — just type the final numeric answer in the following space.)

    My Solution

    I modified an earlier code I wrote for merge sort to arrive at the solution. It needed just a couple of modifications, and if you look carefully, it turns out that the number of inversions are unearthed each and every time we merge two sorted sub-arrays. So, intuitively, if the merge sort algorithm was O(nlog2 n), it would take almost as many operations for counting inversions. In python, the code to sort and count inversions in an array of 10,000 integers took less than 3 seconds.

    # load contents of text file into a list
    # numList
    NUMLIST_FILENAME = "IntegerArray.txt"
    inFile = open(NUMLIST_FILENAME, 'r')
    with inFile as f:
    numList = [int(integers.strip()) for integers in f.readlines()]
    count = 0
    def inversionsCount(x):
    global count
    midsection = len(x) / 2
    leftArray = x[:midsection]
    rightArray = x[midsection:]
    if len(x) > 1:
    # Divid and conquer with recursive calls
    # to left and right arrays similar to
    # merge sort algorithm
    inversionsCount(leftArray)
    inversionsCount(rightArray)
    # Merge sorted sub-arrays and keep
    # count of split inversions
    i, j = 0, 0
    a = leftArray; b = rightArray
    for k in range(len(a) + len(b) + 1):
    if a[i] <= b[j]:
    x[k] = a[i]
    i += 1
    if i == len(a) and j != len(b):
    while j != len(b):
    k +=1
    x[k] = b[j]
    j += 1
    break
    elif a[i] > b[j]:
    x[k] = b[j]
    count += (len(a) – i)
    j += 1
    if j == len(b) and i != len(a):
    while i != len(a):
    k+= 1
    x[k] = a[i]
    i += 1
    break
    return x
    # call function and output number of inversions
    inversionsCount(numList)
    print count

    Test my solution here with your own test cases.

  • Introducing cricketr! : An R package to analyze performances of cricketers

    Wicked! Or must I say ‘howzzat!?’

    Tinniam V Ganesh's avatarGiga thoughts …

    Yet all experience is an arch wherethro’
    Gleams that untravell’d world whose margin fades
    For ever and forever when I move.
    How dull it is to pause, to make an end,
    To rust unburnish’d, not to shine in use!

    Ulysses by Alfred Tennyson

    Introduction

    This is an initial post in which I introduce a cricketing package ‘cricketr’ which I have created. This package was a natural culmination to my earlier posts on cricket and my completing 9 modules of Data Science Specialization, from John Hopkins University at Coursera. The thought of creating this package struck me some time back, and I have finally been able to bring this to fruition.

    So here it is. My R package ‘cricketr!!!’

    This package uses the statistics info available in ESPN Cricinfo Statsguru. The current version of this package only uses data from test cricket. I plan to develop functionality for One-day and…

    View original post 4,951 more words