diff options
author | Jovina Dsouza | 2014-06-18 12:43:07 +0530 |
---|---|---|
committer | Jovina Dsouza | 2014-06-18 12:43:07 +0530 |
commit | 206d0358703aa05d5d7315900fe1d054c2817ddc (patch) | |
tree | f2403e29f3aded0caf7a2434ea50dd507f6545e2 /C++_from_the_Ground | |
parent | c6f0d6aeb95beaf41e4b679e78bb42c4ffe45a40 (diff) | |
download | Python-Textbook-Companions-206d0358703aa05d5d7315900fe1d054c2817ddc.tar.gz Python-Textbook-Companions-206d0358703aa05d5d7315900fe1d054c2817ddc.tar.bz2 Python-Textbook-Companions-206d0358703aa05d5d7315900fe1d054c2817ddc.zip |
adding book
Diffstat (limited to 'C++_from_the_Ground')
25 files changed, 7506 insertions, 0 deletions
diff --git a/C++_from_the_Ground/Chapter_10(1).ipynb b/C++_from_the_Ground/Chapter_10(1).ipynb new file mode 100644 index 00000000..6196736b --- /dev/null +++ b/C++_from_the_Ground/Chapter_10(1).ipynb @@ -0,0 +1,207 @@ +{ + "metadata": { + "name": "Chapter 10" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 10: Structures and Unions<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 10.1, Page Number: 223<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A simple inventory prohram that uses an array of structures/ '''\n'''Implementing structures in python'''\n\n\nclass inv_type:\n def __init__(self):\n self.item=None\n self.cost=0\n self.retail=0\n self.on_hand=0\n self.lead_time=0\n\n#Variable declaration\nsize=100 \ninvtry = []*size\ni=5 #User iput for menu selection\n\n#Initialize the array\ndef init_list():\n for t in range(size):\n invtry.append(inv_type())\n \n#get a menu selection\ndef menu():\n global i\n print \"(E)nter\"\n print \"(D)isplay\"\n print \"(U)pdate\"\n print \"(Q)uit\"\n print \"choose one: \"\n i-=1\n return i\n\n#enter items into the list\ndef enter():\n #find the first free structure\n for i in range(size):\n if not(invtry[i].item==None):\n break\n #i will be size if list is full\n if i==size:\n print \"List full.\"\n return\n input(i)\n \n#Input the information\ndef input(i):\n #Enter information; User input\n invtry[i].item=\"Gloves\"\n invtry[i].cost=10\n invtry[i].retail=25\n invtry[i].on_hand=50\n invtry[i].lead_time=10\n \n#Modify an existing item\ndef update():\n name=\"Gloves\" #User input\n for i in range(size):\n if not(name==invtry[i].item):\n break\n if i==size:\n print \"Item not found.\"\n return\n print \"Enter new information.\"\n input(i)\n \n#Display the list\ndef display():\n for t in range(size):\n if not(invtry[t].item==None):\n print invtry[t].item\n print \"Cost: $\",invtry[t].cost\n print \"Retail: $\",invtry[t].retail\n print \"On hand: \",invtry[t].on_hand\n print \"Resupply time: \",invtry[t].lead_time,\" days\"\n \n\ninit_list()\nwhile True:\n choice=menu()\n if choice==4:\n enter()\n elif choice==3:\n display()\n elif choice==2:\n update()\n elif choice==1:\n break", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "(E)nter\n(D)isplay\n(U)pdate\n(Q)uit\nchoose one: \n(E)nter\n(D)isplay\n(U)pdate\n(Q)uit\nchoose one: \nGloves\nCost: $ 10\nRetail: $ 25\nOn hand: 50\nResupply time: 10 days\n(E)nter\n(D)isplay\n(U)pdate\n(Q)uit\nchoose one: \nEnter new information.\n(E)nter\n(D)isplay\n(U)pdate\n(Q)uit\nchoose one: \n" + } + ], + "prompt_number": 11 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 10.2, Page Number: 226<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Pass a structure(class) to a function'''\n\n#Define a structure(class) type\nclass sample:\n a=None\n ch=None\n \ndef f1(parm):\n print parm.a,\" \",parm.ch\n\n#declare arg\narg=sample() \n\n#initialize arg\narg.a=1000\narg.ch='X'\n\n#call function\nf1(arg)\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1000 X\n" + } + ], + "prompt_number": 12 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 10.3, Page Number: 227<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate structure assignments.'''\n\nclass stype:\n a=None\n b=None\n\n#Variable declaration\nsvar1=stype()\nsvar2=stype()\n\nsvar1.a=svar1.b=10\nsvar2.a=svar2.b=20\n\nprint \"Structures before assignment.\"\nprint \"svar1: \",svar1.a,' ',svar1.b\nprint \"svar1: \",svar2.a,' ',svar2.b\n\nsvar2=svar1 #assign structures\n\n#Result\nprint \"\\nStructures before assignment.\"\nprint \"svar1: \",svar1.a,' ',svar1.b\nprint \"svar1: \",svar2.a,' ',svar2.b", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Structures before assignment.\nsvar1: 10 10\nsvar1: 20 20\n\nStructures before assignment.\nsvar1: 10 10\nsvar1: 10 10\n" + } + ], + "prompt_number": 13 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 10.4, Page Number: 230<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''This program displays the current system time.'''\n\nimport datetime\n\ndate=datetime.datetime.now()\n\n#Result\nprint date.time()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "17:06:28.236000\n" + } + ], + "prompt_number": 14 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 10.5, Page Number: 231<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''This program displays the current system time.'''\n\nimport datetime\n\ndate=datetime.datetime.now()\n\n#Result\nprint date.ctime()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Sat Sep 14 17:07:14 2013\n" + } + ], + "prompt_number": 15 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 10.6, Page Number: 232<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate a reference to a structure'''\n\nclass mystruct:\n a=None\n b=None\n\n#Recieve and return by reference\ndef f(var):\n var[0].a=var[0].a*var[0].a\n var[0].b=var[0].b/var[0].b\n return var[0]\n \n#Variable declaration\nx=[]\nx.append(mystruct())\ny=mystruct()\n\n#Initializing\nx[0].a=10\nx[0].b=20\n\nprint \"Original x.a and x.b: \",x[0].a,' ',x[0].b\n\ny=f(x) #function call\n\n#Result\nprint \"Modified x.a and x.b: \",x[0].a,' ',x[0].b\nprint \"Modified y.a and y.b: \",y.a,' ',y.b\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Original x.a and x.b: 10 20\nModified x.a and x.b: 100 1\nModified y.a and y.b: 100 1\n" + } + ], + "prompt_number": 16 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 10.7, Page Number: 239<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Use a union to exchange the bytes within a short integer'''\n#Class used in place of union \n\nclass swap_bytes:\n ch=[0,0]\n\n#Exchange of bytes\ndef disp_binary(u):\n t=128\n while not(t==0):\n if u&t:\n print \"1 \",\n else:\n print \"0 \",\n t=t/2\n\n#Variable declaration\nsb=swap_bytes()\n\nsb.ch[0]=15\n\nprint \"Original bytes: \",\ndisp_binary(sb.ch[1])\ndisp_binary(sb.ch[0])\n\n#Exchange bytes\ntemp=sb.ch[0]\nsb.ch[0]=sb.ch[1]\nsb.ch[1]=temp\n\n#Result\nprint \"\\nExchanged bytes: \",\ndisp_binary(sb.ch[1])\ndisp_binary(sb.ch[0])\n\n\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Original bytes: 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 \nExchanged bytes: 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 \n" + } + ], + "prompt_number": 17 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 10.8, Page Number: 240<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Display the ASCII code in binary for characters'''\n\n#Variable declaration\nch='a'\n\nwhile True:\n print \"\\n\",ch,\n print bin(ord(ch)) #Display the bit pattern for each character\n ch=chr(ord(ch)+1)\n if ch=='r':\n break", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "\na 0b1100001\n\nb 0b1100010\n\nc 0b1100011\n\nd 0b1100100\n\ne 0b1100101\n\nf 0b1100110\n\ng 0b1100111\n\nh 0b1101000\n\ni 0b1101001\n\nj 0b1101010\n\nk 0b1101011\n\nl 0b1101100\n\nm 0b1101101\n\nn 0b1101110\n\no 0b1101111\n\np 0b1110000\n\nq 0b1110001\n" + } + ], + "prompt_number": 18 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 10.9, Page Number: 242<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of an example of union in python'''\n\n#Variable declaration\nch=['X','Y']\nc=\"\"\ndef disp_bits(u):\n t=128\n global c\n while not(t==0):\n if u&t:\n c=c+\"1\"\n else:\n c=c+\"0\"\n t=t/2 \n return c\n\n#Result\nprint \"union as chars: \",ch[0],ch[1]\nprint \"union as integer: \",\nc= disp_bits(ord(ch[1]))\nc= disp_bits(ord(ch[0]))\nprint int(str(c),2)\n\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "union as chars: X Y\nunion as integer: 22872\n" + } + ], + "prompt_number": 19 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_11(1).ipynb b/C++_from_the_Ground/Chapter_11(1).ipynb new file mode 100644 index 00000000..b59e52c7 --- /dev/null +++ b/C++_from_the_Ground/Chapter_11(1).ipynb @@ -0,0 +1,347 @@ +{ + "metadata": { + "name": "Chapter 11" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 11: Introducing the Class<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.1, Page Number: 249<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Illustration of a class in python'''\n\n#This creates the class queue\nclass queue:\n #Initialize the queue \n def __init__(self):\n self.__sloc=0\n self.__rloc=-1\n self.__q=[]\n \n #Put an integer into the queue\n def qput(self,i):\n if self.__sloc==100:\n print \"Queue is full.\"\n return\n self.__sloc+=1\n self.__q.append(i)\n \n #Get an integer from the queue\n def qget(self):\n if self.__rloc==self.__sloc:\n print \"Queue underflow\"\n return\n self.__rloc+=1\n return self.__q[self.__rloc] \n \n\n \n#Create two queue objects\nb=queue()\na=queue()\n\na.qput(10)\nb.qput(19)\n\na.qput(20)\nb.qput(1)\n\n#Result\nprint \"Contents of queue a: \",\nprint a.qget(),' ',a.qget()\n\nprint \"Contents of queue b: \",\nprint b.qget(),' ',b.qget()\n\n\n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Contents of queue a: 10 20\nContents of queue b: 19 1\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.2, Page Number: 250<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate class member access'''\n \nclass myclass:\n def __init__(self):\n self.__a=None #private member\n self.b=None #public member\n #public functions\n def setlab(self,i):\n self.__a=i #refer to a\n self.b=i*i #refer to b\n return\n def geta(self):\n return self.__a #refer to a\n def reset(self):\n #call setlab using self\n self.setlab(0) #the object is already known\n \n \nob=myclass()\nob.setlab(5) #set ob.a and ob.b\nprint \"ob after setlab(5): \",ob.geta(),' ',\nprint ob.b #can access b because it is public\n\nob.b=20 #can access b because it is public\nprint \"ob after ob.b=20: \",\nprint ob.geta(),' ',ob.b\n\nob.reset()\nprint \"ob after ob.reset(): \",ob.geta(),' ',ob.b\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "ob after setlab(5): 5 25\nob after ob.b=20: 5 20\nob after ob.reset(): 0 0\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.3, Page Number: 254<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate a constructor and a destructor'''\n#The destructors of python behave a little differently.\n\n#This creates the class queue\nclass queue:\n \n #Constructor\n def __init__(self): \n self.__q=[]\n self.__rloc=-1\n self.__sloc=0\n print \"Queue initialized\"\n \n #Destructor\n def __del__(self):\n print (\"Queue destroyed\")\n \n #Put an integer into the queue\n def qput(self,i):\n if self.__sloc == 100:\n print \"Queue is full\"\n return \n self.__sloc+=1\n self.__q.append(i)\n \n #Get an integer from the queue\n def qget(self):\n if self.__rloc==self.__sloc:\n print \"Queue underflow\"\n return\n self.__rloc+=1\n return self.__q[self.__rloc]\n \n#Create two queue objects\na=queue()\n\n\na.qput(10)\na.qput(20)\nb=queue()\nb.qput(19)\n\nb.qput(1)\n\n#Result\nprint a.qget(),' ',\nprint a.qget(),' ',\nprint b.qget(),' ',\nprint b.qget(),' '\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Queue initialized\nQueue destroyed\nQueue initialized\nQueue destroyed\n10 20 19 1 \n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.4, Page Number: 257<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Parameterized Constructors'''\n\n#This creates the class queue\nclass queue: \n \n #Constructor\n def __init__(self,i): \n self.__q=[]\n self.__rloc=-1\n self.__sloc=0\n self.__who=i\n print \"Queue \",self.__who,\" initialized.\"\n \n #Destructor\n def __del__():\n print \"Queue \",self.__who,\" destroyed\"\n \n #Put an integer into the queue\n def qput(self,i):\n if self.__sloc == 100:\n print \"Queue is full\"\n return \n self.__sloc+=1\n self.__q.append(i)\n \n #Get an integer from the queue\n def qget(self):\n if self.__rloc==self.__sloc:\n print \"Queue underflow\"\n return\n self.__rloc+=1\n return self.__q[self.__rloc]\n \na=queue(1)\nb=queue(2)\n\na.qput(10)\nb.qput(19)\n\na.qput(20)\nb.qput(1)\n\n#Result\nprint a.qget(),' ',\nprint a.qget(),' ',\nprint b.qget(),' ',\nprint b.qget(),' '\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Queue 1 initialized.\nQueue destroyed\nQueue 2 initialized.\nQueue destroyed\n10 20 19 1 \n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.5, Page Number: 258<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Passing more than a single arguments'''\nclass widget:\n \n #Pass two arguments to the constructor\n def __init__(self,a,b):\n self.__i=a\n self.__j=b\n \n def put_widget(self):\n print self.__i,\" \",self.__j\n\n#Initializing\nx=widget(10,20)\ny=widget(0,0)\n\nx.put_widget()\ny.put_widget()\n\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 20\n0 0\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.6, Page Number: 259<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An example of class'''\n\nclass myclass:\n \n #Constructor\n def __init__(self,x):\n self.a=x\n #To get the vale of a\n def get_a(self):\n return self.a\n\n#Initializing\nob=myclass(4)\n\n#Result\nprint ob.get_a()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "4\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.7, Page Number: 260<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Using structures to create a class'''\n\nfrom ctypes import *\n\nclass c1(Structure):\n _fields_=[(\"__i\", c_int)] #private member\n def get_i(self): #public finctions\n return self.__i\n def put_i(self,j):\n self.__i=j\n\n#Variable declaration\ns=c1()\n\ns.put_i(10)\n\n#Result\nprint s.get_i()\n \n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.8, Page Number: 261<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Now we use class instead'''\n\nclass c1:\n def __init__(self):\n self.__i=None #private member\n def get_i(self): #public finctions\n return self.__i\n def put_i(self,j):\n self.__i=j\n\n#Variable declaration\ns=c1()\n\ns.put_i(10)\n\n#Result\nprint s.get_i()\n \n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.9, Page Number: 263<h3> " + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Create a union-based class'''\n\nfrom ctypes import *\n\n#Creates a union\nclass u_type(Union):\n _fields_ = [(\"i\",c_short),\n (\"ch\", c_char*2)]\n #Constructor\n def __init__(self,a):\n self.i=a\n \n #Show the characters that comprise a short int.\n def showchars(self):\n print self.ch[0]\n print self.ch[1]\n \n \nu=u_type(1000)\n\n#Displays char of 1000\nu.showchars()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "\ufffd\n\u0003\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.10, Page Number: 264<h3> " + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A simple class program'''\n#There is no inline function in python\n\nclass c1:\n def __init__(self):\n self.__i=None\n def get_i(self):\n return self.i\n def put_i(self,j):\n self.i=j\n\n#Variable declaration\ns=c1()\n\ns.put_i(10)\n\n#Result\nprint s.get_i()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.11, Page Number: 265<h3> " + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A simple class program'''\n#There is no inline functions in python\n\nclass c1:\n def __init__(self):\n self.__i=None\n def get_i(self):\n return self.i\n def put_i(self,j):\n self.i=j\n\n#Variable declaration\ns=c1()\n\ns.put_i(10)\n\n#Result\nprint s.get_i()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.12, Page Number: 267<h3> " + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An example of arrays of objects'''\n\nclass display:\n def __init__(self):\n width=None\n height=None\n res=None\n def set_dim(self,w,h):\n self.width=w\n self.height=h\n def get_dim(self):\n return self.width,self.height\n def set_res(self,r):\n self.res=r\n def get_res(self):\n return self.res\n \n#Variable decleration\nnames=[\"low\",\"medium\",\"high\"] \n(low,medium,high)=(0,1,2) #For enumeration type\nw=None\nh=None\ndisplay_mode=[]*3\n\nfor i in range(3):\n display_mode.append(display())\n\n#Initialize the array of objects using member functions\ndisplay_mode[0].set_res(low)\ndisplay_mode[0].set_dim(640,480)\n\ndisplay_mode[1].set_res(medium)\ndisplay_mode[1].set_dim(800,600)\n\ndisplay_mode[2].set_res(high)\ndisplay_mode[2].set_dim(1600,1200)\n\n#Result\nprint \"Available display modes: \"\nfor i in range(3):\n print names[display_mode[i].get_res()],\" : \",\n w,h=display_mode[i].get_dim()\n print w,\" by \",h", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Available display modes: \nlow : 640 by 480\nmedium : 800 by 600\nhigh : 1600 by 1200\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.13, Page Number: 268<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Initialize an array of objects'''\n\nclass samp:\n __a=None\n def __init__(self,n):\n self.__a=n\n def get_a(self):\n return self.__a\n\n#Initializing the list\nsampArray=[samp(-1),samp(-2),samp(-3),samp(-4)]\n\n#Display\nfor i in range(4):\n print sampArray[i].get_a(),' ',", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "-1 -2 -3 -4 \n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.14, Page Number: 269<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Two dimensional array if objects'''\n\nclass samp:\n __a=None\n __b=None\n def __init__(self,n,m):\n self.__a=n\n self.__b=m\n def get_a(self):\n return self.__a\n def get_b(self):\n return self.__b\n \n#Initializing the list\nsampArray=[[samp(1,2),samp(3,4)],\n [samp(5,6),samp(7,8)],\n [samp(9,10),samp(11,12)],\n [samp(13,14),samp(15,16)]]\n\n#Display\nfor i in range(4):\n print sampArray[i][0].get_a(),' ',\n print sampArray[i][0].get_b()\n print sampArray[i][1].get_a(),' ',\n print sampArray[i][1].get_b()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1 2\n3 4\n5 6\n7 8\n9 10\n11 12\n13 14\n15 16\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.15, Page Number: 270<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A simple example using an object pointer'''\n\nfrom ctypes import *\n\nclass P_example(Structure):\n __num=None\n def set_num(self,val):\n self.__num=val\n def show_num(self):\n print self.__num\n\n#Variable declaration\nob=P_example() #Declare an object to the structure\np=POINTER(P_example) #Declare a pointer to the structure\n\nob.set_num(1) #access ob directly\nob.show_num()\n\np=ob #assign p the address of ob\np.show_num() #access ob using pointer\n \n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1\n1\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 11.16, Page Number: 271<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Pointer to array of objects'''\n\nclass P_example(Structure):\n __num=None\n def set_num(self,val):\n self.__num=val\n def show_num(self):\n print self.__num\n \n#Variable declaration\nob=[P_example(),P_example()] #Declare an object to the structure\np=POINTER(P_example) #Declare a pointer to the structure\n\nob[0].set_num(10) #access objects directly\nob[1].set_num(20)\n\np=ob #obtain pointer to first element\np[0].show_num() #access ob using pointer\n\np[1].show_num()\n\np[0].show_num()\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10\n20\n10\n" + } + ], + "prompt_number": 7 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_12(1).ipynb b/C++_from_the_Ground/Chapter_12(1).ipynb new file mode 100644 index 00000000..abad8d81 --- /dev/null +++ b/C++_from_the_Ground/Chapter_12(1).ipynb @@ -0,0 +1,367 @@ +{ + "metadata": { + "name": "Chapter 12" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 12: A Closer Look at Classes<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.1, Page Number: 274<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of friend functions in python'''\n\nclass myclass:\n __a=None\n __b=None\n def __init__(self,i,j):\n self.__a=i\n self.__b=j\n def sum(self,x): #Friend function\n return sum1(x)\n \ndef sum1(x): \n return x._myclass__a +x._myclass__b #accessing private members\n\n#Variable declaration\nn=myclass(3,4)\n\n#Result\nprint n.sum(n)\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "7\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.2, Page Number: 275<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Use a friend function'''\n\nclass c1:\n __status=None\n def set_status(self,state):\n self.__status=state\n \nclass c2:\n __status=None\n def set_status(self,state):\n self.status=state\n \n#Friend function \ndef idle(a,b):\n if a._c1__status or b._c2__status :\n return 0\n else:\n return 1\n \n#variable declarations\ndef IDLE(): #Constants\n return 0\ndef INUSE():\n return 1\nx=c1()\ny=c2()\n\nx.set_status(IDLE())\ny.set_status(IDLE())\n\nif idle(x,y):\n print \"Screen Can Be Used.\"\n \nx.set_status(INUSE())\n\nif idle(x,y):\n print \"Screen Can Be Used.\"\nelse:\n print \"Pop-up In Use.\"\n \n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Screen Can Be Used.\nPop-up In Use.\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.3, Page Number: 277<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A function can be member of one class and a friend of another'''\n\n #Constants\ndef IDLE(): \n return 0\ndef INUSE():\n return 1\n\nclass c1:\n __status=None\n def set_status(self,state):\n self.__status=state\n def idle(self,b): #now a member of c1\n if self.__status or b._c2__status :\n return 0\n else:\n return 1\n \nclass c2:\n __status=None #IDLE if off INUSE if on screen\n def set_status(self,state):\n self.status=state\n \n#Variable declarations \nx=c1()\ny=c2()\n\nx.set_status(IDLE())\ny.set_status(IDLE())\n\nif idle(x,y):\n print \"Screen Can Be Used.\"\n \nx.set_status(INUSE())\n\nif idle(x,y):\n print \"Screen Can Be Used.\"\nelse:\n print \"Pop-up In Use.\"\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Screen Can Be Used.\nPop-up In Use.\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.4, Page Number: 278<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Use of overloaded constructors'''\n#Printing the time passed since the functon started instead of ringing the bell.\n\nimport time,string\n\nclass timer:\n __seconds=None\n \n def __init__(self,t1,t2=None):\n if t2==None:\n if isinstance(t1,int): #seconds specified as an integer\n self.__seconds=t1\n else: #seconds specified as a string\n self.__seconds=string.atoi(t1)\n else: #time in minutes and seconds\n self.__seconds=t1*60+t2\n \n def run(self):\n t1=time.clock()\n while (time.clock()-t1)<self.__seconds:\n a=10\n print time.clock()-t1\n \n \na=timer(10)\nb=timer(\"20\")\nc=timer(1,10)\na.run() #count 10 seconds\nb.run() #count 20 seconds\nc.run() #count 1 minute,10 seconds\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10.0000009774\n20.0000009774" + }, + { + "output_type": "stream", + "stream": "stdout", + "text": "\n70.0000004887" + }, + { + "output_type": "stream", + "stream": "stdout", + "text": "\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.5, Page Number: 280<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstarate dynamic initialization'''\n#Printing the time passed since the functon started instead of ringing the bell.\n\nimport time,string\n\nclass timer:\n __seconds=None\n \n def __init__(self,t1,t2=None):\n if t2==None:\n if isinstance(t1,int): #seconds specified as an integer\n self.__seconds=t1\n else: #seconds specified as a string\n self.__seconds=string.atoi(t1)\n else: #time in minutes and seconds\n self.__seconds=t1*60+t2\n \n def run(self):\n t1=time.clock()\n while (time.clock()-t1)<self.__seconds:\n a=10\n print time.clock()-t1\n \na=timer(10)\na.run()\n\nprint \"Enter number of seconds: \"\nstr=\"20\"\nb=timer(str) #initialize at the run time\nc.run()\n\nprint \"Enter minutes and seconds: \"\nmin=1\nsec=10\nc=timer(min,sec) #initialize at the run time\nc.run()\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10.0000004887\nEnter number of seconds: \n70.0000009774" + }, + { + "output_type": "stream", + "stream": "stdout", + "text": "\nEnter minutes and seconds: \n70.0000009774" + }, + { + "output_type": "stream", + "stream": "stdout", + "text": "\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.6, Page Number: 282<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate object assignment'''\n\nclass myclass:\n __a=None #private members\n __b=None\n def setab(self,i,j): #publc functons\n self.__a=i\n self.__b=j\n def showab(self):\n print \"a is \",self.__a\n print \"b is \",self.__b\n\n#Variable declaration\nob1 = myclass()\nob2 = myclass()\n\n#Intalizing\nob1.setab(10,20)\nob2.setab(0,0)\n\nprint \"ob1 before assignment: \"\nob1.showab()\nprint \"ob2 before assignment: \"\nob2.showab()\n\nob2 = ob1 #assign ob1 to ob2\n\n#Result\nprint \"ob1 after assignment: \"\nob1.showab()\nprint \"ob2 after assignment: \"\nob2.showab()\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "ob1 before assignment: \na is 10\nb is 20\nob2 before assignment: \na is 0\nb is 0\nob1 after assignment: \na is 10\nb is 20\nob2 after assignment: \na is 10\nb is 20\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.7, Page Number: 283<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstration of passing objects to functions'''\n'''Implementing call by value method in python'''\n\nfrom copy import deepcopy\n \nclass OBJ:\n def set_i(self,x):\n self.__i=x\n def out_i(self):\n print self.__i,\n \ndef f(x):\n x=deepcopy(x)\n x.out_i() #outputs 10\n x.set_i(100) #this affects only local copy\n x.out_i() #outputs 100\n \n#Variable declaration\no=OBJ()\no.set_i(10)\nf(o) \no.out_i() #still outputs 10, value of i unchanged\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 100 10\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.8, Page Number: 284<h3> " + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Constructors, destructors, and passing objects'''\n\nclass myclass: \n def __init__(self,i):\n self.__val=i\n print \"Constructing\"\n def __del__(self):\n print \"Destructing\"\n def getval(self):\n return self.__val\n \ndef display(ob):\n print ob.getval()\n\n#Varable declaration\na=myclass(10)\n\ndisplay(a)\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Constructing\nDestructing\n10\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.9, Page Number: 286<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Passing objects with a pointer'''\n#The problem shown in C++, will not occur in python because it does not have pointers.\n\nfrom ctypes import *\n\nclass myclass:\n def __init__(self,i):\n print \"Allocating p\"\n self.p=pointer(c_int(i))\n def __del__(self):\n print \"Freeing p\"\n def getval(self):\n return self.p[0]\n \ndef display(ob):\n print ob.getval()\n\n#Variable declaration\na=myclass(10)\n\ndisplay(a)\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Allocating p\n10\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.10, Page Number: 287<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Passing objects by reference'''\n\nfrom ctypes import *\nclass myclass:\n def __init__(self,i):\n print \"Allocating p\"\n self.p=pointer(c_int(i))\n def __del__(self):\n print \"Freeing p\"\n def getval(self):\n return self.p[0]\n \ndef display(ob):\n print ob[0].getval()\n\n#Variable declaration\na=[]\na.append(myclass(10))\n\ndisplay(a)\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Freeing p\nAllocating p\n10\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.11, Page Number: 288<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Returning an object'''\n\nclass sample:\n __s=None\n def show(self):\n print self.__s\n def set(self,str):\n self.__s=str\n\n#Return an object of type sample\ndef input():\n str=sample()\n instr = \"Hello\" #User input\n str.set(instr)\n return str\n\n#Variable declaration\nob=sample()\n\n#assign returned object to ob\nob=input()\n\n#Result\nob.show()\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Hello\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.12, Page Number: 289<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Returning an object'''\n#The error shown in C++ doesnt occur here.\nclass sample:\n __s=None\n def __init__(self):\n self.__s=0\n def __del__(self): \n print \"Freeing p\"\n def show(self):\n print self.__s\n def set(self,str):\n self.__s=str\n \n#This function takes one object parameter\ndef input():\n str=sample()\n instr=\"Hello\" #User input\n str.set(instr)\n return str\n\n#Variable declaration\nob=sample()\n\n#assign returned object to ob\nob=input()\n\n#Result\nob.show()\n\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Freeing p\nFreeing p\nHello\n" + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.13, Page Number: 292<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing a copy constructor'''\n#Copy construcor doesnt work in this example, it works only when explicitly called\n\nclass myclass:\n __p=None\n def __init__(self,i):\n if isinstance(i,int):\n print \"Allocating p\"\n self.__p=i\n else:\n print \"Copy constructor called\"\n self.__p=i.getval()\n def __del__(self): \n print \"Freeing p\"\n def getval(self):\n return self.__p\n \n#This function takes one object parameter\ndef display(ob):\n print ob.getval()\n\n#Variable declaration\nob=myclass(10)\n\n#Result\ndisplay(ob)\n\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Allocating p\n10\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.14, Page Number: 294<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing a copy constructor'''\n\n\nclass myclass:\n __p=None\n def __init__(self,i):\n if isinstance(i,int):\n print \"Allocating p\"\n self.__p=i\n else:\n print \"Copy constructor called\"\n self.__p=i.getval()\n def __del__(self): \n print \"Freeing p\"\n def getval(self):\n return self.__p\n \n\n#Variable declaration\na=myclass(10) #calls normal constructor\nb=myclass(a) #calls copy constructor\n\n\n\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Allocating p\nCopy constructor called\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.15, Page Number: 295<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing a copy constructor'''\n\n\nclass myclass:\n def __init__(self,i=0):\n if isinstance(i,int):\n print \"Normal constructor\"\n else:\n print \"Copy constructor\"\n\n\n#Variable declaration\na=myclass() #calls normal constructor\n\nf=myclass()\na=myclass(f) #Invoke copyconstructor\n\n\n\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Normal constructor\nNormal constructor\nCopy constructor\n" + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 12.16, Page Number: 297<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of the this pointer'''\n#Here self works as this\n\nclass c1:\n def __init__(self):\n self.__i=None\n def load_i(self,val):\n self.__i=val\n def get_i(self):\n return self.__i\n \n#Variable declaration \no=c1()\n\no.load_i(100)\n\n#Result\nprint o.get_i()\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "100\n" + } + ], + "prompt_number": 13 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_13(1).ipynb b/C++_from_the_Ground/Chapter_13(1).ipynb new file mode 100644 index 00000000..c38dca6a --- /dev/null +++ b/C++_from_the_Ground/Chapter_13(1).ipynb @@ -0,0 +1,267 @@ +{ + "metadata": { + "name": "Chapter 13" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 13: Operator Overloading<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 13.1, Page Number: 300<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Overloading operators using member functions'''\n\nclass three_d:\n def __init__(self,i=None,j=None,k=None):\n if i==None:\n self.x=self.y=self.z=0\n else:\n self.x=i\n self.y=j\n self.z=k\n #Overload +\n def __add__(self,op2):\n temp=three_d()\n temp.x=self.x + op2.x #These are integer additions\n temp.y=self.y + op2.y #and the + retains its original\n temp.z=self.z + op2.z #meaning relative to them.\n return temp\n #Overload assignment\n def __assign__(self,op2):\n self.x=op2.x #These are integer assignments\n self.y=op2.y #and the = retains its original \n self.z=op2.z #meaning relative to them\n return self\n #Show x,y,z coordinates\n def show(self):\n print self.x,\",\",self.y,\",\",self.z\n \n#Variable declaration\na=three_d(1,2,3)\nb=three_d(10,10,10)\nc=three_d()\n\na.show()\nb.show()\n\n#add a and b together\nc=a+b\nc.show()\n\n#add a,b and c together\nc=a+b+c\nc.show()\n\n#demonstrate multiple assignment\nc=b=a\nc.show()\nb.show()\n \n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1 , 2 , 3\n10 , 10 , 10\n11 , 12 , 13\n22 , 24 , 26\n1 , 2 , 3\n1 , 2 , 3\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 13.2, Page Number: 303<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of ++ operator in python'''\n\nclass three_d:\n def __init__(self,i=None,j=None,k=None):\n if i==None:\n self.x=self.y=self.z=0\n else:\n self.x=i\n self.y=j\n self.z=k\n #Overload +\n def __add__(self,op2):\n temp=three_d()\n temp.x=self.x + op2.x #These are integer additions\n temp.y=self.y + op2.y #and the + retains its original\n temp.z=self.z + op2.z #meaning relative to them.\n return temp\n #Overload assignment\n def __assign__(self,op2):\n self.x=op2.x #These are integer assignments\n self.y=op2.y #and the = retains its original \n self.z=op2.z #meaning relative to them\n return self\n #Overload the increment operator\n def __iadd__(self,op2):\n self.x+=op2\n self.y+=op2\n self.z+=op2\n return self\n #Show x,y,z coordinates\n def show(self):\n print self.x,\",\",self.y,\",\",self.z\n \na=three_d(1,2,3)\nb=three_d(10,10,10)\nc=three_d()\n\na.show()\nb.show()\n\n#add a and b together\nc=a+b\nc.show()\n\n#add a,b and c together\nc=a+b+c\nc.show()\n\n#demonstrate multiple assignment\nc=b=a\nc.show()\nb.show()\n \n#Increment c\nc+=1\nc.show()\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1 , 2 , 3\n10 , 10 , 10\n11 , 12 , 13\n22 , 24 , 26\n1 , 2 , 3\n1 , 2 , 3\n2 , 3 , 4\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 13.3, Page Number: 306<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of prefix and postfix ++ operator in python'''\n\nclass three_d:\n def __init__(self,i=None,j=None,k=None):\n if i==None:\n self.x=self.y=self.z=0\n else:\n self.x=i\n self.y=j\n self.z=k\n #Overload +\n def __add__(self,op2):\n temp=three_d()\n temp.x=self.x + op2.x #These are integer additions\n temp.y=self.y + op2.y #and the + retains its original\n temp.z=self.z + op2.z #meaning relative to them.\n return temp\n #Overload assignment\n def __assign__(self,op2):\n self.x=op2.x #These are integer assignments\n self.y=op2.y #and the = retains its original \n self.z=op2.z #meaning relative to them\n return self\n #Overload the increment operator\n def __iadd__(self,op2):\n self.x+=op2\n self.y+=op2\n self.z+=op2\n return self\n #Show x,y,z coordinates\n def show(self):\n print self.x,\",\",self.y,\",\",self.z\n \na=three_d(1,2,3)\nb=three_d(10,10,10)\nc=three_d()\n\na.show()\nb.show()\n\n#add a and b together\nc=a+b\nc.show()\n\n#add a,b and c together\nc=a+b+c\nc.show()\n\n#demonstrate multiple assignment\nc=b=a\nc.show()\nb.show()\n \n#Increment c (prefix)\nc+=1\nc.show()\n\n#Increment c (postfix)\nc+=1\nc.show()\n\n#Implementing prefix\nc+=1\na=c\na.show()\nc.show()\n\n#Implementing postfix\na=c\na.show()\nc+=1\nc.show()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1 , 2 , 3\n10 , 10 , 10\n11 , 12 , 13\n22 , 24 , 26\n1 , 2 , 3\n1 , 2 , 3\n2 , 3 , 4\n3 , 4 , 5\n4 , 5 , 6\n4 , 5 , 6\n4 , 5 , 6\n5 , 6 , 7\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 13.4, Page Number: 310<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Overload + using a friend'''\n\nclass three_d:\n def __init__(self,i=None,j=None,k=None):\n if i==None:\n self.x=self.y=self.z=0\n else:\n self.x=i\n self.y=j\n self.z=k\n #Overload +\n def __add__(self,op2):\n return add(self,op2)\n #Overload assignment\n def __assign__(self,op2):\n self.x=op2.x #These are integer assignments\n self.y=op2.y #and the = retains its original \n self.z=op2.z #meaning relative to them\n return self\n #Show x,y,z coordinates\n def show(self):\n print self.x,\",\",self.y,\",\",self.z\n \n#friending the funcion\ndef add(op1,op2):\n temp=three_d()\n temp.x=op1.x + op2.x #These are integer additions\n temp.y=op1.y + op2.y #and the + retains its original\n temp.z=op1.z + op2.z #meaning relative to them.\n return temp\n\na=three_d(1,2,3)\nb=three_d(10,10,10)\nc=three_d()\n\na.show()\nb.show()\n\n#add a and b together\nc=a+b\nc.show()\n\n#add a,b and c together\nc=a+b+c\nc.show()\n\n#demonstrate multiple assignment\nc=b=a\nc.show()\nb.show()\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1 , 2 , 3\n10 , 10 , 10\n11 , 12 , 13\n22 , 24 , 26\n1 , 2 , 3\n1 , 2 , 3\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 13.5, Page Number: 311<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Operator overloading when object is on the right side of the operator'''\n\nclass CL:\n def __init__(self):\n self.count=0\n def __assign__(self,obj):\n self.count=obj.count\n return self\n def __add__(self,i): \n return add(self,i)\n def __radd__(self,i):\n return radd(self,i)\n\n#This handles ob + int\ndef add(ob,i):\n temp=CL()\n temp.count=ob.count+i\n return temp\n \n#This handles int + ob \ndef radd(ob,i):\n temp=CL()\n temp.count=i+ob.count\n return temp\n\n#Variable declaration\no=CL()\no.count = 10\n\n#Result\nprint o.count, #outputs 10\no=10+o\nprint o.count, #outputs 20\no=o+12\nprint o.count #outputs 32\n\n\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 20 32\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 13.6, Page Number: 314<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of prefix and postfix ++ as a friend function'''\n\nclass three_d:\n def __init__(self,i=None,j=None,k=None):\n if i==None:\n self.x=self.y=self.z=0\n else:\n self.x=i\n self.y=j\n self.z=k\n #Overload +\n def __add__(self,op2):\n return add(self,op2)\n #Overload assignment\n def __assign__(self,op2):\n self.x=op2.x #These are integer assignments\n self.y=op2.y #and the = retains its original \n self.z=op2.z #meaning relative to them\n return self\n #Overload the increment operator\n def __iadd__(self,op2):\n return iadd(self,op2)\n #Show x,y,z coordinates\n def show(self):\n print self.x,\",\",self.y,\",\",self.z\n\n#friending the funcion\ndef add(op1,op2):\n temp=three_d()\n temp.x=op1.x + op2.x #These are integer additions\n temp.y=op1.y + op2.y #and the + retains its original\n temp.z=op1.z + op2.z #meaning relative to them.\n return temp\ndef iadd(op1,op2):\n op1.x+=op2\n op1.y+=op2\n op1.z+=op2\n return op1\n \na=three_d(1,2,3)\nb=three_d(10,10,10)\nc=three_d()\n\na.show()\nb.show()\n\n#add a and b together\nc=a+b\nc.show()\n\n#add a,b and c together\nc=a+b+c\nc.show()\n\n#demonstrate multiple assignment\nc=b=a\nc.show()\nb.show()\n \n#Increment c (prefix)\nc+=1\nc.show()\n\n#Increment c (postfix)\nc+=1\nc.show()\n\n#Implementing prefix\nc+=1\na=c\na.show()\nc.show()\n\n#Implementing postfix\na=c\na.show()\nc+=1\nc.show()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1 , 2 , 3\n10 , 10 , 10\n11 , 12 , 13\n22 , 24 , 26\n1 , 2 , 3\n1 , 2 , 3\n2 , 3 , 4\n3 , 4 , 5\n4 , 5 , 6\n4 , 5 , 6\n4 , 5 , 6\n5 , 6 , 7\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 13.7, Page Number: 318<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n\nclass sample:\n def __init__(self,ob=0):\n if isinstance(ob,int):\n #Normal constructor\n self.__s=\"\"\n return\n else:\n #Copy constructor\n self.__s=obj._sample__s\n return\n def __del__(self):\n print \"Freeing s\"\n def show(self):\n print self.__s\n def set(self,str):\n self.__s=str\n def __assign__(self,ob): #Overload assignment\n self.s=ob._sample__s\n return self\n \ndef input():\n str=sample()\n instr=\"Hello\" #User input\n str.set(instr)\n return str\n\nob=sample()\n\n#assign returned object to ob\nob=input()\n\n#Result\nob.show()\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Freeing s\nFreeing s\nHello\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 13.8, Page Number: 321<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Overload []'''\n#There is on implementation of overloading [], hence we use normal functions\n\n\nclass atype:\n def __init__(self):\n self.__a=[]\n for i in range(SIZE):\n self.__a.append(i)\n def a(self,i):\n return self.__a[i]\n \n#Variable declaration\nSIZE=3\nob=atype()\n\n#Result\nprint ob.a(2),\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "2\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 13.9, Page Number: 322<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Overload []'''\n\nclass atype:\n def __init__(self):\n self.__a=[]\n for i in range(SIZE):\n self.__a.append(i)\n def a(self,i,j=None):\n if j==None:\n return self.__a[i]\n else:\n self.__a[i]=j\n \n#Variable declaration\nSIZE=3 \nob=atype()\n\nprint ob.a(2), #displays 2\n\nob.a(2,25)\n\nprint ob.a(2) #now displays 25", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "2 25\n" + } + ], + "prompt_number": 7 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 13.10, Page Number: 323<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A safe array example'''\n\nclass atype:\n def __init__(self):\n self.__a=[]\n for i in range(SIZE):\n self.__a.append(i)\n def a(self,i,j=None):\n if (i<0 or i>SIZE-1):\n print \"Index value of\",\n print i,\"is out of bounds.\"\n return\n if j==None:\n return self.__a[i]\n else:\n self.__a[i]=j\n \n#Variable declaration\nSIZE=3 \nob=atype()\n\nprint ob.a(2), #displays 2\n\nob.a(2,25)\n\nprint ob.a(2) #now displays 25\n\nob.a(44,3) #generates runtime error, 3 out of bounds", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "2 25\nIndex value of 44 is out of bounds.\n" + } + ], + "prompt_number": 9 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 13.11, Page Number: 324<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Overload ()'''\n\nclass three_d:\n def __init__(self,i=None,j=None,k=None):\n if i==None:\n self.x=self.y=self.z=0 #3-D coordinates\n else:\n self.x=i\n self.y=j\n self.z=k\n #Show X,Y,Z coordinates\n def show(self):\n print self.x,\",\",self.y,\",\",self.z\n #Overload ()\n def a(self,a,b,c):\n temp = three_d()\n temp.x=self.x+a\n temp.y=self.y+b\n temp.z=self.z+c\n return temp\n \n#Variable declaration\nob1=three_d(1,2,3)\n\nob2=ob1.a(10,11,12) #invoke operator ()\n\n#Result\nprint \"ob1: \",\nob1.show()\nprint \"ob2: \",\nob2.show()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "ob1: 1 , 2 , 3\nob2: 11 , 13 , 15\n" + } + ], + "prompt_number": 10 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 13.12, Page Number: 326<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Expanding the string type'''\n\nclass str_type:\n def __init__(self,str=\"\"):\n self.__string=str\n #String concatenation\n def __add__(self,str):\n temp=str_type()\n if isinstance(str,str_type):\n temp.__string=self.__string+str.__string\n else:\n temp.__string=self.__string+str\n return temp\n #String copy\n def __assign__(self,str):\n if isinstance(str,str_type):\n self.__string=str.__string\n else:\n self.__string=str\n return self\n def show_str(self):\n print self.__string\n \na=str_type(\"Hello \")\nb=str_type(\"There\")\nc=a+b\nc.show_str()\n\na=str_type(\"to program in because\")\na.show_str()\n\nb=c=str_type(\"C++ is fun\")\n\nc=c+\" \"+a+\" \"+b\nc.show_str()\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Hello There\nto program in because\nC++ is fun to program in because C++ is fun\n" + } + ], + "prompt_number": 12 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_14(1).ipynb b/C++_from_the_Ground/Chapter_14(1).ipynb new file mode 100644 index 00000000..0a3df4c8 --- /dev/null +++ b/C++_from_the_Ground/Chapter_14(1).ipynb @@ -0,0 +1,320 @@ +{ + "metadata": { + "name": "Chapter 14" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 14: Inheritance<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.1, Page Number: 333<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate inheritance'''\n\n#Define base class for vehicles\nclass road_vehicle:\n def __init__(self):\n self.__wheels=None\n self.__passengers=None\n def set_wheels(self,num):\n self.__wheels=num\n def get_wheels(self):\n return self.__wheels\n def set_pass(self,num):\n self.__passengers=num\n def get_pass(self):\n return self.__passengers\n\n#Define a truck\nclass truck(road_vehicle):\n def __init__(self):\n self.__cargo=None\n def set_cargo(self,size):\n self.__cargo=size\n def get_cargo(self):\n return self.__cargo\n def show(self):\n print \"wheels: \",self.get_wheels()\n print \"passengers: \",self.get_pass()\n print \"cargo capacity in cubic feet: \",self.__cargo\n \n#Define an enum type\n(car,van,wagon)=(1,2,3)\ntype=[\"car\",\"van\",\"wagon\"]\n \n#Define an automobile\nclass automobile(road_vehicle):\n def __init__(self):\n self.car_type=None\n def set_type(self,t):\n self.car_type=t\n def get_type(self):\n return self.car_type\n def show(self):\n print \"wheels: \",self.get_wheels()\n print \"passengers: \",self.get_pass()\n print \"type: \",\n if self.get_type()==1:\n print \"car\"\n elif self.get_type()==2:\n print \"van\"\n elif self.get_type()==3:\n print \"wagon\"\n \n#Variable declaration\nt1=truck()\nt2=truck()\nc=automobile()\n\nt1.set_wheels(18)\nt1.set_pass(2)\nt1.set_cargo(3200)\n\nt2.set_wheels(6)\nt2.set_pass(3)\nt2.set_cargo(1200)\n\nt1.show()\nt2.show()\n\nc.set_wheels(4)\nc.set_pass(6)\nc.set_type(van)\n\nc.show() \n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "wheels: 18\npassengers: 2\ncargo capacity in cubic feet: 3200\nwheels: 6\npassengers: 3\ncargo capacity in cubic feet: 1200\nwheels: 4\npassengers: 6\ntype: van\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.2, Page Number: 335<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Base class access control'''\n\nclass base:\n def __init__(self):\n self.__i=self.__j=None\n def set(self,a,b):\n self.__i=a\n self.__j=b\n def show(self):\n print self.__i,self.__j\n \nclass derived(base):\n def __init__(self,x):\n self.__k=x\n def showk(self):\n print self.__k\n \n#Variable declaration\nob = derived(3)\n\nob.set(1,2) #access member of base\nob.show() #access member of base\n\nob.showk() #uses member of derived class\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1 2\n3\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.3, Page Number: 337<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing protected members'''\n\nclass base:\n def __init__(self):\n self.__i=self.__j=None #These act as protected members\n def set(self,a,b):\n self.__i=a\n self.__j=b\n def show(self):\n print self.__i,self.__j\n \nclass derived(base):\n def __init__(self):\n self.__k=None\n def setk(self):\n self.__k=self._base__i*self._base__j #accessing private variables in derived class\n def showk(self):\n print self.__k\n \n#Variable declaration\nob = derived()\n\nob.set(2,3) #OK, known to be derived\nob.show() #OK, known to be derived\n\nob.setk()\nob.showk() #uses member of derived class\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "2 3\n6\n" + } + ], + "prompt_number": 10 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.4, Page Number: 338<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Hierarchical Inheritance in python'''\n\nclass base:\n def __init__(self):\n self.__i=None\n self.__j=None\n def set(self,a,b):\n self.__i=a\n self.__j=b\n def show(self):\n print self.__i,self.__j\n \nclass derived1(base):\n def __init__(self):\n self.__k=None\n def setk(self):\n self.__k=self._base__i*self._base__j\n def showk(self):\n print self.__k\n\nclass derived2(derived1):\n def __init__(self):\n self.__m=None\n def setm(self):\n self.__m=self._base__i-self._base__j\n def showm(self):\n print self.__m\n \n \n#Variable declaration\nob1 = derived1()\nob2 = derived2()\n\nob1.set(2,3) #access member of base\nob1.show() #access member of base\nob1.setk() #uses member of derived1 class\nob1.showk() #uses member of derived1 class\n\nob2.set(3,4) #access member of base\nob2.show() #access member of base\nob2.setk() #access member of derived1 class\nob2.setm() #access member of derived2 class\nob2.showk() #uses member of derived1 class\nob2.showm() #uses member of derived1 class\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "2 3\n6\n3 4\n12\n-1\n" + } + ], + "prompt_number": 11 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.5, Page Number: 341<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate inheriting a protected base class'''\n\nclass base:\n def __init__(self):\n self.__i=None\n self._j=None\n self.k=None\n def seti(self,a):\n self.__i=a\n def geti(self):\n return i\n \nclass derived(base):\n def setj(self,a):\n self._j=a\n def setk(self,a):\n self.k=a\n def getj(self):\n return self._j\n def getk(self):\n return self.k\n \n#Variable declaration \nob=derived()\n\nob.setk(10)\nprint ob.getk(),\nob.setj(12)\nprint ob.getj()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 12\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.6, Page Number: 342<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An example of multiple base classes'''\n\nclass base1:\n def __init__(self):\n self.x=None\n def showx(self):\n print self.x\n \nclass base2:\n def __init__(self):\n self.y=None\n def showy(self):\n print self.y\n \nclass derived(base1,base2):\n def set(self,i,j):\n self.x=i\n self.y=j\n \n#Variable declaration\nob = derived()\n\nob.set(10,20) #provided by derived\nob.showx() #from base1\nob.showy() #from base2\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10\n20\n" + } + ], + "prompt_number": 17 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.7, Page Number: 343<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Constructors, Destructors and Inheritance'''\n\nclass base:\n def __init__(self):\n print \"Constructing base\"\n def __del__(self):\n print \"Destructing base\"\n\nclass derived(base):\n def __init__(self):\n base.__init__(self)\n print \"Constructing derived\"\n def __del__(self):\n print \"Destructing derived\"\n for b in self.__class__.__bases__:\n b.__del__(self)\n\n#Variable declaration\nob=derived()\n\n#Does nothing but construct and destruct ob", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Constructing base\nConstructing derived\nDestructing derived\nDestructing base\n" + } + ], + "prompt_number": 19 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.8, Page Number: 344<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "#Inheritance 344 eg:14.8\n'''Constructors, Destructors and Inheritance'''\n\nclass base:\n def __init__(self):\n print \"Constructing base\"\n def __del__(self):\n print \"Destructing base\"\n\nclass derived1(base):\n def __init__(self):\n base.__init__(self)\n print \"Constructing derived1\"\n def __del__(self):\n print \"Destructing derived1\"\n super(derived1,self).__del__(self)\n\nclass derived2(derived1):\n def __init__(self):\n derived1.__init__(self)\n print \"Constructing derived2\"\n def __del__(self):\n print \"Destructing derived2\"\n super(self.__class__,self).__del__(self)\n \n#Variable declaration\nob=derived2()\n\n#Does nothing but construct and destruct ob", + "language": "python", + "metadata": {}, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.9, Page Number: 345<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Constructors and Destructors in Multiple Inheritance'''\n\nclass base1:\n def __init__(self):\n print \"Constructing base1\"\n def __del__(self):\n print \"Destructing base1\"\n \nclass base2:\n def __init__(self):\n print \"Constructing base2\"\n def __del__(self):\n print \"Destructing base2\"\n \nclass derived(base1,base2):\n def __init__(self):\n for b in self.__class__.__bases__:\n b.__init__(self)\n print \"Constructing derived\"\n def __del__(self):\n print \"Destructing derived\"\n for b in self.__class__.__bases__:\n b.__del__(self)\n \n#Variable declaration\nob = derived()\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Constructing base1\nConstructing base2\nConstructing derived\nDestructing derived\nDestructing base1\nDestructing base2\n" + } + ], + "prompt_number": 21 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.10, Page Number: 347<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Passing parameters to parent constructors in inheritance'''\n\nclass base:\n def __init__(self,x):\n self._i=x\n print \"Constructing base\"\n def __del__(self):\n print \"Destructing base\"\n\nclass derived(base):\n def __init__(self,x,y):\n base.__init__(self,y)\n self.__j=x\n print \"Constructing derived\"\n def __del__(self):\n print \"Destructing derived\"\n for b in self.__class__.__bases__:\n b.__del__(self)\n def show(self):\n print self._i,self.__j\n\n#Variable declaration\nob=derived(3,4)\n\n#Result\nob.show() #shows 4 3", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Constructing base\nConstructing derived\nDestructing derived\nDestructing base\n4 3\n" + } + ], + "prompt_number": 23 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.11, Page Number: 348<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Example that uses multiple base classes'''\n\nclass base1:\n def __init__(self,x):\n self._i=x\n print \"Constructing base1\"\n def __del__(self):\n print \"Destructing base1\"\n \nclass base2:\n def __init__(self,x):\n self._k=x\n print \"Constructing base2\"\n def __del__(self):\n print \"Destructing base2\"\n \nclass derived(base1,base2):\n def __init__(self,x,y,z):\n self.__j=x\n i=0\n for b in self.__class__.__bases__:\n if i==0:\n b.__init__(self,y)\n else :\n b.__init__(self,z)\n i+=1\n print \"Constructing derived\"\n def __del__(self):\n print \"Destructing derived\"\n for b in self.__class__.__bases__:\n b.__del__(self)\n def show(self):\n print self._i,self.__j,self._k\n \n#Variable declaration\nob = derived(3,4,5)\n\n#Result\nob.show()\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Constructing base1\nConstructing base2\nConstructing derived\nDestructing derived\nDestructing base1\nDestructing base2\n4 3 5\n" + } + ], + "prompt_number": 25 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.12, Page Number: 348<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Another example that uses multiple base classes'''\n\nclass base1:\n def __init__(self,x):\n self._i=x\n print \"Constructing base1\"\n def __del__(self):\n print \"Destructing base1\"\n \nclass base2:\n def __init__(self,x):\n self._k=x\n print \"Constructing base2\"\n def __del__(self):\n print \"Destructing base2\"\n \nclass derived(base1,base2):\n def __init__(self,x,y):\n i=0\n for b in self.__class__.__bases__:\n if i==0:\n b.__init__(self,x)\n else :\n b.__init__(self,y)\n i+=1\n print \"Constructing derived\"\n def __del__(self):\n print \"Destructing derived\"\n for b in self.__class__.__bases__:\n b.__del__(self)\n def show(self):\n print self._i,self._k\n \n#Variable declaration\nob = derived(3,4)\n\n#Result\nob.show()\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Constructing base1\nConstructing base2\nConstructing derived\nDestructing derived\nDestructing base1\nDestructing base2\n3 4\n" + } + ], + "prompt_number": 26 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.13, Page Number: 351<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Acessing member variables'''\n\nclass base:\n def __init__(self):\n self.__i=None\n self.j=self.k=None\n def seti(self,x):\n self.__i=x\n def geti(self):\n return self.__i\n\nclass derived(base):\n def __init__(self):\n self.a=None\n\n\n#Variable declaration\nob=derived()\n\nob._base__i=10 #Accessing private members of base class\nob.j=20 #legal because j and k are public variable in base\nob.k=30\n\nob.a=40 #legal because a is public in derived class\nob.seti(10)\n\n#Result\nprint ob.geti(),ob.j,ob.a", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 20 40\n" + } + ], + "prompt_number": 28 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.14, Page Number: 354<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Virtual base class'''\n#All classes in pyhton are effectively virtual, hence scope resolution is not needed\n\nclass base:\n def __init__(self):\n self.i=None\n\n#derived1 inherits base\nclass derived1(base):\n def __init__(self):\n self.__j=None\n \n#derived2 inherits base\nclass derived2(base):\n def __init__(self):\n self.__k=None\n\n#derived3 inherits from both derived1 and derived2\nclass derived3(derived1,derived2):\n def __init__(self):\n self.__sum=None\n \n#Variable declaration\nob=derived3()\n\nob.i=10\nob.j=20\nob.k=30\n\nob.sum=ob.i+ob.j+ob.k\n\n#Result\nprint ob.i,ob.j,ob.k,ob.sum", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 20 30 60\n" + } + ], + "prompt_number": 29 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 14.15, Page Number: 355<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Virtual base class'''\n#All classes in pyhton are effectively virtual, hence virtual keyword is not needed\n\nclass base:\n def __init__(self):\n self.i=None\n\n#derived1 inherits base\nclass derived1(base):\n def __init__(self):\n self.__j=None\n \n#derived2 inherits base\nclass derived2(base):\n def __init__(self):\n self.__k=None\n\n#derived3 inherits from both derived1 and derived2\nclass derived3(derived1,derived2):\n def __init__(self):\n self.__sum=None\n \n#Variable declaration\nob=derived3()\n\nob.i=10\nob.j=20\nob.k=30\n\nob.sum=ob.i+ob.j+ob.k\n\n#Result\nprint ob.i,ob.j,ob.k,ob.sum", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 20 30 60\n" + } + ], + "prompt_number": 30 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_15(1).ipynb b/C++_from_the_Ground/Chapter_15(1).ipynb new file mode 100644 index 00000000..53e0df9a --- /dev/null +++ b/C++_from_the_Ground/Chapter_15(1).ipynb @@ -0,0 +1,147 @@ +{ + "metadata": { + "name": "Chapter 15" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 15: Virtual Functions and Polymorphism<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 15.1, Page Number: 358<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Using base pointers on derived class objects'''\n\n\nclass B_class:\n def __init__(self):\n self.author=None\n def put_author(self,s):\n self.author=s\n def show_author(self):\n print self.author\n \nclass D_class(B_class):\n def __init__(self):\n self.title=None\n def put_title(self,num):\n self.title=num\n def show_title(self):\n print \"Title:\",self.title\n \n#Variable declaration\np=[B_class()] #acts as a pointer to B_class type\nB_ob=B_class()\n\ndp=[D_class()] #acts as a pointer to D_class type\nD_ob=D_class()\n\np[0]=B_ob #assigning p to object of base\n\n\n#Access B_class via pointer\np[0].put_author(\"Tom Clancy\")\n\n#Access D_class via base pointer\np[0]=D_ob\np[0].put_author(\"William Shakespeare\")\n\n#Show that each author went into proper object\nB_ob.show_author()\nD_ob.show_author()\nprint \"\\n\"\n\n#Since put_title() and show_title() are not part of the base class, \n#they are not accessible via the base pointer p and must be accessed \n#either directly, or, as shown here, through a pointer to the \n#derived type\ndp[0]=D_ob\ndp[0].put_title(\"The Tempest\")\np[0].show_author()\ndp[0].show_title()\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Tom Clancy\nWilliam Shakespeare\n\n\nWilliam Shakespeare\nTitle: The Tempest\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 15.2, Page Number: 361<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A short example that uses virtual functions'''\n#All functions in python are effectively virtual, hence virtual keyword not required\n\n\nclass base:\n def who(self): #virtual function\n print \"Base\"\n\nclass first_d(base):\n def who(self): #redifine who() relative to first_d\n print \"First derivation\"\n \nclass second_d(base):\n def who(self): #redifine who() relative to second_d\n print \"Second derivation\"\n \n \n#Variable declaration\nbase_obj=base()\np=[base()]\nfirst_obj=first_d()\nsecond_obj=second_d()\n\np[0]=base_obj\np[0].who() #access base's who\n\np[0]=first_obj\np[0].who() #access first_d's who\n\np[0]=second_obj\np[0].who() #access second_d's who\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Base\nFirst derivation\nSecond derivation\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 15.3, Page Number: 363<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An example that shows virtual functions are inherited'''\n\n\nclass base:\n def who(self): #virtual function\n print \"Base\"\n\nclass first_d(base):\n def who(self): #redifine who() relative to first_d\n print \"First derivation\"\n \nclass second_d(base):\n #who not defined\n pass\n \n \n#Variable declaration\nbase_obj=base()\np=[base()]\nfirst_obj=first_d()\nsecond_obj=second_d()\n\np[0]=base_obj\np[0].who() #access base's who\n\np[0]=first_obj\np[0].who() #access first_d's who\n\np[0]=second_obj\np[0].who() #access base's who because\n #second_d does not redefine it.\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Base\nFirst derivation\nBase\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 15.4, Page Number: 364<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Virtual function in hierarchical inheritance'''\n\n\nclass base:\n def who(self): #virtual function\n print \"Base\"\n\nclass first_d(base):\n def who(self): #redifine who() relative to first_d\n print \"First derivation\"\n \n#second_d now inherited first_d -- not base\nclass second_d(first_d):\n #who not defined\n pass\n \n \n#Variable declaration\nbase_obj=base()\np=[base()]\nfirst_obj=first_d()\nsecond_obj=second_d()\n\np[0]=base_obj\np[0].who() #access base's who\n\np[0]=first_obj\np[0].who() #access first_d's who\n\np[0]=second_obj\np[0].who() #access first_d's who because\n #second_d does not redefine it.\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Base\nFirst derivation\nFirst derivation\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 15.5, Page Number: 366<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A simple application of virtual functions'''\n\nclass figure:\n def __init__(self):\n self._x=None\n self._y=None\n def set_dim(self,i,j):\n self._x=i\n self._y=j\n def show_area(self):\n print \"No area computation defined\",\n print \"for this class.\"\n \nclass triangle(figure):\n def show_area(self):\n print \"Triangle with height\",\n print self._x,\"and base\",self._y,\n print \"has an area of\",\n print self._x*0.5*self._y,\".\"\n \nclass rectangle(figure):\n def show_area(self):\n print \"Rectangle with dimensions\",\n print self._x,\"x\",self._y,\n print \"has an area of\",\n print self._x*self._y,\".\"\n \n#Variable declaration\np=[figure()] #pointer to base type\nt=triangle() #objects of derived type\nr=rectangle()\n\np[0]=t\np[0].set_dim(10.0,5.0)\np[0].show_area()\n\np[0]=r\np[0].set_dim(10.0,5.0)\np[0].show_area()\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Triangle with height 10.0 and base 5.0 has an area of 25.0 .\nRectangle with dimensions 10.0 x 5.0 has an area of 50.0 .\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 15.6, Page Number: 368<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An expanded version of previous program'''\n\nclass figure:\n def __init__(self):\n self._x=None\n self._y=None\n def set_dim(self,i,j=0):\n self._x=i\n self._y=j\n def show_area(self):\n print \"No area computation defined\",\n print \"for this class.\"\n \nclass triangle(figure):\n def show_area(self):\n print \"Triangle with height\",\n print self._x,\"and base\",self._y,\n print \"has an area of\",\n print self._x*0.5*self._y,\".\"\n \nclass rectangle(figure):\n def show_area(self):\n print \"Rectangle with dimensions\",\n print self._x,\"x\",self._y,\n print \"has an area of\",\n print self._x*self._y,\".\"\n \nclass circle(figure):\n def show_area(self):\n print \"Circle with radius\",\n print self._x,\n print \"has an area of\",\n print 3.14*self._x*self._x,\".\"\n \n \n#Variable declaration\np=[figure()] #pointer to base type\nt=triangle() #objects of derived type\nr=rectangle()\nc=circle()\n\np[0]=t\np[0].set_dim(10.0,5.0)\np[0].show_area()\n\np[0]=r\np[0].set_dim(10.0,5.0)\np[0].show_area()\n\np[0]=c\np[0].set_dim(9.0)\np[0].show_area()\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Triangle with height 10.0 and base 5.0 has an area of 25.0 .\nRectangle with dimensions 10.0 x 5.0 has an area of 50.0 .\nCircle with radius 9.0 has an area of 254.34 .\n" + } + ], + "prompt_number": 7 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_16(1).ipynb b/C++_from_the_Ground/Chapter_16(1).ipynb new file mode 100644 index 00000000..afb4b4f1 --- /dev/null +++ b/C++_from_the_Ground/Chapter_16(1).ipynb @@ -0,0 +1,267 @@ +{ + "metadata": { + "name": "Chapter 16" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 16: Templates<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 16.1, Page Number: 376<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of templates'''\n\n#The concept of template in in-built in python,hence this is a function template\ndef swapargs(a,b):\n temp=a[0]\n a[0]=b[0]\n b[0]=temp\n\n#Variable declaration\ni=[10]\nj=[20]\nx=[10.1]\ny=[23.3]\na=['x']\nb=['z']\n\nprint \"Original i, j: \",i[0],j[0]\nprint \"Original x,y: \",x[0],y[0]\nprint \"Original a,b: \",a[0],b[0]\n\nswapargs(i,j) #swap integers\nswapargs(x,y) #swap floats\nswapargs(a,b) #swap chars\n\n#Result\nprint \"Swapped i, j: \",i[0],j[0]\nprint \"Swapped x,y: \",x[0],y[0]\nprint \"Swapped a,b: \",a[0],b[0]", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Original i, j: 10 20\nOriginal x,y: 10.1 23.3\nOriginal a,b: x z\nSwapped i, j: 20 10\nSwapped x,y: 23.3 10.1\nSwapped a,b: z x\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 16.2, Page Number: 378<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Template for two generic types'''\n\ndef myfunc(x,y):\n print x,y\n \nmyfunc(10,\"hi\")\nmyfunc(0.23,10L)", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 hi\n0.23 10\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 16.3, Page Number: 379<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Overloading generic functions'''\n\ndef swapargs(a,b):\n if isinstance(a[0],int): #integer version\n temp=a[0]\n a[0]=b[0]\n b[0]=temp\n print \"Inside swapargs int specialization.\"\n else: #generic version\n temp=a[0]\n a[0]=b[0]\n b[0]=temp\n print \"Inside template swapargs.\"\n\n#Variable declaration\ni=[10]\nj=[20]\nx=[10.1]\ny=[23.3]\na=['x']\nb=['z']\n\nprint \"Original i, j: \",i[0],j[0]\nprint \"Original x,y: \",x[0],y[0]\nprint \"Original a,b: \",a[0],b[0]\n\nswapargs(i,j) #calls explicitly overloaded swapargs()\nswapargs(x,y) #calls generic swapargs()\nswapargs(a,b) #calls generic swapargs()\n\n#Result\nprint \"Swapped i, j: \",i[0],j[0]\nprint \"Swapped x,y: \",x[0],y[0]\nprint \"Swapped a,b: \",a[0],b[0]", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Original i, j: 10 20\nOriginal x,y: 10.1 23.3\nOriginal a,b: x z\nInside swapargs int specialization.\nInside template swapargs.\nInside template swapargs.\nSwapped i, j: 20 10\nSwapped x,y: 23.3 10.1\nSwapped a,b: z x\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 16.4, Page Number: 381<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Overload a function template declaration'''\n\n#Function version of f() template\ndef f(a,b=None):\n if(b==None): #First version of f()\n print \"Inside f(X a)\"\n else: #Second version of f()\n print \"Inside f(X a, Y b)\"\n \nf(10) #calls f(X)\nf(10,20) #calls f(X,Y)", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Inside f(X a)\nInside f(X a, Y b)\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 16.5, Page Number: 382<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing templates in python'''\n\n#Display data specified number of times.\ndef repeat(data,times):\n while times:\n print data\n times-=1\n \nrepeat(\"This is a test\",3)\nrepeat(100,5)\nrepeat(99.0/2, 4)\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "This is a test\nThis is a test\nThis is a test\n100\n100\n100\n100\n100\n49.5\n49.5\n49.5\n49.5\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 16.6, Page Number: 383<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A generic version of myabs()'''\n\ndef myabs(val):\n if val<0:\n return -val\n else:\n return val\n\n#Result\nprint myabs(-10)\nprint myabs(-10.0)\nprint myabs(-10L)\nprint myabs(-10.0)\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10\n10.0\n10\n10.0\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 16.7, Page Number: 385<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing a generic queue class'''\n\ndef SIZE():\n return 100\nclass queue:\n def __init__(self):\n self.q=[]\n self.sloc=self.rloc=0\n #Put an object into the queue\n def qput(self,i):\n if self.sloc==SIZE():\n print \"Queue is full.\"\n return\n self.sloc+=1\n self.q.append(i)\n #Get an object from the queue.\n def qget(self):\n if self.rloc==self.sloc:\n print \"Queue Underflow.\"\n return\n a=self.rloc\n self.rloc+=1\n return self.q[a]\n \n#Create two integer queues\na=queue()\nb=queue()\na.qput(10)\nb.qput(19)\na.qput(20)\nb.qput(1)\n\nprint a.qget(),\nprint a.qget(),\nprint b.qget(),\nprint b.qget()\n\n#Create two double queues\nc=queue()\nd=queue()\nc.qput(10.12)\nd.qput(19.99)\nc.qput(-20.0)\nd.qput(0.986)\n\nprint c.qget(),\nprint c.qget(),\nprint d.qget(),\nprint d.qget()\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 20 19 1\n10.12 -20.0 19.99 0.986\n" + } + ], + "prompt_number": 7 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 16.8, Page Number: 387<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Two generic types in a class'''\n\nclass myclass:\n def __init__(self,a,b):\n self.__i=a\n self.__j=b\n def show(self):\n print self.__i,self.__j\n\nob1=myclass(10,0.23)\nob2=myclass('X',\"This is a test\")\n\n#Result\nob1.show() #Show int,double\nob2.show() #Show char.char*\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 0.23\nX This is a test\n" + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 16.9, Page Number: 388<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A generic safe array example'''\n\n#Defining constant\ndef SIZE():\n return 10\n\nclass atype:\n def __init__(self):\n self.a=[]\n for i in range(SIZE()):\n self.a.append(i)\n #Implementing the [] overloading\n def op1(self,i,j):\n if (i<0 or i>=SIZE()):\n print \"\\nIndex value of \",\n print i,\" is out-of-bounds.\"\n return \n self.a[i]=j\n def op2(self,i):\n if (i<0 or i>SIZE()-1):\n print \"\\nIndex value of \",\n print i,\" is out-of-bounds.\"\n return\n return self.a[i]\n \n#Variable declaration\nintob=atype()\ndoubleob=atype()\n \nprint \"Integer array: \",\nfor i in range(SIZE()):\n intob.op1(i,i)\nfor i in range(SIZE()):\n print intob.op2(i),\n \nprint \"\"\n\nprint \"Double array: \",\nfor i in range(SIZE()):\n doubleob.op1(i,float(i)/3)\nfor i in range(SIZE()):\n print doubleob.op2(i),\n \nintob.op1(12,100)", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Integer array: 0 1 2 3 4 5 6 7 8 9 \nDouble array: 0.0 0.333333333333 0.666666666667 1.0 1.33333333333 1.66666666667 2.0 2.33333333333 2.66666666667 3.0 \nIndex value of 12 is out-of-bounds.\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 16.10, Page Number: 389<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing non-type template arguments'''\n\nclass atype:\n def __init__(self,size):\n self.a=[]\n self.size=size\n for i in range(size):\n self.a.append(i)\n #Implementing the [] overloading\n def op1(self,i,j):\n if (i<0 or i>self.size-1):\n print \"\\nIndex value of \",\n print i,\" is out-of-bounds.\"\n return\n self.a[i]=j\n def op2(self,i):\n if (i<0 or i>self.size-1):\n print \"\\nIndex value of \",\n print i,\" is out-of-bounds.\"\n return\n return self.a[i]\n \n#Variable declaration\nintob=atype(10)\ndoubleob=atype(15)\n \nprint \"Integer array: \",\nfor i in range(10):\n intob.op1(i,i)\nfor i in range(10):\n print intob.op2(i),\n \nprint \"\"\n\nprint \"Double array: \",\nfor i in range(15):\n doubleob.op1(i,float(i)/3)\nfor i in range(15):\n print doubleob.op2(i),\n \nintob.op1(12,100) #generates runtime error\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Integer array: 0 1 2 3 4 5 6 7 8 9 \nDouble array: 0.0 0.333333333333 0.666666666667 1.0 1.33333333333 1.66666666667 2.0 2.33333333333 2.66666666667 3.0 3.33333333333 3.66666666667 4.0 4.33333333333 4.66666666667 \nIndex value of 12 is out-of-bounds.\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 16.11, Page Number: 391<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A generic safe array example with default arguments'''\n\nclass atype:\n def __init__(self,size=10):\n self.a=[]\n for i in range(size):\n self.a.append(i)\n #Implementing the [] overloading\n def op1(self,i,j):\n if (i<0 and i>SIZE()-1):\n print \"Index value of \"\n print i,\" is out-of-bounds.\"\n exit(1)\n self.a[i]=j\n def op2(self,i):\n if (i<0 and i>SIZE()-1):\n print \"Index value of \"\n print i,\" is out-of-bounds.\"\n exit()\n return self.a[i]\n \n#Variable declaration\nintob=atype(100)\ndoubleob=atype()\ndefarray=atype()\n \nprint \"Integer array: \",\nfor i in range(100):\n intob.op1(i,i)\nfor i in range(100):\n print intob.op2(i),\n \nprint \"\"\n\nprint \"Double array: \",\nfor i in range(10):\n doubleob.op1(i,float(i)/3)\nfor i in range(10):\n print doubleob.op2(i),\n \nprint \"\"\n\nprint \"Defarray array: \",\nfor i in range(10):\n doubleob.op1(i,i)\nfor i in range(10):\n print doubleob.op2(i),\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Integer array: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 \nDouble array: 0.0 0.333333333333 0.666666666667 1.0 1.33333333333 1.66666666667 2.0 2.33333333333 2.66666666667 3.0 \nDefarray array: 0 1 2 3 4 5 6 7 8 9\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 16.12, Page Number: 393<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate class specialization'''\n\nclass myclass:\n def __init__(self,a):\n if isinstance(a,int):\n print \"Inside myclass<int>specialization\"\n self.__x=a*a\n else:\n print \"Inside generic myclass\"\n self.__x=a\n def getx(self):\n return self.__x\n \nd=myclass(10.1)\nprint \"double: \",d.getx(),\"\\n\"\n\ni=myclass(5)\nprint \"int: \",i.getx()\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Inside generic myclass\ndouble: 10.1 \n\nInside myclass<int>specialization\nint: 25\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_17(1).ipynb b/C++_from_the_Ground/Chapter_17(1).ipynb new file mode 100644 index 00000000..8694627c --- /dev/null +++ b/C++_from_the_Ground/Chapter_17(1).ipynb @@ -0,0 +1,307 @@ +{ + "metadata": { + "name": "Chapter 17" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 17: Exception Handling<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 17.1, Page Number: 397<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A simple exception handling example'''\n\nprint \"start\"\n\ntry: #start a try block\n print \"Inside try block\"\n raise Exception(99) #raise an error\n print \"This will not execute\"\nexcept Exception,i: #catch an error\n print \"Caught an exception -- value is:\",\n print i\n\nprint \"end\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "start\nInside try block\nCaught an exception -- value is: 99\nend\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 17.2, Page Number: 399<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''A simple exception handling example'''\n\nimport sys\n\n\n\ndef main():\n print \"start\"\n try: #start a try block\n print \"Inside try block\"\n raise Exception(99) #raise an error\n print \"This will not execute\"\n except Exception,i: #catch an error\n if isinstance(i,float):\n print \"Caught an exception -- value is:\",\n print i\n else:\n print \"Abnormal program termination\"\n return\n print \"end\"\n\n \nmain()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "start\nInside try block\nAbnormal program termination\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 17.3, Page Number: 400<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Throwing an exception from a function called \n from within a try block'''\n\ndef Xtest(test):\n print \"Inside Xtest, test is: \",test\n if(test):\n raise Exception(test)\n \nprint \"start\"\n\ntry: #start a try block\n print \"Inside try block\"\n Xtest(0)\n Xtest(1)\n Xtest(2)\nexcept Exception,i: #catch an error\n print \"Caught an exception -- value is:\",\n print i\n\nprint \"end\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "start\nInside try block\nInside Xtest, test is: 0\nInside Xtest, test is: 1\nCaught an exception -- value is: 1\nend\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 17.4, Page Number: 401<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A try/except is reset each time a function is entered'''\n\ndef Xhandler(test):\n try:\n if(test):\n raise Exception(test)\n except Exception,i:\n print \"Caught One! Ex #:\",i\n \nprint \"start\"\n\nXhandler(1)\nXhandler(2)\nXhandler(0)\nXhandler(3)\n\nprint \"end\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "start\nCaught One! Ex #: 1\nCaught One! Ex #: 2\nCaught One! Ex #: 3\nend\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 17.5, Page Number: 401<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Use exception class'''\n\nclass MyException:\n def __init__(self,s):\n self.str_what=s\n \n#Variable declaration\na=None \nb=None\n\ntry:\n print \"Enter numerator and denominator:\"\n #User-input\n a=10 \n b=0\n if not(b):\n raise MyException(\"Cannot divide by zero!\")\n else:\n print \"Quotient is\",a/b\nexcept MyException as e: #catch an error\n print e.str_what\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Enter numerator and denominator:\nCannot divide by zero!\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 17.6, Page Number: 403<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Different types of exceptions being caught'''\n\nclass MyException:\n def __init__(self,s):\n self.x=s\n \ndef Xhandler(test):\n try:\n if(test):\n raise MyException(test)\n else:\n raise MyException(\"Value is zero\")\n except MyException as i:\n if isinstance(i.x,int):\n print \"Caught One! Ex #:\",i.x\n else:\n print \"Caught a string:\",\n print i.x\n \nprint \"start\"\n\nXhandler(1)\nXhandler(2)\nXhandler(0)\nXhandler(3)\n\nprint \"end\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "start\nCaught One! Ex #: 1\nCaught One! Ex #: 2\nCaught a string: Value is zero\nCaught One! Ex #: 3\nend\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 17.7, Page Number: 404<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Catching derived classes'''\n\nclass B:\n pass\n\nclass D(B):\n pass\n\nderived=D()\n\ntry:\n raise B()\nexcept B as b:\n print \"Caught a base class.\"\nexcept D as d:\n print \"This wont execute.\"\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Caught a base class.\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 17.8, Page Number: 405<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Example to catch all exceptions'''\n\ndef Xhandler(test):\n try:\n if test==0:\n raise Exception(test) #throw int\n if test==1:\n raise Exception('a') #throw char\n if test==2:\n raise Exception(123.23) #throw double\n except: #Catches all exceptions\n print \"Caught One!\"\n\nprint \"start\"\n\nXhandler(0)\nXhandler(1)\nXhandler(2)\n\nprint \"end\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "start\nCaught One!\nCaught One!\nCaught One!\nend\n" + } + ], + "prompt_number": 7 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 17.9, Page Number: 405<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Example to catch all exceptions'''\n\nclass MyException:\n def __init__(self,s):\n self.x=s\n \ndef Xhandler(test):\n try:\n if test==0:\n raise MyException(test) #throw int\n if test==1:\n raise MyException('a') #throw char\n if test==2:\n raise MyException(123.23) #throw double\n except MyException as i:\n if isinstance(i.x,int): #catch an int exception\n print \"Caught\",i.x \n else: #catch all other exceptions\n print \"Caught One!\"\n \n\nprint \"start\"\n\nXhandler(0)\nXhandler(1)\nXhandler(2)\n\nprint \"end\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "start\nCaught 0\nCaught One!\nCaught One!\nend\n" + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 17.10, Page Number: 407<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Restricting function throw types'''\n\nclass MyException:\n def __init__(self,s):\n self.x=s\n \n#This function can only throw ints, chars and doubles\ndef Xhandler(test):\n if test==0:\n raise MyException(test) #throw int\n if test==1:\n raise MyException('a') #throw char\n if test==2:\n raise MyException(123.23) #throw double\n \n\nprint \"start\"\ntry:\n Xhandler(0)\nexcept MyException as i:\n if isinstance(i.x,int): #catch an int exception\n print \"Caught int\" \n elif isinstance(i.x,str): #catch a char exception\n print \"Caught char\"\n elif isinstance(i.x,float): #catch a float exception\n print \"Caught double\"\n\nprint \"end\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "start\nCaught int\nend\n" + } + ], + "prompt_number": 9 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 17.11, Page Number: 408<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Example of \"rethrowing\" an exception'''\n\ndef Xhandler():\n try:\n raise Exception(\"hello\") #throw a char *\n except Exception,c: #catch a char *\n print \"Caugh char * inside Xhandler\"\n raise #rethrow char * out of function\n \nprint \"start\"\ntry:\n Xhandler()\nexcept Exception,c:\n print \"Caught char * inside main\"\n \nprint \"end\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "start\nCaugh char * inside Xhandler\nCaught char * inside main\nend\n" + } + ], + "prompt_number": 10 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 17.12, Page Number: 410<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Handle exceptions due to allocation failure'''\n\nfrom ctypes import *\n\n#Variable declaration\np=[]\n\ntry:\n for i in range(32):\n p.append(c_int())\nexcept MemoryError,m:\n print \"Allocation failure.\"\n \nfor i in range(32):\n p[i]=i\n \nfor i in range(32):\n print p[i],\n \n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31\n" + } + ], + "prompt_number": 12 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 17.13, Page Number: 410<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Checking allocation failure without raising an exception'''\n\nfrom ctypes import *\n\n#Variable declaration\np=[]\n\n\nfor i in range(32):\n p.append(c_int()) \nif not(p):\n print \"Allocation failure.\"\n \nfor i in range(32):\n p[i]=i\n \nfor i in range(32):\n print p[i],\n \n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31\n" + } + ], + "prompt_number": 13 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 17.13, Page Number: 412<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate overloaded new and delete'''\n\nclass three_d:\n def __init__(self,i=0,j=0,k=0): #3=D coordinates\n if(i==0 and j==0 and k==0):\n self.x=self.y=self.z=0\n print \"Constructing 0, 0, 0\"\n else:\n self.x=i\n self.y=j\n self.z=k\n print \"Constructing\",i,\",\",j,\",\",k\n def __del__(self):\n print \"Destructing\"\n #new overloaded relative to three_d.\n def __new__(typ, *args, **kwargs):\n obj = object.__new__(typ, *args, **kwargs)\n return obj\n def show(self):\n print self.x,\",\",\n print self.y,\",\",\n print self.z\n \np1=[]*3\np2=[]\n \ntry:\n print \"Allocating array of three_d objects.\"\n for i in range(3): #allocate array\n p1.append(three_d())\n print \"Allocating three_d object.\"\n p2.append(three_d(5,6,7)) #allocate object\nexcept MemoryError:\n print \"Allocation error\"\n \np1[2].show()\np2[0].show()\n\n\nfor i in xrange(2,-1,-1):\n del p1[i] #delete array\nprint \"Deleting array of thee_d objects.\"\n\ndel p2[0] #delete object\nprint \"Deleting three_d object.\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Allocating array of three_d objects.\nConstructing 0, 0, 0\nConstructing 0, 0, 0\nConstructing 0, 0, 0\nAllocating three_d object.\nConstructing 5 , 6 , 7\n0 , 0 , 0\n5 , 6 , 7\nDestructing\nDestructing\nDestructing\nDeleting array of thee_d objects.\nDestructing\nDeleting three_d object.\n" + } + ], + "prompt_number": 14 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_18(1).ipynb b/C++_from_the_Ground/Chapter_18(1).ipynb new file mode 100644 index 00000000..3ad3c39c --- /dev/null +++ b/C++_from_the_Ground/Chapter_18(1).ipynb @@ -0,0 +1,413 @@ +{ + "metadata": { + "name": "Chapter 18" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 18: The C++ I/O System<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.1, Page Number: 421<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of overloading << for print in python'''\n\nclass three_d:\n def __init__(self,a,b,c): #3D coordinates\n self.x=a\n self.y=b\n self.z=c\n #Display x,y,z coordinates - three_d inserter.\n def __repr__(self):\n return str(self.x)+\", \"+str(self.y)+\", \"+str(self.z)+\"\\n\"\n\n#Variable declaration\na=three_d(1,2,3)\nb=three_d(3,4,5)\nc=three_d(5,6,7)\n\n#Result\nprint a,b,c", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1, 2, 3\n 3, 4, 5\n 5, 6, 7\n\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.2, Page Number: 423<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Using a friend function implement overloading of << in python'''\n\nclass thrnee_d:\n def __init__(self,a,b,c): #3D coordinates\n self.x=a\n self.y=b\n self.z=c\n #Display x,y,z coordinates - three_d inserter.\n __repr__=repr \n \n#Friend function \ndef repr():\n return str(self.x)+\", \"+str(self.y)+\", \"+str(self.z)+\"\\n\"\n\n#Variable declaration\na=three_d(1,2,3)\nb=three_d(3,4,5)\nc=three_d(5,6,7)\n\nprint a,b,c", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1, 2, 3\n 3, 4, 5\n 5, 6, 7\n\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.3, Page Number: 424<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of overloading << and >> in python'''\n\nclass three_d:\n def __init__(self,a,b,c): #3D coordinates\n self.x=a\n self.y=b\n self.z=c\n #Display x,y,z coordinates - three_d inserter.\n def __repr__(self):\n return str(self.x)+\", \"+str(self.y)+\", \"+str(self.z)\n\n#Variable declaration\na=three_d(1,2,3)\n\nprint a\n\n#User input\nprint \"Enter X,Y,Z values:\"\na=three_d(4,5,6) \nprint a", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1, 2, 3\nEnter X,Y,Z values:\n4, 5, 6\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.4, Page Number: 428<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing some ios flags in python'''\n\n\nprint '{0:+d}'.format(123), #for ios::showpos\nif(123.23>0):\n i='{0:e}'.format(123.23) #for ios::scientific \n i='+'+i\n print i\nelse :\n print '{0:e}'.format(123.23)\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "+123 +1.232300e+02\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.5, Page Number: 430<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing some ios flags in python'''\n\nimport string\n\nprint '{0:+d}'.format(123), #for ios::showpos\nif(123.23>0):\n i='{0:e}'.format(123.23) #for ios::scientific \n i='+'+i\n print i\nelse :\n print '{0:e}'.format(123.23)\n\n \nprint '{:10.2f}'.format(123.23), #2 digits left of decimal\nif(123.23>0):\n i='{0:.2e}'.format(123.23) #for ios::scientific \n i='+'+i\n print i\nelse :\n print '{0:.2e}'.format(123.23)\n \n \nprint '{:#>10}'.format(str(123)), #for ios::fill\nif(123.23>0): \n i='{0:.2e}'.format(123.23) #for ios::scientific \n i='+'+i\n print i\nelse :\n print '{0:.2e}'.format(123.23)\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "+123 +1.232300e+02\n 123.23 +1.23e+02\n#######123 +1.23e+02\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.6, Page Number: 432<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implement io manipulators in python'''\n\nprint '{0:.0e}'.format(1000.243) #for setprecision\nprint '{:>20}'.format(\"Hello There\") #to set width and right align\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1e+03\n Hello There\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.7, Page Number: 433<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing some ios flags in python'''\n\nprint '{0:+d}'.format(123), #for ios::showpos\nif(123.23>0):\n i='{0:e}'.format(123.23) #for ios::scientific \n i='+'+i\n print i\nelse :\n print '{0:e}'.format(123.23)\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "+123 +1.232300e+02\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.8, Page Number: 433<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Removing leading whitespaces from a string'''\n\n#User input\ns=\" Hello\"\n\n#Result\nprint s.lstrip() #lstrip removes leading spaces", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Hello\n" + } + ], + "prompt_number": 7 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.9, Page Number: 434<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing some ios flags in python'''\n\ndef setup(s):\n return '{:$<10}'.format(str(s))\n\n\n#Result\nprint 10,setup(10)\n\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 10$$$$$$$$\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.10, Page Number: 435<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Prompting the user to enter number in hexadecimal form'''\n\ndef prompt():\n print \"Enter number using hex format:\"\n hex=0x46\n return hex\n\n\n#Result\ni=prompt()\nprint i\n\n", + "language": "python", + "metadata": {}, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.11, Page Number: 438<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to write to a file'''\n\n#Open a file, creating one if it does not already exist\nout=open(\"test\",'w')\n\n#In case file cannot open\nif(not(out)):\n print \"Cannot open file.\"\nelse:\n #Write to file\n out.write(\"10 123.23\\n\")\n out.write(\"This is a short text file.\")\n #Close the file\n out.close()", + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.12, Page Number: 438<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to read to a file'''\n\n#Open a file, creating one if it does not already exist\nIn=open(\"test\",'r')\n\n#In case file cannot open\nif(not(In)):\n print \"Cannot open file.\"\nelse:\n #Read file\n i=In.read(2)\n ch=In.read(1)\n f=In.read(6)\n str=In.read()\n print i,f,ch\n print str\n #Close the file\n out.close()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 123.23 \n\nThis is a short text file.\n" + } + ], + "prompt_number": 9 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.13, Page Number: 439<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to read to a file provided on the screen'''\n#Program cannot be provided here, so error is obtained\n\nimport sys\n \nif not(len(sys.argv)==2):\n print \"Usage: PR <filename>\\n\"\nelse:\n #Open a file\n In=open(sys.argv[1],'r')\n\n #In case file cannot open\n if(not(In)):\n print \"Cannot open file.\"\n else:\n #Read file\n ch=In.read()\n print ch\n In.close()\n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Usage: PR <filename>\n\n" + } + ], + "prompt_number": 10 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.14, Page Number: 440<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to write to a file'''\n\nimport sys\n\np=\"hello there\"\n\nout=open(\"test\",'w')\n\n#In case file cannot open\nif(not(out)):\n print \"Cannot open file.\"\nelse:\n #Write to file\n for i in range(len(p)):\n out.write(p[i])\n", + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 11 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.15, Page Number: 441<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to read and write in a file'''\n\nimport sys\n\nn=[1,2,3,4,5]\n\n#Open a file 'test'\nout=open(\"test\",'w')\n\n#In case file cannot open\nif(not(out)):\n print \"Cannot open file.\"\nelse:\n #Write to file\n for i in range(5):\n out.write(chr(n[i]))\n out.close()\n \nfor i in range(5): #clear array\n n[i]=0\n \n#Open the file\nIn=open(\"test\",'r')\n\n#In case file cannot open\nif(not(In)):\n print \"Cannot open file.\"\nelse:\n #Read file\n for i in range(5):\n n[i]=ord(In.read(1))\n\n#Result, shows value from file\nfor i in range(5):\n print n[i],\n \nIn.close()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1 2 3 4 5\n" + } + ], + "prompt_number": 12 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.16, Page Number: 442<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Detect end-of-file for a file on the screen'''\n#File cannot be provided here, so program wont work\nimport sys\n \nif not(len(sys.argv)==2):\n print \"Usage: PR <filename>\\n\"\nelse:\n #Open a file\n In=open(sys.argv[1],'r')\n\n #In case file cannot open\n if(not(In)):\n print \"Cannot open file.\"\n else:\n #Read file\n while True:\n ch=In.read(1)\n if not ch:\n break\n print ch,\n #Close file\n In.close()\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Usage: PR <filename>\n\n" + } + ], + "prompt_number": 13 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.17, Page Number: 443<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to compare files'''\n\n#Since file names cannot be provided, two \n#files are being created test1 and test2\n\n#creating test1\nout=open(\"test1\",'w')\nout.write(\"Hello\")\nout.close()\n\n#creating test2\nout=open(\"test2\",'w')\nout.write(\"There\")\nout.close()\n\n\n#Open test1\nf1=open(\"test1\",'r')\n#In case file cannot open\nif(not(In)):\n print \"Cannot open file.\"\n\n#Open test2\nf2=open(\"test2\",'r')\n#In case file cannot open\nif(not(In)):\n print \"Cannot open file.\"\n \nprint \"Comparing files...\"\n\nbuf1=f1.read()\nbuf2=f2.read()\nprint buf1,buf2\n\nif len(buf1)==len(buf2):\n print \"Files are of different sizes.\"\n f1.close()\n f2.close()\nelse:\n #compare contents of buffers\n flag=1\n for i in range(len(buf1)):\n if not(buf1[i]==buf2[i]):\n print \"Files differ.\"\n f1.close()\n f2.close()\n flag=0\n break\n if flag==1:\n print \"Files are the same.\"\n \n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Comparing files...\nHello There\nFiles are of different sizes.\n" + } + ], + "prompt_number": 14 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.18, Page Number: 445<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Read a string and print it'''\n\nprint \"Enter your name:\"\n\n#User imput\nstr=\"hello world\"\n\nprint str", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Enter your name:\nhello world\n" + } + ], + "prompt_number": 15 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.19, Page Number: 447<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate random access by writing X at a specified location'''\n\n#Since arguments cannot be provided file test \n#is created and X is written in the 3nd location.\n\n#Open test\nout=open(\"test\",'r+b')\nout.write(\"Hello\")\n\n\n#In case file cannot open\nif(not(out)):\n print \"Cannot open file.\"\nelse:\n out.seek(2,0)\n out.write('X')\n out.close()\n \n", + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.20, Page Number: 447<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Display a file from a given point'''\n\n#Here, file is displayed from 3nd position\n\n#Open test\nout=open(\"test\",'r+b')\nout.write(\"Hello\")\nout.close()\n\nIn=open(\"test\",'r')\n#In case file cannot open\nif(not(In)):\n print \"Cannot open file.\"\nelse:\n In.seek(2,0)\n ch=In.read()\n print ch\n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "llo\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 18.21, Page Number: 450<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implement use of overloaded inserter to write three_d'''\n\nclass three_d:\n def __init__(self,a,b,c):\n self.__x=a\n self.__y=b\n self.__z=c\n def __repr__(self):\n c=(\"%d\"%self.__x)+\", \"+(\"%d\"%self.__y)+\", \"+(\"%d\"%self.__z)+\"\\n\"\n return c \n\n#Variable declaration\na=three_d(1,2,3)\nb=three_d(3,4,5)\nc=three_d(5,6,7)\n\n#Open threed\nout=open(\"threed\",'w')\n#In case file cannot open\nif(not(out)):\n print \"Cannot open file.\"\nelse:\n out.write(a.__repr__())\n out.write(b.__repr__())\n out.write(c.__repr__())\n\n ", + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 18 + }, + { + "cell_type": "raw", + "metadata": {}, + "source": "" + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_19(1).ipynb b/C++_from_the_Ground/Chapter_19(1).ipynb new file mode 100644 index 00000000..318b8aaa --- /dev/null +++ b/C++_from_the_Ground/Chapter_19(1).ipynb @@ -0,0 +1,247 @@ +{ + "metadata": { + "name": "Chapter 19" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 19: Run-Time Type ID and the Casting Operators<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 19.1, Page Number: 453<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A simple example taht uses typeid'''\n\nclass myclass:\n pass\n\n#Variable declaration\ni=j=0\nf=0.0\nob=myclass()\n\nprint \"The type of i is:\",type(i).__name__\nprint \"The type of f is:\",type(f).__name__\nprint \"The type of ob is:\",ob.__class__.__name__\nprint \"\\n\"\n\nif type(i)==type(j):\n print \"The types of i and j are the same\"\n \nif not(type(i)==type(f)):\n print \"The types of i and f are not the same\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "The type of i is: int\nThe type of f is: float\nThe type of ob is: myclass\n\n\nThe types of i and j are the same\nThe types of i and f are not the same\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 19.2, Page Number: 454<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An example that uses typeid on a polymorphic class hierarchy'''\n\nclass Base:\n pass\nclass Derived1(Base):\n pass\nclass Derived2(Base):\n pass\n\n#Variable declaration\nbaseob=Base()\np=[Base()]\nob1=Derived1()\nob2=Derived2()\n\n\np[0]=baseob\nprint \"p is pointing to an object of type\",\nprint p[0].__class__.__name__\n\np[0]=ob1\nprint \"p is pointing to an object of type\",\nprint p[0].__class__.__name__\n\np[0]=ob2\nprint \"p is pointing to an object of type\",\nprint p[0].__class__.__name__", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "p is pointing to an object of type Base\np is pointing to an object of type Derived1\np is pointing to an object of type Derived2\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 19.3, Page Number: 455<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An example that uses typeid on a polymorphic class hierarchy'''\n\nclass Base:\n pass\nclass Derived1(Base):\n pass\nclass Derived2(Base):\n pass\n\ndef WhatType(ob):\n print \"ob is referencing an object of type\",\n print ob.__class__.__name__\n \n \n#Variable declaration\nbaseob=Base()\np=[Base()]\nob1=Derived1()\nob2=Derived2()\n\nWhatType(baseob)\nWhatType(ob1)\nWhatType(ob2)", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "ob is referencing an object of type Base\nob is referencing an object of type Derived1\nob is referencing an object of type Derived2\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 19.4, Page Number: 456<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate run-time type id'''\n\nimport random\n\nclass figure:\n def __init__(self,i,j):\n self._x=i\n self._y=j\n \nclass triangle(figure):\n def __init__(self,i,j):\n figure.__init__(self,i,j)\n def area(self):\n return self._x*0.5*self._y\n \nclass rectangle(figure):\n def __init__(self,i,j):\n figure.__init__(self,i,j)\n def area(self):\n return self._x*self._y\n \nclass circle(figure):\n def __init__(self,i,j=0):\n figure.__init__(self,i,j)\n def area(self):\n return self._x*self._x*3.14\n \ndef factory():\n i=random.randint(0,2)\n if i==0:\n return circle(10.0)\n elif i==1:\n return triangle(10.1,5.3)\n elif i==2:\n return rectangle(4.3,5.7)\n \n\nt=c=r=0 \np=[None]\n\n#generate and count objects\nfor i in range(10):\n p[0]=factory() #generate an object\n print \"Object is \",p[0].__class__.__name__,\". \",\n #count it\n if p[0].__class__.__name__==triangle.__name__:\n t+=1\n if p[0].__class__.__name__==rectangle.__name__:\n r+=1\n if p[0].__class__.__name__==circle.__name__:\n c+=1\n #display its area\n print \"Area is\",p[0].area()\n\nprint \"Objects generated:\"\nprint \"Triangles:\",t\nprint \"Rectangles:\",r\nprint \"Circles:\",c", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Object is circle . Area is 314.0\nObject is rectangle . Area is 24.51\nObject is rectangle . Area is 24.51\nObject is circle . Area is 314.0\nObject is rectangle . Area is 24.51\nObject is circle . Area is 314.0\nObject is rectangle . Area is 24.51\nObject is triangle . Area is 26.765\nObject is rectangle . Area is 24.51\nObject is circle . Area is 314.0\nObjects generated:\nTriangles: 1\nRectangles: 5\nCircles: 4\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 19.5, Page Number: 456<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Using typeid with templates'''\n#Since python does not have templates\n#it will give a different output.\n\n#Template class\nclass myclass:\n def __init__(self,i):\n self.__a=i\n \no1=myclass(10)\no2=myclass(9)\no3=myclass(7.2)\n\nprint \"Type of o1 is\",o1.__class__.__name__\n\nprint \"Type of o2 is\",o2.__class__.__name__\n\nprint \"Type of o3 is\",o3.__class__.__name__\n\nprint\n\nif o1.__class__.__name__==o2.__class__.__name__:\n print \"o1 and o2 are the same type\"\n \nif o1.__class__.__name__==o3.__class__.__name__:\n print \"Error\"\nelse:\n print \"o1 and o3 are different types\"\n\n#This prints error because python doesnt use templates.", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Type of o1 is myclass\nType of o2 is myclass\nType of o3 is myclass\n\no1 and o2 are the same type\nError\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 19.6, Page Number: 460<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Template version of figure hierarchy'''\n#Python classes are effectively template classes.\n\nimport random\n\nclass figure:\n def __init__(self,i,j):\n self._x=i\n self._y=j\n \nclass triangle(figure):\n def __init__(self,i,j):\n figure.__init__(self,i,j)\n def area(self):\n return self._x*0.5*self._y\n \nclass rectangle(figure):\n def __init__(self,i,j):\n figure.__init__(self,i,j)\n def area(self):\n return self._x*self._y\n \nclass circle(figure):\n def __init__(self,i,j=0):\n figure.__init__(self,i,j)\n def area(self):\n return self._x*self._x*3.14\n \ndef factory():\n i=random.randint(0,2)\n if i==0:\n return circle(10.0)\n elif i==1:\n return triangle(10.1,5.3)\n elif i==2:\n return rectangle(4.3,5.7)\n \n\nt=c=r=0 \np=[None]\n\n#generate and count objects\nfor i in range(10):\n p[0]=factory() #generate an object\n print \"Object is \",p[0].__class__.__name__,\". \",\n #count it\n if p[0].__class__.__name__==triangle.__name__:\n t+=1\n if p[0].__class__.__name__==rectangle.__name__:\n r+=1\n if p[0].__class__.__name__==circle.__name__:\n c+=1\n #display its area\n print \"Area is\",p[0].area()\n\nprint \"Objects generated:\"\nprint \"Triangles:\",t\nprint \"Rectangles:\",r\nprint \"Circles:\",c", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Object is triangle . Area is 26.765\nObject is circle . Area is 314.0\nObject is circle . Area is 314.0\nObject is rectangle . Area is 24.51\nObject is rectangle . Area is 24.51\nObject is rectangle . Area is 24.51\nObject is circle . Area is 314.0\nObject is circle . Area is 314.0\nObject is rectangle . Area is 24.51\nObject is triangle . Area is 26.765\nObjects generated:\nTriangles: 2\nRectangles: 4\nCircles: 4\n" + } + ], + "prompt_number": 7 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 19.7, Page Number: 463<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implement dynamic casting'''\n#Dynamic casting is not needed in python \n#Also, the output will be different in python since \n#here since pointers are implemented using lists,\n\nclass Base:\n def f(self):\n print \"Inside Base\"\n \nclass Derived(Base):\n def f(self):\n print \"Inside Derived\"\n \nbp=[Base()] #pointer to base\nb_ob=Base() \ndp=[Derived()] #pointer to derived\nd_ob=Derived()\n\ndp[0]=d_ob\nif dp[0]:\n print \"Cast from Derived * to Derived * OK.\"\n dp[0].f()\nelse:\n print \"Error\"\nprint\n\nbp[0]=d_ob\nif bp[0]:\n print \"Cast from Derived * to Base * OK.\"\n bp[0].f()\nelse:\n print \"Error\"\nprint\n\nbp[0]=b_ob\nif bp[0]:\n print \"Cast from Base * to Base * OK.\"\n bp[0].f()\nelse:\n print \"Error\"\nprint\n\ndp[0]=b_ob\nif dp[0]:\n print \"Error\"\nelse:\n print \"Cast from Base * to Derived * not OK.\"\nprint\n\nbp[0]=d_ob #bp points to Derived object\ndp[0]=bp[0]\nif dp[0]:\n print \"Cast bp to a Derived * OK.\"\n print \"because bp is really pointing\\n\",\n print \"to a Derived object.\"\n dp[0].f()\nelse:\n print \"Error\"\nprint\n\nbp[0]=b_ob #bp points to Base object\ndp[0]=bp[0]\nif dp[0]:\n print \"Error\"\nelse:\n print \"Now casting bp to a Derived *\\n\",\n print \"is not OK because bp is really\\n\",\n print \" pointing to a Base object.\"\nprint\n\ndp[0]=d_ob #dp points to Derived object\nbp[0]=dp[0]\nif bp[0]:\n print \"Casting dp to a Base * is OK.\"\n bp[0].f()\nelse:\n print \"Error\"\nprint\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Cast from Derived * to Derived * OK.\nInside Derived\n\nCast from Derived * to Base * OK.\nInside Derived\n\nCast from Base * to Base * OK.\nInside Base\n\nError\n\nCast bp to a Derived * OK.\nbecause bp is really pointing\nto a Derived object.\nInside Derived\n\nError\n\nCasting dp to a Base * is OK.\nInside Derived\n\n" + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 19.8, Page Number: 465<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implement dynamic casting'''\n#Dynamic casting is not needed in python \n#Also, the output will be different in python since \n#here since pointers are implemented using lists,\n\nclass Base:\n def f(self):\n pass\n \nclass Derived(Base):\n def derivedOnly(self):\n print \"Is a Derived Object\"\n \nbp=[Base()] #pointer to base\nb_ob=Base() \ndp=[Derived()] #pointer to derived\nd_ob=Derived()\n\n#Use typeid\n\nbp[0]=b_ob\nif bp[0].__class__.__name__==Derived.__name__:\n dp[0]=bp[0]\n dp[0].derivedOnly()\nelse:\n print \"Cast from Base to Derived failed.\"\n \nbp[0]=d_ob\nif bp[0].__class__.__name__==Derived.__name__:\n dp[0]=bp[0]\n dp[0].derivedOnly()\nelse:\n print \"Error, cast should work!\"\n \n#Use dynamic_cast\n\nbp[0]=b_ob\ndp[0]=bp[0]\nif dp[0].__class__.__name__==Derived.__name__:\n dp[0].derivedOnly()\nelse:\n print \"Cast from Base to Derived failed.\"\n \nbp[0]=d_ob\ndp[0]=bp[0]\nif dp:\n dp[0].derivedOnly()\nelse:\n print \"Error, cast should work!\"\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Cast from Base to Derived failed.\nIs a Derived Object\nCast from Base to Derived failed.\nIs a Derived Object\n" + } + ], + "prompt_number": 9 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 19.9, Page Number: 467<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of const_cast'''\n#Since python does not have constants, const_cast is not needed\n\ndef f(p):\n v=p\n v[0]=100\n \n#Variable declaration\nx=[]\n\nx.append(99)\nprint \"x before call:\",x[0]\nf(x)\nprint \"x after call:\",x[0]\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "x before call: 99\nx after call: 100\n" + } + ], + "prompt_number": 10 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 19.10, Page Number: 468<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implement static_cast'''\n#Since python does not have static variables,\n#static_cast is not needed\n\nf=199.22\n\ni=f\nprint i\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "199.22\n" + } + ], + "prompt_number": 11 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 19.11, Page Number: 469<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An example of reinterpret_cast'''\n#python does not have specific data type variables \n#hence reinterpretation is not required\n\n#Variable Declaration\ni=0 #int\np=\"This is a string\"\n\ni=p #cast pointer to integer \n\n#Result\nprint i\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "This is a string\n" + } + ], + "prompt_number": 12 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_2(1).ipynb b/C++_from_the_Ground/Chapter_2(1).ipynb new file mode 100644 index 00000000..ca5a3177 --- /dev/null +++ b/C++_from_the_Ground/Chapter_2(1).ipynb @@ -0,0 +1,267 @@ +{ + "metadata": { + "name": "Chapter 2" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 2: An Overview of C++<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 2.1, Page Number: 12<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program 1:A first Python(C++) program'''\n\n#Result\nprint \"This is my first C++ program.\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "This is my first C++ program.\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 2.2, Page Number: 17<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program 2: Using a variable'''\n\n#Variable Declaration\nx=None \n\nx=1023 #this assigns 1023 to x\n\n#Result\nprint \"This program prints the value of x: \",x #prints x,i.e, 1023\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "This program prints the value of x: 1023\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 2.3, Page Number: 18<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''This program converts gallons to liters'''\n\n#Variable declaration\ngallons=10 #User input\nliters=None\n\nliters=gallons*4 #convert to liters\n\n#Result\nprint \"Liters: \",liters", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Liters: 40\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 2.4, Page Number: 20<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''This program converts gallons to liters using floating point numbers'''\n\n#Variable declaration\ngallons=10.20 #User input\nliters=None\n\nliters=gallons*3.7854 #convert to liters\n\n#Result\nprint \"Liters: \",liters", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Liters: 38.61108\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 2.5, Page Number: 21<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''This program uses a function'''\n\n#myfunc's definition\ndef myfunc():\n print \"Inside myfunc() \"\n \nprint \"In main()\"\nmyfunc() #call myfunc()\nprint \"Back in main()\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "In main()\nInside myfunc() \nBack in main()\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 2.6, Page Number: 22<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Using the abs() function'''\n\n#Result\nprint abs(-10)", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 2.7, Page Number: 23<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A simple program that demonstrates mul()'''\n\n#mul's definition\ndef mul(x,y):\n print x*y,\n\n#calling mul\nmul(10,20)\nmul(5,6)\nmul(8,9)", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "200 30 72\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 2.8, Page Number: 24<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Returning a value'''\n\n#mul()'s definition; this function returns a value\ndef mul(x,y):\n return x*y #return product of x and y\n\n#Variable declaration\nanswer=mul(10,11) #assign return values\n\n#Result\nprint \"The answer is: \",answer\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "The answer is: 110\n" + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 2.9, Page Number: 26<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''This demonstrates how to got to the next line'''\n\nprint \"one\"\nprint \"two\" #prints in different line\nprint \"three\",\"four\" #prints all in same line", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "one\ntwo\nthree four\n" + } + ], + "prompt_number": 9 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 2.10, Page Number: 27<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''This program illustrates the if statement'''\n\n#Variable declaration\na=10 #user input for two numbers\nb=20\n\n#Result\nif a<b:\n print \"First number is less than second. \"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "First number is less than second. \n" + } + ], + "prompt_number": 10 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 2.11, Page Number: 28<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A program that illustrates the for loop'''\n\nfor count in range(1,100+1):\n print count,", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 2.12, Page Number: 30<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''This program demonstrates a block of code'''\n\n#Variable declaration\na=10 #User input for two numbers\nb=20\n\n#Result\nif a<b:\n print \"First number is less than second\"\n print \"Their difference is: \",b-a\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "First number is less than second\nTheir difference is: 10\n" + } + ], + "prompt_number": 12 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_20(2).ipynb b/C++_from_the_Ground/Chapter_20(2).ipynb new file mode 100644 index 00000000..cc097c14 --- /dev/null +++ b/C++_from_the_Ground/Chapter_20(2).ipynb @@ -0,0 +1,959 @@ +{ + "metadata": { + "name": "" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h1>Chapter 20: Namespaces and Other Advanced Topics<h1>" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.1, Page Number:474<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Implementing a namespace'''\n", + "#A good implementaton of namespaces in python would be\n", + "#creating python files or modules and then importing them.\n", + "#Since that is not possible n ipython, implementation is \n", + "#done using classes.\n", + "\n", + "\n", + "class CounterNameSpace:\n", + " upperbound=None\n", + " lowerbound=None\n", + " class counter:\n", + " def __init__(self,n):\n", + " if n<=CounterNameSpace.upperbound:\n", + " self.count=n\n", + " else:\n", + " self.count=CounterNameSpace.upperbound\n", + " def reset(self,n):\n", + " if n<=CounterNameSpace.upperbound:\n", + " self.count=n\n", + " def run(self):\n", + " if self.count>CounterNameSpace.lowerbound:\n", + " self.count-=1\n", + " return self.count\n", + " else:\n", + " return CounterNameSpace.lowerbound\n", + " \n", + "CounterNameSpace.upperbound=100\n", + "CounterNameSpace.lowerbound=0\n", + "\n", + "\n", + "ob1=CounterNameSpace.counter(10)\n", + "while True:\n", + " i=ob1.run()\n", + " print i,\n", + " if i<=CounterNameSpace.lowerbound:\n", + " break \n", + "print\n", + "\n", + "\n", + "ob2=CounterNameSpace.counter(20)\n", + "while True:\n", + " i=ob2.run()\n", + " print i,\n", + " if i<=CounterNameSpace.lowerbound:\n", + " break \n", + "print\n", + "\n", + "\n", + "ob2.reset(100)\n", + "CounterNameSpace.lowerbound=90\n", + "while True:\n", + " i=ob2.run()\n", + " print i,\n", + " if i<=CounterNameSpace.lowerbound:\n", + " break " + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "9 8 7 6 5 4 3 2 1 0\n", + "19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0\n", + "99 98 97 96 95 94 93 92 91 90\n" + ] + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.2, Page Number:476<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Implementing using'''\n", + "\n", + "class CounterNameSpace:\n", + " upperbound=None\n", + " lowerbound=None\n", + " class counter:\n", + " def __init__(self,n):\n", + " if n<=c.upperbound:\n", + " self.count=n\n", + " else:\n", + " self.count=c.upperbound\n", + " def reset(self,n):\n", + " if n<=c.upperbound:\n", + " self.count=n\n", + " def run(self):\n", + " if self.count>c.lowerbound:\n", + " self.count-=1\n", + " return self.count\n", + " else:\n", + " return c.lowerbound\n", + "\n", + "#Use only upperbound using c\n", + "c=CounterNameSpace()\n", + "c.upperbound=100\n", + "CounterNameSpace.lowerbound=0\n", + "\n", + "\n", + "ob1=CounterNameSpace.counter(10)\n", + "while True:\n", + " i=ob1.run()\n", + " print i,\n", + " if i<=CounterNameSpace.lowerbound:\n", + " break \n", + "print\n", + "\n", + "#Now use entre CounterName Space using c\n", + "\n", + "ob2=c.counter(20)\n", + "while True:\n", + " i=ob2.run()\n", + " print i,\n", + " if i<=c.lowerbound:\n", + " break \n", + "print\n", + "\n", + "\n", + "ob2.reset(100)\n", + "c.lowerbound=90\n", + "while True:\n", + " i=ob2.run()\n", + " print i,\n", + " if i<=c.lowerbound:\n", + " break " + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "9 8 7 6 5 4 3 2 1 0\n", + "19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0\n", + "99 98 97 96 95 94 93 92 91 90\n" + ] + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.3, Page Number:479<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Printing a number'''\n", + "\n", + "#User-input\n", + "print \"Enter a number:\"\n", + "val= 10.00\n", + "\n", + "#Result\n", + "print \"This is your number:\",val" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "Enter a number:\n", + "This is your number: 10.0\n" + ] + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.4, Page Number:479<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Implementing the std:: qualification'''\n", + "\n", + "import sys\n", + "\n", + "#User-input\n", + "sys.stdout.write(\"Enter a number:\")\n", + "val= 10.00\n", + "\n", + "#Result\n", + "sys.stdout.write(\"\\nThis is your number: \")\n", + "sys.stdout.write(str(val))" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "Enter a number:\n", + "This is your number: 10.0" + ] + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.5, Page Number:479<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Bring only a few names into global namespace'''\n", + "\n", + "from sys import stdout\n", + "\n", + "#User-input\n", + "stdout.write(\"Enter a number:\")\n", + "val= 10.00\n", + "\n", + "#Result\n", + "stdout.write(\"\\nThis is your number: \")\n", + "stdout.write(str(val))" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "Enter a number:\n", + "This is your number: 10.0" + ] + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.6, Page Number:480<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Implementing pointers to functions'''\n", + "\n", + "#functions\n", + "def vline(i):\n", + " for j in xrange(i,0,-1):\n", + " print \"|\"\n", + "def hline(i):\n", + " for j in xrange(i,0,-1):\n", + " print \"-\",\n", + " print \n", + "\n", + "p=vline #p points to vline\n", + "p(4) #call vline()\n", + "\n", + "p=hline #p now points to hline\n", + "p(3) #call hline" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "|\n", + "|\n", + "|\n", + "|\n", + "- - -\n" + ] + } + ], + "prompt_number": 7 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.7, Page Number:482<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''qsort in python:for string'''\n", + "#Python doesn't have an in-built function hence,\n", + "#a function for qsort is defined.\n", + "\n", + "import string\n", + "\n", + "def qsort(p):\n", + " if p == []: \n", + " return []\n", + " else:\n", + " pivot = p[0]\n", + " lesser = qsort([x for x in p[1:] if x < pivot])\n", + " greater = qsort([x for x in p[1:] if x >= pivot])\n", + " return lesser + [pivot] + greater\n", + " \n", + "#Variable Declaration \n", + "str=\"Function pointers provide flexibility.\" \n", + "\n", + "#sorting the string\n", + "str=qsort(str)\n", + "str=string.join(str)\n", + "\n", + "#Result\n", + "print \"sorted strng: \",str\n" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "sorted strng: . F b c d e e e f i i i i i i l l n n n o o o p p r r s t t t u v x y\n" + ] + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.8, Page Number:482<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''qsort in python:for int'''\n", + "#Python doesn't have an in-built function hence,\n", + "#a function for qsort is defined.\n", + "\n", + "import string\n", + "\n", + "def qsort(p):\n", + " \"\"\"Quicksort using list comprehensions\"\"\"\n", + " if p == []: \n", + " return []\n", + " else:\n", + " pivot = p[0]\n", + " lesser = qsort([x for x in p[1:] if x < pivot])\n", + " greater = qsort([x for x in p[1:] if x >= pivot])\n", + " return lesser + [pivot] + greater\n", + " \n", + "#Variable Declaration \n", + "num=[10,4,3,6,5,7,8]\n", + "\n", + "#sorting the string\n", + "num=qsort(num)\n", + "\n", + "#Result\n", + "for i in range(7):\n", + " print num[i],\n" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "3 4 5 6 7 8 10\n" + ] + } + ], + "prompt_number": 9 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.9, Page Number:484<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Illustrate assigning function pointers to overload functions'''\n", + "\n", + "#Output count number of spaces.\n", + "def space(count,ch=None):\n", + " if ch==None:\n", + " for i in xrange(count,0,-1):\n", + " print '',\n", + " else:\n", + " for i in xrange(count,0,-1):\n", + " print ch,\n", + " \n", + "\n", + "fp1=space\n", + "fp2=space\n", + "\n", + "fp1(22) #outputs 20 spaces\n", + "print \"|\\n\" \n", + "\n", + "fp2(30,'x') #output 30 xs \n", + "print \"|\\n\"\n", + " " + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + " |\n", + "\n", + "x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x |\n", + "\n" + ] + } + ], + "prompt_number": 10 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.10, Page Number:485<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Implementing static class members'''\n", + "\n", + "num=None #static variable\n", + "\n", + "class ShareVar:\n", + " def setnum(i=0):\n", + " global num\n", + " num=i\n", + " def shownum(self):\n", + " global num\n", + " print num\n", + " \n", + "#Variables declaration\n", + "a=ShareVar()\n", + "b=ShareVar()\n", + "\n", + "a.shownum() #prints None\n", + "b.shownum() #prints None\n", + "\n", + "num=10 #set static num to 10\n", + "\n", + "a.shownum() #prints 10\n", + "b.shownum() #prints 10\n", + " " + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "None\n", + "None\n", + "10\n", + "10\n" + ] + } + ], + "prompt_number": 11 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.11, Page Number:487<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Implement const and mutable member functions'''\n", + "\n", + "class Demo:\n", + " i=None\n", + " j=None\n", + " def geti(self):\n", + " return self.i\n", + " def seti(self,x):\n", + " self.i=x\n", + " \n", + "ob=Demo()\n", + "\n", + "ob.seti(1900)\n", + "print ob.geti()\n" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "1900\n" + ] + } + ], + "prompt_number": 12 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.12, Page Number:488<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''A simple class program'''\n", + "\n", + "class myclass:\n", + " def __init__(self,x):\n", + " self.__a=x\n", + " def geta(self):\n", + " return self.__a\n", + " \n", + "#Variable declaration\n", + "ob=myclass(4)\n", + "\n", + "#Result\n", + "print ob.geta()" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "4\n" + ] + } + ], + "prompt_number": 15 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.13, Page Number:489<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''A Class Example'''\n", + "#explicit not implemented in python\n", + "\n", + "class myclass:\n", + " def __init__(self,x):\n", + " self.__a=x\n", + " def geta():\n", + " return self.__a\n", + " \n", + "ob = myclass(110)" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.14, Page Number:490<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Implementing implicit conversion'''\n", + "\n", + "class myclass:\n", + " def __init__(self,i):\n", + " self.__num=i\n", + " def getnum(self):\n", + " return self.__num\n", + " \n", + "#Variable declaration\n", + "o=myclass(10)\n", + "\n", + "print o.getnum() #display 10\n", + "\n", + "o=myclass(1000)\n", + "\n", + "print o.getnum() #display 1000" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "10\n", + "1000\n" + ] + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.15, Page Number:491<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Member nitialization Syntax'''\n", + "\n", + "class myclass:\n", + " def __init__(self,x,y):\n", + " self.__numA=x\n", + " self.__numB=y\n", + " def getnumA(self):\n", + " return self.__numA\n", + " def getnumB(self):\n", + " return self.__numB\n", + " \n", + "#Variable declaration\n", + "ob1=myclass(7,9)\n", + "ob2=myclass(5,2)\n", + "\n", + "#Result\n", + "print \"Values in ob1 are \",ob1.getnumB(),\"and\",ob1.getnumA()\n", + "print \"Values in ob2 are \",ob2.getnumB(),\"and\",ob2.getnumA()\n", + "\n" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "Values in ob1 are 9 and 7\n", + "Values in ob2 are 2 and 5\n" + ] + } + ], + "prompt_number": 16 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.16, Page Number:492<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Member nitialization Syntax'''\n", + "\n", + "class myclass:\n", + " def __init__(self,x,y):\n", + " self.__numA=x\n", + " self.__numB=y\n", + " def getnumA(self):\n", + " return self.__numA\n", + " def getnumB(self):\n", + " return self.__numB\n", + " \n", + "#Variable declaration\n", + "ob1=myclass(7,9)\n", + "ob2=myclass(5,2)\n", + "\n", + "#Result\n", + "print \"Values in ob1 are \",ob1.getnumB(),\"and\",ob1.getnumA()\n", + "print \"Values in ob2 are \",ob2.getnumB(),\"and\",ob2.getnumA()\n", + "\n" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "Values in ob1 are 9 and 7\n", + "Values in ob2 are 2 and 5\n" + ] + } + ], + "prompt_number": 17 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.17, Page Number:494<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Implementing entern functions'''\n", + "\n", + "def myfunc():\n", + " print \"This links as a C function.\"\n", + " \n", + "myfunc()" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "This links as a C function.\n" + ] + } + ], + "prompt_number": 18 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.18, Page Number:495<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Pointer to member example'''\n", + "from ctypes import *\n", + "\n", + "class myclass: \n", + " sum=c_int(0)\n", + " def sum_it(self,x):\n", + " for i in range(x+1):\n", + " self.sum.value+=i\n", + " fp=sum_it #pointer to function\n", + "\n", + "#Variable declaration\n", + "c=myclass()\n", + "fp=myclass.sum_it #get address of function\n", + "dp=pointer(c.sum) #address of data\n", + "c.fp(7) #compute summation of 7\n", + "\n", + "\n", + "#Result\n", + "print \"summation of 7 is\",dp[0]\n", + " " + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "summation of 7 is 28\n" + ] + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.19, Page Number:496<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Pointer to member example'''\n", + "from ctypes import *\n", + "\n", + "class myclass:\n", + " sum=c_int(0)\n", + " def sum_it(self,x): \n", + " for i in range(x+1):\n", + " self.sum.value+=i\n", + " fp=sum_it #pointer to function\n", + "\n", + "#Variable declaration\n", + "d=myclass()\n", + "c=[d] #ponter to object\n", + "fp=myclass.sum_it #get address of function\n", + "dp=pointer(c[0].sum) #get address of data\n", + "\n", + "c[0].fp(7) #compute summation of 7\n", + "\n", + "\n", + "#Result\n", + "print \"summation of 7 is\",dp[0]\n", + " " + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + " summation of 7 is 28\n" + ] + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "<h3>Example 20.20, Page Number:497<h3>" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "'''Implementing conversion functions'''\n", + "\n", + "class three_d:\n", + " def __init__(self,a,b,c): #3D coordinates\n", + " self.x=a\n", + " self.y=b\n", + " self.z=c\n", + " #Display x,y,z coordinates - three_d inserter.\n", + " def __repr__(self):\n", + " return str(self.x)+\", \"+str(self.y)+\", \"+str(self.z)+\"\\n\"\n", + " def __add__(self,op2):\n", + " if isinstance(op2,int):\n", + " c=self.x*self.y*self.z+op2\n", + " return c\n", + " temp=three_d(self.x+op2.x,self.y+op2.y,self.z+op2.z)\n", + " return temp\n", + " \n", + "a=three_d(1,2,3)\n", + "b=three_d(2,3,4)\n", + "\n", + "print a,b,\n", + "\n", + "print b+100 #displays 124 because of conversion to int\n", + "\n", + "a=a+b #add two three_d objects - no conversion\n", + "\n", + "print a #displays 3,5,7" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "1, 2, 3\n", + " 2, 3, 4\n", + " 124\n", + "3, 5, 7\n", + "\n" + ] + } + ], + "prompt_number": 1 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [], + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_21(1).ipynb b/C++_from_the_Ground/Chapter_21(1).ipynb new file mode 100644 index 00000000..a37db7f8 --- /dev/null +++ b/C++_from_the_Ground/Chapter_21(1).ipynb @@ -0,0 +1,427 @@ +{ + "metadata": { + "name": "Chapter 21" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 21: Introducing the Standard Template Library<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.1, Page Number:507<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An implementation of vector in python'''\n\n#Variable declaratio\nv=[] #Create a zero length vector\n\n#display original size of v\nprint \"Size =\",len(v)\n\n#put values onto end of vector\n#vector will grow as needed\n\nfor i in range(10):\n v.append(i)\n \n#display current size of v\nprint \"Current contents: \"\nprint \"Size now =\",len(v)\n\n#display contents of vector\nfor i in range(len(v)):\n print v[i],\n \nprint\n \n#put more values onto end of vector\n#again, vector will grow as needed.\nfor i in range(10):\n v.append(i+10)\n#display current size of v\nprint \"Size now =\",len(v)\n\n#display contents of vector\nprint \"Current contents:\"\nfor i in range(len(v)):\n print v[i],\nprint\n \n#change contents of vector\nfor i in range(len(v)):\n v[i]=v[i]+v[i]\n \n#display contents of vector\nprint \"Contents doubled:\"\nfor i in range(len(v)):\n print v[i],", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Size = 0\nCurrent contents: \nSize now = 10\n0 1 2 3 4 5 6 7 8 9\nSize now = 20\nCurrent contents:\n0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19\nContents doubled:\n0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.2, Page Number:508<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Access vector usng an terator'''\n\n#Variable declaration\nv=[] #Create a zero length vector\n\n#put values onto end of vector\nfor i in range(10):\n v.append(chr(ord('A')+i))\n \n#can access vector contents using subscripts\nfor i in range(len(v)):\n print v[i], \nprint\n \n#access via iterator\nfor p in v:\n print p,\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "A B C D E F G H I J\nA B C D E F G H I J\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.3, Page Number:509<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate insert and erase'''\n\n#Variable declaration\nv=[] #Create a zero length vector\n\n#put values onto end of vector\nfor i in range(10):\n v.append(chr(ord('A')+i))\n \n#Display original contents of vector\nprint \"Size =\",len(v)\nprint \"Original contents:\"\nfor i in range(len(v)):\n print v[i], \nprint \"\\n\"\n \np=2 #point to 3rd element\nfor i in range(10):\n v.insert(p+i,'X')\n \n#display contents after insertion\nprint \"Size after insert =\",len(v)\nprint \"Contents after insert:\"\nfor i in range(len(v)):\n print v[i],\nprint \"\\n\"\n\n#remove those elements\np=2 #point to 3rd element\nfor i in range(10):\n v.pop(p)\n \n#display contents after insertion\nprint \"Size after erase =\",len(v)\nprint \"Contents after insert:\"\nfor i in range(len(v)):\n print v[i],\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Size = 10\nOriginal contents:\nA B C D E F G H I J \n\nSize after insert = 20\nContents after insert:\nA B X X X X X X X X X X C D E F G H I J \n\nSize after erase = 10\nContents after insert:\nA B C D E F G H I J\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.4, Page Number:511<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Store a class object in a vector'''\n\nclass three_d:\n def __init__(self,a,b,c): #3D coordinates\n self.x=a\n self.y=b\n self.z=c\n #Display x,y,z coordinates - three_d inserter.\n def __repr__(self):\n return str(self.x)+\", \"+str(self.y)+\", \"+str(self.z)+\"\\n\"\n def __add__(self,a):\n self.x+=a\n self.y+=a\n self.z+=a\n return self\n def __lt__(self,b):\n return (self.x+self.y+self.z)<(b.x+b.y+b.z)\n def __eq__(self,b):\n return (self.x+self.y+self.z)==(b.x+b.y+b.z) \n \n#Variable declaration\nv=[]\n\n#add objects to the vector\nfor i in range(10):\n v.append(three_d(i,i+2,i-3))\n \n#Display contents of vector\nfor i in range(len(v)):\n print v[i], \nprint\n\n\n#Modify objects in a vector\nfor i in range(len(v)):\n v[i]=v[i]+10 \n\n#Display modified vector\nfor i in range(len(v)):\n print v[i], \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "0, 2, -3\n 1, 3, -2\n 2, 4, -1\n 3, 5, 0\n 4, 6, 1\n 5, 7, 2\n 6, 8, 3\n 7, 9, 4\n 8, 10, 5\n 9, 11, 6\n\n10, 12, 7\n 11, 13, 8\n 12, 14, 9\n 13, 15, 10\n 14, 16, 11\n 15, 17, 12\n 16, 18, 13\n 17, 19, 14\n 18, 20, 15\n 19, 21, 16\n\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.5, Page Number:513<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Store a class object in a vector'''\n \n#Variable declaration\nv=[]\nv2=[]\n\nfor i in range(10):\n v.append(chr(ord('A')+i))\n \n#Display original contents of vector\nprint \"Size =\",len(v)\nprint \"Original contents:\"\nfor i in range(len(v)):\n print v[i], \nprint \"\\n\"\n\n#initialze second vector\nstr=\"-STL Power-\"\nfor i in range(len(str)):\n v2.append(str[i])\n \n#get iterators to the middle of v and to the start and end of v2.\np=5\np2start=0\np2end=len(v2)-1\n\n#insert v2 into v\nfor i in range(p2end):\n v.insert(p+i,v2[p2start+i])\n \n#display result\nprint \"Contents of v after inserton:\"\nfor i in range(len(v)):\n print v[i],\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Size = 10\nOriginal contents:\nA B C D E F G H I J \n\nContents of v after inserton:\nA B C D E - S T L P o w e r F G H I J\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.6, Page Number:517<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate list basics'''\n\n#Variable declaration\nlst=[] #create an empty list\n\nfor i in range(10):\n lst.append(chr(ord('A')+i))\n \nprint \"Size =\",len(lst)\n\nprint \"Contents:\",\nfor p in lst:\n print p, \nprint \"\\n\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Size = 10\nContents: A B C D E F G H I J \n\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.7, Page Number:518<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''elements can be put on the front or end of a list'''\n\n#Variable declaration\nlst=[] \nrevlst=[]\n\nfor i in range(10):\n lst.append(chr(ord('A')+i))\n \nprint \"Size of list =\",len(lst)\n\nprint \"Original Contents:\",\n#Remove elements from lst and put them into revlst in reverse order.\nfor p in lst:\n print p, \n revlst.insert(0,p) \nfor i in range(10):\n lst.pop(0)\nprint \"\\n\"\n\nprint \"Size of revlst =\",len(revlst)\n\nprint \"Reversed Contents:\",\nfor p in revlst:\n print p,", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Size of list = 10\nOriginal Contents: A B C D E F G H I J \n\nSize of revlst = 10\nReversed Contents: J I H G F E D C B A\n" + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.8, Page Number:519<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Sort a list'''\n\nimport random\n\n#Variable declaration\nlst=[] \n\n#create a list of random integers\nfor i in range(10):\n lst.append(random.randint(0,100))\n\nprint \"Original Contents:\",\nfor p in lst:\n print p, \nprint \"\\n\"\n\n#sort the list\nlst.sort()\n\nprint \"Sorted Contents:\",\nfor p in lst:\n print p,", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Original Contents: 75 73 72 4 88 7 85 21 67 42 \n\nSorted Contents: 4 7 21 42 67 72 73 75 85 88\n" + } + ], + "prompt_number": 9 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.9, Page Number:520<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Merge two lists'''\n\n#Variable declaration\nlst1=[] \nlst2=[]\n\nfor i in xrange(0,10,2):\n lst1.append(chr(ord('A')+i))\nfor i in xrange(1,11,2):\n lst2.append(chr(ord('A')+i))\n\nprint \"Contents of lst1:\",\nfor p in lst1:\n print p, \nprint \"\\n\"\n\nprint \"Contents of lst2:\",\nfor p in lst2:\n print p, \nprint \"\\n\"\n\n#merge the lists\nlst1=lst1+lst2\nlst1.sort()\nlst2=[]\n\nif lst2==[]:\n print \"lst2 is now empty\"\n\nprint \"Contentsof lst1 after merge:\"\nfor p in lst1:\n print p,", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Contents of lst1: A C E G I \n\nContents of lst2: B D F H J \n\nlst2 is now empty\nContentsof lst1 after merge:\nA B C D E F G H I J\n" + } + ], + "prompt_number": 10 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.10, Page Number:521<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Store class objects in a list'''\n\nclass myclass:\n def __init__(self,i=0,j=0):\n self.__a=i\n self.__b=j\n self.sum=self.__a+self.__b\n def getsum(self):\n return self.sum\n def __lt__(self,o2):\n return self.sum<o2.sum\n def __gt__(self,o2):\n return self.sum>o2.sum\n def __eq__(self,o2):\n return self.sum==o2.sum\n def __ne__(self, other):\n return not self.__eq__(self)\n \n#create first list\nlst1=[]\nfor i in range(10):\n lst1.append(myclass(i,i))\n \nprint \"First list:\",\nfor p in lst1:\n print p.getsum(),\nprint\n\n#create second list\nlst2=[]\nfor i in range(10):\n lst2.append(myclass(i*2,i*3))\n \nprint \"First list:\",\nfor p in lst2:\n print p.getsum(),\nprint\n \n#Now merge list\nlst1=lst1+lst2\nlst1.sort()\n\n#Display merge list\nprint \"Merged list:\",\nfor p in lst1:\n print p.getsum(),\nprint", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "First list: 0 2 4 6 8 10 12 14 16 18\nFirst list: 0 5 10 15 20 25 30 35 40 45\nMerged list: 0 0 2 4 5 6 8 10 10 12 14 15 16 18 20 25 30 35 40 45\n" + } + ], + "prompt_number": 12 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.11, Page Number:527<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A simple map implementation'''\n\n#Variable declaration\nm=[] \n\n#define the function find\ndef find(x,ch):\n for p in x:\n if p[0]==ch:\n return p\n return -1\n\n#put pairs into map\nfor i in range(10):\n m.append([chr(ord('A')+i),i])\n \n#User Input\nch='D'\n\n#find value of the given key\np=find(m,ch)\n\nif not(p==-1):\n print p[1]\nelse:\n print \"Key not in the map\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "3\n" + } + ], + "prompt_number": 13 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.12, Page Number:528<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Using a map to create a dictionary'''\n\n#define the function find\ndef find(x,ch):\n for p in x:\n if p[0].get()==ch.get():\n return p\n return -1\n\n\nclass word:\n def __init__(self,s=\"\"):\n self.str=s\n def get(self):\n return self.str\n #must define less than relative to word objects\n def __lt__(self,b):\n return self.str<b.str\n\nclass meaning:\n def __init__(self,s=\"\"):\n self.str=s\n def get(self):\n return self.str\n\ndictionary=[]\n\ndictionary.append([word(\"house\"),meaning(\"A place of dwelling\")])\ndictionary.append([word(\"keyboard\"),meaning(\"An input device\")])\ndictionary.append([word(\"programming\"),meaning(\"The act of writing a program\")])\ndictionary.append([word(\"STL\"),meaning(\"Standard Template Library\")])\n\n#given a word, find meaning\nprint \"Enter word:\"\nstr=\"house\" #User input\n\np=find(dictionary,word(str))\n\nif not(p==-1):\n print \"Definition:\",p[1].get()\nelse:\n print \"Word not in the dictionary.\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Enter word:\nDefinition: A place of dwelling\n" + } + ], + "prompt_number": 14 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.13, Page Number:532<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate count and count_if'''\n\n#This is a unary precdate that determines if character is a vowel\ndef isvowel(ch):\n ch=ch.lower()\n if (ch=='a' or ch=='e'or ch=='i' or ch=='o' or ch=='u'):\n return 1\n else:\n return 0\n\nstr=\"STL programming is powerful.\"\nv=[]\n\nfor i in range(len(str)):\n v.append(str[i])\n \nprint \"Sequence:\",\nfor i in range(len(v)):\n print v[i],\nprint\n\nn=str.count('p')\nprint n,\"characters are p\"\n\n#count if vowel\nn=0\nfor i in v:\n if isvowel(i):\n n+=1\n \nprint n,\"characters are vowels.\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Sequence: S T L p r o g r a m m i n g i s p o w e r f u l .\n2 characters are p\n7 characters are vowels.\n" + } + ], + "prompt_number": 15 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.14, Page Number:534<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate remove_copy and replace_copy'''\n\nstr=\"This is a test\"\nv=[]\nv2=[]\n\nfor i in range(len(str)):\n v.append(str[i])\n \n# ***implement remove_copy***\nprint \"Input sequence:\",\nfor i in range(len(v)):\n print v[i],\nprint \n\n#Remove all i's\nv2 = str.replace(\"i\", \"\")\n\nprint \"Result after removing i's: \",\nprint v2,\"\\n\"\n\n\n# ***implement replace_copy***\nprint \"Input sequence:\",\nfor i in range(len(v)):\n print v[i],\nprint \n\n#Replace s's with X's\nv2 = str.replace(\"s\", \"X\")\n\nprint \"Result after replacning s's with X's: \",\nprint v2", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Input sequence: T h i s i s a t e s t\nResult after removing i's: Ths s a test \n\nInput sequence: T h i s i s a t e s t\nResult after replacning s's with X's: ThiX iX a teXt\n" + } + ], + "prompt_number": 16 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.15, Page Number:535<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Reversing a list'''\n\n#Variable declaration\nv=[]\n\nfor i in range(10):\n v.append(i)\n \nprint \"Initial:\",\nfor i in range(len(v)):\n print v[i],\nprint\n\n#Reversing the list\nv.reverse()\n\nprint \"Reversed:\",\nfor i in range(len(v)):\n print v[i],\nprint \n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Initial: 0 1 2 3 4 5 6 7 8 9\nReversed: 9 8 7 6 5 4 3 2 1 0\n" + } + ], + "prompt_number": 17 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.16, Page Number:536<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An implementation of transform algorithm'''\n\n#A simple transformaton function\ndef xform(i):\n return i*i #square original value\n\n#the transorm function\ndef transform(x,f):\n for i in range(len(x)):\n x[i]= f(x[i])\n \n#Variable declaration\nx1=[]\n\n#put values into list\nfor i in range(10):\n x1.append(i)\n\nprint \"Original contents of x1: \",\nfor p in x1:\n print p,\nprint \n\n#transform x1\np=transform(x1,xform)\n\nprint \"Transformed contents of x1:\",\nfor p in x1:\n print p,", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Original contents of x1: 0 1 2 3 4 5 6 7 8 9\nTransformed contents of x1: 0 1 4 9 16 25 36 49 64 81\n" + } + ], + "prompt_number": 18 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.17, Page Number:540<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A short string demonstration'''\n\nstr1=\"The string class gives \"\nstr2=\"C++ high strng handlng.\"\n\n#assign a string\nstr3=str1\nprint str1,\"\\n\",str3\n\n#Concatenate two strings\nstr3=str1+str2\nprint str3\n\n#Compare strings\nif str3>str1:\n print \"str3 > str1\"\nif str3==str1+str2:\n print \"str3 == str1+str2\"\n \nstr1=\"This is a null-terminated string.\"\nprint str1\n\n#create a string object using another string object\nstr4=str1\nprint str4\n\n#nput a string\nprint \"Enter a string:\"\nstr4=\"Hello\"\nprint str4", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "The string class gives \nThe string class gives \nThe string class gives C++ high strng handlng.\nstr3 > str1\nstr3 == str1+str2\nThis is a null-terminated string.\nThis is a null-terminated string.\nEnter a string:\nHello\n" + } + ], + "prompt_number": 19 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.18, Page Number:542<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate insert(), erase(), and replace()'''\n\nstr1=\"This is a test\"\nstr2=\"ABCDEFG\"\n\nprint \"Initial strings:\"\nprint \"str1:\",str1\nprint \"str2:\",str2\nprint\n\n#demonstrate insert\nprint \"Insert str2 into str1:\"\nstr1=str1[:5]+str2+str1[5:]\nprint str1,\"\\n\"\n\n#demonstrate erase\nprint \"Remove 7 charecters from str1:\"\nstr1=str[:5]+str[5:]\nprint str1,\"\\n\"\n\n#demonstrate replace\nprint \"Replace 2 characters in str1 with str2:\"\nstr1=str1[:5]+str2+str1[7:]\nprint str1\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Initial strings:\nstr1: This is a test\nstr2: ABCDEFG\n\nInsert str2 into str1:\nThis ABCDEFGis a test \n\nRemove 7 charecters from str1:\nThis is a test \n\nReplace 2 characters in str1 with str2:\nThis ABCDEFG a test\n" + } + ], + "prompt_number": 21 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.19, Page Number:543<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of find()'''\n\nimport string\n\n#Variable declaration \ns1=\"The string class makes string handling easy.\"\n\ni=string.find(s1,\"class\")\nif not(i==-1):\n print \"Match found at\",i\n print \"Remaining string is:\",\n s2=s1[i:]\n print s2", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Match found at 11\nRemaining string is: class makes string handling easy.\n" + } + ], + "prompt_number": 22 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 21.20, Page Number:545<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Using a map to create a dictionary'''\n\n#define the function find\ndef find(x,ch):\n for p in x:\n if p[0]==ch:\n return p\n return -1\n\n\ndictionary=[]\n\ndictionary.append([\"house\",\"A place of dwelling\"])\ndictionary.append([\"keyboard\",\"An input device\"])\ndictionary.append([\"programming\",\"The act of writing a program\"])\ndictionary.append([\"STL\",\"Standard Template Library\"])\n\n#given a word, find meaning\nprint \"Enter word:\"\nstr=\"house\" #User input\n\np=find(dictionary,str)\n\nif not(p==-1):\n print \"Definition:\",p[1]\nelse:\n print \"Word not in the dictionary.\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Enter word:\nDefinition: A place of dwelling\n" + } + ], + "prompt_number": 23 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_22(1).ipynb b/C++_from_the_Ground/Chapter_22(1).ipynb new file mode 100644 index 00000000..83be7161 --- /dev/null +++ b/C++_from_the_Ground/Chapter_22(1).ipynb @@ -0,0 +1,207 @@ +{ + "metadata": { + "name": "Chapter 22" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 22: The C++ Preprocessor<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 22.1, Page Number: 550<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implement a function-like macro'''\n\ndef MIN(a,b):\n if a<b:\n return a\n else:\n return b\n\n#Variable declaration\nx=10\ny=20\n\n#Result\nprint \"The minimum is\",MIN(x,y)", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "The minimum is 10\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 22.2, Page Number: 551<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implement a function-like macro'''\n#Since macros is implemented here using functions,\n#it wont give a wrong answer.\n\ndef EVEN(a):\n if a%2==0:\n return 1\n else:\n return 0\n\nif EVEN(9+1):\n print \"is even\"\nelse:\n print \"is odd\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "is even\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 22.3, Page Number: 551<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implement a function-like macro'''\n\ndef EVEN(a):\n if a%2==0:\n return 1\n else:\n return 0\n\nif EVEN(9+1):\n print \"is even\"\nelse:\n print \"is odd\"", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "is even\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 22.4, Page Number: 553<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Impementing #if'''\n\ndef MAX():\n return 100\n\nif MAX()>10:\n print \"Extra memory required.\"\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Extra memory required.\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 22.5, Page Number: 554<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Impementing #if/#else'''\n\ndef MAX():\n return 6\n\nif MAX()>10:\n print \"Extra memory required.\"\nelse:\n print \"Current memory OK.\"\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Current memory OK.\n" + } + ], + "prompt_number": 7 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 22.6, Page Number: 556<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of #ifdef and #ifndef'''\n\ndef TOM():\n pass\n\n\ntry:\n TOM()\nexcept NameError:\n print \"Programmer is unknown.\"\nelse:\n print \"Programmer is Tom.\"\n \ntry:\n RALPH()\nexcept NameError:\n print \"RALPH not defined.\"\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Programmer is Tom.\nRALPH not defined.\n" + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 22.7, Page Number: 558<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implement __LINE__ '''\n\nimport inspect\n\n#Returns the current line number in our program.\ndef lineno():\n return inspect.currentframe().f_back.f_lineno\n \nprint lineno()+200\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "209\n" + } + ], + "prompt_number": 9 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 22.8, Page Number: 559<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implemention # operator'''\n\ndef mkstr(s):\n return str(s)\n\n#Result\nprint mkstr('I like C++')\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "I like C++\n" + } + ], + "prompt_number": 10 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 22.9, Page Number: 560<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implemention # operator'''\n\ndef concat(a,b):\n return a+b\n#Variable declaration\nxy=10\n\n#Result\nexec(\"print %s\")%concat('x','y')", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10\n" + } + ], + "prompt_number": 11 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_3(1).ipynb b/C++_from_the_Ground/Chapter_3(1).ipynb new file mode 100644 index 00000000..b0b5479c --- /dev/null +++ b/C++_from_the_Ground/Chapter_3(1).ipynb @@ -0,0 +1,207 @@ +{ + "metadata": { + "name": "Chapter 3" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 3: The Basic Data Types<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 3.1, Page Number: 35<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Local Variables'''\n\ndef func():\n x=-199 #local to func\n print x #displays -199 \n \nx=10 #local to main\n\nfunc()\nprint x #displays 10\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "-199\n10\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 3.2, Page Number: 37<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Global Variables'''\n\ndef func1():\n global count\n print \"count: \",count #access global count\n func2()\n\ndef func2():\n for count in range(3): #this is local variable\n print '.',\n\n \ncount=None #global variables\n\nfor i in range(10):\n count=i*2\n func1()\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "count: 0\n. . . count: 2\n. . . count: 4\n. . . count: 6\n. . . count: 8\n. . . count: 10\n. . . count: 12\n. . . count: 14\n. . . count: 16\n. . . count: 18\n. . .\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 3.3, Page Number: 40<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Singned and Unsigned integers'''\n#Since there is no limit to values stored\n#by integers in python, the output would \n#be different from the one in C++.\n\nfrom ctypes import *\n\n#Variable declaration\nj=c_uint(60000)\ni=c_int(60000)\n\n#Result\nprint i.value,j.value", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "60000 60000\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 3.4, Page Number: 41<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to print the alphabet in reverse order'''\n\nfor letter in xrange(ord('Z'),ord('A')-1,-1):\n print chr(letter),\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Z Y X W V U T S R Q P O N M L K J I H G F E D C B A\n" + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 3.5, Page Number: 44<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate character escape sequences'''\n\n#prints a newline, a backslash and a backspace\nprint \"\\n\\\\\\b\"\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "\n\\\b\n" + } + ], + "prompt_number": 9 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 3.6, Page Number: 45<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An example that uses variable initalization'''\n\ndef total(x):\n sum=0\n for i in xrange(1,x+1):\n sum=sum+i\n for count in range(10):\n print '-',\n print \"The current sum is\",sum\n \nprint \"Computing summation of 5.\"\ntotal(5)\n\nprint \"Computing summation of 6.\"\ntotal(6)", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Computing summation of 5.\n- - - - - - - - - - The current sum is 1\n- - - - - - - - - - The current sum is 3\n- - - - - - - - - - The current sum is 6\n- - - - - - - - - - The current sum is 10\n- - - - - - - - - - The current sum is 15\nComputing summation of 6.\n- - - - - - - - - - The current sum is 1\n- - - - - - - - - - The current sum is 3\n- - - - - - - - - - The current sum is 6\n- - - - - - - - - - The current sum is 10\n- - - - - - - - - - The current sum is 15\n- - - - - - - - - - The current sum is 21\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 3.7, Page Number: 47<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate arithmetic operations'''\n\n#Variable declaration\nx=10\ny=3\n\nprint x/y #will display 3\nprint x%y #will display1, the remainder\n\nx=1\ny=2\n\n#Result\nprint x/y,x%y #will display 0 1", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "3\n1\n0 1\n" + } + ], + "prompt_number": 11 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 3.8, Page Number: 51<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate the xor function'''\n\n#the xor function\ndef xor(a,b):\n return (a or b)and(not(a and b))\n\n#User-input\nprint \"Enter P(0 or 1):\"\np=1 \nprint \"Enter Q(0 or 1):\"\nq=0\n\n#Result\nprint \"P AND Q:\",(p and q)\nprint \"P OR Q:\",(p or q)\nprint \"P XOR Q:\",xor(p,q)\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Enter P(0 or 1):\nEnter Q(0 or 1):\nP AND Q: 0\nP OR Q: 1\nP XOR Q: True\n" + } + ], + "prompt_number": 12 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 3.9, Page Number: 54<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate casting'''\n\nfor i in xrange(1,100+1):\n print i,\"/ 2 is:\",float(i)/2\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1 / 2 is: 0.5\n2 / 2 is: 1.0\n3 / 2 is: 1.5\n4 / 2 is: 2.0\n5 / 2 is: 2.5\n6 / 2 is: 3.0\n7 / 2 is: 3.5\n8 / 2 is: 4.0\n9 / 2 is: 4.5\n10 / 2 is: 5.0\n11 / 2 is: 5.5\n12 / 2 is: 6.0\n13 / 2 is: 6.5\n14 / 2 is: 7.0\n15 / 2 is: 7.5\n16 / 2 is: 8.0\n17 / 2 is: 8.5\n18 / 2 is: 9.0\n19 / 2 is: 9.5\n20 / 2 is: 10.0\n21 / 2 is: 10.5\n22 / 2 is: 11.0\n23 / 2 is: 11.5\n24 / 2 is: 12.0\n25 / 2 is: 12.5\n26 / 2 is: 13.0\n27 / 2 is: 13.5\n28 / 2 is: 14.0\n29 / 2 is: 14.5\n30 / 2 is: 15.0\n31 / 2 is: 15.5\n32 / 2 is: 16.0\n33 / 2 is: 16.5\n34 / 2 is: 17.0\n35 / 2 is: 17.5\n36 / 2 is: 18.0\n37 / 2 is: 18.5\n38 / 2 is: 19.0\n39 / 2 is: 19.5\n40 / 2 is: 20.0\n41 / 2 is: 20.5\n42 / 2 is: 21.0\n43 / 2 is: 21.5\n44 / 2 is: 22.0\n45 / 2 is: 22.5\n46 / 2 is: 23.0\n47 / 2 is: 23.5\n48 / 2 is: 24.0\n49 / 2 is: 24.5\n50 / 2 is: 25.0\n51 / 2 is: 25.5\n52 / 2 is: 26.0\n53 / 2 is: 26.5\n54 / 2 is: 27.0\n55 / 2 is: 27.5\n56 / 2 is: 28.0\n57 / 2 is: 28.5\n58 / 2 is: 29.0\n59 / 2 is: 29.5\n60 / 2 is: 30.0\n61 / 2 is: 30.5\n62 / 2 is: 31.0\n63 / 2 is: 31.5\n64 / 2 is: 32.0\n65 / 2 is: 32.5\n66 / 2 is: 33.0\n67 / 2 is: 33.5\n68 / 2 is: 34.0\n69 / 2 is: 34.5\n70 / 2 is: 35.0\n71 / 2 is: 35.5\n72 / 2 is: 36.0\n73 / 2 is: 36.5\n74 / 2 is: 37.0\n75 / 2 is: 37.5\n76 / 2 is: 38.0\n77 / 2 is: 38.5\n78 / 2 is: 39.0\n79 / 2 is: 39.5\n80 / 2 is: 40.0\n81 / 2 is: 40.5\n82 / 2 is: 41.0\n83 / 2 is: 41.5\n84 / 2 is: 42.0\n85 / 2 is: 42.5\n86 / 2 is: 43.0\n87 / 2 is: 43.5\n88 / 2 is: 44.0\n89 / 2 is: 44.5\n90 / 2 is: 45.0\n91 / 2 is: 45.5\n92 / 2 is: 46.0\n93 / 2 is: 46.5\n94 / 2 is: 47.0\n95 / 2 is: 47.5\n96 / 2 is: 48.0\n97 / 2 is: 48.5\n98 / 2 is: 49.0\n99 / 2 is: 49.5\n100 / 2 is: 50.0\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_4(1).ipynb b/C++_from_the_Ground/Chapter_4(1).ipynb new file mode 100644 index 00000000..5bc3dfe7 --- /dev/null +++ b/C++_from_the_Ground/Chapter_4(1).ipynb @@ -0,0 +1,399 @@ +{ + "metadata": { + "name": "Chapter 4" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 4: Program Control Statements<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.1, Page Number: 58<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Magic Number Program'''\n\nimport random\n\n#Variable declaration and initialization\nmagic = random.randint(0,100) #Number which the user has to guess\nguess = 10 #Number which the user guesses\n\nif guess == magic:\n print \"***Right***\" #Result\n\n\n \n\n", + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 10 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.2, Page Number: 59<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Magic Number program: 1st improvement'''\n\nimport random\n\n#Variable decleration and initialization\nmagic=random.randint(0,100) #Number to be guessed\nguess = 10 #Number the user guesses\n\n#Result\nif guess == magic:\n print \"***Right***\"\nelse:\n print \"... Sorry, you're wrong.\"\n\n\n\n \n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "... Sorry, you're wrong.\n" + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.3, Page Number: 60<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''#Divide the first number by the second.'''\n\n#Variable decleration and initialization\na = 30 #User input for the two nos.\nb = 10\n\n#Calculation and Result\nif b:\n print a/b\nelse:\n print \"Cannot divide by zero.\"\n\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "3\n" + } + ], + "prompt_number": 11 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.4, Page Number: 61<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Magic Number Program: 2nd improvement'''\n\nimport random\n\n#Variable decleration \nmagic = random.randint(0,100) #Numbr to be guessed\nguess = 10 #Number the user guesses\n\n#Result\nif guess == magic:\n print \"***Right***\"\n print magic,\" is the magic number.\"\nelse:\n print \"... Sorry, you're wrong\" \n if(guess>magic): #use a nested if statement\n print \"Your guess is too high\"\n else:\n print \"Your guess is too low\"\n\n \n \n\n \n \n", + "language": "python", + "metadata": {}, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.5, Page Number: 62<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Demonstrate an if-else-if ladder'''\n\nfor x in range(6):\n if x==1: #using if-else ladder in a for loop\n print \"x is one\"\n elif x==2:\n print \"x is two\"\n elif x==3:\n print \"x is three\"\n elif x==4:\n print \"x is four\"\n else:\n print \"x is not between 1 nd 4\"\n \n \n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "x is not between 1 nd 4\nx is one\nx is two\nx is three\nx is four\nx is not between 1 nd 4\n" + } + ], + "prompt_number": 13 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.6, Page Number: 63<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''For loop demonstration'''\n\nimport math\n\nfor num in range(100):\n sq_root = math.sqrt(float(num)) #Calculation\n print num,\" \",sq_root #Result\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "0 0.0\n1 1.0\n2 1.41421356237\n3 1.73205080757\n4 2.0\n5 2.2360679775\n6 2.44948974278\n7 2.64575131106\n8 2.82842712475\n9 3.0\n10 3.16227766017\n11 3.31662479036\n12 3.46410161514\n13 3.60555127546\n14 3.74165738677\n15 3.87298334621\n16 4.0\n17 4.12310562562\n18 4.24264068712\n19 4.35889894354\n20 4.472135955\n21 4.58257569496\n22 4.69041575982\n23 4.79583152331\n24 4.89897948557\n25 5.0\n26 5.09901951359\n27 5.19615242271\n28 5.29150262213\n29 5.38516480713\n30 5.47722557505\n31 5.56776436283\n32 5.65685424949\n33 5.74456264654\n34 5.83095189485\n35 5.9160797831\n36 6.0\n37 6.0827625303\n38 6.16441400297\n39 6.2449979984\n40 6.32455532034\n41 6.40312423743\n42 6.48074069841\n43 6.5574385243\n44 6.63324958071\n45 6.7082039325\n46 6.78232998313\n47 6.8556546004\n48 6.92820323028\n49 7.0\n50 7.07106781187\n51 7.14142842854\n52 7.21110255093\n53 7.28010988928\n54 7.34846922835\n55 7.4161984871\n56 7.48331477355\n57 7.54983443527\n58 7.61577310586\n59 7.68114574787\n60 7.74596669241\n61 7.81024967591\n62 7.87400787401\n63 7.93725393319\n64 8.0\n65 8.0622577483\n66 8.12403840464\n67 8.18535277187\n68 8.24621125124\n69 8.30662386292\n70 8.36660026534\n71 8.42614977318\n72 8.48528137424\n73 8.54400374532\n74 8.60232526704\n75 8.66025403784\n76 8.71779788708\n77 8.77496438739\n78 8.83176086633\n79 8.88819441732\n80 8.94427191\n81 9.0\n82 9.05538513814\n83 9.11043357914\n84 9.16515138991\n85 9.21954445729\n86 9.2736184955\n87 9.32737905309\n88 9.38083151965\n89 9.43398113206\n90 9.48683298051\n91 9.53939201417\n92 9.59166304663\n93 9.64365076099\n94 9.69535971483\n95 9.74679434481\n96 9.79795897113\n97 9.8488578018\n98 9.89949493661\n99 9.94987437107\n" + } + ], + "prompt_number": 14 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.7, Page Number: 64<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Printin numbers 100 to -100 in decrements of 5'''\n\nfor i in xrange(100,-100,-5): \n print i,\n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "100 95 90 85 80 75 70 65 60 55 50 45 40 35 30 25 20 15 10 5 0 -5 -10 -15 -20 -25 -30 -35 -40 -45 -50 -55 -60 -65 -70 -75 -80 -85 -90 -95\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.8, Page Number: 66<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Runs a loop till 123 is typed'''\n\n#Variable decleration\nx=0\n\n#Loop till 123 is entered\nwhile x!=123:\n print \"Enter a number: \"\n x = 123\n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Enter a number: \n" + } + ], + "prompt_number": 11 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.9, Page Number: 68<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Demonstrate switch usig \"help\" program'''\n\n#Displaying the menu\nprint \"Help on:\"\nprint \"1. for\"\nprint \"2. if\"\nprint \"3. while\"\n\n\nchoice = 2 #Choice of user\n\nif choice==1: #Executing users choice with if-else\n print \"for is c++'s most versatile loop.\"\nelif choice==2:\n print \"if is c++'s conditional branch statement.\"\nelif choice==3:\n print \"switch is C++'s multiway branch statement. \"\nelse:\n print \"You must enter a number between 1 and 3.\"\n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Help on:\n1. for\n2. if\n3. while\nif is c++'s conditional branch statement.\n" + } + ], + "prompt_number": 19 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.10, Page Number: 69<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing the switch statement'''\n#If switch without break is used(as in the book), \n#it gives a different output(Fall through).'''\n\nfor i in range(5):\n if i==0:\n print \"less than 1\"\n elif i==1:\n print \"less than 2\"\n elif i==2:\n print \"less than 3\"\n elif i==3:\n print \"less than 4\"\n elif i==4:\n print \"less than 5\"\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "less than 1\nless than 2\nless than 3\nless than 4\nless than 5\n" + } + ], + "prompt_number": 20 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.11, Page Number: 71<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Displays all printable characters.'''\n\n#Variable decleration\nch = 32\n\n#Loop to print the characters\nfor ch in range(128):\n print chr(ch)\n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "\u0000\n\u0001\n\u0002\n\u0003\n\u0004\n\u0005\n\u0006\n\u0007\n\b\n\t\n\n\n\u000b\n\f\n\r\n\u000e\n\u000f\n\u0010\n\u0011\n\u0012\n\u0013\n\u0014\n\u0015\n\u0016\n\u0017\n\u0018\n\u0019\n\u001a\n\u001b\n\u001c\n\u001d\n\u001e\n\u001f\n \n!\n\"\n#\n$\n%\n&\n'\n(\n)\n*\n+\n,\n-\n.\n/\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n:\n;\n<\n=\n>\n?\n@\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\nU\nV\nW\nX\nY\nZ\n[\n\\\n]\n^\n_\n`\na\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np\nq\nr\ns\nt\nu\nv\nw\nx\ny\nz\n{\n|\n}\n~\n\u007f\n" + } + ], + "prompt_number": 21 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.12, Page Number: 72<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Example for while loop'''\n\n#Variable decleration\nlen = 5\n\nwhile (len>0 & len<80):\n print \".\"\n len-=1\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": ".\n.\n.\n.\n.\n" + } + ], + "prompt_number": 22 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.13, Page Number: 73<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to loop till number 100 is entered'''\n\n#Variable Declaration\nnum=95\n\nwhile True:\n print \"Enter a number(100 to stop): \"\n num+=1 #User input, incrementing num till it reaches 100\n if(num==100): #Condition check to stop loop\n break\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Enter a number(100 to stop): \nEnter a number(100 to stop): \nEnter a number(100 to stop): \nEnter a number(100 to stop): \nEnter a number(100 to stop): \n" + } + ], + "prompt_number": 9 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.14, Page Number: 73<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Magic Number program: 3rd improvement.'''\n\nimport random\n\n#Variable decleration\nmagic = random.randint(0,100) #Number which the user has to guess\nlow=0\nhigh=100\n\n#Play thr magic number game\nwhile True:\n guess = random.randint(low,high) #Number which the user guesses\n if guess==magic: \n print \"**Right**\"\n print magic,\" is the magic number.\"\n break\n else:\n print \"...Sorry, you're wrong.\"\n if(guess>magic):\n print \"Your guess is too high.\"\n high=guess\n else:\n print \"Your guess is too low.\"\n low=guess\n \n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "...Sorry, you're wrong.\nYour guess is too low.\n...Sorry, you're wrong.\nYour guess is too high.\n...Sorry, you're wrong.\nYour guess is too low.\n...Sorry, you're wrong.\nYour guess is too high.\n...Sorry, you're wrong.\nYour guess is too low.\n...Sorry, you're wrong.\nYour guess is too high.\n...Sorry, you're wrong.\nYour guess is too low.\n...Sorry, you're wrong.\nYour guess is too high.\n...Sorry, you're wrong.\nYour guess is too low.\n...Sorry, you're wrong.\nYour guess is too low.\n...Sorry, you're wrong.\nYour guess is too high.\n...Sorry, you're wrong.\nYour guess is too high.\n...Sorry, you're wrong.\nYour guess is too high.\n...Sorry, you're wrong.\nYour guess is too low.\n**Right**\n72 is the magic number.\n" + } + ], + "prompt_number": 26 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.15, Page Number: 74<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Example for continue statement'''\n\nfor x in range(100+1):\n if x%2: #Condition check to continue the loop\n continue\n print x,\n \n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.16, Page Number: 75<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Iterates from 0 to 9, not to 100'''\n\nfor t in range(100):\n if t==10: #Condition check to break out of the loop\n break\n print t,\n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "0 1 2 3 4 5 6 7 8 9\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.17, Page Number: 75<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An example for break'''\n\nfor t in range(100):\n count = 1 \n while True:\n print count,\n count+=1\n if count==10: \n break #Breaks from the inner loop\n print\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n1 2 3 4 5 6 7 8 9\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.18, Page Number: 76<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''This Program finds the prime nos. from 2 to 1000'''\n\nfor i in range(2,1000):\n j=2\n for j in range(2,i/j): #Nested for loop\n if i%j == False: #Check for prime no.\n break\n if j>(i/j):\n print i,\" is prime.\" #Result\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "2 is prime.\n3 is prime.\n11 is prime.\n13 is prime.\n17 is prime.\n19 is prime.\n23 is prime.\n29 is prime.\n31 is prime.\n37 is prime.\n41 is prime.\n43 is prime.\n47 is prime.\n53 is prime.\n59 is prime.\n61 is prime.\n67 is prime.\n71 is prime.\n73 is prime.\n79 is prime.\n83 is prime.\n89 is prime.\n97 is prime.\n101 is prime.\n103 is prime.\n107 is prime.\n109 is prime.\n113 is prime.\n127 is prime.\n131 is prime.\n137 is prime.\n139 is prime.\n149 is prime.\n151 is prime.\n157 is prime.\n163 is prime.\n167 is prime.\n173 is prime.\n179 is prime.\n181 is prime.\n191 is prime.\n193 is prime.\n197 is prime.\n199 is prime.\n211 is prime.\n223 is prime.\n227 is prime.\n229 is prime.\n233 is prime.\n239 is prime.\n241 is prime.\n251 is prime.\n257 is prime.\n263 is prime.\n269 is prime.\n271 is prime.\n277 is prime.\n281 is prime.\n283 is prime.\n293 is prime.\n307 is prime.\n311 is prime.\n313 is prime.\n317 is prime.\n331 is prime.\n337 is prime.\n347 is prime.\n349 is prime.\n353 is prime.\n359 is prime.\n367 is prime.\n373 is prime.\n379 is prime.\n383 is prime.\n389 is prime.\n397 is prime.\n401 is prime.\n409 is prime.\n419 is prime.\n421 is prime.\n431 is prime.\n433 is prime.\n439 is prime.\n443 is prime.\n449 is prime.\n457 is prime.\n461 is prime.\n463 is prime.\n467 is prime.\n479 is prime.\n487 is prime.\n491 is prime.\n499 is prime.\n503 is prime.\n509 is prime.\n521 is prime.\n523 is prime.\n541 is prime.\n547 is prime.\n557 is prime.\n563 is prime.\n569 is prime.\n571 is prime.\n577 is prime.\n587 is prime.\n593 is prime.\n599 is prime.\n601 is prime.\n607 is prime.\n613 is prime.\n617 is prime.\n619 is prime.\n631 is prime.\n641 is prime.\n643 is prime.\n647 is prime.\n653 is prime.\n659 is prime.\n661 is prime.\n673 is prime.\n677 is prime.\n683 is prime.\n691 is prime.\n701 is prime.\n709 is prime.\n719 is prime.\n727 is prime.\n733 is prime.\n739 is prime.\n743 is prime.\n751 is prime.\n757 is prime.\n761 is prime.\n769 is prime.\n773 is prime.\n787 is prime.\n797 is prime.\n809 is prime.\n811 is prime.\n821 is prime.\n823 is prime.\n827 is prime.\n829 is prime.\n839 is prime.\n853 is prime.\n857 is prime.\n859 is prime.\n863 is prime.\n877" + }, + { + "output_type": "stream", + "stream": "stdout", + "text": " is prime.\n881 is prime.\n883 is prime.\n887 is prime.\n907 is prime.\n911 is prime.\n919 is prime.\n929 is prime.\n937 is prime.\n941 is prime.\n947 is prime.\n953 is prime.\n967 is prime.\n971 is prime.\n977 is prime.\n983 is prime.\n991 is prime.\n997 is prime.\n" + } + ], + "prompt_number": 30 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 4.19, Page Number: 78<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Magic Number program: Final improvement'''\n\nimport random\n\n#Variable declaration\nmagic = random.randint(0,100) #Number to be guessed\ni=1\nhigh=100\nlow=0\n\n#Function to play the magic number game\ndef play(m):\n low=0\n high=100\n for t in range(100):\n x = random.randint(low,high) #Number guessed by the user\n if x==m:\n print \"***Right***\"\n return\n else:\n if(x<m):\n print \"Too low.\"\n low=x\n else:\n print \"Too high.\"\n high=x\n print \"You've used up all your guesses\" \n\n#Menu\nwhile True:\n print \"1.Get a new magic number.\" \n print \"2.Play\"\n print \"3.Quit\"\n while True:\n option = i \n if option>=1 and option<=3:\n break\n if option==1:\n magic=random.randint(0,100) #Number to be guessed\n elif option==2:\n play(magic) #Calls the function play\n elif option==3:\n print \"Goodbye\" \n break\n i+=1 #increments i such that the 3 options get selected sequentially\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1.Get a new magic number.\n2.Play\n3.Quit\n1.Get a new magic number.\n2.Play\n3.Quit\nToo low.\nToo low.\nToo low.\nToo low.\nToo high.\nToo low.\nToo high.\nToo low.\nToo high.\nToo high.\nToo high.\nToo high.\nToo low.\n***Right***\n1.Get a new magic number.\n2.Play\n3.Quit\nGoodbye\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_5(1).ipynb b/C++_from_the_Ground/Chapter_5(1).ipynb new file mode 100644 index 00000000..4ae8f6f6 --- /dev/null +++ b/C++_from_the_Ground/Chapter_5(1).ipynb @@ -0,0 +1,668 @@ +{ + "metadata": { + "name": "Chapter 5" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 5: Arrays ans Strings<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.1, Page Number: 82<h3>\n " + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Loads sample with the numbers 0 to 9'''\n\n#Variable declaration\nsample = range(10) #Declares an array [0,1,2,3,4,5,6,7,8,9]\n\n#Displays the array\nfor t in range(10):\n print sample[t],\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "0 1 2 3 4 5 6 7 8 9\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.2, Page Number: 83<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Maximum and Minimum value from a list'''\n\nimport random\n\n#Variable declaration\nlist = [] #List of integers\n\nfor i in range(10):\n list.append(random.randint(0,1000)) #randomely assigning integers\n \n#Finding the minimum value\nmin_value = list[0]\n\nfor i in range(10):\n if min_value>list[i]:\n min_value=list[i]\nprint \"minimum value: \",min_value #Result:Minimum value\n\n#Finding maximum value\nmax_value = list[0]\n\nfor i in range(10):\n if max_value<list[i]:\n max_value=list[i]\nprint \"maximum value: \",max_value #Result:Maximum value\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "minimum value: 192\nmaximum value: 684\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.3, Page Number: 85<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Bubble Sort'''\n\nimport random\n\n#Variable declaration\nnums = []\nsize = 10\n\n#Initializing list with random numbers\nfor t in range(size):\n nums.append(random.randint(0,1000))\n\n#Displays original array\nprint \"Original array is: \"\nprint nums\n\n#Bubble Sort\nfor a in range(size):\n for b in xrange(size-1,a,-1):\n if nums[b-1]>nums[b]:\n t=nums[b-1]\n nums[b-1]=nums[b]\n nums[b] = t\n\n#Display sorted array\nprint \"Sorted array is: \"\nprint nums\n\n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Original array is: \n[388, 661, 218, 595, 167, 46, 704, 140, 559, 428]\nSorted array is: \n[46, 140, 167, 218, 388, 428, 559, 595, 661, 704]\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.4, Page Number: 87<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Example for a string; Implementing cin and cout'''\n\n#Variable decleration\nstr = \"Hello\"\n\n#Result\nprint \"Here is your string:\",\nprint str\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Here is your string: Hello\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.5, Page Number: 88<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Example for a string; Implementing gets for input'''\n\nprint \"Enter a string: \"\n\n#user input\nstr = \"Hello\"\n\n#Result\nprint \"Here is your string:\",\nprint str\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Enter a string: \nHere is your string: Hello\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.6, Page Number: 89<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Implementing strcpy'''\n\n#Variable decleration\ns=str\nstr = s #copying s into str\n\n#Result\nprint str\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Hello\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.7, Page Number: 89<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Example for concatenation'''\n\n#Variable decleration\ns1 = \"Hello\"\ns2 = \" There\"\n\n#Concatenation\ns1+=s2\n\n#Result\nprint s1\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Hello There\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.8, Page Number: 90<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n#Example for string compare: Password verification\n\n#Function for password verification\ndef password():\n print \"Enter password: \" #User input for password\n s= \"pass\"\n if s==\"password\":\n return True\n else:\n print \"Invalid password.\"\n return False\n\n#Result\nif password() :\n print \"Logged On.\"\nelse:\n print \"Access denied\"\n \n \n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Enter password: \nInvalid password.\nAccess denied\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.9, Page Number: 91<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Takes user input till strings match'''\n\nwhile True:\n s=raw_input(\"Enter a string: \") #User input of string;\n if s==\"quit\": #Sting comparison\n break\n \n \n\n \n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter a string: ddc\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter a string: hello\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter a string: quit\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.10, Page Number: 91<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''String length; Implementing strlen'''\n\n#Variable declaration\nstr = \"Hello\"\n\n#Result\nprint \"Length is: \",len(str)\n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Length is: 5\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.11, Page Number: 92<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Print a string backwards.'''\n\n#Taking a user input string\nstr = \"Hello World\"\n\n#Reversing a String\nrev = str[::-1]\n\n#Result\nprint rev\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "dlroW olleH\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.12, Page Number: 92<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "\n'''Illustrating string functions'''\n\n#Variable declaration\ns1 = \"Hello\"\ns2 = \"there\"\n\n#Printing lengths\nprint \"lengths: \",len(s1),' ',len(s2)\n\n#Comparing\nif(s1==s2):\n print \"The strings are equal\"\nelse:\n print \"not equal\"\n\n#Concatenation\ns1+=s2\nprint s1\n\n\n#Copying\ns1=s2\n\n#Result\nprint s1,\"and\",s2,\" are now the same\"\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "lengths: 5 5\nnot equal\nHellothere\nthere and there are now the same\n" + } + ], + "prompt_number": 9 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.13, Page Number: 93<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Convert a string to upper case'''\n\nimport string\n\n#Variable Initialization\nstr= \"this is a test\"\n\nstr=string.upper(str)\n\n#Result\nprint str\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "THIS IS A TEST\n" + } + ], + "prompt_number": 12 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.14, Page Number: 94<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Load a two-dimensional array with values 1-12'''\n\n#Variable Initialization\narr=[] #The 2-D list\nnew=[] #The nested list\n\n#Initializing the 2-D array\nfor i in range(3):\n new=[]\n for j in range(4):\n new.append(i*4+j+1)\n arr.append(new)\n\n#Result\nfor i in range(3):\n for j in range(4):\n print arr[i][j],\n print", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1 2 3 4\n5 6 7 8\n9 10 11 12\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.15, Page Number: 98<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Looks up a no. in an array n prints the corresponding square'''\n\n#Variabe Initialzation\nsqrs= [[1,1],[2,4],[3,9],[4,16],[5,25],\n [6,36],[7,49],[8,64],[9,81],[10,100]] #Array storing the squares\ni=6 #User input of number whose square is to be looked up\n\n#Search for the number\nfor j in range(10):\n if sqrs[j][0]==i:\n break\n \n#Result\nprint \"The square of \",i,\" is \", sqrs[j][1]", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "The square of 6 is 36\n" + } + ], + "prompt_number": 15 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.16, Page Number: 99<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstating how local strings are initialized each time they are called'''\n\ndef f1():\n s=\"this is a test\" #initial s\n print s\n s=\"CHANGED\" #s is now changed \n print s\n\n#Calling the function twice\nf1()\nf1()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "this is a test\nCHANGED\nthis is a test\nCHANGED\n" + } + ], + "prompt_number": 17 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.17, Page Number: 101<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Enter and display strings'''\n\n#Variable decleration\ntext=[]\nstr=['eat','play','work'] #user input of strings\np=len(str)\n\nfor t in range(p):\n print t,\":\"\n text.append(str[t]) #Here, user input taken from the list\n \n#Result; redisplay the strings\nfor i in range(p):\n print text[i]\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "0 :\n1 :\n2 :\neat\nplay\nwork\n" + } + ], + "prompt_number": 18 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 5.18, Page Number: 103<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A simple employee database program'''\nimport random \n\n#Variable decleration\nname=[] #this list holds employee names\nwage=[] #their phone numbers\nphone=[] #hours worked per week\nhours=[] #wage\nnum=0 #User choice\n\n#Menu \ndef menu():\n global num #All options are chosen one by one\n print \"0.Quit.\"\n print \"1.Enter information\"\n print \"2.Report information\"\n print \"Choose one: \"\n num=int(input())\n return num #Return users selction\n\n#Enter information\ndef enter():\n for i in range(10):\n n=raw_input(\"Enter your name: \")\n name.append(n)\n phone.append(int(input(\"Enter your phone number\")))\n hours.append(int(input(\"Enter number of hours worked: \")))\n wage.append(int(input(\"Enter wage: \")))\n\n#Display report\ndef report():\n p=len(name)\n for i in range(p):\n print name[i],' ',phone[i]\n print \"Pay for the week: \",wage[i]*hours[i]\n\n\nwhile True:\n ch=menu() #get selection\n if ch==0:\n break\n elif ch==1:\n enter()\n elif ch==2:\n report()\n else:\n print \"Try again.\"\n if ch==0:\n break\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "0.Quit.\n1.Enter information\n2.Report information\nChoose one: \n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "1\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your name: Anny\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your phone number987654321\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter number of hours worked: 10\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter wage: 50\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your name: Billy\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your phone number9456783652\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter number of hours worked: 10\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter wage: 50\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your name: Catherene\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your phone number9476836578\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter number of hours worked: 10\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter wage: 50\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your name: Dolly\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your phone number9831356748\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter number of hours worked: 15\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter wage: 50\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your name: Emily\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your phone number9576843721\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter number of hours worked: 15\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter wage: 40\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your name: Jack\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your phone number9485738567\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter number of hours worked: 10\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter wage: 45\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your name: Kevin\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your phone number9345678923\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter number of hours worked: 10\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter wage: 45\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your name: Lily\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your phone number9345672831\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter number of hours worked: 10\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter wage: 45\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your name: Monica\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your phone number9475867483\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter number of hours worked: 10\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter wage: 50\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your name: Irene\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter your phone number5674356776\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter number of hours worked: 10\n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "Enter wage: 20\n" + }, + { + "output_type": "stream", + "stream": "stdout", + "text": "0.Quit.\n1.Enter information\n2.Report information\nChoose one: \n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "2\n" + }, + { + "output_type": "stream", + "stream": "stdout", + "text": "Anny 987654321\nPay for the week: 500\nBilly 9456783652\nPay for the week: 500\nCatherene 9476836578\nPay for the week: 500\nDolly 9831356748\nPay for the week: 750\nEmily 9576843721\nPay for the week: 600\nJack 9485738567\nPay for the week: 450\nKevin 9345678923\nPay for the week: 450\nLily 9345672831\nPay for the week: 450\nMonica 9475867483\nPay for the week: 500\nIrene 5674356776\nPay for the week: 200\n0.Quit.\n1.Enter information\n2.Report information\nChoose one: \n" + }, + { + "name": "stdout", + "output_type": "stream", + "stream": "stdout", + "text": "0\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_6(1).ipynb b/C++_from_the_Ground/Chapter_6(1).ipynb new file mode 100644 index 00000000..052075ed --- /dev/null +++ b/C++_from_the_Ground/Chapter_6(1).ipynb @@ -0,0 +1,287 @@ +{ + "metadata": { + "name": "Chapter 6" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 6: Pointers<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 6.1, Page Number: 107<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing pointers in python'''\n\nfrom ctypes import *\n\nbalance =c_int(3200) #int variable\nbalptr=pointer(balance) #pointer to int\nvalue=balptr[0] #accessing the value using the pointer\n\n#Result\nprint \"balance: \",value \n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "balance: 3200\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 6.2, Page Number: 109<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''This program will not create the problem as in C++ since \n python does'nt have specific data types'''\n\n#Variable declaration\nx=123.23\ny=c_double()\np=POINTER(c_int)\n\np=pointer(c_int(int(x))) #type case double to int\ny=p[0]\n\n#Result\nprint y", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "123\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 6.3, Page Number: 110<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate usage of pointers'''\n\nfrom ctypes import *\n\n#Variable declaration\nnum=c_int() #declaring int\np=pointer(num) #pointer to int\n\np[0]=100\nprint num.value,\np[0]+=1\nprint num.value,\np[0]-=1\nprint num.value", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "100 101 100\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 6.4, Page Number: 111<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate pointer arithmetic'''\n\nfrom ctypes import *\n\n#Variable declaration\nj=c_int()\ng=c_double()\ni=pointer(j)\nf=pointer(g)\n\n\nfor x in range(10):\n print addressof(i.contents)+x,addressof(f.contents)+x\n \n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "84638480 84639248\n84638481 84639249\n84638482 84639250\n84638483 84639251\n84638484 84639252\n84638485 84639253\n84638486 84639254\n84638487 84639255\n84638488 84639256\n84638489 84639257\n" + } + ], + "prompt_number": 10 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 6.5, Page Number: 114<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Tokenizing program: pointer verion'''\n\nfrom ctypes import *\n\n#Variable declaration\nstr=\"This is a test\"\ntoken =\"\"\ni=0\n\n#Read a token at a time from the string\nwhile i<len(str):\n token=c_char_p(\"\") #set token to null string\n q=pointer(token) \n #Read characters until either a space or the null terminator is encountered'''\n while i<len(str) and not(str[i]==\" \"):\n q[0]+=str[i]\n i+=1\n i+=1 #advance past the space\n print q[0]", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "This\nis\na\ntest\n" + } + ], + "prompt_number": 12 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 6.6, Page Number: 115<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Tokenizing program: array-indexing verion'''\n\n#Variable declaration\nstr=\"This is a test\"\ni=0\n\n#Read a token at a time from the string\nwhile i<len(str):\n token=\"\" #set q to null string\n #Read characters until either a space or the null terminator is encountered'''\n while i<len(str) and not(str[i]==\" \"):\n token+=str[i]\n i+=1\n i+=1 #advance past the space\n print token", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "This\nis\na\ntest\n" + } + ], + "prompt_number": 14 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 6.7, Page Number: 115<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Converting to uppercase using pointer indexing'''\n\nimport string\n\nstr=c_char_p(\"hello tom\")\nq=\"\"\np=pointer(str) #put address of str into p\n \np[0]=string.upper(p[0])\n\n#Result\nprint p[0]", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "HELLO TOM\n" + } + ], + "prompt_number": 15 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 6.8, Page Number: 117<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Pointers and string literals'''\n\n#Varible declaration\ns=\"Pointers are fun to use\"\n\n#Result\nprint s\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Pointers are fun to use\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 6.9, Page Number: 118<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An example of pointers and arrays'''\n\nfrom ctypes import *\n\n#Variable declaration\nnum=[]\n\n#User input\nfor i in range(10):\n num.append(i)\n \nstart=num #set start to the starting pointer \nfor i in range(10):\n print start[i],\n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "0 1 2 3 4 5 6 7 8 9\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 6.10, Page Number: 119<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A fortune cookie program'''\n\nimport random\n\nfortunes=[\"Soon, you will come into some money.\",\n \"A new love will enter your lifr. \",\n \"You will live long and prosper.\",\n \"Now is a good time to invest for the future.\",\n \"A close friend will ask for a favour.\"]\n\nprint \"To see your fortune, press a key: \"\n\n#Randomize the random number generator\nchance=random.randint(0,100)\nchance=chance%5\n\n#Result\nprint fortunes[chance]", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "To see your fortune, press a key: \nA close friend will ask for a favour.\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 6.11, Page Number: 120<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A simple C++ keyword synopsis program'''\n\nkeyword=[[\"for\",\"for(initialization; condition; increment\"],\n [\"if\",\"if(condition) ... else ...\"],\n [\"switch\",\"switch(value) { case-list }\"],\n [\"while\",\"while(condition) ...\"],\n [\"\",\"\"]] #Terminates the list with nulls\n \n#User input \nprint \"Enter keyword: \"\nstr=\"for\" \n\nfor i in range(4):\n if str==keyword[i][0]:\n print keyword[i][1]\n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Enter keyword: \nfor(initialization; condition; increment\n" + } + ], + "prompt_number": 7 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 6.12, Page Number: 123<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate multiple indirection'''\n\nfrom ctypes import *\n\n#Variable declaration\nx=c_int(10) #int variable\np=pointer(x) #pointer to int\nq=pointer(p) #pointer to a pointer\n\n#Result\nprint q[0][0] #accessing the value using a pointer to a pointer\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 6.13, Page Number: 126<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Print ASCII value of each character of string using pointer'''\n\nfrom ctypes import *\n\n#Variable declaration\ns=c_char_p()\np1=pointer(s)\nx=0\n\nwhile True:\n print \"\\nEnter a string: \",\n if x==2:\n p1[0]=c_char_p(\"done\")\n else:\n p1[0]=c_char_p(\"Hello\")\n #print the ASCII values of each characcter\n for i in range(0,len(p1[0])):\n print ord(p1[0][i]),\n x+=1\n if p1[0]==\"done\":\n break\n \n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "\nEnter a string: 72 101 108 108 111 \nEnter a string: 72 101 108 108 111 \nEnter a string: 100 111 110 101\n" + } + ], + "prompt_number": 9 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_7(1).ipynb b/C++_from_the_Ground/Chapter_7(1).ipynb new file mode 100644 index 00000000..4e347f41 --- /dev/null +++ b/C++_from_the_Ground/Chapter_7(1).ipynb @@ -0,0 +1,472 @@ +{ + "metadata": { + "name": "Chapter 7" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 7: Functions,Part One: The Fundamentals<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.1, Page Number: 129<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Example of a function'''\n\ndef f1():\n print \"Enter something: \"\n str= \"Hello\" #User-input\n print str\n \n#Variable decleration\nstr=\"This is str in main\"\n\nprint str\nf1() #function call\nprint str", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "This is str in main\nEnter something: \nHello\nThis is str in main\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.2, Page Number: 130<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''This program illustrates how variables can be local to a block'''\n\n#Variable decleration\nchoice=0\n\nprint \"(1) add numbers or (2) concatenate strings?: \"\nchoice=2 #User Input taken as 2\n\nif choice==1:\n print \"Enter two numbers: \"\n a=5 #Variable decleration; User Input\n b=7\n print a+b #Result\nelse :\n print \"Enter two strings: \"\n s1=\"Hello\" #Variable decleration; User Input\n s2=\"World\"\n s1+=s2 #Concatenation\n print s1 #Result", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "(1) add numbers or (2) concatenate strings?: \nEnter two strings: \nHelloWorld\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.3, Page Number: 131<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''This program illustrates the scope of variables'''\n\n'''This program will give same output for inner and outer i's\n because pyhton doesnt consider the if statment block as a scope'''\n#Variable decleration\ni=10\nj=100\n\nif j>0:\n i=None \n i= j/2\n print \"inner i: \",i #Result\n\nprint \"outer i: \",i #Result", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "inner i: 50\nouter i: 50\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.4, Page Number: 132<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Example for declaring variables anywhere in the program'''\n\na=5 #Variable decleration; user input\n\nb=10 #declaration of another variable; user input\n\n#Result\nprint \"Product: \",a*b", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Product: 50\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.5, Page Number: 134<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A simple addition drill program.'''\n\nimport random\n\n#Variable decleration\ncount=None\nnum_right=0\n\n#Function for the drill\ndef drill():\n #Generate two numbers between 0 and 99.\n a=random.randint(0,99)\n b=random.randint(0,99)\n #The user gets three tries to get it right.\n for count in range(3):\n print \"What is \",a,\" + \",b,\"? \"\n ans = random.randint(0,200) #user input\n if ans==a+b:\n print \"Right\"\n num_right+=1\n print \"You've used up all your tries.\"\n print \"The answer is \",a+b\n \n#Main function \nprint \"How many practice problems: \"\ncount=2 #User input taken as 2\nnum_right=0\nwhile True:\n drill()\n count-=1\n if(count==0):\n break\n \n#Result\nprint \"You got \",num_right,\" right. \" \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "How many practice problems: \nWhat is 9 + 89 ? \nWhat is 9 + 89 ? \nWhat is 9 + 89 ? \nYou've used up all your tries.\nThe answer is 98\nWhat is 85 + 98 ? \nWhat is 85 + 98 ? \nWhat is 85 + 98 ? \nYou've used up all your tries.\nThe answer is 183\nYou got 0 right. \n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.6, Page Number: 136<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Pass by reference(pointer) to a function'''\n\nfrom ctypes import *\n\n#Function to change the reference value\ndef f(j):\n j[0]=100 #j is assigned 100\n\n#Variable decleration\ni=c_int(1)\np=pointer(i)\n\n#Calling the function\nf(p) \n\nprint i", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "c_long(100)\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.7, Page Number: 137<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Pass by reference(pointer) to a function'''\n\nfrom ctypes import *\n\n#Function to change the reference value\ndef f(j):\n j[0]=100 #j is assigned 100\n\n#Variable decleration\ni=c_int(1)\np=pointer(i)\n\n#Calling the function\nf(p) \n\nprint i", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "c_long(100)\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.8, Page Number: 137<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Calling function with a list(array)'''\n\n#function to print some nos.\ndef display(num):\n for i in range(10):\n print num[i],\n \n#Variable declaration\nt=[]\n\nfor i in range(10):\n t.append(i)\n#Pass list to a function\ndisplay(t)", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "0 1 2 3 4 5 6 7 8 9\n" + } + ], + "prompt_number": 7 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.9, Page Number: 138<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Displaying list without passing the list'''\n\n#Print some nos.\ndef display(num):\n print num,\n\n#Variable declaration\nt=[]\n\nfor i in range(10):\n t.append(i)\n \n#Printing without passing entire list\nfor i in range(10):\n display(t[i])", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "0 1 2 3 4 5 6 7 8 9\n" + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.10, Page Number: 139<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to convert each of the array element into its cube'''\n\n#Function to convert into cubes\ndef cube(n,num):\n num-=1\n while num:\n n[num]=n[num]*n[num]*n[num]\n num-=1\n\n#Variable declaration\nnums=[]\n\nfor i in range(10):\n nums.append(i+1)\n \nprint \"Original contents: \",\nfor i in range(10):\n print nums[i],\nprint\n\ncube(nums,10) #Compute cubes\n\n#Result\nprint \"Altered contents: \",\nfor i in range(10):\n print nums[i],", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Original contents: 1 2 3 4 5 6 7 8 9 10\nAltered contents: 1 8 27 64 125 216 343 512 729 1000\n" + } + ], + "prompt_number": 10 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.11, Page Number: 140<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to convert a string to uppercase'''\n\nimport string\n\ndef stringupper(str):\n str=string.upper(str) #convert to uppercase\n return str\n\n#Variable declaration \nstr=\"this is a test\"\n\n#Calling the function\nstr=stringupper(str)\n\n#Result\nprint str", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "THIS IS A TEST\n" + } + ], + "prompt_number": 7 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.12, Page Number: 141<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to find length of string'''\n\n#Function to fond length\ndef mystrlen(str):\n l=len(str)\n return l\n\n#Result\nprint \"Length of Hello There is: \",\nprint mystrlen(\"Hello There\")", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Length of Hello There is: 11\n" + } + ], + "prompt_number": 11 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.13, Page Number: 142<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrates how to access command line arguments.'''\n#This wont work because we cannot provide command line arguments\n\nimport sys\n\ndef main():\n if len(sys.argv)!=2:\n print \"You forgot to type your name.\" #CHECK!!!!\n return\n #Result\n print \"Hello \",sys.argv[1]\n\nmain()", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "You forgot to type your name.\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.14, Page Number: 143<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''The program prints all command line arguments '''\nimport sys\n\n#Result\nfor t in range(len(sys.argv)):\n i=0\n print sys.argv[t] ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "-c\n-f\nC:\\Users\\Anandi\\.ipython\\profile_default\\security\\kernel-6e851974-75ff-4911-bdf9-e089a03e5741.json\n--KernelApp.parent_appname='ipython-notebook'\n--interrupt=904\n--parent=876\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.15, Page Number: 144<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''This program concatenates the two string arguments and displays them'''\n\nimport sys\n\nif len(sys.argv)!=3:\n print \"usage: add num num\" \nelse :\n #Variable Decleration\n a=sys.argv[1]\n b=sys.argv[2]\n #Result\n print a+b\n \n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "usage: add num num\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.16, Page Number: 145<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An example program'''\n\nimport string\n\n#Variable Decleration\ni=string.atoi(\"100\")\nj=string.atoi(\"100000\")\nk=string.atof(\"-0.123\")\n\n#Result\nprint i,\" \",j,\" \",k", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "100 100000 -0.123\n" + } + ], + "prompt_number": 13 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.17, Page Number: 147<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Example to use the function abs()'''\n\n#Variable Decleration\ni=abs(-10)\n\n#Result\nprint abs(-23)\nabs(100)", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "23\n" + }, + { + "output_type": "pyout", + "prompt_number": 5, + "text": "100" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.18, Page Number: 148<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to find a substring'''\n\n#Return index of substring or -1 if not found.\ndef find_substr(sub,str):\n l=str.find(sub)\n return l\n\n#Variable decleration;Calling the function\nindex=find_substr(\"three\",\"one two three four\")\n\n#Result\nprint \"Index of three is \",index", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Index of three is 8\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.19, Page Number: 149<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to print a string vertically downward'''\n\nimport sys\n\ndef print_vertical(str):\n l=len(str)\n for i in range(l):\n print str[i],\n \nprint_vertical(sys.argv[1])\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "- f\n" + } + ], + "prompt_number": 14 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.20, Page Number: 150<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Rework find_substr() to return pointer'''\n\n#Return position of substring\ndef find_substr(sub,str):\n return str.find(sub)\n\n#Variable declaration\ns=\"one two three four\"\n\nsubstr = find_substr(\"three\",s)\n\n#Result\nprint \"substring found:\",s[substr:]\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "substring found: three four\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.21, Page Number: 154<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to calculate factorial'''\n\n#Recursive version\ndef factr(n):\n if n==1:\n return 1\n answer=factr(n-1)*n\n return answer\n\n#Iterative version\ndef fact(n):\n answer=1\n for t in range(n):\n answer=answer*(t+1)\n return answer\n\n#Using recursion version\nprint \"4 factorial is \",factr(4)\n\n#Using iterative version\nprint \"4 factorial is \",fact(4)\n\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "4 factorial is 24\n4 factorial is 24\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 7.22, Page Number: 155<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Print a string backwards using recursion'''\n\n#Reversing a string\ndef reverse(s):\n r = \"\"\n for c in s:\n r=c+r\n print r\n \n#VariabDecleration \nstr=\"this is a test\"\n\n#Calling function\nreverse(str)\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "tset a si siht\n" + } + ], + "prompt_number": 9 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_8(1).ipynb b/C++_from_the_Ground/Chapter_8(1).ipynb new file mode 100644 index 00000000..da5f88d2 --- /dev/null +++ b/C++_from_the_Ground/Chapter_8(1).ipynb @@ -0,0 +1,327 @@ +{ + "metadata": { + "name": "Chapter 8" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 8: Functions,Part Two: References, Overloading, and Default Arguments<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.1, Page Number: 158<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Example for call by value'''\n\ndef sqr_it(x):\n x=x*x\n return x\n\n#Variable decleration\nt=10\n\n#Result; function calling\nprint sqr_it(t),' ',t\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "100 10\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.2, Page Number: 159<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to swap two values; implementing call by pointers'''\n\ndef swap(x,y):\n temp=x\n x=y\n y=temp\n return x, y\n\n#Variable decleration\ni=10\nj=20 \n\n#Initial values\nprint \"Initial values of i and j: \",\nprint i,' ',j\n\n#Calling function to swap\ni, j=swap(i,j)\n\n#Result\nprint \"Swapped values of i and j: \",\nprint i,' ',j", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Initial values of i and j: 10 20\nSwapped values of i and j: 20 10\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.3, Page Number: 161<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Example to implement call by reference in python'''\n\ndef f(i):\n i=10\n return i #Returning the value since the function cannot access the variables in the calling scope.\n\n#Variable Decleration\nval=1\n\nprint \"Old value for val: \",val\nval=f(val) #Function call\n\n#Result\nprint \"New value for val: \",val\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Old value for val: 1\nNew value for val: 10\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.4, Page Number: 162<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Program to swap two values; implementing call by reference'''\n\ndef swap(i,j):\n temp=i[0]\n i[0]=j[0]\n j[0]=temp\n return i, j\n\n#Variable decleration\ni=[]\nj=[]\ni.append(10)\nj.append(20)\n\n#Initial values\nprint \"Initial values of i and j: \",\nprint i[0],' ',j[0]\n\n#Calling function to swap\ni, j=swap(i,j)\n\n#Result\nprint \"Swapped values of i and j: \",\nprint i[0],' ',j[0]", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Initial values of i and j: 10 20\nSwapped values of i and j: 20 10\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.5, Page Number: 164<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An example program'''\n#Since python cannot return references, the value is changed using the variable itself\n\n#Variable Decleration\nval = 100.0\n\ndef f():\n global val\n return val\n\n#Result\nprint val\n\nnewval=f() #function call\nprint newval\n\nval=99.1 #change val's value\nprint f() #print val's new value\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "100.0\n100.0\n99.1\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.6, Page Number: 166<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Changing contents of a list'''\n#Since python cannot return references, the program has been modified.\n\n#Function definition\ndef change_it(i,n):\n global vals\n vals[i]=n\n\n#Variable Decleration\nvals=[1.1,2.2,3.3,4.4,5.5]\n\nprint \"Here are the original values: \",\nfor i in range(5):\n print vals[i],\nprint\n \n#Function call\nchange_it(1,5298.23)\nchange_it(3,-98.8)\n\n#Result\nprint \"Here are the changed values: \",\nfor i in range(5):\n print vals[i],", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Here are the original values: 1.1 2.2 3.3 4.4 5.5\nHere are the changed values: 1.1 5298.23 3.3 -98.8 5.5\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.7, Page Number: 167<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing a simple safe array'''\n\n#Variable Decleration\nvals=[None]*10\nerror=-1\n\n#put values into the array\ndef put(i,n):\n global vals\n if i>=0 and i<10:\n vals[i]=n\n else:\n print \"Bounds Error!\"\n error=n\n\n#obtain a value from the array\ndef get(i):\n if i>=0 and i<10:\n return vals[i]\n else:\n print \"Bounds error!\"\n return -1\n \n#put values into the array\nput(0,10)\nput(1,20)\nput(9,30)\n\n#Result\nprint get(0),' ',get(1),' ',get(9),\n\n#now, intentionally generate an errer\nput(12,1)", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 20 30 Bounds Error!\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.8, Page Number: 169<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing references in pyhton'''\n\n#Variable Decleration\ni=[]\nj=i #independent reference\n\nj.append(10) #Here i and j are just references to [10]\n\nprint j[0],\" \",i[0] \n\nk=121\ni[0]=k #copies k's value into j[0] \n\n#Result\nprint j[0]", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 10\n121\n" + } + ], + "prompt_number": 7 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.9, Page Number: 170<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Function overloading in python'''\n#Overloading is not supported by python, hence it is implemented by default arguments.\n\ndef f(i,j=None):\n if j==None: \n if isinstance(i,int): #for 1st function\n print \"In f(int), i is \",i \n else: #for 3rd function\n print \"In f(double), k is \",i\n else: #for 2nd arguments\n print \"In f(int,int), i is \",i,\", j is \",j\n \n#calling function\nf(10)\nf(10,20)\nf(12.23)\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "In f(int), i is 10\nIn f(int,int), i is 10 , j is 20\nIn f(double), k is 12.23\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.10, Page Number: 171<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Create an overloaded function of abs called myabs()'''\n\n#myabs() in three ways\ndef myabs(i):\n if isinstance(i,int): #first instance\n print \"Using integer myabs(): \",\n if i<0:\n return -i\n else:\n return i\n elif isinstance(i,float): #second instance\n print \"Using double myabs(): \",\n if(i<0.0):\n return -i\n else:\n return i\n elif isinstance(i,long): #third instance\n print \"Using long myabs(): \",\n if i<0:\n return -i\n else:\n return i\n\n#Result; calling the function \nprint myabs(-10)\nprint myabs(-11.0)\nprint myabs(-9L)\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Using integer myabs(): 10\nUsing double myabs(): 11.0\nUsing long myabs(): 9\n" + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.11, Page Number: 174<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''An example of default arguments'''\n\nimport os\n\ndef clrscr(size=25):\n while(size):\n print \"\"\n size-=1\n \nfor i in range(30):\n print i\n clrscr() #clears 25 lines\n\nfor i in range(30):\n print i\n clrscr(10) #clears 10 lines\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "0\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n1\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n2\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n3\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n4\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n5\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n6\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n7\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n8\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n9\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n10\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n11\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n12\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n13\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n14\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n15\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n16\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n17\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n18\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n19\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n20\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n21\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n22\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n23\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n24\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n25\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n26\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n27\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n28\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n29\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n0\n \n \n \n \n \n \n \n \n \n \n1\n \n \n \n \n \n \n \n \n \n \n2\n \n \n \n \n \n \n \n \n \n \n3\n \n \n \n \n \n \n \n \n \n \n4\n \n \n \n \n \n \n \n \n \n \n5\n \n \n \n \n \n \n \n \n \n \n6\n \n \n \n \n \n \n \n \n \n \n7\n \n \n \n \n \n \n \n \n \n \n8\n \n \n \n \n \n \n \n \n \n \n9\n \n \n \n \n \n \n \n \n \n \n10\n \n \n \n \n \n \n \n \n \n \n11\n \n \n \n \n \n \n \n \n \n \n12\n \n \n \n \n \n \n \n \n \n \n13\n \n \n \n \n \n \n \n \n \n \n14\n \n \n \n \n \n \n \n \n \n \n15\n \n \n \n \n \n \n \n \n \n \n16\n \n \n \n \n \n \n \n \n \n \n17\n \n \n \n \n \n \n \n \n \n \n18\n \n \n \n \n \n \n \n \n \n \n19\n \n \n \n \n \n \n \n \n \n \n20\n \n \n \n \n \n \n \n \n \n \n21\n \n \n \n \n \n \n \n \n \n \n22\n \n \n \n \n \n \n \n \n \n \n23\n \n \n \n \n \n \n \n \n \n \n24\n \n \n \n \n \n \n \n \n \n \n25\n \n \n \n \n \n \n \n \n \n \n26\n \n \n \n \n \n \n \n \n \n \n27\n \n \n \n \n \n \n \n \n \n \n28\n \n \n \n \n \n \n \n \n \n \n29\n \n \n \n \n \n \n \n \n \n \n" + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.12, Page Number: 176<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''A customized version of strcat'''\n\n#Variable Decleration\nstr1 = \"This is a test\"\nstr2 = \"0123456789\"\n\n#function for concatenation\ndef mystrcat(s1,s2,l=-1):\n if l==-1:\n l=len(str2)\n s2=s2[:l] #truncates s2\n s1=s1+s2 #concatenates the 2 strings\n return s1\n\nstr1=mystrcat(str1,str2,5) #concatenate 5 chars\nprint str1\n\nstr1 = \"this is a test\" #reset str1\n\nstr1=mystrcat(str1, str2) #concatenate entire string\nprint str1", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "This is a test01234\nthis is a test0123456789\n" + } + ], + "prompt_number": 9 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.13, Page Number: 177<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Overload ambiguity'''\n#Here there wont be any ambiguity because float and double are the same.\n\ndef myfunc(i):\n return i\n \nprint myfunc(10.1),\nprint myfunc(10)", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10.1 10\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.14, Page Number: 178<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Another ambiguity'''\n\nfrom ctypes import *\n\ndef myfunc(ch):\n if isinstance(ch,c_int):\n return chr(ch.value+1)\n elif isinstance(ch,c_uint):\n return chr(ch.value-1)\n \n \nprint myfunc(c_int(ord('c'))),\nprint myfunc(c_uint(88))", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": " d W\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 8.15, Page Number: 179<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''More ambiguity'''\n\ndef myfunc(i,j=1):\n if j==1:\n return i*j\n else:\n return i\n \n \nprint myfunc(4,5),\nprint myfunc(10)", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "4 10\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/Chapter_9(1).ipynb b/C++_from_the_Ground/Chapter_9(1).ipynb new file mode 100644 index 00000000..b31c36a0 --- /dev/null +++ b/C++_from_the_Ground/Chapter_9(1).ipynb @@ -0,0 +1,387 @@ +{ + "metadata": { + "name": "Chapter 9" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h1>Chapter 9: More Data Types and Operations<h1>" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.1, Page Number: 182<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Printing a string'''\n#pyhton doesnt have constants, hence a normal object has been used\n\ndef code(str):\n print str\n\n#Calling function\ncode(\"this is a test\")", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "this is a test\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.2, Page Number: 183<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing const references'''\n\ndef f(i):\n i=100\n print i\n \n#Variable declaration\nk=10\n\n#function call\nf(k)\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "100\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.3, Page Number: 187<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementing extern in pyhton'''\n\n#Variable Declaration\nfirst=10 #global definition of first and last\nlast=20\n\n#Result\nprint first,last\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 20\n" + } + ], + "prompt_number": 7 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.4, Page Number: 188<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Compute a running average of numbers entered by the user'''\n'''Implementing static variables in python'''\n\n#Variable declaration\nsum=0 \ncount=0\nnum=5 #Loop for user entries\n\n#compute a running average\ndef r_avg(i):\n global sum,count\n sum=sum+i\n count+=1\n return sum/count\n\n\nwhile True:\n print \"Enter numbers(-1 to quit): \"\n num-=1 #User input\n if not(num==-1):\n print \"Running average is: \",r_avg(num) #Result\n if num<0:\n break", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Enter numbers(-1 to quit): \nRunning average is: 4\nEnter numbers(-1 to quit): \nRunning average is: 3\nEnter numbers(-1 to quit): \nRunning average is: 3\nEnter numbers(-1 to quit): \nRunning average is: 2\nEnter numbers(-1 to quit): \nRunning average is: 2\nEnter numbers(-1 to quit): \n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.5, Page Number: 189<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Compute a running average of numbers entered by the user'''\n'''Implementing static variables in python'''\n\n#Variable declaration\nsum=0 \ncount=0\nnum=10 #Loop for user entries\n\n#user input given: 9,8,7,6,-2,4,3,2,1,-1\n\n#compute a running average\ndef r_avg(i):\n global sum,count\n sum=sum+i\n count+=1\n return sum/count\n\ndef reset():\n global sum,count\n sum=0\n count=0\n \nwhile True:\n print \"Enter numbers(-1 to quit, -2 to reset): \"\n num-=1 #User input\n if num==5:\n num=-2\n if num==-2: #for reset\n num=4\n reset()\n continue\n if not(num==-1):\n print \"Running average is: \",r_avg(num) #Result\n else:\n break", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Enter numbers(-1 to quit, -2 to reset): \nRunning average is: 9\nEnter numbers(-1 to quit, -2 to reset): \nRunning average is: 8\nEnter numbers(-1 to quit, -2 to reset): \nRunning average is: 8\nEnter numbers(-1 to quit, -2 to reset): \nRunning average is: 7\nEnter numbers(-1 to quit, -2 to reset): \nEnter numbers(-1 to quit, -2 to reset): \nRunning average is: 3\nEnter numbers(-1 to quit, -2 to reset): \nRunning average is: 2\nEnter numbers(-1 to quit, -2 to reset): \nRunning average is: 2\nEnter numbers(-1 to quit, -2 to reset): \nRunning average is: 1\nEnter numbers(-1 to quit, -2 to reset): \n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.6, Page Number: 196<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of enumeration in python'''\n\n#Array of strings that correspond to the enumeration\nname=[\"Jonathan\",\"Golden Delicious\",\"Red Delicious\",\"Winesap\",\n \"Cortland\",\"McIntosh\"]\n\n#enumeration type\n(Jonathan,Golden_Delicious,Red_Delicious,Winesap,Cortland,McIntosh) = (0,1,2,3,4,5)\n\nfruit=Jonathan\nprint name[fruit]\n\nfruit = Winesap\nprint name[fruit]\n\nfruit = McIntosh\nprint name[fruit]", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Jonathan\nWinesap\nMcIntosh\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.7, Page Number: 198<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Convert to uppercase letter'''\n\n#Variable declaration\nch='j' #User input\nwhile True:\n #This statement turns off the 6th but.\n c=chr(ord(ch)&223) #ch is now uppercase\n print c\n if c=='Q':\n break \n else:\n ch = chr(ord(ch)+1) #incrementing for different user inputs\n \n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "J\nK\nL\nM\nN\nO\nP\nQ\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.8, Page Number: 200<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Convert to lowercase letter'''\n\n#Variable declaration\nch='J' #User input\nwhile True:\n #This statement turns off the 6th but.\n c=chr(ord(ch)|32) #ch is now uppercase\n print c\n if c=='q':\n break \n else:\n ch = chr(ord(ch)+1) #incrementing for different user inputs\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "j\nk\nl\nm\nn\no\np\nq\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.9, Page Number: 201<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Display the bits within a byte'''\n\n#function to display the bits\ndef disp_binary(u):\n t=128\n while t:\n if u&t:\n print 1,\n else:\n print 0,\n t=t/2\n print \"\"\n \n#Variable declaration\nu=99 #User Input\n\nprint \"Here's the number in binary: \",\ndisp_binary(u)\n\nprint \"Here's the complement of th number: \",\ndisp_binary(~u)\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Here's the number in binary: 0 1 1 0 0 0 1 1 \nHere's the complement of th number: 1 0 0 1 1 1 0 0 \n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.10, Page Number: 202<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate bitshifting'''\n\n#unction to display the bits within a byte\ndef disp_binary(u):\n t=128\n while t:\n if u&t:\n print 1,\n else:\n print 0,\n t=t/2\n print \"\"\n \n#Variable dclaration\ni=1\n\n#Result\nfor t in range(8):\n disp_binary(i)\n i=i<<1\n\nprint\"\\n\"\n\nfor t in range(8):\n i=i>>1\n disp_binary(i)\n ", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "0 0 0 0 0 0 0 1 \n0 0 0 0 0 0 1 0 \n0 0 0 0 0 1 0 0 \n0 0 0 0 1 0 0 0 \n0 0 0 1 0 0 0 0 \n0 0 1 0 0 0 0 0 \n0 1 0 0 0 0 0 0 \n1 0 0 0 0 0 0 0 \n\n\n1 0 0 0 0 0 0 0 \n0 1 0 0 0 0 0 0 \n0 0 1 0 0 0 0 0 \n0 0 0 1 0 0 0 0 \n0 0 0 0 1 0 0 0 \n0 0 0 0 0 1 0 0 \n0 0 0 0 0 0 1 0 \n0 0 0 0 0 0 0 1 \n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.11, Page Number: 204<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''This program implements ? operator in python'''\n\ndef div_zero():\n print \"Cannot divide by zero.\"\n return 0\n \n#Variable declaration\ni=10 #User Input\nj=0\n\n#This statement prevents a divide by zero\nif j:\n result=i/j\nelse:\n result=div_zero()\n\n#Result\nprint \"Result: \",result", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "Cannot divide by zero.\nResult: 0\n" + } + ], + "prompt_number": 7 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.12, Page Number: 206<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of the comma operator'''\n\n#Variable declaration\nj=10\ni=None\n\nj+=1\nj+100\ni=999+j\n\n#Result\nprint i", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1010\n" + } + ], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.13, Page Number: 207<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Demonstrate sizeof'''\n\nfrom ctypes import *\n\n#Variable declaration\nch=c_char\ni=c_int\n\nprint sizeof(ch), #size of char\nprint sizeof(i), #size of int\nprint sizeof(c_float), #size of float\nprint sizeof(c_double) #size of double\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "1 4 4 8\n" + } + ], + "prompt_number": 2 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.14, Page Number: 209<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Example of pointers'''\n\nfrom ctypes import *\n\n#Variabke declaration \ni=c_int(20) #allocate memory for int\np=pointer(i) #assign a pointer to the memory\n\n#Result\nprint p[0] #proove that it works by displaying value\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "20\n" + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.15, Page Number: 210<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Imlementation of dynamic initialization in python'''\n\nfrom ctypes import *\n\n#Variable declaration \ni=c_int(99) #initialize with 99\np=pointer(i) #assign a pointer to the value\n\n#Result\nprint p[0] #displays 99\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "99\n" + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.16, Page Number: 211<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Imlementation of dynamic initialization in python'''\n\nfrom ctypes import *\n\n#Variable declaration \ni=c_double(10) \np=pointer(i)\n\n#assign the values 100 to 109\nfor i in range(10):\n p[i]=100.00+i\n\n#display the contents of the array\nfor i in range(10):\n print p[i],\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "100.0 101.0 102.0 103.0 104.0 105.0 106.0 107.0 108.0 109.0\n" + } + ], + "prompt_number": 5 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.17, Page Number: 211<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of malloc int python'''\n\n#Variable declaration\ni=c_int() \nj=c_double()\npi=pointer(i) #pointer to int\npj=pointer(j) #pointer to double\n\n#Assign values using pointers\npi[0]=10\npj[0]=100.123\n\n#Result\nprint pi[0],pj[0]\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 100.123\n" + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": "<h3>Example 9.18, Page Number: 212<h3>" + }, + { + "cell_type": "code", + "collapsed": false, + "input": "'''Implementation of dynamic memory allocation'''\nfrom ctypes import *\n\n#Variable declaration\ni=pointer(c_int())\nj=pointer(c_double())\n\n#Checking if i and j have been allocated memory addresses\nif not(id(i)):\n print \"Allocation Failure.\"\n \nif not(id(j)):\n print \"Allocation Failure.\" \n\ni[0]=10\nj[0]=100.123\n\n\n#Result\nprint i[0],j[0]\n\n", + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": "10 100.123\n" + } + ], + "prompt_number": 11 + }, + { + "cell_type": "code", + "collapsed": false, + "input": "", + "language": "python", + "metadata": {}, + "outputs": [] + } + ], + "metadata": {} + } + ] +}
\ No newline at end of file diff --git a/C++_from_the_Ground/README.txt b/C++_from_the_Ground/README.txt new file mode 100644 index 00000000..6e0fd27d --- /dev/null +++ b/C++_from_the_Ground/README.txt @@ -0,0 +1,10 @@ +Contributed By: Anandi Bharwani +Course: btech +College/Institute/Organization: National Institute Of Technology, Durgapur +Department/Designation: Computer Science And Engineering +Book Title: C++ from the Ground +Author: Herbert Schildt +Publisher: McGraw-Hill Osborne Media +Year of publication: 2003 +Isbn: 0072228970 +Edition: 3rd
\ No newline at end of file diff --git a/C++_from_the_Ground/screenshots/c++preproce.png b/C++_from_the_Ground/screenshots/c++preproce.png Binary files differnew file mode 100644 index 00000000..656d9ed9 --- /dev/null +++ b/C++_from_the_Ground/screenshots/c++preproce.png diff --git a/C++_from_the_Ground/screenshots/datatypes.png b/C++_from_the_Ground/screenshots/datatypes.png Binary files differnew file mode 100644 index 00000000..08d8ff2d --- /dev/null +++ b/C++_from_the_Ground/screenshots/datatypes.png diff --git a/C++_from_the_Ground/screenshots/inheritence.png b/C++_from_the_Ground/screenshots/inheritence.png Binary files differnew file mode 100644 index 00000000..49b24c1d --- /dev/null +++ b/C++_from_the_Ground/screenshots/inheritence.png |