id
int64
0
25.6k
text
stringlengths
0
4.59k
19,900
point polygon rectangle text graphwin methods summary gregorian epact gui hailstone function halting problem happy happy birthday lyrics problem description program happy py hard drive hardware hash array hierarchy chartsee structure chart house house (of representatives) identifier definition of rules for forming idle...
19,901
label ladder leap year len with string with list lexicographic ordering library definition of graphicssee graphics library mathsee math library randomsee random library lightning line line continuation using backslash (\) using brackets linear time list as sequence creation empty indexing merging methods operators remo...
19,902
parameterless accessor call (invoke) mutator normal parameter object parameters self parameter string methods activate clicked deactivate dictionary list model-view module file module hierarchy chartsee structure chart molecular weight monte carlo month abbreviation problem description program month py month py move mo...
19,903
execution modes there are two ways to use the python interpreterainteractive mode bscript mode interactive mode allows execution of individual statement instantaneously whereasscript mode allows us to write more than one instruction in file called python source code file that can be executed (ainteractive mode to work ...
19,904
computer science class xi cthe output appears on shell as shown in figure program - write program to show print statement in script mode figure python source code file (prog - pyfigure execution of python in script mode using idle figure output of program executed in script mode python keywords keywords are reserved wo...
19,905
true and as assert break def del elif else except from global if import in nonlocal not or pass raise while with yield identifiers in programming languagesidentifiers are names used to identify variablefunctionor other entities in program the rules for naming an identifier in python are as followsthe name should begin ...
19,906
computer science class xi gender 'mprice message "keep smilingprogram - write program to display values of variables in python #program - #to display values of variables message "keep smilingprint(messageuserno print('user number is'usernooutputkeep smiling user number is in the program - the variable message holds str...
19,907
they are added with the purpose of making the source code easier for humans to understand they are used primarily to document the meaning and purpose of source code and its input and output requirementsso that we can remember later how it functions and how to use it for large and complex softwareit may require programm...
19,908
computer science class xi example num id(num #identity of num num id(num #identity of num and num #are same as both refers to #object data types every value belongs to specific data type in python data type identifies the type of data values variable can hold and the operations that can be performed on that data figure...
19,909
let us now try to execute few statements in interactive mode to determine the data type of the variable using built-in function type(example num type(num num - type(num var true type(var float - type(float float - * ** print(float type(float )- var - + print(var type(var )(- + jvariables of simple data types like integ...
19,910
computer science class xi notes marks ( 'hello'or in double quotation marks ( "hello"the quotes are not part of the stringthey are used to mark the beginning and end of the string for the interpreter for examplestr 'hello friendstr " we cannot perform numerical operations on stringseven when the string contains numeric...
19,911
set { , , , print(set { none none is special data type with single value it is used to signify the absence of value in situation none supports no special operationsand it is neither same as false nor (zeroexample myvar none print(type(myvar)print(myvarnone mapping mapping is an unordered data type in python currentlyth...
19,912
computer science class xi change the values once variable of that type has been created and assigned values variables whose values can be changed after they are created and assigned are called mutable variables whose values cannot be changed after they are created and assigned are called immutable when an attempt is ma...
19,913
in this manner makes the assignment effective by copying only the referenceand not the datanum num figure variables with different values have different identifiers this statement num num links the variable num to new object stored at memory location number say having value as num is an integerwhich is an immutable typ...
19,914
arithmetic operators python supports arithmetic operators that are used to perform the four basic arithmetic operations as well as modular divisionfloor division and exponentiation table arithmetic operators in python operator operation addition example (try in labdescription adds the two numeric values on num num eith...
19,915
them assume the python variables num num num str "good"str "afternoonfor the following examplestable relational operators in python operator operation =equals to description example (try in labif the values of two operands are num =num equalthen the condition is truefalse otherwise it is false >str =str !not equal to i...
19,916
+it adds the value of right-side operand to the left-side operand and assigns the result to the left-side operand notex + is same as num num num +num num num str 'hellostr 'indiastr +str str 'helloindia-it subtracts the value of right-side operand from the left-side operand and assigns the result to left-side operand n...
19,917
logical operators there are three logical operators supported by python these operators (andornotare to be written in lower case only the logical operator evaluates to either true or false based on the logical operands on either side every value is logically either true or false by defaultall values are true except non...
19,918
computer science class xi variables are referring to the same object or not there are two identity operators table identity operators in python operator is is not description example (try in labnum type(num is int true num num id(num id(num num is num true evaluates to false if the variables on num is not num either si...
19,919
precedence of operators evaluation of the expression is based on precedence of operators when an expression contains different kinds of operatorsprecedence determines which operator should be applied first higher precedence operator is evaluated before the lower precedence operator most of the operators studied till no...
19,920
computer science class xi notes solution ( #step #step #step #precedence of is more than that of example how will python evaluate the following expression solutionthe two operators (-and (+have equal precedence thusthe first operatori subtraction is applied before the second operatori addition (left to right( #step - #...
19,921
notes input and output sometimesa program needs to interact with the user' to get some input data or information from the end user and process it to give the desired output in pythonwe have the input(function for taking the user input the input(function prompts the user to enter data it accepts all user input as string...
19,922
computer science class xi outputs complete line and then moves to the next line for subsequent output the syntax for print(isobserve that plus sign does not add any space between the two strings while comma inserts space between two strings in print statement print(value [sep 'end '\ ']septhe optional parameter sep is ...
19,923
this is because the value returned by the input function is string (" "by default as resultin statement num num num has string value and acts as repetition operator which results in output as " to get as outputwe need to convert the data type of the value entered by the user to integer thuswe modify the program as foll...
19,924
computer science class xi str(xchr(xord(xconverts to string representation converts ascii value of to character returns the character associated with the ascii code program - program of explicit type conversion from int to float #program - #explicit type conversion from int to float num num num num num print(num print(...
19,925
figure output of program - on executionprogram - gives an error as shown in figure informing that the interpreter cannot convert an integer value to string implicitly it may appear quite intuitive that the program should convert the integer value to string depending upon the usage howeverthe interpreter may not decide ...
19,926
computer science class xi price int(icecream)+int(brownieprint("total price rs str(price)outputtotal price rs total price rs implicit conversion implicit conversionalso known as coercionhappens when data type conversion is done automatically by python and is not instructed by the programmer program - program to show im...
19,927
syntax errors like other programming languagespython has its own rules that determine its syntax the interpreter interprets the statements only if it is syntactically (as per the rules of pythoncorrect if any syntax error is presentthe interpreter shows error message(sand stops the execution there for exampleparenthese...
19,928
computer science class xi or value ' the program generates correct output when the user inputs an integer value for num program - example of program which generates runtime error #program - #runtime errors example num num int(input("num ")#if user inputs string or zeroit leads to runtime error print(num /num figure out...
19,929
datatype conversion can happen either explicitly or implicitly operators are constructs that manipulate the value of operands operators may be unary or binary an expression is combination of valuesvariables and operators python has input(function for taking user input python has print(function to output data to standar...
19,930
computer science class xi notes is between the values of integers num and num dthe string 'middleis larger than the string 'firstand smaller than the string 'lastelist stationery is empty add pair of parentheses to each expression so that it evaluates to true abc = = = = write the output of the followingabcnum num num ...
19,931
notes print( /( + )num + *(( * )- )/ print(num efnum / / print(num gnum float( print (num num int(' 'print (num print('bye='bye'print( ! and > print( * ! // - and > / print( and < print(( or (not( = and ( < ))hijklmn categorise the following as syntax errorlogical error or runtime errorab num num num /num dartboard of ...
19,932
computer science class xi notes principal or money lent prate of interest rper annum and time years then simple interest (si( ) amount payable principal si pr and are given as input to the program write program to calculate in how many days work will be completed by three persons ab and together abc take daysy days and...
19,933
introduction these lecture notes cover the key ideas involved in designing algorithms we shall see how they depend on the design of suitable data structuresand how some structures and algorithms are more efficient than others for the same task we will concentrate on few basic taskssuch as storingsorting and searching d...
19,934
will primarily be concerned with developing algorithms that map easily onto the imperative programming approach algorithms can obviously be described in plain englishand we will sometimes do that howeverfor computer scientists it is usually easier and clearer to use something that comes somewhere in between formatted e...
19,935
of the algorithm indeedthis is what normally drives the development of new data structures and algorithms we shall study the general ideas concerning efficiency in and then apply them throughout the remainder of these notes data structuresabstract data typesdesign patterns for many problemsthe ability to formulate an e...
19,936
reliable information on all the relevant topicsbut you hopefully shouldn' need reminding that not everything you read on the internet is necessarily true it is also worth pointing out that there are often many different equally-good ways to solve the same taskdifferent equally-sensible names used for the same thingand ...
19,937
arraysiterationinvariants data is ultimately stored in computers as patterns of bitsthough these days most programming languages deal with higher level objectssuch as charactersintegersand floating point numbers generallywe need to build algorithms that manipulate collections of such objectsso we need procedures for st...
19,938
loops and iteration the standard approach in most programming languages for repeating process certain number of timessuch as moving sequentially through an array to perform the same operations on each iteminvolves loop in pseudocodethis would typically take the general form for ,ndo something and in programming languag...
19,939
float min [ ]/min equals the minimum item in [ ], [ for(int ! ++/min equals the minimum item in [ ], [ - if ( [iminmin [ ]/min equals the minimum item in [ ], [ - ]and == return minat the beginning of each iterationand end of any iterations beforethe invariant "min equals the minimum item in [ ] [ ]is true it starts of...
19,940
listsrecursionstacksqueues we have seen how arrays are convenient way to store collections of itemsand how loops and iteration allow us to sequentially process those items howeverarrays are not always the most efficient way to store collections of items in this sectionwe shall see that lists may be better way to store ...
19,941
using thoseour last example list can be constructed as makelist( makelist( makelist( makelist( makelist( emptylist))))and it is clearly possible to construct any list in this way this inductive approach to data structure creation is very powerfuland we shall use it many times throughout these notes it starts with the "...
19,942
in order to communicate data structures between different computers and possibly different programming languagesxml (extensible markup languagehas become quasi-standard the above list could be represented in xml as howeverthere are usually many different ways to represent the same object in xml for instancea cell-orien...
19,943
sizewhich means array based implementation with fixed-sized arrays can only approximate the general concept for many applicationsthis is not problem because maximal number of list members can be determined priori ( the maximum number of students taking one particular module is limited by the total number of students in...
19,944
stacks stacks areon an abstract levelequivalent to linked lists they are the ideal data structure to model first-in-last-out (filo)or last-in-first-out (lifo)strategy in search graphical representation their relation to linked lists means that their graphical representation can be the samebut one has to be careful abou...
19,945
there are two different ways we can think about implementing stacks so far we have implied functional approach that ispush does not change the original stackbut creates new stack out of the original stack and new element that isthere are at least two stacks aroundthe original one and the newly created one this function...
19,946
the two selectors are the same as for stackstop(queue)which gives the top element of queuethat is in the exampleand pop(queue)which gives the queue without the top element andas with stacksthe selectors only work for non-empty queuesso we again need condition which returns whether queue is emptyisempty(queuein later we...
19,947
returns new doubly linked list with the element added to the left of the original doubly linked list makelistright(elementlist)which takes an element and doubly linked list and returns new doubly linked list with the element added to the right of the original doubly linked list it is clear that it may possible to const...
19,948
advantage of abstract data types it is clear that the implementation of the abstract linked-list data type has the disadvantage that certain useful procedures may not be directly accessible for instancethe standard abstract data type of list does not offer an efficient procedure last(lto give the last element in the li...
19,949
searching an important and recurring problem in computing is that of locating information more succinctlythis problem is known as searching this is good topic to use for preliminary exploration of the various issues involved in algorithm design requirements for searching clearlythe information to be searched has to fir...
19,950
specification of the search problem we can now formulate specification of our search problem using that data structuregiven an array and integer xfind an integer such that if there is no such that [jis xthen is - otherwisei is any for which [jis the first clause says that if does not occur in the array then should be -...
19,951
on the particular languageoperating system and machine you are usingthe actual effect of this error will be different for examplein running under unixyou may get execution aborted followed by the message "segmentation fault"or you may be given the wrong answer as the output in javayou will always get an error message m...
19,952
to midand the other going from mid to rightwhere mid is the position half way from lef to rightand whereinitiallylef and right are the leftmost and rightmost positions of the array because the array is sortedit is easy to see which of each pair of segments the searched-for item is inand the search can then be restricte...
19,953
efficiency and complexity we have already noted thatwhen developing algorithmsit is important to consider how efficient they areso we can make informed choices about which are best to use in particular circumstances sobefore moving on to study increasingly complex data structures and algorithmswe first look in more det...
19,954
of the worst case for examplethe most efficient algorithm on average might have particularly bad worst case efficiency we will see particular examples of this when we consider efficient algorithms for sorting and searching concrete measures for performance these dayswe are mostly interested in time complexity for thisw...
19,955
the algorithm on large numbers of items if an algorithm is such that we may consider all steps equally costlythen usually the complexity class of the algorithm is simply determined by the number of loops and how often the content of those loops are being executed the reason for this is that adding constant number of in...
19,956
time span they describe hence the following table gives time spans rather than instruction countsbased on the assumption that we have computer which can operate at speed of mipwhere one mip million instructions per secondf ( log log log nlog = usec usec usec usec usec usec usec usec usec usec usec usec usec usec msec m...
19,957
log log it is clear from these plots why the non-principal growth terms can be safely ignored when computing algorithm complexity formal definition of complexity classes we have noted that complexity classes are concerned with growthand the tables and graph above have provided an idea of what different behaviours mean ...
19,958
( (log log no(log ( ) (no(nlog no( ( ( we only consider the principal growth classso when adding functions from different growth classestheir sum will always be in the larger growth class this allows us to simplify terms for examplethe growth class of ( log can be determined as follows the summand with the largest grow...
19,959
trees in computer sciencea tree is very general and powerful data structure that resembles real tree it consists of an ordered set of linked nodes in connected graphin which each node has at most one parent nodeand zero or more children nodes with specific order general specification of trees generallywe can specify tr...
19,960
oneconnected to the given node (via an edgeon the level aboveis its parent for instancenode is the parent of node (and of node as wellnodes that have the same parent are known as siblings siblings areby definitionalways on the same level if node is the child of child of of another node then we say that the first node i...
19,961
lu(qt)which returns the left-upper quad-tree ru(qt)which returns the right-upper quad-tree ll(qt)which returns the left-lower quad-tree rl(qt)which returns the right-lower quad-tree which can be applied whenever isvalue(qtis false for cases when isvalue(qtis truewe could define an operator value(qtthat returns the valu...
19,962
(rule the empty tree emptytreeor (rule it consists of node and two binary treesthe left subtree and right subtree againrule is the "base caseand rule is the "induction stepthis definition may appear circularbut actually it is notbecause the subtrees are always simpler than the original oneand we eventually end up with ...
19,963
maketree( ,maketree( ,emptytree,leaf( )),maketree( ,leaf( ),leaf( )))which is much simpler than the construction using the primitive operatorst maketree( maketree( ,maketree( ,emptytree,emptytree)maketree( ,emptytree,maketree( ,emptytree,emptytree)))maketree( ,maketree( ,emptytree,maketree( ,emptytree,emptytree))maketr...
19,964
the height of binary tree binary trees don' have simple relation between their size and height the maximum height of binary tree with nodes is ( )which happens when all non-leaf nodes have precisely one childforming something that looks like chain on the other handsuppose we have nodes and want to build from them binar...
19,965
log ( log in which the approximation is valid for large hence perfectly balanced tree consisting of nodes has height approximately log this is goodbecause log is very smalleven for relatively large nn log we shall see later how we can use binary trees to hold data in such way that any search has at most as many steps a...
19,966
pointer to the relevant root-noderather than having to pass complete copies of whole trees how data structures and pointers are implemented in different programming languages will varyof coursebut the general idea is the same binary tree can be implemented as data record for each node consisting simply of the node valu...
19,967
recursive factorial functionfactorial(int nif = return return *factorial( - another examplewith two termination or base-case conditionsis direct implementation of the recursive definition of fibonacci numbers (see appendix ) (int nif = return if = return return ( - ( - though this is an extremely inefficient algorithm ...
19,968
binary search trees we now look at binary search treeswhich are particular type of binary tree that provide an efficient way of storing data that allows particular items to be found as quickly as possible then we consider further elaborations of these treesnamely avl trees and -treeswhich operate more efficiently at th...
19,969
from the point of view of the search algorithms we are going to consider in what followswe shall concentrate on the search keysbut should always bear in mind that there is usually more substantial data entry associated with it notice the use of the word "abstracthere what we mean is that we abstract or remove any detai...
19,970
if is smaller than the value of the rootinsert into the left sub-tree if is larger than the value of the rootinsert into the right sub-tree if is equal to the value of the rootreport violated assumption thususing the primitive binary tree operatorswe have the procedureinsert( ,bstif isempty(bstreturn maketree(vemptytre...
19,971
normally write the algorithm in pseudocodesuch as the following recursive procedureisin(value vtree tif isempty(treturn false elseif =root(treturn true elseif root(treturn isin(vleft( )else return isin(vright( )each recursion restricts the search to either the left or right subtree as appropriatereducing the search tre...
19,972
by successive insertions as we have seen aboveperfectly balanced trees achieve minimal height for given number of nodesand it turns out that the more balanced treethe more ways there are of building it this is demonstrated in the figure below the only way of getting the tree on the left hand side is by inserting into t...
19,973
otherwise just delete it the last part works because the left-most node in the right sub-tree is guaranteed to be bigger than all nodes in the left sub-treesmaller than all the other nodes in the right sub-treeand have no left sub-tree itself for instanceif we delete the node with value from the tree in figure we get t...
19,974
produced when they are notbut that may have significant time cost if the procedure is called many times firstto find the smallest nodewe havesmallestnode(tree /preconditiont is non-empty binary search tree if isempty(left(treturn root(telse return smallestnode(left( ))which uses the fact thatby the definition of binary...
19,975
if isempty(treturn true else return (root(tvand allsmaller(left( ),vand allsmaller(right( ),vallbigger(tree tvalue vif isempty(treturn true else return (root(tvand allbigger(left( ),vand allbigger(right( ),vhoweverthe simplest or most obvious algorithm is not always the most efficient exerciseidentify what is inefficie...
19,976
balancing binary search trees if the items are added to binary search tree in random orderthe tree tends to be fairly well balanced with height not much more than log howeverthere are many situations where the added items are not in random ordersuch as when adding new student ids in the extreme case of the new items be...
19,977
of the treebut generally it is worthwhile the earliest type of self-balancing binary search tree was the avl tree (named after its inventors adelson-velskii and landisthese maintain the difference in heights of the two sub-trees of all nodes to be at most one this requires the tree to be periodically rebalanced by perf...
19,978
tree separates the values held in its two sub-trees for exampleif node has child nodes (or sub-treesthen it must have separation values and all values in the leftmost subtree will be less than all values in the middle subtree will be between and and all values in the rightmost subtree will be greater than that allows i...
19,979
priority queues and heap trees trees stored in arrays it was noted earlier that binary trees can be stored with the help of pointer -like structuresin which each item contains references to its children if the tree in question is complete binary treethere is useful array based alternative definition binary tree is comp...
19,980
return log(iint parent(int ireturn int left(int ireturn int right(int ireturn which make the processing of these trees much easier this way of storing binary tree as an arrayhoweverwill not be efficient if the tree is not completebecause it involves reserving space in the array for every possible node in the tree since...
19,981
every node is higher than (or equal tothat of all its descendants oras complete binary tree for which the priorities become smaller along every path down through the tree the most obvious difference between binary heap tree and binary search trees is that the biggest number now occurs at the root rather than at the rig...
19,982
return = int root(array heapint nif heapempty(heap,nerror('heap is empty'else return heap[ int lastleaf(array heapint nif heapempty(heap,nerror('heap is empty'else return heap[ninserting and deleting heap tree nodes is also straightforwardbut not quite so easy inserting new heap tree node since we always keep track of ...
19,983
separately by whatever algorithm calls it inserting node takes at most (log nstepsbecause the maximum number of times we may have to 'bubble upthe new element is the height of the tree which is log deleting heap tree node to use binary heap tree as priority queuewe will regularly need to delete the rooti remove the nod...
19,984
if left(in /no children return elseif right(in /only left child if heap[iheap[left( )swap heap[iand heap[left( )else /two children if heap[left( )heap[right( )and heap[iheap[left( )swap heap[iand heap[left( )bubbledown(left( ),heap,nelseif heap[iheap[right( )swap heap[iand heap[right( )bubbledown(right( ),heap,nin the ...
19,985
then the rearrangement algorithm starts by bubbling down [ / [ which turns out not to be necessaryso the array remains the same next [ is bubbled downswapping with [ giving next [ is bubbled downswapping with [ giving finallya[ is bubbled downswapping with [ to give first then swapping with [ to give and finally swappi...
19,986
treethere are more nodesand fewer potential bubble down stepsso the total number of operations will actually be much less than nlog to be sure of the complexity classwe need to perform more accurate calculation at each level of tree of height there will be nodeswith at most bubble down stepseach with comparisonsso the ...
19,987
approachthen that may look like better choice of approach than the third approach howevermaketree will itself generally be an (nprocedure if the trees are array-basedrather than pointer-basedwhich they usually are for binary heap trees sofor array-based similarly-sized binary heapsthe third approach is usually best if ...
19,988
contains exactly nodesand binomial heap can only contain zero or one binomial tree of each orderso the total number of nodes in binomial heap must be nx bk bk [ = where bk specifies the number of trees of order thus there is one-to-one mapping between the binomial heap structure and the standard binary representation o...
19,989
the existing operations by increasing the relevant node priority to infinitybubbling-upand using the root delete operationagain with (log ncomplexity overall sothe complexity of delete is always (log nexercisefind pseudocode versions of the mergeinsert and delete algorithms for binomial heapsand see exactly how their t...
19,990
out how fibonacci numbers are involved in computing their time complexities comparison of heap time complexities it is clear that the more complex binomial and fibonacci heaps offer average time complexity advantages over simple binary heap trees the following table summarizes the average time complexities of the cruci...
19,991
sorting the problem of sorting in computer science'sortingusually refers to bringing set of items into some well-defined order to be able to do thiswe first need to specify the notion of order on the items we are considering for examplefor numbers we can use the usual numerical order (that isdefined by the mathematical...
19,992
new algorithms tend to be derived by simply tweaking existing principlesalthough we still do not have accurate measures of performance for some sorting algorithms common sorting strategies one way of organizing the various sorting algorithms is by classifying the underlying ideaor 'strategysome of the key strategies ar...
19,993
how well particular sorting algorithms compare against that theoretical lower bound in generalquestions of this kind are rather hardbecause of the need to consider all possible algorithms in factfor some problemsoptimal lower bounds are not yet known one important example is the so-called travelling salesman problem (t...
19,994
itemsso we are asking how many ways there are of arranging items the first item can be any of the itemsthe second can be any of the remaining itemsand so forthso their total number is ( )( nthus we want to know the height of binary tree that can accommodate as many as nleaves the number of leaves of tree of height is a...
19,995
[ ]= with [ ]= these entries are in orderso nothing happens (note that these numbers have been compared before there is nothing in bubble sort that prevents it from repeating comparisonswhich is why it tends to be pretty slow!then it compares [ ]= and [ ]= these are not in orderso they have to be swappedgiving since we...
19,996
being taken to remember [ first!)and then we can move the old [ to [ ]giving at the next stepthe algorithm treats [ ], [ as an already sorted array and tries to insert [ ]= this value obviously has to fit between [ ]= and [ ]= this is achieved by moving [ 'upone slot to [ (the value of which we assume we have remembere...
19,997
number of steps for of insertion sort are both proportional to and hence the average and worst case time complexities are both ( selection sort selection sort is (not surprisinglya form of selection sorting it first finds the smallest item and puts it into [ by exchanging it with whichever item is in that position alre...
19,998
comparison of ( sorting algorithms we have now seen three different array based sorting algorithmsall based on different sorting strategiesand all with ( time complexity so one might imagine that it does not make much difference which of these algorithms is used howeverin practiceit can actually make big difference whi...
19,999
sorting algorithm stability one often wants to sort items which might have identical keys ( ages in yearsin such way that items with identical keys are kept in their original orderparticularly if the items have already been sorted according to different criteria ( alphabeticalsoif we denote the original order of an arr...