Browsing Tag

Programming Languages

Classes

10 Lessons Needed To Learn Programming In Any Language*

October 19, 2015

Without farther delay, here is my top 10 lessons to learn programming in the order they should be taught:

  1. Environment Setup, Input/Output
  2. Integers and basic arithmetic (+,-,*,/,%) + order of operations ()
  3. Float Arithmetic
  4. Variables
  5. Booleans
  6. Conditional Statements & Control Structures
  7. Functions
  8. Strings & Arrays
  9. Classes
  10. Exceptions

Ok, I lied. A lot of these have to be broken down and cross referenced. However, I think that should be the order in which people are introduced to programming. Too often people try to learn everything all at once. You can’t learn how to swim by jumping into the deep end. Well, some of us can. Learning a new skill isn’t always as easy to other people as it was to the teacher. Whenever I get a chance to be a bookstore, I like to look at beginner programming books. They all promise to teach a lot in a very short time. The honest truth is there is no shortcut. It takes a couple of years of programming in order to become a half dissent programmer. It is not because it is hard, it is just because there are too many variables. There are so many different things that you need to learn, that it can’t occupy just one book. It can’t even occupy the whole Internet. New things come up everyday that change what you knew before. Becoming a programmer is just one of these thing that require time.

So what is with this list? I got asked too many times at this point how I started programming and where/how to start. I have decided to write my own intro to programming. Over the next weeks I will publish small lessons that will build up to an ebook on programming. I will use Python-ish style code and most of the content will be generalized for almost any language. By the end of the book, you will be able to learn the syntax to a new language and program in any language you want. Best of all, the ebook and lessons will all be posted on this site and will be FREE. No strings attached. I believe anyone can learn programming at any age and that education should be available to all.

I have taught a few students before and there are several reasons why my list is different from other learn programming classes. The main objective is to start with something familiar that everyone in the 5th grade should know. Basic arithmetic and numbers. Than slowly build up while introducing new ideas and concepts. The secondary objective is to fully learn a topic before moving forward. That means when we will talk about a new concept we will go back and see how it reflects on other topics we have learned before. We are going to aim to turn fragile knowledge into concrete building blocks that will help us move forward and ultimately complete our objectives.

It should be mentioned what this course will not achieve. Beyond all else, you will not become a certified programmer or a hacker. Like I said before, that will take time. There is no class in the universe that can teach time. After you have completed the lessons, you will have to continuously learn new skills and develop yourself as a programmer. Think about learning programming more like going to the gym. You will not get a six pack and lose 50 lbs. in one setting, it takes time. Same thing with programming. You need to invest time to become a programmer. Just like going to the gym everyday, it will pay off in the long run and you future self will look back and thank you.

There are a bunch of reasons of why you should learn programming, I don’t feel like repeating most of them. I will just mention one. Programming is everywhere and it is here to stay. Programming has become a tool that used in virtually every field, even philosophy and history. Programming is almost equivalent to using excel. It is a skill more and more employers are looking for and will make you more valuable and your job easier. There are endless examples of how programming can shorten your job and sometimes turn an impossible human task into a simple short snippet of code. I believe that if you are reading up until this point, you already have a goal to learn programming. Or maybe you have already been through a class, but feel like you have missed the points and you want to know more. In programming there is always more to learn. Remember that.

First lesson will be published within a week. Make sure to follow me on Twitter @CptDeadBones to get notified.

* Ok. So technical, the class will teach you how to program in almost any language.

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

Code:

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

Code Output:

wpid-python_is_even_output-2014-01-6-19-281.png

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]

Code:

* 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:

wpid-python_remove_evens-2014-01-6-19-281.png

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

Code:

def minval(alist):
	return min(alist)

Code Output:

wpid-python_minval-2014-01-6-19-281.png

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

Code:

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

Code Output:

wpid-python_minval_index_2-2014-01-6-19-281.png

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

Code:

def remove_a_value(val, alist):
	try:
		alist.remove(val)
		return True
	except:
		return False

Code Output:

wpid-python_remove_value-2014-01-6-19-281.png

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]

Code:

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

Code Output:

wpid-demo_function_6-2014-01-6-19-281.png

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]
distraction_sort(list_a)

Code:

#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:

wpid-demo_function_7-2014-01-6-19-281.png

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

Code:

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:

wpid-demo_function_8-2014-01-6-19-281.png

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

Code:

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

Code Output:

wpid-demo_function_9-2014-01-6-19-28.png

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')]

Code:

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

Code Output:

wpid-demo_function_10_b-2014-01-6-19-28.png

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]

Code:

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

Code Output:

wpid-demo_cundtion_11-2014-01-6-19-28.png

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

Code:

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

Code Output:

wpid-demo_function_12-2014-01-6-19-28.png

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]

Code:

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

Code Output:

wpid-demo_function_13-2014-01-6-19-28.png

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]

Code:

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

Code Output:

wpid-demo_function_14-2014-01-6-19-28.png

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']
riffle_shuffle(list_a)

Code:

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:

wpid-demo_function_15-2014-01-6-19-28.png

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')]

Code:

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

Code Output:

wpid-demo_function_16-2014-01-6-19-28.png

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:
new_deck()

Code:

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

Code Output:

wpid-demo_function_17_b-2014-01-6-19-28.png

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]

Code:

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

Code Output:

wpid-demo_function_18-2014-01-6-19-28.png

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]

Code:

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

Code Output:

wpid-demo_function_19-2014-01-6-19-28.png

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]

Code:

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

Code Output:

wpid-demo_function_20-2014-01-6-19-28.png

Infographics

The Visual History of Programming Langagues

June 4, 2013

wpid-History-Of-Programming-Languages-Veracode-2013-06-4-09-11.jpg

Programming Languages

Programming Languages to a Non-Programmer

December 24, 2012

As a non-programmer, you have often heard programming languages names being used. Marketers have always tried to used technical words to market new products and to claim superiority using “fancy” words. Many have come across HTML, java, flash, but do not know what that means. It is to my intend to educate those who may not know.

As for the programmers among you, many of us do not go a day without using several programming languages. If you really think about it, after the first few languages, learning new ones become easier. This may not encompass human languages, but learning new computer languages became easier for me with time. One thing that helped me the most was learning about the different types of programming languages. Knowing where to categories a new language helped me relate things I already know with new information. Hopefully you too will find this true. Learning new programming languages is a vital tool any programmer needs to acquire.

A Programming language is a communication method for humans to interact with machines. That is a very high level view. Machines, computers to be exact, work on binary sequences. That is strings of 0’s and 1’s. At the end of the day that is all computers understand. Further more, the entire operations a computer knows how to do is limited to operations on those strings of 0’s and 1’s. Any more complicated operations is done via multiple operations on said strings. Thankfully, we can store and reuse a sequence of operations. This is the closet level of operations, Machine Language. In the early days of computing, computers were programmed in such method. However, it is very impractical to program anything complex in this matter. Every set of commands in any languages must end up as a Machine Language instruction set suitable for a target computer architecture.

To take a step farther form Machine Language, we created Assembly. Assembly is the attempt to combine machine language operations into symbolic ones. It often group several Machine Language instructions into a single Assembly command. This enables programmer to create more complex programs, however still resides close to Machine Language. It provides better readability, with the same efficacy of Machine language. Assembly instructions are compiled into their Machine Language representations in order to be executed on a target architecture.

The next step away from Machine Languages are the low and high level programming languages. Some are easy to specify as while others are in-between. Languages that allow direct access to memory are often considered low. Languages such as c, c++, java to some extend, are low level. High level languages include matlab, matamitica, php, and other. Python for example, could be argued to be somewhere in-between. Depending on the programmer and the libraries used, python could be utilized as a low level or a high level language.

There are many types of programming languages. The Wikipedia entry for List of programming languages by type counts 43 languages as of the date of this post. Some of the ones I highly recommend on learning are (in no particular order of preference):

  • c, java, python
  • Lisp
  • Prolog
  • web langs: php, javascript, mysql, html, css
  • matlab