Monthly Archives

March 2014


The Cold Reality of a Wrench...

March 31, 2014


Computer Programming I, Java, Programming Languages

The Rainfall Problem in Java

March 28, 2014

It has been quite a while since I have posted any code in Java. As I was going through some Java questioners, I came across the Rainfall problem. The rainfall problem in java is quite simple, the user is going to enter data, the average participation per day r something, and the output is some statistical information. To keep things interesting, no arrays can be used, so everything needs to be computed on the fly. For our purpose, the user will enter the last 12 months data, an he output will be the minimum, maximum and average participation. This is fairly simple and a great exam or interview question.

Note that the code will check that enteries are non negative numbers.

Here is how this is going to look in Java:

import java.util.Scanner;

public class Rainfall {

 public static void main(String[] args) {

  //variable setup
  Scanner input = new Scanner(;
  String userInput = "";
  double sum = 0.0;
  final int COUNT = 12;
  boolean valid = true;

  //initiazlize variables min and max to something out of range
  double min = 999999999999.9;
  double max = -0.1;
  int min_month = 0;
  int max_month = 0;

  //temp variable
  double curr = 0.0;

  for (int i=0; i < COUNT; i++){

    //user input validation

		//get user input
        System.out.print("enter the rainfall for month number " + (i+1) +": ");


			//convert input to double
			curr = Double.parseDouble(userInput);
			valid = true;

			//throw error if input is less than 0
			if(curr < 0) throw new Exception();

		} catch (Exception e) {

			System.err.println("\nThat was not a valid entry! \nPlease try again.\n");
			valid = false;
   } while (!valid);

   //keep a running total
   sum+= curr;

   //find min
   if(curr < min){
     min = curr;
     min_month = i+1;

   //find max
   if(curr > max){
     max = curr;
     max_month = i+1;

  } //end for loop

  //compute the average
  double avg = sum/COUNT;

  //report the result
  System.out.println("\nThe avg rainfall is " + String.format("%.2f", avg) +
    "\n" + "The min rainfall is " + min + " for month number " + min_month +
    "\n" + "The max rainfall is " + max + " for month number " + max_month );

Here is how the output should look like:


Cool Stuff, Infographics, Random

How Japanese Kids Learn to Multiply...

March 27, 2014

Japan Math

Programming Languages, Python

20 Good Functions to Know in Python

March 24, 2014

To wrap up our last 2 discussions about functions, namely how to use functions in Python and the temperature convertor, let us take a look at some functions that you may find useful in the future. We are going to start off easy and stack up. As before, we are going to be using Python 2.7. Before we get started let me remind every one, yes there are other ways, perhaps even better ways to code these functions. This is How I did it. It does not mean this is how you should do it. In fact, I would lover it if you left your version in the comments bellow! If you think it is too long for the comment section, send me an email and I will make it into a post. Lastly, these function are meant as an exercise, please be patient even if some of them do not make sense.

For each function (There are 22) we are going to look at the following:

  1. Brief description of the function
  2. Input types
  3. Excepted output
  4. Notes (if any)
  5. Example execution
  6. Code
  7. Example Output for code
  8. Final Notes (if any)

This is going to be long, so hang on. Let’s get started!

1. Even numbers:
Return a boolean value representing whether x is even or not.

input: number (integer)
output: True or False (boolean)

Example execution:
is_even(5) => False
is_even(42) => True


def is_even(n):
	return (n % 2) == 0

Code Output:


Final notes: Be aware the although the function is excepting an integer, a float might be passed in as the value of n. The result would always be False unless n is an even integer.

2. Remove evens:
Given a list of integers, remove all even values from the list and return an odd list of numbers.

input: a list of integers (list)
output: a list of odd numbers (list)

Example execution:
remove_evens([1,2,3,4,5,6]) => [1,3,5]


* Edited thanks to Eric Wilson (See comments)

def remove_evens(alist):
	res = []
	for n in alist:
		if not is_even(n): res.append(n)
	return res

Code Output:


Final Note: You will notice that in this function we are calling another function within the module.

3. Min Value:
Accepts a list of numbers, and returns a copy of the smallest value in it.

input: a list if integers (list)
output: the minimum number (integer)

Example execution:
minval([104,22,31,4,54,61]) => 4


def minval(alist):
	return min(alist)

Code Output:


Final notes: Although in the input section we assumed that the function should only accept a list of integers. The function, as coded above, will also work for a mixed valued list. Python will use simple comparison to make sense and determine what the min value is.

Final notes 2: I am aware that that this function is useless since all it does is called the built in function min().

4. Index of Min Value:
Accepts a list of numbers, and returns the index (zero based) where the smallest value can be found. It must return the earliest index, in case of ties.

input: a list if integers (list)
output: the minimum number’s index in the list (integer)

Example execution:
min_index([104,22,31,4,54,61]) => 3


def min_index(alist):
	return alist.index(minval(alist))

Code Output:


Final Note: You will notice that in this function we are calling another function within the module.

5. Remove Value:
Finds the first instance of a value, and removes it from the list. Return a boolean, True when the value was removed, and False when the value wasn't found.

input: an integer value and a list of integer numbers
output: True or False (boolean)

Example execution:
remove_a_value(22,[104,22,31,4,54,61]) => True
remove_a_value(105,[104,22,31,4,54,61]) => False


def remove_a_value(val, alist):
		return True
		return False

Code Output:


6. Simple Sort:
Given a list of numbers, you will return a copy of the list with all elements in sorted (ascending) order. You must implement the following algorithm:

make a copy of the list make an empty result list
LOOP as long as the copylist isn't empty:
find the minimum value in the copylist, remove it
add that minval to the end of the resultlist return the result list

input: a list if integers (list)
output: a list of sorted integers (list)

Example execution:
simple_sort([104, 22, 31, 4, 54, 61]) => [4, 22, 31, 54, 61, 104]


def simple_sort(alist):
	copy = alist[:]
	res = []
	while len(copy) > 0:
		x = minval(copy)
	return res

Code Output:


Final Note: Although the function is assuming to work on integers, it may also work on other data types. Try it out.

7. Destructive Sort:
This behaves the same as Simple Sort, except that it must modify the original.

input: a list if integers (list)
output: NONE.

NOTE: In this function we will be modifying the original list, meaning it is a destructive function to the arguments passed in. Also note that the function does not have any return statements or a return value.

Example execution:
list_a = [33,94,1,92,54,12]


#The code uses simple_sot(alist) to sort the list and then rewrites the original list values
def distraction_sort(xs):
	temp = simple_sort(xs)
	for i in range(len(temp)):
		xs[i] = temp[i]

Code Output:


8. Middle Sort:
Without modifying the original list, find out what the middle element would be when all the elements are sorted. If the length is even (and thus no true 'middle' element), then out of the two elements closest to the middle, prefer the left one.

input: a list if integers (list)
output: the middle number if the list was sorted (an integer)

Example execution:
median_value([5,34,29,91,102,44,1,4]) => 29


def median_value(xs):
	temp = simple_sort(xs)
	mid = int(len(xs)/2)
	if is_even(len(xs)): mid -= 1
	return temp[mid]

Code Output:


9. Kth Sorted:
Like Middle Sort, only we seek the Kth spot, not the middle spot. K is a zero-based integer index into the sorted version of list.

input: a list if integers (list)
output: the kth number if the list was sorted (an integer)

Example execution:
kth(2,[71,43,67,10,4,3,87,103s]) => 10


def kth(k,xs):
	temp = simple_sort(xs)
	return temp[k]

Code Output:


10. Zip List:
Given two lists of values, create and return a list of tuples that "zip" up the values from the two lists together - first items in a pair, second items in a pair, and so on.

input: 2 lists of integers (lists)
output: a single list of tuples with values from both lists (a list)

Example execution:
zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']) => [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]


def zip(xs,ys):
	res = []
	i = 0
	while i < len(xs) and i < len(ys):
		i += 1
	return res

Code Output:


11. Multiply Lists:
Given two lists of numbers, create a new list of numbers by multiplying the same-indexed values. As soon as one list runs out of values, the resulting list ends.

input: 2 lists of integers (lists)
output: a single list with the values from both list multiplied, while both lists have values (a list)

Example execution:
pairwise_multiply([2, 3, 10, 11], [35, 10, 29, 3]) => [70, 30, 290, 33]


def pairwise_multiply(xs,ys):
	res = []
	i = 0
	while i < len(xs) and i < len(ys):
		i += 1
	return res

Code Output:


12. Dot Product:
Given two lists of numbers, return a single number found by multiplying each same-indexed pair of numbers, and adding the results together.

input: 2 lists of integers (lists)
output: the sum of each pair of elements multiplied (an integer)

Example execution:
dot_product([1, 2, 3], [3, 2, 1]) => 10


def dot_product(alist, blist):
	return sum(pairwise_multiply(alist,blist))

Code Output:


13. N Copies:
Return a list with n copies of val.

input: a number and a value (integer,any)
output: a list with n copies of a given value (a list)

Example execution:
n_copy(5,3) => [5, 5, 5]


def n_copy(val,n):
	res = []
	for i in range(n):
	return res

Code Output:


14. Interleave:
Given two lists of values, create (and return) the interleaved version by making a new list with the first value of list_a, then the first value of list_b, then the second value of list_a, second value of list_b, and so on. Once a list is done the rest of the values from the other list are added to the resulting list.

input: 2 lists of integers (lists)
output: A single list with the values from both lists interleaved (a list)

NOTE: Etra valuees for either list are added to the end of the result list

Example execution:
interleave(['a', 'b', 'c'], [1, 2, 3]) => ['a', 1, 'b', 2, 'c', 3]


def interleave(alist,blist):
	res = []
	i = 0
	while i<len(alist) and i<len(blist):
		i += 1
	for j in range(i,len(alist)):
	for j in range(i,len(blist)):
	return res

Code Output:


15. Riffle Shuffle:
Imagine we were shuffling cards with the standard "riffle" shuffle (just interleaving two halves of the deck together). For many card games, we need to perform multiple shuffling in order to get enough apparent randomness in the order of cards. List represents the 'deck' to be shuffled, and n represents how many "riffle" shuffling need to be performed.

input: a single list (a list)
output: a shuffled list (a list)

NOTE: Like function 7, distraction_sort, this function modifies the original values given

Example execution:
list_a = ['a','b','c','d','e','f','g']


def riffle_shuffle(alist):
	temp = alist
	mid = int(len(alist)/2)
	temp = interleave(temp[0:mid],temp[mid:len(alist)])
	for i in range(len(alist)):
		alist[i] = temp[i]

Code Output:


16. Pairs:
Create and return a list of all possible pairs from values in list_a and values in list_b. The order of elements is important! all of the pairs of list_a first element must appear before all pairs involving list_a second element; similarly, when pairing with a specific element from list_a, these pairs must include list_b elements in the same order as original.

input: 2 lists of integers (lists)
output: a single list with pairs of values from both lists (a list)

Example execution:
all_pairs([1, 2, 3], ['a', 'b', 'c']) => [(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c')]


def all_pairs(alist,blist):
	res = []
	for x in alist:
		for y in blist:
	return res

Code Output:


17. Build Deck:
Create a fresh, organized deck. You must generate the result from these two strings: one representing all the pips (card values) "23456789TJQKA", and another representing the suits, "CDHS".

input: 2 strings, “23456789TJQKA” and “CDHS” (strings)
output: a list of cards (a list)

NOTE: each card will be repressed by a value and suit. For example: 4C is 4 of clubs, TS is ten of spades and QH is queen of heats.

Example execution:


def new_deck():
	val = "23456789TJQKA"
	shapes = "CDHS"
	return (all_pairs(val,shapes))

Code Output:


18. Reduce Dimension:
Given a list of more than one dimension, create and return a new list by collapsing that outermost dimension.

input: a multidimensional list (a list)
output: the list without the outmost dimension (a list)

NOTE: This function only reduces the original list dimension by 1, not a full flatten.

Example execution:
flatten([[[1, 2, 3], 4], [5]]) => [[1, 2, 3], 4, 5]


def flatten(alist):
	res = []
	for i in alist:
		for j in i:
	return res

Code Output:


19. Map:
Given a python function and a sequence of values, create and return a new list by calling the function on each value in the sequence and placing the results into the returned list.

input: a function name and a sequence of values (string,tuple/list)
output: the results from the mapped function onto the sequence of values (a list)

Example execution:
map(ord,”Hello World”) => [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]


def map(f,alist):
	res = []
	for x in alist:
	return res

Code Output:


20. Zip With:
Combine elements of list_a and list_b together while using the operator, generating a new list.

input: a function and 2 lists (string,lists)
output: a list with the values from applying the function on the lists values (a list)

Example execution:
zip_with(add, [1, 2, 3], [4, 5, 6]) => [5, 7, 9]


def zip_with(f,alist,blist):
	res = []
	i = 0
	while i<len(alist) and i<len(blist):
		i += 1
	return res

Code Output:


Mathematics, Random

As someone who has been through a lot of math...

March 17, 2014
Dear Math

Infographics, Random

Make the Juice Last: Battery Advice for Mobile Devices

March 15, 2014

It's happened again - you're dead. Or at least your connection to the outside world is. Your battery life decreased so rapidly you could almost watch the percentage fall. These days, if you even think about relying on GPS, setting the display to bright, playing a video or connecting to Bluetooth, let alone making a call, you may be down to no battery power in a blink. The longest you can expect your battery to last between charging sessions on the best phones available is about 15 hours, according to CNET. But there are some simple ways to avoid draining your battery while still actually using your device. Here are some battery advice for Mobile Devices.


Battery ‘Bloodsuckers’

One of the biggest energy drains on your battery is your device’s display, but you don’t have to reduce brightness when you really need it. When you aren’t using it, however, minimize the brightness as much as you can or turn off the display altogether. Adjust your settings so that the screen goes black every couple of minutes when the device is not in use.

It’s so easy to forget to turn off your GPS function after you’ve reached a destination, but it guzzles a battery’s power. Now that you know where you are, close out of this app.

Bluetooth and Wi-Fi also suck power from your battery. Unchecking these functions in your “Settings” options when you don’t need them can double your battery life, with one exception. Using the Wi-Fi calling feature on some of T-Mobile’s Windows phones can actually boost battery life.

Flying high? On an airplane, your phone will continuously search for non-existent signals, burning battery power. Simply switch to “airplane mode” when you’re on a plane to prevent this, suggests PC World.

More Remedies

Adjust the settings on your device to switch automatically to battery-saving mode when the device is losing power. On a Windows phone, go to “Settings” then “Battery Saver.” It turns off some services while in standby to preserve battery life, but you can receive calls and texts. Emails must be refreshed manually. Even if your battery charge isn’t low, you can activate the battery saver manually by clicking the advanced button.

It’s advisable to turn off another feature on a Windows phone: the double tap to wake up the phone. Turning it off saves battery life; instead, all you have to do is press the power button to wake up the phone.

‘App’ the Battery Life with the Latest Releases

Several downloadable apps can alert you to flagging battery power and some can even extend battery life. The “Go Battery Saver & Power Widget” for Android phones, for example, extends the life of a battery with power-saving modes. The app also shows the time remaining before the device will switch off and has a widget with a personalized user interface that enhances battery performance. To keep the process of charging the battery "safe,” the app's charging maintenance helps in the overall extension of battery life during charging.

Another Android app is the “DU Battery Saver & Widgets” available in 17 languages that claims it can increase battery life by 50 percent. The app lets users pre-set battery power management modes or personalize modes to suit their habits. Its one-touch widget can close all power-eating apps working in the background. In addition, its “healthy charge manager” tracks practices that will enhance battery life.

The more of these "fixes" you turn to, the longer you can expect your battery to function between charges. Preserving device battery power is simply a matter of being aware of how many functions and processes are part of your device.

Cool Stuff

Python + Wiimote + 15 tonnes of Metal!

March 7, 2014

Old, but worth it,