Sunday, April 5, 2015

With every beginning there comes an end.

    Hi everyone. As this post's title suggests, this is going to be the last SLOG that I will write on for the CSC148 course. I feel like this course had an amazing impact on my knowledge of programming and although I was always interested in computer science and programming (well not always but for a few couple of years now) but this course really started to show me how cool programming can be, specially with our three joined assignments! I mean, you gotta admit, writing a game that can play smart moves is kinda awesome! There were lots of slogs that I checked regularly because of their good and helpful content. some of them which stood out from the others for me were ;
this SLOG
and this one
oh wait and this one

    I hope you who visited my SLOGs throughout this semester have found it useful and interesting. I want to wish you a good luck on the exams. study well. PEACE!

Tuesday, March 31, 2015

Week 11 (revisiting an old post)

    Hi everyone! We are getting close to the end of his semester which for many of you, including myself will be the end of our first year in university of Toronto. As I mentioned in an earlier post, don't forget to pick your subjects posts tomorrow on ROSI. My decision is to double major in CS and Mathematics but I have to do some more research on this. It is good news that we have our TAs back to help us in the remaining weeks of this course to get ready for assignment 3, our last assignment for csc148 and for the upcoming term test in late April. I am pretty sure that the office hours and help center will continue working in April.

    Alright back to our weekly topic! In this week, since I chose option B in assignment 3 to work on, I will be visiting this SLOG entry! For any of you who chose option A, I strongly suggest to practice on option B's functions! an extremely helpful and awesome practice in recursion. you do things like using sets instead of lists to be efficient. A lot of fun challenges to solve will be ahead on your way and with each one, you will learn something new.

I feel like as we are getting more and more comfortable with programming and algorithms, the more I understand how something with a fairly simple idea behind it (we are talking about trees here), can come in handy to makes hard problems fairly easy and doable. In my opinion it's because of the way that you can express the problem you are trying to solve as a drawing of a tree on a piece of paper. and you can actually run each line of your code on that picture. The idea of having paths, children, root and leaves did not have the same respect in my eyes as it does right now. Now that I understand what those simple  concepts can do.

Sunday, March 22, 2015

What happened in week 8 and 9?

   
yes that's right! two entries as one!

    I hope you all had a good term test 2! I found the questions 3 fair considering we had 50 minutes to answer them all and I was in the evening section so if you were too, you are probably aware that one of the questions was from a lab exercise. I really like to know how I did on the exams I take but given the current situation, it's not really fair to ask our instructors Danny and Dianne for marks because I am sure like most of our other lectures, they are working really hard to enable us to finish this semester. There is a tentative agreement that is being discussed between the university and CUPE members as I am writing this entry for you, I hope they do reach an agreement soon so we can have our TAs back and use their knowledge for the rest of the course.
    
    One more thing before I get back to the the course topics of the past two weeks! Remember that subjectPOSts are happening soon and the first opening is April 1 for some applications! Check out more stuff about the open house and the deadlines and what you should do right here.

I don't have a lot to talk about around the BTS topic, I think in my last entries I have talked about them. And you have to excuse me when I say I haven't had the time to work on the lab09 exercises. These remaining two weeks will be a really busy time for me, I have an important calculus midterm, two papers and we have A3 for this beloved course.

Me and My body Keirn have been working on the assignments together. In A2 his focus was on Minimax which he did a great job and I tried to implement an smart Tippy game (which I failed to do so but it still was great practice). therefore now that we have been given two options for A3, Keirn has decided to go with option be, since he has a good grasp of what he did on Minimax and he is improving it on the three levels asked by option A.  I on the other hand decided to work on option B! In the first two days it was a mess! a huge MESS. I couldn't even get one function right! I would get NoneType outputs when I was supposed to get integers and so on. But on the third day, after I stubbed my toe really hard and blood was everywhere, in my first attempt, I suddenly got what I was doing wrong, which I will write about in upcoming weeks. I have implemented all the functions except the last two! I ran into a small detail-ish problem in game_descriptions but i'm confident that with a little thinking, it's going to be fixed.



Sunday, March 8, 2015

Week 8 (The Rise of our TAs)

    Hi everyone! Hope you all had a great weekend! First of all, I,m really sad that the university has not come to an agreement with our TAs (CUPE1) and we don't have tutorials and labs until this issue is resolved! I think the effect is really bad on us SC students! I feel that now that the interaction between us and our TAs are gone in labs and help center, it is harder to grasp a good concept of every week's material, specially now that we only have a few more weeks left until our final exams and don't forget our test 2 on the upcoming Wednesday. I feel like, now more than ever we need to help each other and finish CSC148 like every other course strong! the lab07 solutions are now posted on Here and for the other labs, there are great students like my buddy Keirn who are posting solutions on their blog!

    Back to our topic of the week, "Link Lists"! working with trees and nodes prepared me for getting the whole idea of linked lists pretty fast! but when it came to implementing the functions in our lab07 exercises, I honestly was lost! what ever I tried, I failed all the doctests and it was really annoying! I spent 2 days and a lot of different ways to make those functions and methods work but I got nowhere! Finally yesterday afternoon after spending 3 hours with the lovely kids in our lil' strikers class, Tired of all the running and jumping around, I headed down to the library and started working on my program, hoping I can finish it by the end of the night! suddenly it hit me and I figured out what I've been doing wrong!
I was dealing with the values, like they are nods, I would do commands like:

- cur_node = lnk.front
  cur_node = value (oops you cannot do this bro!)

-what should I do then?
   cur_node.value = value! (yeap!)

-or another way is doing this:
new_node = LLNode(value)
cur_node = new_node
     
       

Tuesday, March 3, 2015

Week 7 (It will be on Recursion)!

    I have to say, So far Recursion has been the most interesting topic for me we have came across in CSC148! and the fact that we could do something like Minimax, using recursion makes it even cooler. doing something so powerful with something that gets easier and easier with more practice!

To be honest it was really hard for me to get my head around the whole idea of recursion and I would get really confused about how the base cases and the whole idea of calling the function in itself. But lab after lab if got more clear!

I loved the idea of the simple game of Subtract Square and the not so easy Tippy we did you our two assignments! and the Minimax strategy just makes everything better in there. I really wanted to do a Tic-Tac-Toe game, I will share the code with you at the end of this slog, but unfortunately I can't share the Minimax code since we still have not handed in our work for the assignment.

Ok getting back to recursion! since we are getting marked on this entry, I though it's better to do a summary of recursion and what we have thought with some examples.

What is Recursion?
Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem (as opposed to iteration).[1]The approach can be applied to many types of problems, and recursion is one of the central ideas of computer science.[2]
"The power of recursion evidently lies in the possibility of defining an infinite set of objects by a finite statement. In the same manner, an infinite number of computations can be described by a finite recursive program, even if this program contains no explicit repetitions." [3]  (from wikipedia)
a simple example would be the factorial in mathematics! we know that every term can be achieved by multiplying it with the factorial of the integer before it! that's what makes the factorial recursive!

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)
The two key elements of a recursive algorithm are:
  • The termination condition: n == 0
  • The reduction step where the function calls itself with a smaller number each time: factorial(n - 1)

If  you are on of the students taking MAT137, you have felt that great feeling when the instructor is talking about Recursive sequences and nobody knows what they are talking about except you!

Another example of recursive things in mathematics could be the pascal's triangle.
Pascal's triangle is the BOMB for us computer scientists! If you don't know about it check this link out!


I also want to post some of the lab exercises on trees, BT trees for you here, they are probably going to take a bunch of space but I will try to post them regularly for you
But first things first, here is the code for the tic-tac-toe game;

TIC-TAC-TOE:
import random
new = ['','','','','','','','','']
man = ''
machine = ''
null = ''


def sign(man, machine):
    man = input("What team you want to be? X or O ")
    while man not in ('x','X','o','O'):
        print ("Invalid Choice!")
        man = raw_input("What team you want to be? X or O ")
    if man == 'x' or man == 'X':
        print ("Ok, X is yours!")
        machine = 'o'
    else:
        print ("Ok, O is yours!")
        machine = 'x'
    return man.upper(), machine.upper()
   
   

def decide_turn():
    turn = None
    while turn not in ('y','Y','n','N'):
        turn = input("Do you want to go first? ")
        if turn == 'y' or turn == 'Y':
            return 1
        elif turn == 'n' or turn == 'N':
            return 0
        else:
            print ("its an invalid choice.")

def draw(a):
   
    print ("\n\t",a[0],"|",a[1],"|",a[2])
    print ("\t", "--------")
    print ("\n\t",a[3],"|",a[4],"|",a[5])
    print ("\t", "--------")
    print ("\n\t",a[6],"|",a[7],"|",a[8], "\n")

def congo_man():
    print ("You won!!")

def congo_machine():
    print ("Hahha, I won!!!")

def man_first(man, machine, new):
    while winn(man, machine, new) is None:
        move = man_move(man, new)
        new[int(move)] = man
        draw(new)
        if winn(man, machine, new) != None:
            break
        else:
            pass
        print ("ummmm....i'll take..")
        p_move = machine_move(man, machine, new)
        print (p_move)
        new[int(p_move)] = machine
        draw(new)
    q = winn(man, machine, new)
    if q == 1:
        congo_man()
    elif q == 0:
        congo_machine()
    else:
        print ("Its tie man...")
 


def machine_first(man, machine, new):
    while not winn(man, machine, new):
        print ("i'll take...")
        p_move = machine_move(man, machine, new)
        print (p_move)
        new[p_move] = machine
        draw(new)
        if winn(man, machine, new) != None:
            break
        else:
            pass
        move = man_move(man, new)
        new[int(move)] = man
        draw(new)
    q = winn(man, machine, new)
    if q == 1:
        congo_man()
    elif q == 0:
        congo_machine()
    else:
        print ("It's a tie man...")


def winn(man, machine, new):
    ways = ((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6))
    for i in ways:
        if new[i[0]] == new[i[1]] == new[i[2]] != null:
            winner = new[i[0]]
            if winner == man:
                return 1
            elif winner == machine:
                return 0
            if null not in new:
                return 'TIE'
    if null not in new:
        return 'TIE'  
    return None


def man_move(man, new):
    a = input("where you want to move? ")
    while True:
        if a not in ('0','1','2','3','4','5','6','7','8'):
            print ("Sorry, invalid move")
            a = input("where you want to move? ")
        elif new[int(a)] != null:
            print ("Sorry, the place is already taken")
            a = input("where you want to move? ")
        else:
            return int(a)



   
def machine_move(man, machine, new):
    best = [4, 0, 2, 6, 8]
    blank = []
    for i in range(0,9):
        if new[i] == null:
            blank.append(i)
   
    for i in blank:
        new[i] = machine
        if winn(man, machine, new) is 0:

            return i
        new[i] = null

    for i in blank:
        new[i] = man
        if winn(man, machine, new) is 1:

            return i
        new[i] = null

    return int(blank[random.randrange(len(blank))])
       



def display_instruction():
    """ Displays Game Instuructions. """
    print
    ("""
    Welcome to the Game...
    You will make your move known by entering a number, 0 - 8.
    The will correspond to the board position as illustrated:


                          0 | 1 | 2          
                         -----------
                          3 | 4 | 5          
                         -----------
                          6 | 7 | 8

                         
      Prepare yourself, the ultimate bettel is about to begin.....
      """
     )

 
def main(man, machine, new):
    display_instruction()
    print ("so lets begin..")
    a = sign(man, machine)
    man = a[0]
    machine = a[1]
    b = decide_turn()
    if b == 1:
        print ("Ok, you are first!")
        print ("Lets get started, here's a new board!")
        draw(new)
        man_first(man, machine, new)
    elif b == 0:
        print ("Ok, I'll be the first!")
        print ("So, lets start..")
        draw(new)
        machine_first(man, machine, new)
    else:
        pass


main(man, machine, new)
input("Press enter to exit")

Saturday, February 21, 2015

Summary of "OOP"

    Hey everyone! Hope you all are getting the most out of your reading week. This week's blog is supposed to be on the topic; "summary of Object-Oriented Programming concepts".
First before going for the topic I would like to say that if you have not started on the assignment yet, you really should soon! I started working on the paper and just play around with some Tippy Games! It will give you a great idea. Also the more you read the section on Minimax in the handout, the better you'll be able to start working on it! If you think about it, I think Minimax is the coolest thing that we can do by knowing the concept of recursion up until now

Back to out topic I would like to go through some of the definitions and things we came across in OOP(Object Oriented Programming)



What Is an Object?

An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. This lesson explains how state and behavior are represented within an object, introduces the concept of data encapsulation, and explains the benefits of designing your software in this manner.

What Is a Class?

A class is a blueprint or prototype from which objects are created. This section defines a class that models the state and behavior of a real-world object. It intentionally focuses on the basics, showing how even a simple class can cleanly model state and behavior.

What Is Inheritance?

Inheritance provides a powerful and natural mechanism for organizing and structuring your software. This section explains how classes inherit state and behavior from their super-classes, and explains how to derive one class from another using the simple syntax provided by the python programming language.

Creating instance objects:

To create instances of a class, you call the class using class name and pass in whatever arguments its__init__ method accepts.

Accessing attributes:

You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows

Class Inheritance:

Instead of starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name.
The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent.

#!/usr/bin/python

class Parent:        # define parent class
   parentAttr = 100
   def __init__(self):
      print "Calling parent constructor"

   def parentMethod(self):
      print 'Calling parent method'

   def setAttr(self, attr):
      Parent.parentAttr = attr

   def getAttr(self):
      print "Parent attribute :", Parent.parentAttr

class Child(Parent): # define child class
   def __init__(self):
      print "Calling child constructor"

   def childMethod(self):
      print 'Calling child method'

c = Child()          # instance of child
c.childMethod()      # child calls its method
c.parentMethod()     # calls parent's method
c.setAttr(200)       # again call parent's method
c.getAttr()          # again call parent's method

Tuesday, February 10, 2015

Trees, Linked lists!

    I hope you all had a good week considering all the midterms! So As I talked about recursion in the  last SLOG entry, I thought I talk about trees a little bit.
    To be honest I feel kind of bad that I have a two hour lecture day each week instead of two one hour lectures. It's just harder to keep up with the lap handouts since we get the info of each weeks material one/two day before each lab and in a cold winter's night at MS3150! So I decided to do a little digging myself and find out more about trees. I have used them theoretically before using these two books which I'm pretty sure we will encounter in upper years; CLRS and Intro to Graph theory !

    Since we haven't been thought trees yet, I'm not going to go through What they are and the implementations! but as you get to learn it, your reaction at first might be(just like my first reaction); why go through so much trouble and implementing these nasty things? So I will link below an algorithm called "Red/ Black trees"! I recommend reading the Wikipedia link first "Baby click me please!" and then watch this tutorial type video "watch me"