Artificial Intelligence A Primer for the Labs

Size: px
Start display at page:

Download "Artificial Intelligence A Primer for the Labs"

Transcription

1 Artificial Intelligence A Primer for the Labs Mathias Broxvall, Lia Susana d.c. Silva Lopez, November 2011

2

3 Chapter 1 General python instructions This document contains a quick primer for using Python in the laborations for the Artificial Intelligence course at Örebro University, autumn To do the exercises here, you will need Python and the IDLE environment. These are installed on all computers on the NT network, and can also be downloaded from You may also want to use the book Python programming by Zelle, or one of the Python tutorials or reference manual linked to from the course web page, as the present document does not give any complete description of Python. 1.1 Programming in Python To refresh your memory of Python programming, look at this function that computes the faculty of an integer ( 0). def fac(n): res = 1 for i in range(2,n+1): res=res*i return res You can notice some peculiarities of Python in this little function. First, there are no curly brackets ({, }) as in C, to show the structure of the different statements in the function. Instead, indentation (tabs) is used. You can also notice that certain statements, namely those with other statements indented under them, end with a colon (:). You should remember to use this colon whenever you e.g. start a function definition, or write an if statement (conditional) or a for or while statement (iteration). You may also notice that the variables are not declared as in C. We do assign a value to res in the beginning, but we never say that res has to be an integer. Indeed, we could assign any other type of value to res as well, like a string or a list. While C is a strongly typed language, Python is weakly typed. However, you should take care to always use your variables in a consistent manner. 1

4 The absence of variable declarations can make it difficult to see where a certain variable belongs. You can use the following rule of thumb: If a variable is among the parameters of a function, or assigned a value inside that function, it is a local variable in that function. Otherwise, it is a global variable. Of course, you should avoid referring to global variables inside functions. Information to functions should always be passed via their parameters. This makes the functions easier to understand, and more generally useful. If you define the function above in a file that you load, you can then type in the Python shell window: fac(3) to call the function with the value 3 as argument (it will be bound to the parameter n). You can of course also call the function inside other functions. Because you can incrementally write, modify and test functions, without having to compile anything, Python is called an incremental language. You can always print out the value of a variable, or even go in and manually inspect or modify you data structures in a very easy way. The following is another function for computing the faculty: def facr(n): if n <= 1: return 1 else: return n*facr(n-1) This function is recursive: it calls itself on the last line. Remember that a recursive function needs to handle two cases: a base case when a value can be computed and returned directly (lines 2 and 3 above) a recursive case when the function has to call itself, but with different arguments, to complete the computation (lines 4 and 5). It is important that the recursive call is made with a smaller or simpler value than before, in this case n-1 instead of n. In that way, the base case (with the really simple or small values, like 1 above), will eventually be reached. The first faculty function solved the same problem in an iterative way, using a for-loop. Sometimes you can write a function either recursively or iteratively, but in other cases the recursive way is the only way. 2

5 1.2 Some important data types The following section goes through the most important data types in Python. As mentioned before, variables in Python are not typed, but you can always check what type the present value of a variable is by using the function type, as in: type(3) == int The types in this section are bool, int, float, str, list, tuple and dict Booleans The boolean type consists of the values True and False, and the boolean operations are and, or, and not. All tests, such as equality (x==y), return a boolean value Numbers Numbers in Python can either be integers (like 1 and 12) or floating point numbers like 1.0 or There are the usual arithmetic operators: +, -, *, / and ** (power, m**n means m n ). Note that if the arguments to / are integers, then it is interpreted as integer division, and the result is also an integer. The remainder can then be obtained by %. If at least one of the numbers is floating point, then / works like ordinary division. You can convert a number to floating point with the function float, and to an integer with the function int. There are also the functions min and max, which can take any number of arguments, and abs which takes one argument. There are also comparisons, like == (equals),!= (not equals), <, >, <= and >= Characters and strings Strings are written surrounded by single or double quotes: hello, "hello". A character is a string of length 1: a or "a". The function len(s) gives the length of a string s, and the character at position n is obtained by s[n], where the first character is at position 0. You can also use negative numbers to count backwards: s[-1] gives the last character in the string, and so on. You can get a part of a string with s[n:m]: this gives the substring from position n to position m 1 (position m is not included). Finally, s[n:] gives the substring from position n to the end, and s[:m] gives the substring from the beginning to position m 1. You can concatenate (put together) strings with the operation +, and use * to repeat the same string a number of times (e.g. 3* a ). These operations do not change the strings involved, but creates a new string. Finally, you can check if a character or a substring occurs in a string by in a in cab To work with strings, one can either iterate over the positions in the strings. Eg. 3

6 for i in range(0,len(s)): print s[i] One can also iterate directly over the characters, as in the following example: for c in "YANKEES": print("give me a "+c+"!") A nice way to construct strings from other data is to use the string formatting operator %. It takes a string on the left side, and a number of arguments on the right side, and it returns a new string. For instance: "I am %d years" % 5 would return the string "I am 5 years". The %d part of the formatting string indicates where the argument should go, and that it should be shown as a decimal (base 10) integer. You can also use %f for floating point arguments and %s for strings (or almost anything else). You can use several arguments, inside parentheses: "My name is %s, I m %d years old, and %f meters tall." % ("Gimli", 150, 1.40) Lists Lists are very versatile data structures, and very useful for AI applications. A list is a sequence of objects, which can be of any type including another list. The following are some examples: [5, 3, 8, 10] [ hello, there ] [[1,2],[4,2],[6,12]] You can access elements in a list just like in a string, e.g. l[1] or l[1:3]. If there are lists inside the list, you can access their elements by repeating those operations, e.g. l[2][1] would give element in position 1 of the list at position 2 in the list l, which would be 12 if l was the third list above. In addition, you can change the elements of a list, like: l[0] = [2,1] l[1][0] = 3 You can concatenate lists with the operation +, and use * to repeat the same list a number of times. With in, you can check whether a certain element occurs in the list. An efficient way to create lists is to use list comprehension. For instance, the following statement creates the multiplication table for the number 3. mult_3 = [ 3*x for x in range(1,11) ] It takes elements x ranging from 1 to 10, and create a list of elements computed as 3*x. Here is a statement for computing the entire multiplication table, as a matrix: mult_table = [ [x*y for x in range(11) ] for y in range(1,11) ] One can iterate over the elements of a list, just like over the characters of a string. Indeed, when one writes e.g. for i in range(1,11), the expression range(1,11) actually returns a list containing numbers from 1 to 11. 4

7 1.2.5 Tuples Tuples are pretty similar to lists, but you cannot modify their elements. Here are some examples: (1,2) ("Bill", "Fulton", 55) (1,) Note that you need to include a comma when you have a tuple of length one, as in the last line. A useful feature of tuples is that you can assign their elements to multiple variables at the same time: person = ("Bill", "Fulton", 55) firstname, familyname, age = person This comes particularly handy when you have a function that returns several values. def inverse_and_square_and_root(x): return (1.0/x, x**2, x**0.5) When you call this function, you can assign the result to three different variables: x_inverse, x_square, x_root = inverse_and_square_and_root(2.0) Dictionaries Dictionaries are also similar to lists, but instead of referring to elements by position, one refer to them by a key, which is a string. The following is an example: cities = { "London" : "England", "Glasgow" : "Scotland", "Cardiff": "Wales" } One can now access and update the different elements like this: x = cities["london"] cities["birmingham"] = "England" One can also check if a key exists in the dictionary using in: "London" in cities The values (as opposed to the keys) need not be strings. They can be of any type, including another dictionary. One can iterate over the keys of a dictionary: for x in cities: print(x+" lies in "+cities[x]+".") Dictionaries are useful for storing and accessing symbolic information. This makes them well suited for AI applications. Python dictionaries are implemented as hash tables, which make them quite efficient. 5

8 6

9 Chapter 2 Object orientation 2.1 Classes and objects Python supports object-oriented programming. You can define classes, and create objects belonging to these classes. We will only take a very cursory look at classes and objects here. The following is an example of a class definition: class Gridmap: grid=[] width=0 height=0 This is an extremely simple class - in practice nothing more than a record with three fields. Each field is supplied with a default value. We can create instances of this class by calling its constructor, which is a function with the same name as the class itself. You can also give values to the different fields: my_map = Gridmap() my_map.grid = [[0,0],[0,0]] my_map.width=2 my_map.height=2 The different fields can then be accessed in the obvious way: w = my_map.width h = my_map.height print(my_map.grid[0][0]) You can also define classes with methods. The following class, which is a subclass of the previous class, has two methods. One is for initializing an instance when the constructor is called. The other is for checking whether a certain square in the grid is a free passage. class Labyrinth(Gridmap): def init (self,grid,startx,starty,goalx,goaly): 7

10 self.grid=grid self.start=(startx,starty) self.goal=(goalx,goaly) self.width=len(grid[0]) self.height=len(grid) def is_free_passage(self,x,y): return self.grid[y][x] == 1 mylab = Labyrinth(labyrinth,6,0,1,7) print(mylab.is_free_passage(2,2)) You may notice that the first parameter in each method is called self. When a method is called, this parameter will be bound to the object that the method belongs to, i.e. the object given in front of the method name (mylab in the last line above). It will be the object just being initialized when the constructor is invoked. The parameter need not be called self, but it is good practice to do so. 8

11 Chapter 3 Functional programming Python can also be used as a functional programming language. Among other things, this means that functions are first-order objects in Python. For instance, try typing len in the shell window. You get the response <built-in function len>. Now try the assignment foo = len, and then try foo("hello"). The variable foo has been bound to the function len! Or to be more specific, foo has been bound to the same function object as len. You can also create function objects without any name. This is done by using lambda expressions. The following is one example: lambda x: 2*x This is a function with one parameter x, which computes and returns 2*x. You can call this function like any other function, i.e. by supplying arguments directly after it: (lambda x: 2*x)(3) You could indeed also give it a name: foo = lambda x: 2*x The latter has the same effect as an ordinary function definition. There are a number of functions in Python that take a function as one of their arguments. They are called higher-order functions. When you call them, it can sometimes come in handy to use a lambda expression. The function map takes a function and a list (or string, or similar) and applies the function to every element in the list, and returns a list with the resulting elements. map(lambda x: 2*x, [1,2,3,4,5]) The function filter takes a function and a list (or string, or similar) and applies the function to every element in the list, and returns a list with the elements for which the function returned True. In other words, filter performs a test on each element, and only keeps those that pass the test. filter(lambda x: x>2, [1,2,3,4,5]) 9

12 The function functools.reduce takes a binary function and a list, and applies the function to the values in the list, until a single aggregated value has been computed. For instance: import functools functools.reduce(lambda x,y: x*y, [1,2,3,4,5]) is equivalent to 1*2*3*4*5. Likewise, reduce(max,[1,2,3,4,5]) returns the maximal value in the list. You can also write your own higher-order functions. The following is a function that checks whether every element satisfies a given test. def every(fn,item_list): for i in item_list: if not fn(i): return False return True 3.1 Evaluation and execution There is a function in Python called eval, which takes a Python expression in the form of a string and evaluates it. For instance, try: eval("2+3") The command exec takes a string as well, and interprets and executes this string as Python code. For instance, try: exec "for i in [1,2,3]:\n\tprint(i)" Note that \n stands for a newline, and \t stands for a tab (to get the indentation). The eval function and the exec command actually make it possible to write programs that write and execute code. Your program becomes a programmer. Note: The eval function is often considered a dangerous function since it risks creating security holes if user generated input is fed directly or indirectly to eval. Also for most systems it is less efficient since the that s evaluated cannot be statically compiled. 10

13 Chapter 4 Search algorithms A very simple way to find solutions to problems in a brute force search is by a simple recursion. We will illustrate this by an example. 4.1 The Knapsack problem Image that you have a backpack ( knapsack ), of finite size S, and a number of objects that you want to take with you. Each object has a name, a size and a value. We can describe each object as tuples ("name",size,value). Let s assume for instance that we have a backpack of size 6 and the objects given by the list below: [("A",3,4),("B",2,2),("C",2,3)] Since the total size of all the objects are 7 (check this yourself!) we obviously cannot take all the objects with us? Now, the problem is, how can you maximize the value of the objects to take with you if you can t fit everything inside your backpack? The easiest way to answer this is to try all combinations and check the values of each combination. This can be reduced into three recursive cases. Firstly, if we have no objects to take, then value will then be zero. Secondly, if the first object in the list is bigger than the backpack we can just check how much we can get if we only consider the rest of the items. Lastly, if the first item would fit in the backpack, we can see what the total value would be if we take it or if we don t. In both of these two cases we recurse on the rest of the items. In python we can write this as follows: # Items are a list of tuples [(name,size,value),...] # Return value is tuple ([name,name,name,...], total_value) def knapsack(items,sizeleft): if items == []: # No more things left to pack return ([],0); elif items[0][1] > sizeleft: 11

14 # Next item is too large return knapsack(items[1:],sizeleft) else: # Case 1: do not pack this item items1,value1 = knapsack(items[1:],sizeleft) # Case 2: do pack this item items2,value2 = knapsack(items[1:],sizeleft - items[0][1]) # Return alternative giving the highest value? if value1 > value2+items[0][2]: return (items1,value1) else: return ([items[0][0]]+items2,value2+items[0][2]) If we test this algorithm on our problem, we see that the best solution is to take object A and C if our backpack is of size 6. Otherwise, other object combinations are better. >>> knapsack([("a",3,4),("b",2,2),("c",2,3)],3) ([ A ], 4) >>> knapsack([("a",3,4),("b",2,2),("c",2,3)],4) ([ B, C ], 5) >>> knapsack([("a",3,4),("b",2,2),("c",2,3)],5) ([ A, C ], 7) >>> knapsack([("a",3,4),("b",2,2),("c",2,3)],6) ([ A, C ], 7) >>> knapsack([("a",3,4),("b",2,2),("c",2,3)],7) ([ A, B, C ], 9) What we have done with this algorithm is an example of depth-first search, where we explore the full search space of the problem, to find an optimal solution. Unfortunately this solution is quite inefficient, but since the problem above is NP-complete you probably would not find any better method (and if you do, it is a revolutionary discovery!). 4.2 Stack based search An alternative way to implement a depth-first search is to implement your own stack. Remember that a stack is a data structure which has two operations: push an element to the top of the stack, and pop the element from the top of the stack. In Python, a stack can easily be represented by a list, and you can use the methods l.append(e) and l.pop() to push and pop from the stack. These methods actually modify the list which they are applied to. Notice that the top of the stack is at the end of the list. The following is an implementation of the path finding algorithm using a stack. In practice, this algorithm will perform exactly the same search as a recursive approach. def find_path_df(labyrinth,startx,starty,endx,endy): 12

15 # create initial stack with one element - the path # starting at the given start position stack = [ [(startx,starty)] ] # While the stack is not empty, go on... while stack: # Get the path at the top of the stack current_path = stack.pop() # Get the last place of that path x,y = current_path[-1] # Check if we have reached the goal if true: # *** Add your own goal check here! *** return current_path else: # Check were we can go from here # *** Add your own computation of next steps here! *** next_steps = [] # Add the new paths (one step longer) to the stack for s in next_steps: # *** You may want to perform some check here! *** stack.append(current_path+[s]) return False Now, a very nice thing about the stack-based depth-first algorithm, is that it is very easy to change it to a different search strategy. For instance, you can implement a breadth-first algorithm simply by changing the stack to a queue. Recall that in a queue, you insert elements at one end, and remove them from the other. To insert an element into a queue, you can use q.insert(0,e). 13

Artificial Intelligence Lecture 1

Artificial Intelligence Lecture 1 Artificial Intelligence Lecture 1 istrative Matters Webpage: www.aass.oru.se/~mbl/ai Examiner: Mathias Broxvall Assistant: Lia Susana d.c. Silva Lopez Schedule 20 hours/week on this course. 4 hours lectures,

More information

Language Reference Manual

Language Reference Manual ALACS Language Reference Manual Manager: Gabriel Lopez (gal2129) Language Guru: Gabriel Kramer-Garcia (glk2110) System Architect: Candace Johnson (crj2121) Tester: Terence Jacobs (tj2316) Table of Contents

More information

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0 6 Statements 43 6 Statements The statements of C# do not differ very much from those of other programming languages. In addition to assignments and method calls there are various sorts of selections and

More information

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Introduction to Python

Introduction to Python Introduction to Python Reading assignment: Perkovic text, Ch. 1 and 2.1-2.5 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions

More information

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s Intro to Python Python Getting increasingly more common Designed to have intuitive and lightweight syntax In this class, we will be using Python 3.x Python 2.x is still very popular, and the differences

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

Introduction to Python (All the Basic Stuff)

Introduction to Python (All the Basic Stuff) Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

More information

Python and Bioinformatics. Pierre Parutto

Python and Bioinformatics. Pierre Parutto Python and Bioinformatics Pierre Parutto October 9, 2016 Contents 1 Common Data Structures 2 1.1 Sequences............................... 2 1.1.1 Manipulating Sequences................... 2 1.1.2 String.............................

More information

The SPL Programming Language Reference Manual

The SPL Programming Language Reference Manual The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming

More information

Week - 01 Lecture - 04 Downloading and installing Python

Week - 01 Lecture - 04 Downloading and installing Python Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 01 Lecture - 04 Downloading and

More information

Statements 2. a operator= b a = a operator b

Statements 2. a operator= b a = a operator b Statements 2 Outline Note: i=i+1 is a valid statement. Don t confuse it with an equation i==i+1 which is always false for normal numbers. The statement i=i+1 is a very common idiom: it just increments

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

The current topic: Python. Announcements. Python. Python

The current topic: Python. Announcements. Python. Python The current topic: Python Announcements! Introduction! reasons for studying languages! language classifications! simple syntax specification Object-oriented programming: Python Types and values Syntax

More information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts COMP519 Web Programming Lecture 17: Python (Part 1) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

Fundamentals: Expressions and Assignment

Fundamentals: Expressions and Assignment Fundamentals: Expressions and Assignment A typical Python program is made up of one or more statements, which are executed, or run, by a Python console (also known as a shell) for their side effects e.g,

More information

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman 1. BASICS OF PYTHON JHU Physics & Astronomy Python Workshop 2017 Lecturer: Mubdi Rahman HOW IS THIS WORKSHOP GOING TO WORK? We will be going over all the basics you need to get started and get productive

More information

The Pyth Language. Administrivia

The Pyth Language. Administrivia Administrivia The Pyth Language Lecture 5 Please make sure you have registered your team, created SSH keys as indicated on the admin page, and also have electronically registered with us as well. Prof.

More information

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Introduction to: Computers & Programming: Review prior to 1 st Midterm Introduction to: Computers & Programming: Review prior to 1 st Midterm Adam Meyers New York University Summary Some Procedural Matters Summary of what you need to Know For the Test and To Go Further in

More information

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers Python Tutorial Lecture for EE562 Artificial Intelligence for Engineers 1 Why Python for AI? For many years, we used Lisp, because it handled lists and trees really well, had garbage collection, and didn

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. Plan for the rest of the semester: Programming We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. We saw earlier that computers

More information

python 01 September 16, 2016

python 01 September 16, 2016 python 01 September 16, 2016 1 Introduction to Python adapted from Steve Phelps lectures - (http://sphelps.net) 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: 7

More information

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

Comp Exam 1 Overview.

Comp Exam 1 Overview. Comp 170-400 Exam 1 Overview. Resources During the Exam The exam will be closed book, no calculators or computers, except as a word processor. In particular no Python interpreter running in a browser or

More information

Python: common syntax

Python: common syntax Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable

More information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More information

DaMPL. Language Reference Manual. Henrique Grando

DaMPL. Language Reference Manual. Henrique Grando DaMPL Language Reference Manual Bernardo Abreu Felipe Rocha Henrique Grando Hugo Sousa bd2440 flt2107 hp2409 ha2398 Contents 1. Getting Started... 4 2. Syntax Notations... 4 3. Lexical Conventions... 4

More information

Programming with Python

Programming with Python Programming with Python Dr Ben Dudson Department of Physics, University of York 21st January 2011 http://www-users.york.ac.uk/ bd512/teaching.shtml Dr Ben Dudson Introduction to Programming - Lecture 2

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

This example highlights the difference between imperative and functional programming. The imperative programming solution is based on an accumulator

This example highlights the difference between imperative and functional programming. The imperative programming solution is based on an accumulator 1 2 This example highlights the difference between imperative and functional programming. The imperative programming solution is based on an accumulator (total) and a counter (i); it works by assigning

More information

6.001 Notes: Section 6.1

6.001 Notes: Section 6.1 6.001 Notes: Section 6.1 Slide 6.1.1 When we first starting talking about Scheme expressions, you may recall we said that (almost) every Scheme expression had three components, a syntax (legal ways of

More information

CS 211 Programming Practicum Fall 2018

CS 211 Programming Practicum Fall 2018 Due: Wednesday, 11/7/18 at 11:59 pm Infix Expression Evaluator Programming Project 5 For this lab, write a C++ program that will evaluate an infix expression. The algorithm REQUIRED for this program will

More information

CS Advanced Unix Tools & Scripting

CS Advanced Unix Tools & Scripting & Scripting Spring 2011 Hussam Abu-Libdeh slides by David Slater March 4, 2011 Hussam Abu-Libdeh slides by David Slater & Scripting Python An open source programming language conceived in the late 1980s.

More information

A LISP Interpreter in ML

A LISP Interpreter in ML UNIVERSITY OF OSLO Department of Informatics A LISP Interpreter in ML Mandatory Assignment 1 INF3110 September 21, 2009 Contents 1 1 Introduction The purpose of this assignment is to write an interpreter,

More information

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17 01.433/33 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/2/1.1 Introduction In this lecture we ll talk about a useful abstraction, priority queues, which are

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

Python - Variable Types. John R. Woodward

Python - Variable Types. John R. Woodward Python - Variable Types John R. Woodward Variables 1. Variables are nothing but named reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

More information

SECOND EDITION SAMPLE CHAPTER. First edition by Daryl K. Harms Kenneth M. McDonald. Naomi R. Ceder MANNING

SECOND EDITION SAMPLE CHAPTER. First edition by Daryl K. Harms Kenneth M. McDonald. Naomi R. Ceder MANNING SECOND EDITION SECOND EDITION Covers Python 3 SAMPLE CHAPTER First edition by Daryl K. Harms Kenneth M. McDonald Naomi R. Ceder MANNING The Quick Python Book Second Edition by Naomi R. Ceder Chapter 8

More information

LISP. Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits.

LISP. Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits. LISP Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits. From one perspective, sequences of bits can be interpreted as a code for ordinary decimal digits,

More information

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G. Haskell: Lists CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks

More information

Some material adapted from Upenn cmpe391 slides and other sources

Some material adapted from Upenn cmpe391 slides and other sources Some material adapted from Upenn cmpe391 slides and other sources History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

CSC148 Week 2. Larry Zhang

CSC148 Week 2. Larry Zhang CSC148 Week 2 Larry Zhang 1 Admin Discussion board is up (link on the course website). 2 Outline for this week Abstract Data Type Stack Queue 3 Abstract Data Type (ADT) 4 What is an abstract data type

More information

Scripting Languages. Python basics

Scripting Languages. Python basics Scripting Languages Python basics Interpreter Session: python Direct conversation with python (>>>) Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright",

More information

1007 Imperative Programming Part II

1007 Imperative Programming Part II Agenda 1007 Imperative Programming Part II We ve seen the basic ideas of sequence, iteration and selection. Now let s look at what else we need to start writing useful programs. Details now start to be

More information

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an  . Michigan State University CSE 231, Fall 2013 CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?

More information

CS1 Lecture 5 Jan. 25, 2019

CS1 Lecture 5 Jan. 25, 2019 CS1 Lecture 5 Jan. 25, 2019 HW1 due Monday, 9:00am. Notes: Do not write all the code at once before starting to test. Take tiny steps. Write a few lines test... add a line or two test... add another line

More information

ENGR 101 Engineering Design Workshop

ENGR 101 Engineering Design Workshop ENGR 101 Engineering Design Workshop Lecture 2: Variables, Statements/Expressions, if-else Edgardo Molina City College of New York Literals, Variables, Data Types, Statements and Expressions Python as

More information

CME 193: Introduction to Scientific Python Lecture 1: Introduction

CME 193: Introduction to Scientific Python Lecture 1: Introduction CME 193: Introduction to Scientific Python Lecture 1: Introduction Nolan Skochdopole stanford.edu/class/cme193 1: Introduction 1-1 Contents Administration Introduction Basics Variables Control statements

More information

GeoCode Language Reference Manual

GeoCode Language Reference Manual GeoCode Language Reference Manual Contents 1 Introduction... 3 2 Lexical Elements... 3 2.1 Identifiers... 3 2.2 Keywords... 3 2.3 Literals... 3 2.4 Line Structure... 4 2.5 Indentation... 4 2.6 Whitespace...

More information

DSC 201: Data Analysis & Visualization

DSC 201: Data Analysis & Visualization DSC 201: Data Analysis & Visualization Arrays Dr. David Koop Class Example class Rectangle: def init (self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h def set_corner(self, x, y): self.x =

More information

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

Emil Sekerinski, McMaster University, Winter Term 16/17 COMP SCI 1MD3 Introduction to Programming

Emil Sekerinski, McMaster University, Winter Term 16/17 COMP SCI 1MD3 Introduction to Programming Emil Sekerinski, McMaster University, Winter Term 16/17 COMP SCI 1MD3 Introduction to Programming In Python, variables are names of objects base 5 >>> base = 5 >>> height = 4 >>> area = base*height/2 >>>

More information

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems CSSE 120 Introduction to Software Development Exam 1 Format, Concepts, What you should be able to do, and Sample Problems Page 1 of 6 Format: The exam will have two sections: Part 1: Paper-and-Pencil o

More information

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016 Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada Under Supervision of: Dr. Richard Kelley Chief Engineer, NAASIC March 6th, 2016 Science Technology Engineering

More information

Overview of List Syntax

Overview of List Syntax Lists and Sequences Overview of List Syntax x = [0, 0, 0, 0] Create list of length 4 with all zeroes x 4300112 x.append(2) 3 in x x[2] = 5 x[0] = 4 k = 3 Append 2 to end of list x (now length 5) Evaluates

More information

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015 SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Chapter 2 Getting Started with Python

Chapter 2 Getting Started with Python Chapter 2 Getting Started with Python Introduction Python Programming language was developed by Guido Van Rossum in February 1991. It is based on or influenced with two programming languages: 1. ABC language,

More information

SCHEME AND CALCULATOR 5b

SCHEME AND CALCULATOR 5b SCHEME AND CALCULATOR 5b COMPUTER SCIENCE 6A July 25, 203 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Introduction to TURING

Introduction to TURING Introduction to TURING Comments Some code is difficult to understand, even if you understand the language it is written in. To that end, the designers of programming languages have allowed us to comment

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

Python memento TI-Smart Grids

Python memento TI-Smart Grids Python memento TI-Smart Grids Genoveva Vargas-Solar French Council of Scientific Research, LIG genoveva.vargas@imag.fr http://vargas-solar.com/data-centric-smart-everything/ * This presentation was created

More information

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CS2304: Python for Java Programmers. CS2304: Sequences and Collections CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for

More information

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1 A First Look at ML Chapter Five Modern Programming Languages, 2nd ed. 1 ML Meta Language One of the more popular functional languages (which, admittedly, isn t saying much) Edinburgh, 1974, Robin Milner

More information

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Some material adapted from Upenn cmpe391 slides and other sources Invented in the Netherlands,

More information

TUPLES AND RECURSIVE LISTS 5

TUPLES AND RECURSIVE LISTS 5 TUPLES AND RECURSIVE LISTS 5 COMPUTER SCIENCE 61A July 3, 2012 1 Sequences From the Pig project, we discovered the utility of having structures that contain multiple values. Today, we are going to cover

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Binghamton University. CS-120 Summer Introduction to C. Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13

Binghamton University. CS-120 Summer Introduction to C. Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13 Introduction to C Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13 Problem: Too Many Details For example: Lab 7 Bubble Sort Needed to keep track of too many details! Outer Loop When do

More information

CS 102 Lab 3 Fall 2012

CS 102 Lab 3 Fall 2012 Name: The symbol marks programming exercises. Upon completion, always capture a screenshot and include it in your lab report. Email lab report to instructor at the end of the lab. Review of built-in functions

More information

8. Control statements

8. Control statements 8. Control statements A simple C++ statement is each of the individual instructions of a program, like the variable declarations and expressions seen in previous sections. They always end with a semicolon

More information

CS 115 Lecture 4. More Python; testing software. Neil Moore

CS 115 Lecture 4. More Python; testing software. Neil Moore CS 115 Lecture 4 More Python; testing software Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 8 September 2015 Syntax: Statements A statement

More information

CS1 Lecture 3 Jan. 22, 2018

CS1 Lecture 3 Jan. 22, 2018 CS1 Lecture 3 Jan. 22, 2018 Office hours for me and for TAs have been posted, locations will change check class website regularly First homework available, due Mon., 9:00am. Discussion sections tomorrow

More information

CS61A Lecture 15. Amir Kamil UC Berkeley February 25, 2013

CS61A Lecture 15. Amir Kamil UC Berkeley February 25, 2013 CS61A Lecture 15 Amir Kamil UC Berkeley February 25, 2013 Announcements HW5 due on Wednesday Trends project out Partners are required; find one in lab or on Piazza Will not work in IDLE New bug submission

More information

Python in 10 (50) minutes

Python in 10 (50) minutes Python in 10 (50) minutes https://www.stavros.io/tutorials/python/ Python for Microcontrollers Getting started with MicroPython Donald Norris, McGrawHill (2017) Python is strongly typed (i.e. types are

More information

Babu Madhav Institute of Information Technology, UTU 2015

Babu Madhav Institute of Information Technology, UTU 2015 Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?

More information

Problem Solving for Intro to Computer Science

Problem Solving for Intro to Computer Science Problem Solving for Intro to Computer Science The purpose of this document is to review some principles for problem solving that are relevant to Intro to Computer Science course. Introduction: A Sample

More information

CS109A ML Notes for the Week of 1/16/96. Using ML. ML can be used as an interactive language. We. shall use a version running under UNIX, called

CS109A ML Notes for the Week of 1/16/96. Using ML. ML can be used as an interactive language. We. shall use a version running under UNIX, called CS109A ML Notes for the Week of 1/16/96 Using ML ML can be used as an interactive language. We shall use a version running under UNIX, called SML/NJ or \Standard ML of New Jersey." You can get SML/NJ by

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1 Lecture #15: Generic Functions and Expressivity Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 1 Consider the function find: Generic Programming def find(l, x, k): """Return the index in L of

More information

Scheme as implemented by Racket

Scheme as implemented by Racket Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the

More information

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement Outline Expression Evaluation and Control Flow In Text: Chapter 6 Notation Operator evaluation order Operand evaluation order Overloaded operators Type conversions Short-circuit evaluation of conditions

More information

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON Table of contents 2 1. Learning Outcomes 2. Introduction 3. The first program: hello world! 4. The second program: hello (your name)! 5. More data types 6.

More information

Introduction to Python Programming

Introduction to Python Programming advances IN SYSTEMS AND SYNTHETIC BIOLOGY 2018 Anna Matuszyńska Oliver Ebenhöh oliver.ebenhoeh@hhu.de Ovidiu Popa ovidiu.popa@hhu.de Our goal Learning outcomes You are familiar with simple mathematical

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information