Lectures from a Python workshop I taught in 2013 at the University of Pittsburgh. These are introductory slides to teach important aspects of the Python language.
Update: python limits the number of recursion calls, so computing the factorial as shown in the slides may not be generally usable.
The document outlines a presentation on mobile game programming and stacks. It discusses abstract data types (ADTs), data structures, and specifically focuses on stacks. It provides examples of stack implementations in C++ using classes and templates. Finally, it discusses algorithms that use stacks, including converting number systems, evaluating postfix notation, and converting infix to postfix notation.
A Gentle Introduction to Coding ... with PythonTariq Rashid
A gentle introduction to coding (programming) for complete beginners. Starting from then basics - electrical wires - proceeding through variables, data structures, loops, functions, and exploring libraries for visualisation and specialist tools. Finally we use flask to make a very simple twitter clone web application.
Can two fixpoint types in Mendler style unite?Ki Yung Ahn
This document discusses Mendler-style recursion schemes for mixed-variant datatypes. It introduces Mendler-style iteration (mit) and iteration with a syntactic inverse (msfit). msfit allows formatting of untyped and simply-typed higher-order abstract syntax (HOAS) by evaluating at different kinds. A new recursion scheme is proposed to define a function for evaluating simply-typed HOAS into a user-defined value domain. The relationship between Mu and Mu' fixed point types is also discussed.
The document discusses top-down and bottom-up parsing techniques, with top-down parsing constructing a parse tree starting from the root node and working downward, while bottom-up parsing uses shift-reduce parsing to shift input symbols onto a stack and reduce the stack based on grammar rules. It also covers topics like recursive descent parsing, predictive parsing tables, LL(1) grammars, and error recovery techniques used in parsing.
The document is a model question paper for the subject Fundamentals of Theory of Computer Science. It contains questions in three parts - Part A contains one mark questions, Part B contains two mark questions, and Part C contains four mark questions. The questions cover topics related to sets, functions, graphs, formal languages, grammars, automata and regular expressions.
The document discusses stacks and queues. A stack follows the LIFO (last in, first out) principle where the last element added is the first to be removed. Real-world examples include plates and books. Queues follow the FIFO (first in, first out) principle where the first element added is the first to be removed, as seen with ticket lines. Visual simulations and examples of using stacks for recursion and queues for threading are provided.
This document discusses top-down parsing and predictive parsing. It begins with an overview of top-down parsing, noting that the parse tree is constructed from the top-down and left-to-right. It then discusses recursive descent parsing and its limitations for ambiguous, left-recursive, or non-left-factored grammars. Finally, it introduces LL(1) parsing and how LL(1) parsing tables can be used to predict the next production without backtracking, making parsing more efficient.
The document discusses 10 important C programming interview questions. It provides detailed solutions to questions such as swapping two variables without a temporary variable, solving the 8 queens problem, printing a matrix helically, reversing words in a sentence in-place, generating permutations, and calculating the factorial of a number recursively. For each question, it explains the algorithm and provides sample C code to implement the solution.
The document outlines a presentation on mobile game programming and stacks. It discusses abstract data types (ADTs), data structures, and specifically focuses on stacks. It provides examples of stack implementations in C++ using classes and templates. Finally, it discusses algorithms that use stacks, including converting number systems, evaluating postfix notation, and converting infix to postfix notation.
A Gentle Introduction to Coding ... with PythonTariq Rashid
A gentle introduction to coding (programming) for complete beginners. Starting from then basics - electrical wires - proceeding through variables, data structures, loops, functions, and exploring libraries for visualisation and specialist tools. Finally we use flask to make a very simple twitter clone web application.
Can two fixpoint types in Mendler style unite?Ki Yung Ahn
This document discusses Mendler-style recursion schemes for mixed-variant datatypes. It introduces Mendler-style iteration (mit) and iteration with a syntactic inverse (msfit). msfit allows formatting of untyped and simply-typed higher-order abstract syntax (HOAS) by evaluating at different kinds. A new recursion scheme is proposed to define a function for evaluating simply-typed HOAS into a user-defined value domain. The relationship between Mu and Mu' fixed point types is also discussed.
The document discusses top-down and bottom-up parsing techniques, with top-down parsing constructing a parse tree starting from the root node and working downward, while bottom-up parsing uses shift-reduce parsing to shift input symbols onto a stack and reduce the stack based on grammar rules. It also covers topics like recursive descent parsing, predictive parsing tables, LL(1) grammars, and error recovery techniques used in parsing.
The document is a model question paper for the subject Fundamentals of Theory of Computer Science. It contains questions in three parts - Part A contains one mark questions, Part B contains two mark questions, and Part C contains four mark questions. The questions cover topics related to sets, functions, graphs, formal languages, grammars, automata and regular expressions.
The document discusses stacks and queues. A stack follows the LIFO (last in, first out) principle where the last element added is the first to be removed. Real-world examples include plates and books. Queues follow the FIFO (first in, first out) principle where the first element added is the first to be removed, as seen with ticket lines. Visual simulations and examples of using stacks for recursion and queues for threading are provided.
This document discusses top-down parsing and predictive parsing. It begins with an overview of top-down parsing, noting that the parse tree is constructed from the top-down and left-to-right. It then discusses recursive descent parsing and its limitations for ambiguous, left-recursive, or non-left-factored grammars. Finally, it introduces LL(1) parsing and how LL(1) parsing tables can be used to predict the next production without backtracking, making parsing more efficient.
The document discusses 10 important C programming interview questions. It provides detailed solutions to questions such as swapping two variables without a temporary variable, solving the 8 queens problem, printing a matrix helically, reversing words in a sentence in-place, generating permutations, and calculating the factorial of a number recursively. For each question, it explains the algorithm and provides sample C code to implement the solution.
The document discusses top-down and bottom-up parsing techniques. Top-down parsing constructs a parse tree starting from the root node and progresses depth-first. It can require backtracking. Bottom-up parsing uses shift-reduce parsing, shifting input symbols onto a stack until they can be reduced based on grammar rules.
A queue is a data structure that follows the first-in, first-out (FIFO) principle. Elements are added to the rear of the queue and removed from the front. A queue can be implemented using an array, with indexes to track the front and rear elements. When an element is added (enqueued), the rear index is incremented; when an element is removed (dequeued), the front index is incremented and the element at that index is returned. The queue has a limited capacity based on the size of the array.
The document discusses top-down parsing and predictive parsing. It defines key concepts like scanners, parsers, syntax analyzers, parse trees, top-down parsing, and predictive parsing. It also describes the process of constructing a predictive parsing table using the First and Follow sets of a grammar's productions.
THIS PPT CONSISTS OF MOST ASKED QUESTIONS OF FIRST CHAPTER OF CLASS 12 PYTHON. THERE ARE QUESTIONS FROM BOARD PAPERS AS WELL AS KENDRIYALA VIDYALAYA SCHOOL.
This document discusses plotting experimental data using Python. It covers plotting points, lists, reading data from a file, and generating a plot of pendulum length vs period-squared from experimental data. The document demonstrates plotting points, using lists to store x and y data, reading a data file line-by-line and splitting each line into a list, converting data from strings to floats, and generating a plot of pendulum length vs period-squared using the data read from the file.
The document discusses several advanced intermediate code generation techniques used in compilers, including:
1) Reusing temporary variable names to avoid using new temps whenever possible.
2) Addressing elements in one-dimensional and multi-dimensional arrays using base addresses and calculating offsets.
3) Translating logical, relational, and Boolean expressions using three-address code with temporary variables to store intermediate values.
The document discusses different ways to implement tables or dictionaries using data structures like arrays, linked lists, and skip lists. It explains that tables consist of rows and columns of data with fields/keys that uniquely identify each entry. Arrays allow fast searching if sorted but slow insertion/deletion. Linked lists allow fast insertion/deletion but slow searching. Skip lists combine fast search of sorted data structures with fast insertion/deletion of unsorted structures.
This document discusses Java bytecodes and provides examples of evaluating expressions and decompiling Java bytecode. It begins with an introduction to Java bytecodes and shows the bytecode generated from a Java source code example. Stack-based evaluation of an expression using bytecode operations is demonstrated. The document also shows using javap to disassemble a Java class file and decompiling bytecode back into Java source code.
Binary search is like looking up a phone number or a word in the dictionary Start in middle of book If name you're looking for comes before names on page, look in first half
Otherwise, look in second half
Monoids - Part 1 - with examples using Scalaz and CatsPhilip Schwarz
A monoid is an algebraic structure consisting of a set and a binary operation that is associative and has an identity element. Some key properties of monoids include:
1) A monoid consists of a type A, a binary operation op that combines two values of type A, and a zero value that acts as an identity.
2) The binary operation must be associative, meaning op(op(x,y),z) = op(x,op(y,z)).
3) The zero value must satisfy the identity laws: op(x, zero) = x and op(zero, x) = x.
4) Common examples of monoids include string concatenation
Monoids - Part 2 - with examples using Scalaz and CatsPhilip Schwarz
The document discusses monoids in Scalaz and Cats, specifically for the Option type. It explains that in Scalaz there are three Option monoids (optionFirst, optionLast, optionMonoid) that combine Options in different ways, while Cats only has one Option monoid (optionMonoid) that combines the contents. It also introduces MonoidK, which allows constructing a monoid that behaves like optionFirst by combining Options based on their orElse method. The document provides examples and explanations of how Semigroup, SemigroupK, Monoid, and MonoidK work and differ for types like List, Set, and Option. It also defines a monoid for endofunctions that composes
The document discusses queues, which are a data structure that provides first-in, first-out (FIFO) access to elements. Queues are useful for applications like print jobs and network communications where elements need to be processed in the order they are received. The key queue operations are enqueue, which inserts an element at the rear, and dequeue, which removes an element from the front. The document provides code for an IntQueue class that implements these operations using a circular array to represent the queue.
This document discusses LR parsers and the process of constructing SLR parsing tables. It begins by defining LR(0) items and the closure operation, which is used to find all LR(0) items that are reachable from a given set. The goto operation finds the set of LR(0) items for a given non-terminal. The canonical LR(0) collection is constructed by applying closure and goto until no new items can be added. This collection forms the basis for the SLR parsing tables, which are constructed by determining shift and reduce actions based on the LR(0) items in each state. The document provides examples of shift-reduce and reduce-reduce conflicts that can occur in SLR parsing tables.
Programming Paradigms Which One Is The Best?Netguru
The document discusses different programming paradigms and which one may be best. It describes object-oriented programming, imperative programming, and declarative programming. For each, it provides examples in code to illustrate the paradigm. It argues that while imperative programming is popular and easy, it can be error-prone and not scale well. Declarative programming is described as simpler, safer, and more scalable by declaring intent rather than implementation. In the end, the document concludes that no single paradigm is best, and that they are often used together in practice.
This document discusses top-down parsing and different types of top-down parsers, including recursive descent parsers, predictive parsers, and LL(1) grammars. It explains how to build predictive parsers without recursion by using a parsing table constructed from the FIRST and FOLLOW sets of grammar symbols. The key steps are: 1) computing FIRST and FOLLOW, 2) filling the predictive parsing table based on FIRST/FOLLOW, 3) using the table to parse inputs in a non-recursive manner by maintaining the parser's own stack. An example is provided to illustrate constructing the FIRST/FOLLOW sets and parsing table for a sample grammar.
Big picture of category theory in scala with deep dive into contravariant and...Piotr Paradziński
A big picture of category theory in Scala - starting from regular functors with additional structure (Apply, Applicative, Monad) to Comonads. Usually, we think about structures like Monoids in a monoidal category with particular tensor. In here I analyze just signatures of different abstractions.
Exploration of Contravariant functors as a way to model computation "backward" or abstract over input with the ability to prepend operation. Examples for predicates, sorting, show and function input (or any other function parameter except the last one).
Profunctors as abstraction unifying Functors and Contravariant functors to model both input and output. Example for Profunctor - function with one argument.
Relation to Bifunctors, Kan extensions, Adjunctions, and Free constructions.
The document discusses several concepts related to code optimization including flow graphs, basic blocks, control flow graphs, successor and predecessor blocks, and liveness analysis using next-use information. It describes how basic block partitioning works and how common code transformations like common subexpression elimination, dead code elimination, and instruction reordering can optimize code. It also covers register allocation techniques like graph coloring to minimize register spills.
Why functional programming and category theory strongly mattersPiotr Paradziński
Abstractions of Category Theory to define abstractions (Functor, Applicative, Monad, Comonad, Coyoneda) commonly used in functional programming (FP). Using definitions from Category Theory to reason about modular and composable design. Examples based on Haskell papers: Functional pearls translated to Scala.
Lecture 5 – Computing with Numbers (Math Lib).pptxjovannyflex
This document provides an overview of numeric data types and operations in Python. It discusses integers and floats, and how they represent numeric values differently. Functions for determining data types like type() and converting between types are presented. Core numeric operations like addition, subtraction, multiplication, division, and modulo are covered. The use of accumulators and loops to calculate factorial and solve other numeric problems is demonstrated. Finally, the math library module is introduced for accessing advanced math functions like square root, trigonometric functions, rounding, and random number generation.
Lecture 5 – Computing with Numbers (Math Lib).pptxjovannyflex
This document provides an overview of numeric data types and operations in Python. It discusses integers and floats, and how they represent numeric values differently. Functions for determining data types like type() and converting between types are presented. Core numeric operations like addition, subtraction, multiplication, division, and modulus are covered. The use of accumulators and loops to calculate factorial and solve other numeric problems is demonstrated. Finally, the math library module is introduced for accessing advanced math functions like square root, trigonometric functions, rounding, and random number generation.
The document discusses top-down and bottom-up parsing techniques. Top-down parsing constructs a parse tree starting from the root node and progresses depth-first. It can require backtracking. Bottom-up parsing uses shift-reduce parsing, shifting input symbols onto a stack until they can be reduced based on grammar rules.
A queue is a data structure that follows the first-in, first-out (FIFO) principle. Elements are added to the rear of the queue and removed from the front. A queue can be implemented using an array, with indexes to track the front and rear elements. When an element is added (enqueued), the rear index is incremented; when an element is removed (dequeued), the front index is incremented and the element at that index is returned. The queue has a limited capacity based on the size of the array.
The document discusses top-down parsing and predictive parsing. It defines key concepts like scanners, parsers, syntax analyzers, parse trees, top-down parsing, and predictive parsing. It also describes the process of constructing a predictive parsing table using the First and Follow sets of a grammar's productions.
THIS PPT CONSISTS OF MOST ASKED QUESTIONS OF FIRST CHAPTER OF CLASS 12 PYTHON. THERE ARE QUESTIONS FROM BOARD PAPERS AS WELL AS KENDRIYALA VIDYALAYA SCHOOL.
This document discusses plotting experimental data using Python. It covers plotting points, lists, reading data from a file, and generating a plot of pendulum length vs period-squared from experimental data. The document demonstrates plotting points, using lists to store x and y data, reading a data file line-by-line and splitting each line into a list, converting data from strings to floats, and generating a plot of pendulum length vs period-squared using the data read from the file.
The document discusses several advanced intermediate code generation techniques used in compilers, including:
1) Reusing temporary variable names to avoid using new temps whenever possible.
2) Addressing elements in one-dimensional and multi-dimensional arrays using base addresses and calculating offsets.
3) Translating logical, relational, and Boolean expressions using three-address code with temporary variables to store intermediate values.
The document discusses different ways to implement tables or dictionaries using data structures like arrays, linked lists, and skip lists. It explains that tables consist of rows and columns of data with fields/keys that uniquely identify each entry. Arrays allow fast searching if sorted but slow insertion/deletion. Linked lists allow fast insertion/deletion but slow searching. Skip lists combine fast search of sorted data structures with fast insertion/deletion of unsorted structures.
This document discusses Java bytecodes and provides examples of evaluating expressions and decompiling Java bytecode. It begins with an introduction to Java bytecodes and shows the bytecode generated from a Java source code example. Stack-based evaluation of an expression using bytecode operations is demonstrated. The document also shows using javap to disassemble a Java class file and decompiling bytecode back into Java source code.
Binary search is like looking up a phone number or a word in the dictionary Start in middle of book If name you're looking for comes before names on page, look in first half
Otherwise, look in second half
Monoids - Part 1 - with examples using Scalaz and CatsPhilip Schwarz
A monoid is an algebraic structure consisting of a set and a binary operation that is associative and has an identity element. Some key properties of monoids include:
1) A monoid consists of a type A, a binary operation op that combines two values of type A, and a zero value that acts as an identity.
2) The binary operation must be associative, meaning op(op(x,y),z) = op(x,op(y,z)).
3) The zero value must satisfy the identity laws: op(x, zero) = x and op(zero, x) = x.
4) Common examples of monoids include string concatenation
Monoids - Part 2 - with examples using Scalaz and CatsPhilip Schwarz
The document discusses monoids in Scalaz and Cats, specifically for the Option type. It explains that in Scalaz there are three Option monoids (optionFirst, optionLast, optionMonoid) that combine Options in different ways, while Cats only has one Option monoid (optionMonoid) that combines the contents. It also introduces MonoidK, which allows constructing a monoid that behaves like optionFirst by combining Options based on their orElse method. The document provides examples and explanations of how Semigroup, SemigroupK, Monoid, and MonoidK work and differ for types like List, Set, and Option. It also defines a monoid for endofunctions that composes
The document discusses queues, which are a data structure that provides first-in, first-out (FIFO) access to elements. Queues are useful for applications like print jobs and network communications where elements need to be processed in the order they are received. The key queue operations are enqueue, which inserts an element at the rear, and dequeue, which removes an element from the front. The document provides code for an IntQueue class that implements these operations using a circular array to represent the queue.
This document discusses LR parsers and the process of constructing SLR parsing tables. It begins by defining LR(0) items and the closure operation, which is used to find all LR(0) items that are reachable from a given set. The goto operation finds the set of LR(0) items for a given non-terminal. The canonical LR(0) collection is constructed by applying closure and goto until no new items can be added. This collection forms the basis for the SLR parsing tables, which are constructed by determining shift and reduce actions based on the LR(0) items in each state. The document provides examples of shift-reduce and reduce-reduce conflicts that can occur in SLR parsing tables.
Programming Paradigms Which One Is The Best?Netguru
The document discusses different programming paradigms and which one may be best. It describes object-oriented programming, imperative programming, and declarative programming. For each, it provides examples in code to illustrate the paradigm. It argues that while imperative programming is popular and easy, it can be error-prone and not scale well. Declarative programming is described as simpler, safer, and more scalable by declaring intent rather than implementation. In the end, the document concludes that no single paradigm is best, and that they are often used together in practice.
This document discusses top-down parsing and different types of top-down parsers, including recursive descent parsers, predictive parsers, and LL(1) grammars. It explains how to build predictive parsers without recursion by using a parsing table constructed from the FIRST and FOLLOW sets of grammar symbols. The key steps are: 1) computing FIRST and FOLLOW, 2) filling the predictive parsing table based on FIRST/FOLLOW, 3) using the table to parse inputs in a non-recursive manner by maintaining the parser's own stack. An example is provided to illustrate constructing the FIRST/FOLLOW sets and parsing table for a sample grammar.
Big picture of category theory in scala with deep dive into contravariant and...Piotr Paradziński
A big picture of category theory in Scala - starting from regular functors with additional structure (Apply, Applicative, Monad) to Comonads. Usually, we think about structures like Monoids in a monoidal category with particular tensor. In here I analyze just signatures of different abstractions.
Exploration of Contravariant functors as a way to model computation "backward" or abstract over input with the ability to prepend operation. Examples for predicates, sorting, show and function input (or any other function parameter except the last one).
Profunctors as abstraction unifying Functors and Contravariant functors to model both input and output. Example for Profunctor - function with one argument.
Relation to Bifunctors, Kan extensions, Adjunctions, and Free constructions.
The document discusses several concepts related to code optimization including flow graphs, basic blocks, control flow graphs, successor and predecessor blocks, and liveness analysis using next-use information. It describes how basic block partitioning works and how common code transformations like common subexpression elimination, dead code elimination, and instruction reordering can optimize code. It also covers register allocation techniques like graph coloring to minimize register spills.
Why functional programming and category theory strongly mattersPiotr Paradziński
Abstractions of Category Theory to define abstractions (Functor, Applicative, Monad, Comonad, Coyoneda) commonly used in functional programming (FP). Using definitions from Category Theory to reason about modular and composable design. Examples based on Haskell papers: Functional pearls translated to Scala.
Lecture 5 – Computing with Numbers (Math Lib).pptxjovannyflex
This document provides an overview of numeric data types and operations in Python. It discusses integers and floats, and how they represent numeric values differently. Functions for determining data types like type() and converting between types are presented. Core numeric operations like addition, subtraction, multiplication, division, and modulo are covered. The use of accumulators and loops to calculate factorial and solve other numeric problems is demonstrated. Finally, the math library module is introduced for accessing advanced math functions like square root, trigonometric functions, rounding, and random number generation.
Lecture 5 – Computing with Numbers (Math Lib).pptxjovannyflex
This document provides an overview of numeric data types and operations in Python. It discusses integers and floats, and how they represent numeric values differently. Functions for determining data types like type() and converting between types are presented. Core numeric operations like addition, subtraction, multiplication, division, and modulus are covered. The use of accumulators and loops to calculate factorial and solve other numeric problems is demonstrated. Finally, the math library module is introduced for accessing advanced math functions like square root, trigonometric functions, rounding, and random number generation.
This document provides a quick tour of the Python programming language. It introduces basic Python concepts like data types, variables, operators, conditional statements, loops, and functions. It explains how to get user input, perform type conversions, and work with common data types like integers, floats, strings, and booleans. It also demonstrates how to define functions, use default arguments and keyword arguments, and handle global variables. The document uses examples to illustrate concepts like arithmetic operations, string slicing, indexing, concatenation, and repetition.
Good morning Salma Hayek you have to do is your purpose of the best time to plant grass seed in the morning Salma Hayek you have to do is your purpose of the best time to plant grass seed in the morning Salma Hayek you have to do is your purpose of the best time to plant grass seed in the morning Salma Hayek you want me potter to plant in spring I will be there in the morning Salma Hayek you have a nice weekend with someone legally allowed in spring a contract for misunderstanding and tomorrow I hope it was about the best msg you want me potter you want me potter you want to do is your purpose of the best time to plant grass seed in the morning Salma Hayek you have to do it up but what do you think about the pros of the morning Salma good mornings are you doing well and tomorrow I hope it goes well and I hope you to do it goes well and tomorrow I have to be there at both locations in spring a nice day service and I hope it goes away soon as I can you have to be to get a I hope it goes away soon I hope it goes away soon I hope it goes away soon as I can you have to be to work at a time I can do is
The document provides an introduction and tutorial to the Python programming language. It covers 13 chapters that introduce very basic Python concepts up to more advanced topics like classes and CGI programming. The chapters include variables, data types, operators, conditionals, functions, iteration, strings, collection data types, exception handling, modules, files, documentation, and classes. The document also notes several sources that were used to create the tutorial and provides example code snippets throughout to demonstrate the concepts discussed.
This presentation about Python Interview Questions will help you crack your next Python interview with ease. The video includes interview questions on Numbers, lists, tuples, arrays, functions, regular expressions, strings, and files. We also look into concepts such as multithreading, deep copy, and shallow copy, pickling and unpickling. This video also covers Python libraries such as matplotlib, pandas, numpy,scikit and the programming paradigms followed by Python. It also covers Python library interview questions, libraries such as matplotlib, pandas, numpy and scikit. This video is ideal for both beginners as well as experienced professionals who are appearing for Python programming job interviews. Learn what are the most important Python interview questions and answers and know what will set you apart in the interview process.
Simplilearn’s Python Training Course is an all-inclusive program that will introduce you to the Python development language and expose you to the essentials of object-oriented programming, web development with Django and game development. Python has surpassed Java as the top language used to introduce U.S. students to programming and computer science. This course will give you hands-on development experience and prepare you for a career as a professional Python programmer.
What is this course about?
The All-in-One Python course enables you to become a professional Python programmer. Any aspiring programmer can learn Python from the basics and go on to master web development & game development in Python. Gain hands on experience creating a flappy bird game clone & website functionalities in Python.
What are the course objectives?
By the end of this online Python training course, you will be able to:
1. Internalize the concepts & constructs of Python
2. Learn to create your own Python programs
3. Master Python Django & advanced web development in Python
4. Master PyGame & game development in Python
5. Create a flappy bird game clone
The Python training course is recommended for:
1. Any aspiring programmer can take up this bundle to master Python
2. Any aspiring web developer or game developer can take up this bundle to meet their training needs
Learn more at https://www.simplilearn.com/mobile-and-software-development/python-development-training
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
Python
Language
is uesd in engineeringStory adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they s
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
This document provides an introduction to learning Python. It discusses prerequisites for Python, basic Python concepts like variables, data types, operators, conditionals and loops. It also covers functions, files, classes and exceptions handling in Python. The document demonstrates these concepts through examples and exercises learners to practice char frequency counting and Caesar cipher encoding/decoding in Python. It encourages learners to practice more to master the language and provides additional learning resources.
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnArnaud Joly
We first present the Python programming language and the NumPy package for scientific computing. Then, we devise a digit recognition system highlighting the scikit-learn package.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists, and tuples. It explains that lists are mutable while tuples are immutable. The document also covers topics like functions, modules, control flow, and the Python interpreter.
This question paper is divided into 3 sections for the Computer Science exam. Section A has 25 multiple choice questions to attempt 20. Section B has 24 multiple choice questions to attempt 20. Section C has 6 case study based questions to attempt 5. All questions carry equal marks. The document provides a sample question paper format and questions asked in sections A and B. Rohit has been given an incomplete Python code to create a CSV file from a list of student records and needs help completing it.
The document provides an overview of the Python programming language. It discusses why Python is useful for students and professionals, its major features like being object-oriented and having a large standard library. The document also covers Python's history, how to install it and set the environment variables, basic syntax like variables and data types, operators, and common programming constructs like conditionals and loops.
Hamid Milton Mansaray teaches the chapter on arrays, pointers, and strings in week 8. Some key points covered include initializing and accessing elements of one-dimensional arrays using indexing or pointers, passing arrays to functions by reference using pointers, pointer arithmetic and comparing pointers, dynamic memory allocation for arrays using calloc and malloc, and how strings are implemented as character arrays in C with a null terminator. Examples are provided for summing arrays, merging sorted arrays, and basic pointer operations.
This document provides a quick introduction to the C programming language. It discusses basic C syntax like main functions, header files, comments, and variables. It also covers data types, memory, functions, scopes, expressions, control flow statements like if/else and loops. Functions can access arguments and global variables from their own scope but not variables from outer scopes unless passing their addresses.
The document provides a quick introduction to C programming, covering topics like functions, variables, memory, expressions, and recursion. It uses a recursive pow() function to demonstrate recursion and the call stack. Each function call gets its own copy of arguments and local variables, stored on the call stack.
The document provides a quick introduction to C programming. It discusses some key concepts in C including functions, variables, memory, data types, expressions and evaluation, and recursion. It provides an example of a recursive pow() function to calculate powers and discusses how function calls are handled through the stack.
SMS API Integration in Saudi Arabia| Best SMS API ServiceYara Milbes
Discover the benefits and implementation of SMS API integration in the UAE and Middle East. This comprehensive guide covers the importance of SMS messaging APIs, the advantages of bulk SMS APIs, and real-world case studies. Learn how CEQUENS, a leader in communication solutions, can help your business enhance customer engagement and streamline operations with innovative CPaaS, reliable SMS APIs, and omnichannel solutions, including WhatsApp Business. Perfect for businesses seeking to optimize their communication strategies in the digital age.
E-commerce Development Services- Hornet DynamicsHornet Dynamics
For any business hoping to succeed in the digital age, having a strong online presence is crucial. We offer Ecommerce Development Services that are customized according to your business requirements and client preferences, enabling you to create a dynamic, safe, and user-friendly online store.
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesQuickdice ERP
Explore the seamless transition to e-invoicing with this comprehensive guide tailored for Saudi Arabian businesses. Navigate the process effortlessly with step-by-step instructions designed to streamline implementation and enhance efficiency.
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppGoogle
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-fusion-buddy-review
AI Fusion Buddy Review: Key Features
✅Create Stunning AI App Suite Fully Powered By Google's Latest AI technology, Gemini
✅Use Gemini to Build high-converting Converting Sales Video Scripts, ad copies, Trending Articles, blogs, etc.100% unique!
✅Create Ultra-HD graphics with a single keyword or phrase that commands 10x eyeballs!
✅Fully automated AI articles bulk generation!
✅Auto-post or schedule stunning AI content across all your accounts at once—WordPress, Facebook, LinkedIn, Blogger, and more.
✅With one keyword or URL, generate complete websites, landing pages, and more…
✅Automatically create & sell AI content, graphics, websites, landing pages, & all that gets you paid non-stop 24*7.
✅Pre-built High-Converting 100+ website Templates and 2000+ graphic templates logos, banners, and thumbnail images in Trending Niches.
✅Say goodbye to wasting time logging into multiple Chat GPT & AI Apps once & for all!
✅Save over $5000 per year and kick out dependency on third parties completely!
✅Brand New App: Not available anywhere else!
✅ Beginner-friendly!
✅ZERO upfront cost or any extra expenses
✅Risk-Free: 30-Day Money-Back Guarantee!
✅Commercial License included!
See My Other Reviews Article:
(1) AI Genie Review: https://sumonreview.com/ai-genie-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIFusionBuddyReview,
#AIFusionBuddyFeatures,
#AIFusionBuddyPricing,
#AIFusionBuddyProsandCons,
#AIFusionBuddyTutorial,
#AIFusionBuddyUserExperience
#AIFusionBuddyforBeginners,
#AIFusionBuddyBenefits,
#AIFusionBuddyComparison,
#AIFusionBuddyInstallation,
#AIFusionBuddyRefundPolicy,
#AIFusionBuddyDemo,
#AIFusionBuddyMaintenanceFees,
#AIFusionBuddyNewbieFriendly,
#WhatIsAIFusionBuddy?,
#HowDoesAIFusionBuddyWorks
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Microservice Teams - How the cloud changes the way we workSven Peters
A lot of technical challenges and complexity come with building a cloud-native and distributed architecture. The way we develop backend software has fundamentally changed in the last ten years. Managing a microservices architecture demands a lot of us to ensure observability and operational resiliency. But did you also change the way you run your development teams?
Sven will talk about Atlassian’s journey from a monolith to a multi-tenanted architecture and how it affected the way the engineering teams work. You will learn how we shifted to service ownership, moved to more autonomous teams (and its challenges), and established platform and enablement teams.
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsPeter Muessig
The UI5 tooling is the development and build tooling of UI5. It is built in a modular and extensible way so that it can be easily extended by your needs. This session will showcase various tooling extensions which can boost your development experience by far so that you can really work offline, transpile your code in your project to use even newer versions of EcmaScript (than 2022 which is supported right now by the UI5 tooling), consume any npm package of your choice in your project, using different kind of proxies, and even stitching UI5 projects during development together to mimic your target environment.
Using Query Store in Azure PostgreSQL to Understand Query PerformanceGrant Fritchey
Microsoft has added an excellent new extension in PostgreSQL on their Azure Platform. This session, presented at Posette 2024, covers what Query Store is and the types of information you can get out of it.
E-commerce Application Development Company.pdfHornet Dynamics
Your business can reach new heights with our assistance as we design solutions that are specifically appropriate for your goals and vision. Our eCommerce application solutions can digitally coordinate all retail operations processes to meet the demands of the marketplace while maintaining business continuity.
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeAftab Hussain
Understanding variable roles in code has been found to be helpful by students
in learning programming -- could variable roles help deep neural models in
performing coding tasks? We do an exploratory study.
- These are slides of the talk given at InteNSE'23: The 1st International Workshop on Interpretability and Robustness in Neural Software Engineering, co-located with the 45th International Conference on Software Engineering, ICSE 2023, Melbourne Australia
DDS Security Version 1.2 was adopted in 2024. This revision strengthens support for long runnings systems adding new cryptographic algorithms, certificate revocation, and hardness against DoS attacks.
Transform Your Communication with Cloud-Based IVR SolutionsTheSMSPoint
Discover the power of Cloud-Based IVR Solutions to streamline communication processes. Embrace scalability and cost-efficiency while enhancing customer experiences with features like automated call routing and voice recognition. Accessible from anywhere, these solutions integrate seamlessly with existing systems, providing real-time analytics for continuous improvement. Revolutionize your communication strategy today with Cloud-Based IVR Solutions. Learn more at: https://thesmspoint.com/channel/cloud-telephony
WhatsApp offers simple, reliable, and private messaging and calling services for free worldwide. With end-to-end encryption, your personal messages and calls are secure, ensuring only you and the recipient can access them. Enjoy voice and video calls to stay connected with loved ones or colleagues. Express yourself using stickers, GIFs, or by sharing moments on Status. WhatsApp Business enables global customer outreach, facilitating sales growth and relationship building through showcasing products and services. Stay connected effortlessly with group chats for planning outings with friends or staying updated on family conversations.
Hand Rolled Applicative User ValidationCode KataPhilip Schwarz
Could you use a simple piece of Scala validation code (granted, a very simplistic one too!) that you can rewrite, now and again, to refresh your basic understanding of Applicative operators <*>, <*, *>?
The goal is not to write perfect code showcasing validation, but rather, to provide a small, rough-and ready exercise to reinforce your muscle-memory.
Despite its grandiose-sounding title, this deck consists of just three slides showing the Scala 3 code to be rewritten whenever the details of the operators begin to fade away.
The code is my rough and ready translation of a Haskell user-validation program found in a book called Finding Success (and Failure) in Haskell - Fall in love with applicative functors.
8 Best Automated Android App Testing Tool and Framework in 2024.pdfkalichargn70th171
Regarding mobile operating systems, two major players dominate our thoughts: Android and iPhone. With Android leading the market, software development companies are focused on delivering apps compatible with this OS. Ensuring an app's functionality across various Android devices, OS versions, and hardware specifications is critical, making Android app testing essential.
Do you want Software for your Business? Visit Deuglo
Deuglo has top Software Developers in India. They are experts in software development and help design and create custom Software solutions.
Deuglo follows seven steps methods for delivering their services to their customers. They called it the Software development life cycle process (SDLC).
Requirement — Collecting the Requirements is the first Phase in the SSLC process.
Feasibility Study — after completing the requirement process they move to the design phase.
Design — in this phase, they start designing the software.
Coding — when designing is completed, the developers start coding for the software.
Testing — in this phase when the coding of the software is done the testing team will start testing.
Installation — after completion of testing, the application opens to the live server and launches!
Maintenance — after completing the software development, customers start using the software.
3. a · b =
n
ÿ
i=1
ai bi
Assembler
1 g l o b a l _mult3
2 sum equ 16
3 s e c t i o n . t e x t
4 _mult3 :
5 push ebp
6 mov ebp , esp
7 push e s i
8 push edi
9 sub esp , 4
10 mov esi , [ ebp+12 ]
11 mov edi , [ ebp+8 ]
12 mov dword [ ebp≠sum ] , 0
13 mov ecx , 3
14 . f o r l o o p :
15 mov eax , [ edi ]
16 imul dword [ e s i ]
17 add edi , 4
18 add esi , 4
19 add [ ebp≠sum ] , eax
20 loop . f o r l o o p
21 mov eax , [ ebp≠sum ]
22 add esp , 4
23 pop edi
24 pop e s i
25 pop ebp
26 r e t
C source1
1 i n t mult 3 ( i n t dst , i n t s r c )
2 {
3 i n t sum = 0 , i ;
4
5 f o r ( i = 0 ; i < 3 ; i ++)
6 sum += dst [ i ] s r c [ i ] ;
7
8 return sum ;
9 }
10
11 i n t main ( void )
12 {
13 i n t d [ 3 ] = { 1 , 2 , 3 };
14 i n t s [ 3 ] = {8 , 9 , 10 } ;
15
16 p r i n t f ( "answer is %in" , mult 3 (d , s ) ) ;
17 return 0 ;
18 }
1The first compiler was written by Grace Hopper in 1952 for the A-0 language
4. a · b =
n
ÿ
i=1
ai bi
Python
1 import numpy
2 d i s t = numpy . a r r a y ( [ 1 , 2 , 3 ] )
3 s r c = numpy . a r r a y ( [ 8 , 9 , 10 ] )
4
5 p r i n t d i s t . dot ( s r c )
6. History of Python
I December 1989
I Implementation by Guido van Rossum as successor of ABC to
provide exception handling
I February 1991
I Python 0.9.0 had classes with inheritance, exception handling,
functions, and the core datatypes
I January 1994
I Version 1.0 has functional programming features
I October 2000
I Python 2.0 brings garbage collections
I Python 2.2 improves Python’s types to be purely object oriented
I December 2008
I Python 3
I Reduce feature duplication by removing old ways of doing things
I Not backwards compatible with Python 2.x
7. What’s so great about Python?
I Portable
I Your program will run if the interpreter works and the modules are
installed
8. What’s so great about Python?
I E cient
I Rich language features built in
I Simple syntax for ease of reading
I Focus shifts to “algorithm” and away from implementation
9. What’s so great about Python?
I Flexible
I Imperative
I Object-oriented
I Functional
10. What’s so great about Python?
I Extendible
I Plenty of easy-to-use modules
I If you can imagine it, then someone has probably developed a module
for it
I Your program can adjust the way the interpreter works
11. Why use python for science?
I A highly programmable calculator
I Fast proto-typing new algorithms or program design
I Use C or Fortran routines directly
I Many science and mathematics modules already exist
15. Python syntax
I Extremely simplified syntax
I Nearly devoid of special characters
I Intended to be nearly English
I Dynamic types
I It is the responsibility of the programmer
I Still “strongly typed”
16. Python objects
I All data in Python is represented by objects
I Objects have
I an identity
I a type
I a value
I a name (“variable”)2
I Variables are names assigned to objects
2http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.
html#other-languages-have-variables
18. Numerical objects
I Integers
I a = 1
I Floats
I a = 1.0
I Complex numbers
I a = 1.5 + 0.5j
I a. real and a.imag return each component
I Type casts
I myFloat = float(myInteger)
I myInt = int(myFloat)
I Operators
I Addition +
I Subtraction ≠
I Multiplication
I Exponentiation
I Division /
I Modulus %
19. Mathematical functions
I many functions exist with the math module
1 import math
2
3 help ( math )
4
5 p r i n t math . cos ( 0 )
6 p r i n t math . p i
21. Strings
I a = ’single quoted’
I a = "double quoted"
I Triple quotes preserve whitespace and newlines
1 a = """ t r i p l e
2 quoted
3 s t r i n g """
I “” is the escape character
23. Formatted strings
I width placeholders
%s string
%d integer
%f float with 6 decimals
%E scientific notation
%% the % sign
I modifiers
I integers after % adjust with width to print
I decimal points are specified after the width as “.x”
I use a hyphen after % to left justify
I printing long strings or large numbers will skew columns
1 from math import pi , e
2
3 p r i n t "pi is %d and e is %d" % ( pi , e )
4 p r i n t "pi is %6.4f and e is %6.4f" % ( pi , e )
5 p r i n t "pi is %f and e is %f" % ( pi , e )
6 p r i n t "pi is %10.8e and e is %10.8e" % ( pi , e )
7 p r i n t "pi is %15.8e and e is %15.8e" % ( pi , e )
24. Writing a script file
I save the file to hello.py
1 #/ usr / bin / env python
2
3 #This i s my comment about the f o l l o w i n g s c r i p t
4 p r i n t ’Hello , world!’
I run the file
> module load python/epd-7.2
> python hello.py
Hello, world!
25. Structured blocks
1 i f ( a>b ) :
2 p r i n t ’a is bigger ’
3 e l i f (b>a ) :
4 p r i n t ’big is bigger ’
5 e l s e :
6 p r i n t ’a must equal b’
26. Structured blocks
1 i f ( a>b ) :
2 p r i n t ’a is bigger ’
3 e l i f (b>a ) :
4 p r i n t ’big is bigger ’
5 e l s e :
6 p r i n t ’a must equal b’
I Why is it indented?
29. Structured blocks
1 f o r i i n range ( 4 ) :
2 p r i n t i
I for is not limited to arithmetic
30. Simple loops
I range( start ,stop,step)
I list of integers from start to stop-1 in step increments
I End point is always omitted
1 f o r i i n range ( 4 ) :
2 p r i n t i
31. Simple Functions
I Simplify your program
I Easier debugging
I Improved elegance
1 import math
2 def area ( r a d i u s ) :
3 return math . p i r a d i u s 2
32. Simple Functions
I Functions must be defined before being used
I Arguments are passed by reference to the object3
I Variables do not have values, objects do
I Functions are first class citizens
1
2 def y ( x ) :
3 x=x+1
4 return x 2
5
6 x=5
7 y ( x )
8 p r i n t x
3http://me.veekun.com/blog/2012/05/23/python-faq-passing/
33. Mathematical Exercises
I Print a table of temperature conversion
C =
5
9
(F ≠ 32)
I Compute Pi using the Wallis formula
fi = 2
ŒŸ
i=1
4i2
4i2 ≠ 1
34. Python for Scientific Computing
Lecture 2: Data Structures
Albert DeFusco
Center for Simulation and Modeling
September 18, 2013
35. Download your own Python
https://www.enthought.com/products/epd/free/
37. Review fi
fi = 2
ŒŸ
i=1
4i2
4i2 ≠ 1
1 p i = 2 .
2 f o r i i n range ( 1 , n ) :
3 p i = 4 . i 2 / ( 4 . i 2 ≠ 1 )
4 p r i n t p i
38. Containers
I tuples, lists and strings
I Elements are accessed with container[ ]
I Indexed starting at 0
I Arguments for len(container)
I Each type has special features
39. Tuples
I Tuple = (1,3.,’red’)
I Contain references to other objects
I The structure cannot be changed
I A convenient way to pass multiple objects
I Packing and un-packing
40. Lists
I List = [’red’,’green’,’blue’]
I Resizable
I List-of-Lists is a multi-dimensional list
I Lists are not arrays
I range() is a list
41. Dictionaries
I Key - value pairs
Protons = {’Oxygen’: 8, ’Hydrogen’: 1}
Protons[’Carbon’] = 6
I Any type can be a key or value
I Look-up tables
I Sorting and searching operations
42. Indexing Lists and tuples
I Slicing just like Fortran 90
L[ start :stop: stride ]
start Æ i < stop; i+ = stride
I Negative indices start at the end of the list
I -1 is the last element
44. Loops
I Iterate over any sequence
I string, list, keys in dictionary, lines in file
1 vowels = ’aeiouy ’
2 f o r i i n ’orbital ’ :
3 i f i i n vowels :
4 p r i n t ( i )
45. Loops
I Keep a counter
1 s h e l l s = ( ’s’ , ’p’ , ’d’ , ’f’)
2 f o r index , t h i s S h e l l i n enumerate ( s h e l l s ) :
3 p r i n t index , t h i s S h e l l
46. Loops
I List comprehension
1 even = [ i f o r i i n range ( 100 ) i f i%2 == 0 ]
2
3 l i s t X = [≠1 , 0 , 1 ]
4 l i s t Y = [ 2 , 4 ]
5 myTuple = [ ( x , y ) f o r x i n l i s t X f o r y i n l i s t Y ]
47. Mutability of objects
I Immutable objects get created and destroyed upon assignment and
collection
I Strings
I Numbers (no ++ operator)
I Tuples
I Mutable objects create references to contained objects upon
assignment
I Lists
I Dictionaries
49. Tuples or Lists?
I List: homogeneous data
I Elements can be added or deleted
I Elements can be in any order
I Mutable
I Tuples: heterogeneous data (structs)
I Constant size
I Order matters
I Immutable
50. Container examples
I List
I Particles
I Lines in an input file
I Tuple
I Position data
I Dictionary
I Associated lists
I Look-up tables
I Histograms
I Networks
I Graphs
53. Functions
1 def d i v i d e ( x , y ) :
2 """ Divide take s two i n t e g e r s as i np u t
3 r e t u r n s a tupe of q u o t i e n t and remainder """
4 return x/y , x%y
55. Mathematical Exercises
I Write a function to di erentiate another function
f Õ
(x) ¥
f (x + h) ≠ f (x ≠ h)
2h
I f (x) and h are arguments
I make h = 0.01 the default value
I Practice with the following functions
I f (x) = x2
at x = 1
I f (x) = cos(x) at x = 2fi
I f (x) = e≠2x2
at x = 0
56. recursions
n! =
nŸ
k=1
k
1 def f a c t o r i a l ( n ) :
2 i f ( n==0 ) :
3 return 1
4 return n f a c t o r i a l (n≠1 )
57. Python for Scientific Computing
Lecture 3: Object-oriented Programming
Albert DeFusco
Center for Simulation and Modeling
September 20, 2013
58. Modules
I Import math.py such that math becomes the object name
import math
print math.pi
print math.sin(math.pi)
I Alternatives
I from math import sin
I import math as maths
I Avoid
I from math import
If you can imagine it, someone probably has a module that can do it.
http://docs.python.org/2/py-modindex.html
http://wiki.python.org/moin/UsefulModules
59. Modules
I Any python script can be imported
I The contents are run when imported
I Use __main__ to just import definitions
I Name space defaults to the script’s file name
60. Functions and variables
I Functions can be documented easily
1 def p i ( i ) :
2 """ Compute the i t h term of the W a l l i s formula """
3 return 4 . i 2 / ( 4 . i 2 ≠ 1 )
4
5 help ( p i )
I Multiple returns are tuples
1 def myFunction ( x , y ) :
2 return x 2 , y 4
3
4 a , b = myFunction ( y=2 , x=8 )
I Default and optional arguments
1 def d e r i v a t i v e ( f , x , h=0 . 01 ) :
2 return ( f ( x+h ) ≠ f ( x≠h ) ) / 2 . h
3
4 def f ( x ) :
5 return x 2
6
7 d e r i v a t i v e ( f , x=0 )
61. Functionals and variables
I Functions are objects
I Global variables can be defined
I Not always good practice
I May reduce the usability of a module
63. Function Scope
I Variables assigned in a function are private
1 def p i ( i ) :
2 """ Compute the i t h term of the W a l l i s formula """
3 temp=4 . i 2
4 return temp / ( temp ≠ 1 )
5
6 p r i n t p i ( 2 )
7 p r i n t temp
64. Function Scope
I Warning!
I Variables assigned before a function are still in scope
I It helps to define functions first
1 myVar = 5
2 def p i ( i ) :
3 """ Compute the i t h term of the W a l l i s formula """
4 p r i n t myVar
5 temp=4 . i 2
6 return temp / ( temp ≠ 1 )
7
8 p r i n t temp
65. Module Scope
I Names assigned in a module are readable by functions
I Names assigned in functions do not a ect the outer scope
66. Object Oriented Programming
I Focus on data, not on the procedure
I Encapsulate procedures with data
I Create modular code that can be reused
67. Object Oriented Programming
I Class
I The description of a type of object
I Object
I The realization of the description
I An instance of a class
68. Object Oriented Programming
I Classes define
I Attributes
I Methods
I Instances have
I data stored in attributes
I Methods to operate on the data
I Objects can interact with each other by passing attributes to
methods
70. Classes
1 c l a s s shape ( o b j e c t ) :
2 """ Shapes have a name and c o l o r """
3 def __init__ ( s e l f , name=’shape ’ , c o l o r=’white ’ ) :
4 s e l f . name=name
5 s e l f . c o l o r=c o l o r
6
7 c l a s s Molecule ( o b j e c t ) :
8 """ Molecules have a name and chemical formula """
9 def __init__ ( s e l f , name , formula )
10 s e l f . name = name
11 s e l f . formula = formula
71. Operator Overloading
Change or define the behavior of operations
1 c l a s s Molecule ( o b j e c t ) :
2 . . .
3 def __add__( s e l f , other ) :
4 newName = s e l f . name + " + " + other . name
5 newFormula = "[" + s e l f . formula + "]" + "[" + other . formula +
6 return Molecule (newName , newFormula )
7
8
9 mol1=Molecule ( ’water ’ , ’h2o ’)
10 mol2=Molecule ( ’ammonia ’ , ’nh3 ’)
11
12 mol3 = mol1 + mol2
72. Inheritance
I Child classes can be more specific than the parent
I Subclasses can override the superclass†
1 import math
2 c l a s s shape ( object ) :
3 def __init__ ( s e l f , name=’shape ’ , c o l o r=’white ’ ) :
4 s e l f . name=name
5 s e l f . c o l o r=c o l o r
6
7 c l a s s c i r c l e ( shape ) :
8 def __init__ ( s e l f , r a d i u s=1 . , name=’circle ’ , c o l o r=’white ’ ) :
9 super ( c i r c l e , s e l f ) . __init__ (name , c o l o r )
10 s e l f . r a d i u s=r a d i u s
11 def area ( ) :
12 return math . p i s e l f . r a d i u s 2
13
14 c l a s s square ( shape ) :
15 def __init__ ( s e l f , s i z e=1 . , name=’square ’ , c o l o r=’white ’ ) :
16 super ( square , s e l f ) . __init__ (name , c o l o r )
17 s e l f . s i z e=s i z e
18 def area ( ) :
19 return s e l f . s i z e 2
†
Polymorphism in Python is achieved when classes implement the same methods, which reduces
the number of if statements