Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Wednesday, April 11, 2018

C on the go - 3- \n to set a new line

Video:- https://www.youtube.com/watch?v=aRAg1tJItn8


References: https://www.tutorialspoint.com/learn_c_by_examples/index.htm
                    https://www.learn-c.org/en

 
Notes:-

  printf( "Hello, World\n" ); //we will need to call the function printf to print our sentence. \n is used to set a new line

   int op1, op2, sum, sub;      // variable declaration

   op1 = 5;                // variable definition
   op2 = 3;

   sum = op1 + op2;        // addition operation

   printf("sum of %d and %d is %d", op1, op2, sum);




Check out the C programming playlist at https://www.youtube.com/playlist?list=PLDMwfcFQi85p0B1w3o6gLaVQ6eOkCHJz5

C on the go - 2- Variables

Video:-  https://www.youtube.com/watch?v=d9bWO9DASjQ

References: https://www.tutorialspoint.com/learn_c_by_examples/index.htm
                    https://www.learn-c.org/en

Notes:-

int op1, op2, sum;      // variable declaration

   op1 = 5;                // variable definition
   op2 = 3;

   sum = op1 + op2;        // addition operation

printf("sum of %d and %d is %d", op1, op2, sum);

Tuesday, April 10, 2018

C on the go - 1- 'Hello World'

Video -  https://www.youtube.com/watch?v=MPp09MgBaKA
References:- https://www.tutorialspoint.com/learn_c_by_examples/index.htm
                    https://www.learn-c.org/en

Notes:-

 //include library called stdio.h

 int main() //code which will run will always reside in the main function. The int keyword indicates that the function main will return an integer - a simple number, in this case 0

 printf( "Hello, World" ); //we will need to call the function printf to print our sentence.
 
 return 0;

Sunday, December 13, 2015

Python on the go - Application in calculating resistances

Here is a program that calculates resistances in series or  in parallel.


def resistor(l):
    a=raw_input("series or parallel? (s or p)")
    if a== 's':
       sum1 = 0
       for v in l:
                    
           sum1 = sum1 + float(v)
                    
       return sum1

    elif a =='p':
            sum1 = 0
            for v in l:
                    
                    sum1 = sum1 + (1/float(v))
                    
            return 1/sum1


So, how does it work? Firstly, def means that this is a functional program with a list called 'l' so when you run it, you should type 'resistor ([2,3,5])' for example to calculate three resistances of values 2, 3 and 5 ohms.

 In the second line of the program , you will need to  accept variable 'a' as a raw input which may be s or p.  If a='s' to signify that resistances are in series, then the variable suml is first set to 0. In a way  you can think of the variable suml as some kind of container or box where  values (or variables) v can be added to it. Next, there is a  for loop for each variable v  in list 'l' and this for loop will add each variable in 'l' until the end of the list. Once it has reached the end of the list , 'return sum1' displays the value of sum1 and the program exits.

If a=' p',    to signify that resistances are in  parallel, the process is almost the same, only that  the formula for parallel resistances is  different so some changes need to be made near the end.

Monday, August 31, 2015

edX - HKUSTx: ELEC1200.1x A System View of Communications: From Signals to Packets (Part 1)

Am in  the second week of the course and has been quite interesting for the most part so far. Usually communication systems courses are tough but this one has been quite comprehensible so far. I am quite impressed by it. There is  Matlab programming which I am not really that fond of as I had only just completed some Python courses but I do realize, it is used quite a lot in  the workplace. The wonderful thing about these courses is that there are sandboxes where you can try out these softwares and take your time to learn them if you want.

However, datelines for this course is quite short as it is not really self paced - if you are not too worried about earning a cert but just want to learn something  then this is fine.

Sunday, August 23, 2015

Python on the go - Revision of Class and Inheritance

Referred from https://en.wikibooks.org/wiki/A_Beginner%27s_Python_Tutorial/Classes


  A class can be defined as a template for creating objects such as functions. For example the program below provides a description of a shape  and what operations you can do with the shape (that is, the functions). The  __init__()  function is always run when the class is called.

class Shape:

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.description = "This shape has not been described yet"
        self.author = "Nobody has claimed to make this shape yet"
        
        
    def area(self):
        return self.x * self.y

    def perimeter(self):
        return 2 * self.x + 2 * self.y

    def describe(self, text):
        self.description = text

    def authorName(self, text):
        self.author = text

    def scaleSize(self, scale):
        self.x = self.x * scale
        self.y = self.y * scale



rectangle = Shape(100, 45)      #calling the class Shape
print rectangle.area()                # the area of the rectangle:

print rectangle.perimeter()       #the perimeter of it:

rectangle.scaleSize(0.5)         #makes it 50% smaller
print rectangle.area()              #the new area of the rectangle


It is possible to add extra features to a new class by using inheritance. The example below shows how a new class has inherited some of the features of the old one but its  __init__() function has changed.


class Square(Shape):
    def __init__(self,x):
        self.x = x
        self.y = x
        
square1=Square(10)
print square1.area()


Sunday, August 16, 2015

Python on the go - Revision of Files

One of the simplest ways for programs to maintain their data is by reading and writing
text files.

To write a file, you have to open it with mode 'w' as a second parameter:

file = open('out.txt', 'w')
file.write("Hello there.\n")
file.close()


If the file already exists in the same directory as the program, opening it in write mode clears out the old data . If the file doesn’t exist, a new one is created.


To read a file, you have to open it with mode 'r' as a second parameter:

file = open('out.txt', 'r')
print file.read()


file.read() returns a string with all the characters in the file. With print, the output can be seen in the Python shell.

The above two programs can be combined in one program to write and read a file.


file = open('out.txt', 'w')
file.write("Hello there.\n")
file.close()

file = open('out.txt', 'r')
print file.read()

Sunday, August 9, 2015

Python on the go - Revision of Tuples and Dictionaries

Tuples are very similar to lists but they are not modifiable and they are not used as often as lists. The items in a tuple are enclosed by round brackets instead of the  square brackets that are used in lists.

days=("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",  "Sunday")

Dictionaries have keys and values. Each value in a dictionary can be obtained by using a key. These keys and values are enclosed in curly brackets.

 phonebook={'Jon':456782,  'Peter':2345233,  'Fred':5678123}

Dictionaries can be useful for finding values of certain keys such as the phone  number in the case above. For example, to find the phone number or value of the key 'Jo' , type in the python shell -

phonebook["Jon"]

An additional key and value can be added to the dictionary by typing in the program-

phonebook["Jack"]=546773


Sunday, August 2, 2015

Python on the go - Revision of Lists

Lists are similar to arrays and in Python, it is quite easy to build them. Here is a simple program that adds a list of numbers using the built-in function sum.


mylist = [1,2,3]
print 'sum of the list is',sum(mylist)


Sometimes we may wish to take certain items from a list and use them for a certain purpose, for example  item 1 minus item 3  or adding the first two items of a list .


mylist = [1,2,3]
print 'sum of the list is',sum(mylist)
print

print 'item 1 minus item 3 of the list is ',mylist[0] - mylist[2]
print 'sum of first two items of the list is ' ,sum(mylist[0:2]) 

Sunday, July 19, 2015

Python on the go - Revision of Repetitions

To repeat a certain task a fixed number of times, a for loop is used:-


 for x in range(5): 
    print x


To repeat a task until a certain condition is met, a while loop is used:-

def countdown(n):
    while n > 0:
          print n
          n = n-1
    print 'Blastoff!'


Another way a process can be repeated is recursion  which can be difficult to implement :-

def countdown(n):
    if n <= 0:
       print 'Blastoff!'
    else:
         print n
         countdown(n-1)


A recursion  usually consists of
(1)  a base case (when to stop)
(2) a work towards a base case
(3) a recursive call that calls itself


Updated - 27-7-2015

Saturday, July 11, 2015

Python on the go - Revision of Conditional Execution

There are times in a program when there is a need to execute certain instructions after a certain condition is met  and this process may be carried out by using   "if"  statements as shown:-


num = raw_input('Input a number? ')
num2=float(num)
if num2>0:
   print "The number is positive"
elif num2==0:
     print "The number is zero"
else:
     print "The number is negative"


elif is an abbreviation for  "else if"  and it can be used more than once. else is used for the possible remaining conditions and normally used at the end of the "if" statements.  However, there does not need to be one.


Sunday, July 5, 2015

Python on the go - Revision of Functions

A function is a block of code which performs a computation. They can be reused in a program.
Here are some functions that can be used on lists

https://docs.python.org/2/tutorial/datastructures.html

These are inbuilt functions.  Certain functions like maths functions can be imported into the program by typing

from math import* 

We can also create our own functions. The 'Hello World' program can be written in a function as shown below.

def hello():
      print  "Hello World"

To call and run the function type  hello()  in the python shell

Monday, June 29, 2015

Python on the go - List Comprehensions

Back to what I have been doing. Here is a way of simplifying some of the things that are done with lists

From https://docs.python.org/2/tutorial/datastructures.html


5.1.4. List Comprehensions

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
For example, assume we want to create a list of squares, like:
>>>
>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
We can obtain the same result with:
squares = [x**2 for x in range(10)]
This is also equivalent to squares = map(lambda x: x**2, range(10)), but it’s more concise and readable.
A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and ifclauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:
>>>
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Friday, June 26, 2015

Python on the go - Revision of Variables

Variables in Python can be declared on the go. For example if you input your age with raw_input which inputs your age as a string , it can be converted into a number by declaring it as a float. eg float(age)    as shown below

age = raw_input('How old are you? ')
age2=float(age)
print "You are ",age2,"  years old"

Variables  can be  declared as numbers usually in the form  of a float or integer.  For accuracy, numbers are usually declared as floats.

But you don't always have to declare variables in Python . Sometimes Python recognizes it for you automatically. If you type  a variable like temp=31.0 (short form of temperature) ,  Python recognizes it as a float. In otherwords, any variable with  a decimal number assigned to it,  will be recognized as a float in Python. You can check this with the program as shown


temp=31.0

print type(temp)

The program will print the type of variable temp is - which is a float.


updated 12-7-2015


Wednesday, June 24, 2015

Python on the go

Those five points from 'Think Python'  lie the basis of most computer programs. I could not think of simplifying it much more than that.

What has been done so far is to output data  with  print.

There are generally two types of data - words and numbers but in the programming world, words are described by strings or characters while numbers are described by integers, floats etc.  "Hello World!" is a string.

To input a string, use raw_input()

name = raw_input('What is your name?')
print name

The above, stores the input  into a variable called name and then prints the name.

What is stored in a variable,  can be changed in the program.



Tuesday, June 23, 2015

Python on the go

In Python, a simple “Hello, World!” program would look like this

 print 'Hello, World!'


In C, it will look like this














One can see how much simpler it is, to write certain programs in Python. 

What is in most programs are generally the same. They have the following:-


input: Input data from the keyboard, a file, or some other device. (eg. raw_input)
output: Display data on the screen or send data to a file or other device. (eg print)
math: Perform basic mathematical operations like addition and multiplication. (eg  +   -     *      /   and %)
conditional execution: Check for certain conditions and execute the appropriate code. (eg. if, elif, else)
repetition: Perform some action repeatedly. ( eg. for, while and  the process of recursion)





Python on the go

I have been trying out three introductory courses  from Harvey Mudd College, MIT  and University of Michigan. The first two from edX and the last one from Coursera.

The hardest ones  seem to be the ones from edX - Harvey Mudd and MIT - but the content for those courses are very good and those who are up for the challenge, should probably try them out. For those who are starting out programming  and want to learn it in a more relaxed manner,  the one from Coursera - University of Michigan may be the better option. Generally all three so far, appear to be good enough courses to gain some knowledge  in programming. Professor Charles Severance from the Coursera one,  University of Michigan has written a remixed version of the 'Think Python' book.
Professor Zachary Dodds from Harvey Mudd  has  teamed up with others to also write a book about Python while Professor Eric Grimson    from MIT has won awards for his research in computer vision.

Python is made from C so, according to this article, it is good to learn as many languages as possible.

Unlike Python, getting a C compiler can be a headache in itself as there are many out there and some may not run properly . CodeBlocks  is relatively easy to set up and seems to have not much problems in running the programs.
http://www.cprogramming.com/code_blocks/


Sunday, June 21, 2015

Python on the go

I have been trying out some courses on this programming language for the last few weeks and have found it to be an interesting one.

It's less than  20 MB in download size and it is text based but the language itself is quite simple - probably the simplest I have seen so far. I have had to set it as  - use as admin - as it was crashing quite a few times at the beginning.

In Windows, Python is run through Idle. The version that is used in most courses is Python 2.7.  I read that the reason is due to incompatibility of the code of 2.7 in version 3.

https://wiki.python.org/moin/Python2orPython3

 Idle in Windows, is found by clicking  Start , All Programs , look for  the Python 2.7 folder and click on Idle. Programs are usually written in the Idle text editor and saved as .py files before running them.  The .py files can be edited by right clicking on them.(A simple text document (.txt) can also be used by Idle to run the programs.  Idle can save them in the .py files by typing .py at the end of the filename.)

The programs are run by pressing F5. Idle  will usually automatically prompt you to save the file before it runs.

Here are some resources about Python:  (updated 12-7-2015)

Tutorial:-  The Python Tutorial

Books : -
Think Python by Allen B. Downey
 Python for Informatics by Charles Severance - a remixed version of the above book
CS for All by Christine Alvarado (UC San Diego), Zachary Dodds (Harvey Mudd), Geoff Kuenning (Harvey Mudd), Ran Libeskind-Hadas (Harvey Mudd)


Debugging: - Online Python Tutor by Philip Guo

The courses that I have been trying out are also very good. The one from Coursera  goes at a more gentle pace while the other two from edX   seem to have quite a lot of content in them.

Tuesday, May 26, 2015

edX: - HarveyMuddX: CS002x Programming in Scratch

This is a fun course to try out. I have learnt quite a few things from it and though it may seem to be more geared towards children, adults can join in and will probably find Scratch to be a useful program. I think it brings out the child in everyone of us and it is one of the better edX courses.


Monday, May 18, 2015

edX: - HarvardX: CS50x3 Introduction to Computer Science - week 3 Continue

Obama was not totally wrong when it came to answering a Computer Science question.



bubblesort
(n(n-1))/2
big O    - eg  order of n^2   or O(n^2)

O(n) - finding maximum number in a list
O(log n)  -eg  phonebook -approximately decreases  problem in half every step - list has to be sorted 
O(1)  -  constant

lower bound (n) or   Ω(n)  - eg  bubblesort
lower bound (1)  - phonebook
selection sort -    upper bound and lower bound of n^2
insertion sort -  upper bound and lower bound of n^2
merge sort - eg sort left, sort right and merge  O(n log(n))  which is much faster

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.