docid
stringlengths
25
45
url
stringlengths
14
987
title
stringlengths
0
45k
headings
stringlengths
1
259k
segment
stringlengths
2
10k
start_char
int64
0
9.96k
end_char
int64
2
10k
msmarco_v2.1_doc_01_1669144381#15_2448155955
http://interactivephysiology.com/login/endodemo/misc/assignmentfiles/endocrine/endocrine_review.pdf
Endocrine System Review Endocrine System Review Page 1. Endocrine System Review Page 2. Goals/ What You Need to Know Goals What You Need to Know Pituitary gland Pineal Gland Thyroid gland Parathyroid glands Thymus Adrenal glands Pancreas Ovaries Testes Hypothalamus Heart Stomach Gut (Small intestines) Kidneys Page 5. Summary Quiz Question #2: Hormones and Target Tissues Quiz Question #3: Hormone Function Quiz Question #4: Hormone Production / Hormone Stimulation Study Questions on Endocrine System Review
Ovaries  Secrete the female steroid sex hormones estrogen and progesterone and the peptide hormone inhibin.  Estrogen is important for egg development inside the ovarian follicles.  Progesterone is important after ovulation for maintaining the integrity of the uterine lining and during pregnancy.  Inhibin regulates the secretion of FSH from the anterior pituitary in a negative feedback mechanism. *Be sure to view the animation of the ovary/uterine cycles. Testes  Secretes the male steroid sex hormone testosterone and the peptide hormone inhibin.  Testosterone aids in the development of gametes, is responsible for secondary sex characteristics, and controls libido.  Inhibin regulates the secretion of FSH by the anterior pituitary. Page 4. Endocrine Tissues:
7,254
8,231
msmarco_v2.1_doc_01_1669144381#16_2448158196
http://interactivephysiology.com/login/endodemo/misc/assignmentfiles/endocrine/endocrine_review.pdf
Endocrine System Review Endocrine System Review Page 1. Endocrine System Review Page 2. Goals/ What You Need to Know Goals What You Need to Know Pituitary gland Pineal Gland Thyroid gland Parathyroid glands Thymus Adrenal glands Pancreas Ovaries Testes Hypothalamus Heart Stomach Gut (Small intestines) Kidneys Page 5. Summary Quiz Question #2: Hormones and Target Tissues Quiz Question #3: Hormone Function Quiz Question #4: Hormone Production / Hormone Stimulation Study Questions on Endocrine System Review
Testes  Secretes the male steroid sex hormone testosterone and the peptide hormone inhibin.  Testosterone aids in the development of gametes, is responsible for secondary sex characteristics, and controls libido.  Inhibin regulates the secretion of FSH by the anterior pituitary. Page 4. Endocrine Tissues: Hormones and Functions *Be sure to review all the endocrine tissues listed on this page.  Endocrine tissues are composed of groups of endocrine cells that are found in glands that are not specifically endocrine glands.  The endocrine tissues include the following: hypothalamus, heart, stomach, small intestine and kidneys. Hypothalamus  Has clusters of neurons that secrete neurohormones into the circulation.
7,840
8,755
msmarco_v2.1_doc_01_1669144381#17_2448160350
http://interactivephysiology.com/login/endodemo/misc/assignmentfiles/endocrine/endocrine_review.pdf
Endocrine System Review Endocrine System Review Page 1. Endocrine System Review Page 2. Goals/ What You Need to Know Goals What You Need to Know Pituitary gland Pineal Gland Thyroid gland Parathyroid glands Thymus Adrenal glands Pancreas Ovaries Testes Hypothalamus Heart Stomach Gut (Small intestines) Kidneys Page 5. Summary Quiz Question #2: Hormones and Target Tissues Quiz Question #3: Hormone Function Quiz Question #4: Hormone Production / Hormone Stimulation Study Questions on Endocrine System Review
Hormones and Functions *Be sure to review all the endocrine tissues listed on this page.  Endocrine tissues are composed of groups of endocrine cells that are found in glands that are not specifically endocrine glands.  The endocrine tissues include the following: hypothalamus, heart, stomach, small intestine and kidneys. Hypothalamus  Has clusters of neurons that secrete neurohormones into the circulation.  The paraventricular and supraoptic nuclei secrete hormones into the posterior pituitary where they are released into the blood.  The posterior pituitary hormones are: Oxytocin – a peptide that stimulates contractions of the uterus during labor and promotes milk ejection by the mammary glands. Antidiuretic Hormone (ADH) causes the kidneys to reabsorb water and has effects on blood pressure.  The ventral hypothalamic neurons secrete releasing hormones that travel via the hypothalamic portal system into the anterior pituitary where they stimulate or inhibit the production of anterior pituitary hormones.
8,231
9,539
msmarco_v2.1_doc_01_1669144381#18_2448162981
http://interactivephysiology.com/login/endodemo/misc/assignmentfiles/endocrine/endocrine_review.pdf
Endocrine System Review Endocrine System Review Page 1. Endocrine System Review Page 2. Goals/ What You Need to Know Goals What You Need to Know Pituitary gland Pineal Gland Thyroid gland Parathyroid glands Thymus Adrenal glands Pancreas Ovaries Testes Hypothalamus Heart Stomach Gut (Small intestines) Kidneys Page 5. Summary Quiz Question #2: Hormones and Target Tissues Quiz Question #3: Hormone Function Quiz Question #4: Hormone Production / Hormone Stimulation Study Questions on Endocrine System Review
 The paraventricular and supraoptic nuclei secrete hormones into the posterior pituitary where they are released into the blood.  The posterior pituitary hormones are: Oxytocin – a peptide that stimulates contractions of the uterus during labor and promotes milk ejection by the mammary glands. Antidiuretic Hormone (ADH) causes the kidneys to reabsorb water and has effects on blood pressure.  The ventral hypothalamic neurons secrete releasing hormones that travel via the hypothalamic portal system into the anterior pituitary where they stimulate or inhibit the production of anterior pituitary hormones.  The releasing hormones of the ventral hypothalamus are: Thyrotropin releasing hormone (TRH) Growth hormone releasing hormone (GHRH) Somatostatin – inhibits secretion of GH Gonadotropic releasing hormone (GNRH) Dopamine (DA) converts into prolactin inhibiting hormone (PIH) Corticotropic releasing hormone (CRH) Complete the following table. Hypothalami
8,755
10,000
msmarco_v2.1_doc_01_1669166377#0_2448165535
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsComputerScience.html
1.3. What Is Computer Science? — Problem Solving with Algorithms and Data Structures
1.3. What Is Computer Science? ¶ 1.3. What Is Computer Science? ¶
1.3. What Is Computer Science? — Problem Solving with Algorithms and Data Structures 1.3. What Is Computer Science? ¶ Computer science is difficult to define. This is probably due to the unfortunate use of the word “computer” in the name. As you are perhaps aware, computer science is not simply the study of computers. Although computers play an important supporting role as a tool in the discipline, they are just that–tools. Computer science is the study of problems, problem-solving, and the solutions that come out of the problem-solving process. Given a problem, a computer scientist’s goal is to develop an algorithm, a step-by-step list of instructions for solving any instance of the problem that might arise.
0
718
msmarco_v2.1_doc_01_1669166377#1_2448166693
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsComputerScience.html
1.3. What Is Computer Science? — Problem Solving with Algorithms and Data Structures
1.3. What Is Computer Science? ¶ 1.3. What Is Computer Science? ¶
This is probably due to the unfortunate use of the word “computer” in the name. As you are perhaps aware, computer science is not simply the study of computers. Although computers play an important supporting role as a tool in the discipline, they are just that–tools. Computer science is the study of problems, problem-solving, and the solutions that come out of the problem-solving process. Given a problem, a computer scientist’s goal is to develop an algorithm, a step-by-step list of instructions for solving any instance of the problem that might arise. Algorithms are finite processes that if followed will solve the problem. Algorithms are solutions. Computer science can be thought of as the study of algorithms. However, we must be careful to include the fact that some problems may not have a solution. Although proving this statement is beyond the scope of this text, the fact that some problems cannot be solved is important for those who study computer science.
159
1,134
msmarco_v2.1_doc_01_1669166377#2_2448168100
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsComputerScience.html
1.3. What Is Computer Science? — Problem Solving with Algorithms and Data Structures
1.3. What Is Computer Science? ¶ 1.3. What Is Computer Science? ¶
Algorithms are finite processes that if followed will solve the problem. Algorithms are solutions. Computer science can be thought of as the study of algorithms. However, we must be careful to include the fact that some problems may not have a solution. Although proving this statement is beyond the scope of this text, the fact that some problems cannot be solved is important for those who study computer science. We can fully define computer science, then, by including both types of problems and stating that computer science is the study of solutions to problems as well as the study of problems with no solutions. It is also very common to include the word computable when describing problems and solutions. We say that a problem is computable if an algorithm exists for solving it. An alternative definition for computer science, then, is to say that computer science is the study of problems that are and that are not computable, the study of the existence and the nonexistence of algorithms. In any case, you will note that the word “computer” did not come up at all.
719
1,795
msmarco_v2.1_doc_01_1669166377#3_2448169598
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsComputerScience.html
1.3. What Is Computer Science? — Problem Solving with Algorithms and Data Structures
1.3. What Is Computer Science? ¶ 1.3. What Is Computer Science? ¶
We can fully define computer science, then, by including both types of problems and stating that computer science is the study of solutions to problems as well as the study of problems with no solutions. It is also very common to include the word computable when describing problems and solutions. We say that a problem is computable if an algorithm exists for solving it. An alternative definition for computer science, then, is to say that computer science is the study of problems that are and that are not computable, the study of the existence and the nonexistence of algorithms. In any case, you will note that the word “computer” did not come up at all. Solutions are considered independent from the machine. Computer science, as it pertains to the problem-solving process itself, is also the study of abstraction. Abstraction allows us to view the problem and solution in such a way as to separate the so-called logical and physical perspectives. The basic idea is familiar to us in a common example. Consider the automobile that you may have driven to school or work today.
1,135
2,217
msmarco_v2.1_doc_01_1669166377#4_2448171103
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsComputerScience.html
1.3. What Is Computer Science? — Problem Solving with Algorithms and Data Structures
1.3. What Is Computer Science? ¶ 1.3. What Is Computer Science? ¶
Solutions are considered independent from the machine. Computer science, as it pertains to the problem-solving process itself, is also the study of abstraction. Abstraction allows us to view the problem and solution in such a way as to separate the so-called logical and physical perspectives. The basic idea is familiar to us in a common example. Consider the automobile that you may have driven to school or work today. As a driver, a user of the car, you have certain interactions that take place in order to utilize the car for its intended purpose. You get in, insert the key, start the car, shift, brake, accelerate, and steer in order to drive. From an abstraction point of view, we can say that you are seeing the logical perspective of the automobile. You are using the functions provided by the car designers for the purpose of transporting you from one location to another. These functions are sometimes also referred to as the interface.
1,796
2,745
msmarco_v2.1_doc_01_1669166377#5_2448172465
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsComputerScience.html
1.3. What Is Computer Science? — Problem Solving with Algorithms and Data Structures
1.3. What Is Computer Science? ¶ 1.3. What Is Computer Science? ¶
As a driver, a user of the car, you have certain interactions that take place in order to utilize the car for its intended purpose. You get in, insert the key, start the car, shift, brake, accelerate, and steer in order to drive. From an abstraction point of view, we can say that you are seeing the logical perspective of the automobile. You are using the functions provided by the car designers for the purpose of transporting you from one location to another. These functions are sometimes also referred to as the interface. On the other hand, the mechanic who must repair your automobile takes a very different point of view. She not only knows how to drive but must know all of the details necessary to carry out all the functions that we take for granted. She needs to understand how the engine works, how the transmission shifts gears, how temperature is controlled, and so on. This is known as the physical perspective, the details that take place “under the hood.” The same thing happens when we use computers.
2,218
3,237
msmarco_v2.1_doc_01_1669166377#6_2448173907
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsComputerScience.html
1.3. What Is Computer Science? — Problem Solving with Algorithms and Data Structures
1.3. What Is Computer Science? ¶ 1.3. What Is Computer Science? ¶
On the other hand, the mechanic who must repair your automobile takes a very different point of view. She not only knows how to drive but must know all of the details necessary to carry out all the functions that we take for granted. She needs to understand how the engine works, how the transmission shifts gears, how temperature is controlled, and so on. This is known as the physical perspective, the details that take place “under the hood.” The same thing happens when we use computers. Most people use computers to write documents, send and receive email, surf the web, play music, store images, and play games without any knowledge of the details that take place to allow those types of applications to work. They view computers from a logical or user perspective. Computer scientists, programmers, technology support staff, and system administrators take a very different view of the computer. They must know the details of how operating systems work, how network protocols are configured, and how to code various scripts that control function. They must be able to control the low-level details that a user simply assumes.
2,745
3,877
msmarco_v2.1_doc_01_1669166377#7_2448175461
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsComputerScience.html
1.3. What Is Computer Science? — Problem Solving with Algorithms and Data Structures
1.3. What Is Computer Science? ¶ 1.3. What Is Computer Science? ¶
Most people use computers to write documents, send and receive email, surf the web, play music, store images, and play games without any knowledge of the details that take place to allow those types of applications to work. They view computers from a logical or user perspective. Computer scientists, programmers, technology support staff, and system administrators take a very different view of the computer. They must know the details of how operating systems work, how network protocols are configured, and how to code various scripts that control function. They must be able to control the low-level details that a user simply assumes. The common point for both of these examples is that the user of the abstraction, sometimes also called the client, does not need to know the details as long as the user is aware of the way the interface works. This interface is the way we as users communicate with the underlying complexities of the implementation. As another example of abstraction, consider the Python math module. Once we import the module, we can perform computations such as >>> import math >>> math.sqrt(16) 4.0 >>> This is an example of procedural abstraction. We do not necessarily know how the square root is being calculated, but we know what the function is called and how to use it.
3,238
4,539
msmarco_v2.1_doc_01_1669166377#8_2448177177
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsComputerScience.html
1.3. What Is Computer Science? — Problem Solving with Algorithms and Data Structures
1.3. What Is Computer Science? ¶ 1.3. What Is Computer Science? ¶
The common point for both of these examples is that the user of the abstraction, sometimes also called the client, does not need to know the details as long as the user is aware of the way the interface works. This interface is the way we as users communicate with the underlying complexities of the implementation. As another example of abstraction, consider the Python math module. Once we import the module, we can perform computations such as >>> import math >>> math.sqrt(16) 4.0 >>> This is an example of procedural abstraction. We do not necessarily know how the square root is being calculated, but we know what the function is called and how to use it. If we perform the import correctly, we can assume that the function will provide us with the correct results. We know that someone implemented a solution to the square root problem but we only need to know how to use it. This is sometimes referred to as a “black box” view of a process. We simply describe the interface: the name of the function, what is needed (the parameters), and what will be returned.
3,877
4,946
msmarco_v2.1_doc_01_1669166377#9_2448178670
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsComputerScience.html
1.3. What Is Computer Science? — Problem Solving with Algorithms and Data Structures
1.3. What Is Computer Science? ¶ 1.3. What Is Computer Science? ¶
If we perform the import correctly, we can assume that the function will provide us with the correct results. We know that someone implemented a solution to the square root problem but we only need to know how to use it. This is sometimes referred to as a “black box” view of a process. We simply describe the interface: the name of the function, what is needed (the parameters), and what will be returned. The details are hidden inside (see Figure 1 ). Figure 1: Procedural Abstraction ¶
4,540
5,029
msmarco_v2.1_doc_01_1669171843#0_2448179587
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsProgramming.html
1.4. What Is Programming? — Problem Solving with Algorithms and Data Structures
1.4. What Is Programming? ¶ 1.4. What Is Programming? ¶
1.4. What Is Programming? — Problem Solving with Algorithms and Data Structures 1.4. What Is Programming? ¶ Programming is the process of taking an algorithm and encoding it into a notation, a programming language, so that it can be executed by a computer. Although many programming languages and many different types of computers exist, the important first step is the need to have the solution. Without an algorithm there can be no program. Computer science is not the study of programming. Programming, however, is an important part of what a computer scientist does. Programming is often the way that we create a representation for our solutions.
0
650
msmarco_v2.1_doc_01_1669171843#1_2448180638
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsProgramming.html
1.4. What Is Programming? — Problem Solving with Algorithms and Data Structures
1.4. What Is Programming? ¶ 1.4. What Is Programming? ¶
Although many programming languages and many different types of computers exist, the important first step is the need to have the solution. Without an algorithm there can be no program. Computer science is not the study of programming. Programming, however, is an important part of what a computer scientist does. Programming is often the way that we create a representation for our solutions. Therefore, this language representation and the process of creating it becomes a fundamental part of the discipline. Algorithms describe the solution to a problem in terms of the data needed to represent the problem instance and the set of steps necessary to produce the intended result. Programming languages must provide a notational way to represent both the process and the data. To this end, languages provide control constructs and data types. Control constructs allow algorithmic steps to be represented in a convenient yet unambiguous way.
257
1,198
msmarco_v2.1_doc_01_1669171843#2_2448181972
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsProgramming.html
1.4. What Is Programming? — Problem Solving with Algorithms and Data Structures
1.4. What Is Programming? ¶ 1.4. What Is Programming? ¶
Therefore, this language representation and the process of creating it becomes a fundamental part of the discipline. Algorithms describe the solution to a problem in terms of the data needed to represent the problem instance and the set of steps necessary to produce the intended result. Programming languages must provide a notational way to represent both the process and the data. To this end, languages provide control constructs and data types. Control constructs allow algorithmic steps to be represented in a convenient yet unambiguous way. At a minimum, algorithms require constructs that perform sequential processing, selection for decision-making, and iteration for repetitive control. As long as the language provides these basic statements, it can be used for algorithm representation. All data items in the computer are represented as strings of binary digits. In order to give these strings meaning, we need to have data types. Data types provide an interpretation for this binary data so that we can think about the data in terms that make sense with respect to the problem being solved.
651
1,754
msmarco_v2.1_doc_01_1669171843#3_2448183468
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsProgramming.html
1.4. What Is Programming? — Problem Solving with Algorithms and Data Structures
1.4. What Is Programming? ¶ 1.4. What Is Programming? ¶
At a minimum, algorithms require constructs that perform sequential processing, selection for decision-making, and iteration for repetitive control. As long as the language provides these basic statements, it can be used for algorithm representation. All data items in the computer are represented as strings of binary digits. In order to give these strings meaning, we need to have data types. Data types provide an interpretation for this binary data so that we can think about the data in terms that make sense with respect to the problem being solved. These low-level, built-in data types (sometimes called the primitive data types) provide the building blocks for algorithm development. For example, most programming languages provide a data type for integers. Strings of binary digits in the computer’s memory can be interpreted as integers and given the typical meanings that we commonly associate with integers (e.g. 23, 654, and -19). In addition, a data type also provides a description of the operations that the data items can participate in. With integers, operations such as addition, subtraction, and multiplication are common.
1,199
2,342
msmarco_v2.1_doc_01_1669171843#4_2448185010
http://interactivepython.org/courselib/static/pythonds/Introduction/WhatIsProgramming.html
1.4. What Is Programming? — Problem Solving with Algorithms and Data Structures
1.4. What Is Programming? ¶ 1.4. What Is Programming? ¶
These low-level, built-in data types (sometimes called the primitive data types) provide the building blocks for algorithm development. For example, most programming languages provide a data type for integers. Strings of binary digits in the computer’s memory can be interpreted as integers and given the typical meanings that we commonly associate with integers (e.g. 23, 654, and -19). In addition, a data type also provides a description of the operations that the data items can participate in. With integers, operations such as addition, subtraction, and multiplication are common. We have come to expect that numeric types of data can participate in these arithmetic operations. The difficulty that often arises for us is the fact that problems and their solutions are very complex. These simple, language-provided constructs and data types, although certainly sufficient to represent complex solutions, are typically at a disadvantage as we work through the problem-solving process. We need ways to control this complexity and assist with the creation of solutions. You have attempted 1 of 1 activities on this page
1,755
2,878
msmarco_v2.1_doc_01_1669175085#0_2448186532
http://interactivepython.org/courselib/static/pythonds/Recursion/WhatIsRecursion.html
5.2. What Is Recursion? — Problem Solving with Algorithms and Data Structures
5.2. What Is Recursion? ¶ 5.2. What Is Recursion? ¶
5.2. What Is Recursion? — Problem Solving with Algorithms and Data Structures 5.2. What Is Recursion? ¶ Recursion is a method of solving problems that involves breaking a problem down into smaller and smaller subproblems until you get to a small enough problem that it can be solved trivially. Usually recursion involves a function calling itself. While it may not seem like much on the surface, recursion allows us to write elegant solutions to problems that may otherwise be very difficult to program. You have attempted 1 of 1 activities on this page
0
553
msmarco_v2.1_doc_01_1669175980#0_2448187475
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition 6.2. Functions that Return Values ¶ Most functions require arguments, values that control how the function does its job. For example, if you want to find the absolute value of a number, you have to indicate what the number is. Python has a built-in function for computing the absolute value: Load History Show CodeLens 4 1 print(abs(5)) 2 ​ 3 print(abs(-5)) 4 ​ Activity: 6.2.1 ActiveCode (ch04_4) In this example, the arguments to the abs function are 5 and -5. Some functions take more than one argument. For example the math module contains a function called pow which takes two arguments, the base and the exponent.
0
715
msmarco_v2.1_doc_01_1669175980#1_2448188692
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
Python has a built-in function for computing the absolute value: Load History Show CodeLens 4 1 print(abs(5)) 2 ​ 3 print(abs(-5)) 4 ​ Activity: 6.2.1 ActiveCode (ch04_4) In this example, the arguments to the abs function are 5 and -5. Some functions take more than one argument. For example the math module contains a function called pow which takes two arguments, the base and the exponent. Load History Show CodeLens 5 1 import math 2 print(math.pow(2, 3)) 3 ​ 4 print(math.pow(7, 4)) 5 ​ Activity: 6.2.2 ActiveCode (ch04_5) Note Of course, we have already seen that raising a base to an exponent can be done with the ** operator. Another built-in function that takes more than one argument is max. Load History Show CodeLens 4 1 print(max(7, 11)) 2 print(max(4, 1, 17, 2, 12)) 3 print(max(3 * 11, 5 ** 3, 512 - 9, 1024 ** 0)) 4 ​ Activity: 6.2.3 ActiveCode (ch04_6) max can be sent any number of arguments, separated by commas, and will return the maximum value sent.
323
1,294
msmarco_v2.1_doc_01_1669175980#2_2448190198
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
Load History Show CodeLens 5 1 import math 2 print(math.pow(2, 3)) 3 ​ 4 print(math.pow(7, 4)) 5 ​ Activity: 6.2.2 ActiveCode (ch04_5) Note Of course, we have already seen that raising a base to an exponent can be done with the ** operator. Another built-in function that takes more than one argument is max. Load History Show CodeLens 4 1 print(max(7, 11)) 2 print(max(4, 1, 17, 2, 12)) 3 print(max(3 * 11, 5 ** 3, 512 - 9, 1024 ** 0)) 4 ​ Activity: 6.2.3 ActiveCode (ch04_6) max can be sent any number of arguments, separated by commas, and will return the maximum value sent. The arguments can be either simple values or expressions. In the last example, 503 is returned, since it is larger than 33, 125, and 1. Note that max also works on lists of values. Furthermore, functions like range, int, abs all return values that can be used to build more complex expressions. So an important difference between these functions and one like drawSquare is that drawSquare was not executed because we wanted it to compute a value — on the contrary, we wrote drawSquare because we wanted it to execute a sequence of steps that caused the turtle to draw a specific shape.
715
1,880
msmarco_v2.1_doc_01_1669175980#3_2448191880
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
The arguments can be either simple values or expressions. In the last example, 503 is returned, since it is larger than 33, 125, and 1. Note that max also works on lists of values. Furthermore, functions like range, int, abs all return values that can be used to build more complex expressions. So an important difference between these functions and one like drawSquare is that drawSquare was not executed because we wanted it to compute a value — on the contrary, we wrote drawSquare because we wanted it to execute a sequence of steps that caused the turtle to draw a specific shape. Functions that return values are sometimes called fruitful functions . In many other languages, a chunk that doesn’t return a value is called a procedure , but we will stick here with the Python way of also calling it a function, or if we want to stress it, a non-fruitful function. Fruitful functions still allow the user to provide information (arguments). However there is now an additional piece of data that is returned from the function. How do we write our own fruitful function?
1,295
2,367
msmarco_v2.1_doc_01_1669175980#4_2448193434
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
Functions that return values are sometimes called fruitful functions . In many other languages, a chunk that doesn’t return a value is called a procedure , but we will stick here with the Python way of also calling it a function, or if we want to stress it, a non-fruitful function. Fruitful functions still allow the user to provide information (arguments). However there is now an additional piece of data that is returned from the function. How do we write our own fruitful function? Let’s start by creating a very simple mathematical function that we will call square. The square function will take one number as a parameter and return the result of squaring that number. Here is the black-box diagram with the Python code following. Load History Show CodeLens 8 1 def square(x): 2 y = x * x 3 return y 4 ​ 5 toSquare = 10 6 result = square(toSquare) 7 print("The result of", toSquare, "squared is", result) 8 ​ Activity:
1,880
2,806
msmarco_v2.1_doc_01_1669175980#5_2448194873
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
Let’s start by creating a very simple mathematical function that we will call square. The square function will take one number as a parameter and return the result of squaring that number. Here is the black-box diagram with the Python code following. Load History Show CodeLens 8 1 def square(x): 2 y = x * x 3 return y 4 ​ 5 toSquare = 10 6 result = square(toSquare) 7 print("The result of", toSquare, "squared is", result) 8 ​ Activity: 6.2.4 ActiveCode (ch04_square) The return statement is followed by an expression which is evaluated. Its result is returned to the caller as the “fruit” of calling this function. Because the return statement can contain any Python expression we could have avoided creating the temporary variable y and simply used return x*x . Try modifying the square function above to see that this works just the same. On the other hand, using temporary variables like y in the program above makes debugging easier.
2,368
3,308
msmarco_v2.1_doc_01_1669175980#6_2448196333
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
6.2.4 ActiveCode (ch04_square) The return statement is followed by an expression which is evaluated. Its result is returned to the caller as the “fruit” of calling this function. Because the return statement can contain any Python expression we could have avoided creating the temporary variable y and simply used return x*x . Try modifying the square function above to see that this works just the same. On the other hand, using temporary variables like y in the program above makes debugging easier. These temporary variables are examples of local variables, pursued further in the next section. Notice something important here. The name of the variable we pass as an argument — toSquare — has nothing to do with the name of the formal parameter — x. It is as if x = toSquare is executed when square is called. It doesn’t matter what the value was named in the caller. In square, it’s name is x. You can see this very clearly in codelens, where the global variables (variables defined outside of any function) and the local variables for the square function are in separate boxes.
2,807
3,889
msmarco_v2.1_doc_01_1669175980#7_2448197923
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
These temporary variables are examples of local variables, pursued further in the next section. Notice something important here. The name of the variable we pass as an argument — toSquare — has nothing to do with the name of the formal parameter — x. It is as if x = toSquare is executed when square is called. It doesn’t matter what the value was named in the caller. In square, it’s name is x. You can see this very clearly in codelens, where the global variables (variables defined outside of any function) and the local variables for the square function are in separate boxes. As you step through the example in codelens notice that the return statement not only causes the function to return a value, but it also returns the flow of control back to the place in the program where the function call was made. this is true in general: Note The call to a function terminates after the execution of a return statement. This is fairly obvious if the return statement is the last statement in the function, but we will see later where it makes sense to have a return statement even when other statements follow, and the further statements are not executed. 1 def square (x):
3,309
4,483
msmarco_v2.1_doc_01_1669175980#8_2448199595
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
As you step through the example in codelens notice that the return statement not only causes the function to return a value, but it also returns the flow of control back to the place in the program where the function call was made. this is true in general: Note The call to a function terminates after the execution of a return statement. This is fairly obvious if the return statement is the last statement in the function, but we will see later where it makes sense to have a return statement even when other statements follow, and the further statements are not executed. 1 def square (x): 2 y = x * x 3 return y 4 5 toSquare = 10 6 squareResult = square (toSquare) 7 print ("The result of", toSquare, "squared is", squareResult) Edit this code line that just executed next line to execute << First Last >> Step 1 of 8 Submit Python Tutor by Philip Guo Customize visualization ( NEW!) Print output (drag lower right corner to resize) Frames Global frame Objects Activity: CodeLens 6.2.5 (ch04_clsquare) Another important thing to notice as you step through this codelens demonstration is the movement of the red and green arrows. Codelens uses these arrows to show you where it is currently executing. Recall that the red arrow always points to the next line of code that will be executed.
3,889
5,184
msmarco_v2.1_doc_01_1669175980#9_2448201391
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
2 y = x * x 3 return y 4 5 toSquare = 10 6 squareResult = square (toSquare) 7 print ("The result of", toSquare, "squared is", squareResult) Edit this code line that just executed next line to execute << First Last >> Step 1 of 8 Submit Python Tutor by Philip Guo Customize visualization ( NEW!) Print output (drag lower right corner to resize) Frames Global frame Objects Activity: CodeLens 6.2.5 (ch04_clsquare) Another important thing to notice as you step through this codelens demonstration is the movement of the red and green arrows. Codelens uses these arrows to show you where it is currently executing. Recall that the red arrow always points to the next line of code that will be executed. The light green arrow points to the line that was just executed in the last step. When you first start running this codelens demonstration you will notice that there is only a red arrow and it points to line 1. This is because line 1 is the next line to be executed and since it is the first line, there is no previously executed line of code. When you click on the forward button, notice that the red arrow moves to line 5, skipping lines 2 and 3 of the function (and the light green arrow has now appeared on line 1). Why is this?
4,483
5,717
msmarco_v2.1_doc_01_1669175980#10_2448203125
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
The light green arrow points to the line that was just executed in the last step. When you first start running this codelens demonstration you will notice that there is only a red arrow and it points to line 1. This is because line 1 is the next line to be executed and since it is the first line, there is no previously executed line of code. When you click on the forward button, notice that the red arrow moves to line 5, skipping lines 2 and 3 of the function (and the light green arrow has now appeared on line 1). Why is this? The answer is that function definition is not the same as function execution. Lines 2 and 3 will not be executed until the function is called on line 6. Line 1 defines the function and the name square is added to the global variables, but that is all the def does at that point. The body of the function will be executed later. Continue to click the forward button to see how the flow of control moves from the call, back up to the body of the function, and then finally back to line 7, after the function has returned its value and the value has been assigned to squareResult.
5,185
6,295
msmarco_v2.1_doc_01_1669175980#11_2448204708
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
The answer is that function definition is not the same as function execution. Lines 2 and 3 will not be executed until the function is called on line 6. Line 1 defines the function and the name square is added to the global variables, but that is all the def does at that point. The body of the function will be executed later. Continue to click the forward button to see how the flow of control moves from the call, back up to the body of the function, and then finally back to line 7, after the function has returned its value and the value has been assigned to squareResult. Finally, there is one more aspect of function return values that should be noted. All Python functions return the value None unless there is an explicit return statement with a value other than None. Consider the following common mistake made by beginning Python programmers. As you step through this example, pay very close attention to the return value in the local variables listing. Then look at what is printed when the function returns.
5,718
6,738
msmarco_v2.1_doc_01_1669175980#12_2448206201
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
Finally, there is one more aspect of function return values that should be noted. All Python functions return the value None unless there is an explicit return statement with a value other than None. Consider the following common mistake made by beginning Python programmers. As you step through this example, pay very close attention to the return value in the local variables listing. Then look at what is printed when the function returns. 1 def square (x): 2 y = x * x 3 print (y) # Bad! should use return instead! 4 5 toSquare = 10 6 squareResult = square (toSquare) 7 print ("The result of", toSquare, "squared is", squareResult) Edit this code line that just executed next line to execute << First Last >> Step 1 of 8 Submit Python Tutor by Philip Guo Customize visualization ( NEW!) Print output (drag lower right corner to resize) Frames Global frame Objects Activity:
6,295
7,175
msmarco_v2.1_doc_01_1669175980#13_2448207580
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
1 def square (x): 2 y = x * x 3 print (y) # Bad! should use return instead! 4 5 toSquare = 10 6 squareResult = square (toSquare) 7 print ("The result of", toSquare, "squared is", squareResult) Edit this code line that just executed next line to execute << First Last >> Step 1 of 8 Submit Python Tutor by Philip Guo Customize visualization ( NEW!) Print output (drag lower right corner to resize) Frames Global frame Objects Activity: CodeLens 6.2.6 (ch04_clsquare_bad) The problem with this function is that even though it prints the value of the square, that value will not be returned to the place where the call was made. Since line 6 uses the return value as the right hand side of an assignment statement, the evaluation of the function will be None. In this case, squareResult will refer to that value after the assignment statement and therefore the result printed in line 7 is incorrect. Typically, functions will return values that can be printed or processed in some other way by the caller. Check your understanding func-2-7:
6,738
7,778
msmarco_v2.1_doc_01_1669175980#14_2448209121
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
CodeLens 6.2.6 (ch04_clsquare_bad) The problem with this function is that even though it prints the value of the square, that value will not be returned to the place where the call was made. Since line 6 uses the return value as the right hand side of an assignment statement, the evaluation of the function will be None. In this case, squareResult will refer to that value after the assignment statement and therefore the result printed in line 7 is incorrect. Typically, functions will return values that can be printed or processed in some other way by the caller. Check your understanding func-2-7: What is wrong with the following function definition: def addEm(x, y, z): return x + y + z print('the answer is', x + y + z) A. You should never use a print statement in a function definition. B. You should not have any statements in a function after the return statement. Once the function gets to the return statement it will immediately stop executing the function.
7,176
8,147
msmarco_v2.1_doc_01_1669175980#15_2448210568
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
What is wrong with the following function definition: def addEm(x, y, z): return x + y + z print('the answer is', x + y + z) A. You should never use a print statement in a function definition. B. You should not have any statements in a function after the return statement. Once the function gets to the return statement it will immediately stop executing the function. C. You must calculate the value of x+y+z before you return it. D. A function cannot return a number. Compare me Activity: 6.2.7 Multiple Choice (test_question5_2_1) func-2-8: What will the following function return?
7,779
8,363
msmarco_v2.1_doc_01_1669175980#16_2448211628
http://interactivepython.org/courselib/static/thinkcspy/Functions/Functionsthatreturnvalues.html
6.2. Functions that Return Values — How to Think like a Computer Scientist: Interactive Edition
6.2. Functions that Return Values ¶ 6.2. Functions that Return Values ¶ Note Note Check your understanding
C. You must calculate the value of x+y+z before you return it. D. A function cannot return a number. Compare me Activity: 6.2.7 Multiple Choice (test_question5_2_1) func-2-8: What will the following function return? def addEm(x, y, z): print(x + y + z) A. None B. The value of x + y + z C. The string 'x + y + z' Compare me Activity: 6.2.8 Multiple Choice (test_question5_2_2)
8,147
8,524
msmarco_v2.1_doc_01_1669185184#0_2448212484
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition 6.1. Functions ¶ YouTube Runestone Interactive 1.29K subscribers Subscribe FunctionsIntro Watch later Copy link Info Shopping Tap to unmute If playback doesn't begin shortly, try restarting your device. You're signed out Videos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer. Cancel Confirm More videos More videos Switch camera Share Include playlist An error occurred while retrieving sharing information. Please try again later. Watch on 0:00 0:00 0:00 / 7:06 Live • Activity: 6.1.1 YouTube (function_intro) In Python, a function is a named sequence of statements that belong together.
0
763
msmarco_v2.1_doc_01_1669185184#1_2448213699
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
To avoid this, cancel and sign in to YouTube on your computer. Cancel Confirm More videos More videos Switch camera Share Include playlist An error occurred while retrieving sharing information. Please try again later. Watch on 0:00 0:00 0:00 / 7:06 Live • Activity: 6.1.1 YouTube (function_intro) In Python, a function is a named sequence of statements that belong together. Their primary purpose is to help us organize programs into chunks that match how we think about the solution to the problem. The syntax for a function definition is: def name( parameters ): statements You can make up any names you want for the functions you create, except that you can’t use a name that is a Python keyword, and the names must follow the rules for legal identifiers that were given previously. The parameters specify what information, if any, you have to provide in order to use the new function. Another way to say this is that the parameters specify what the function needs to do its work.
388
1,372
msmarco_v2.1_doc_01_1669185184#2_2448215121
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
Their primary purpose is to help us organize programs into chunks that match how we think about the solution to the problem. The syntax for a function definition is: def name( parameters ): statements You can make up any names you want for the functions you create, except that you can’t use a name that is a Python keyword, and the names must follow the rules for legal identifiers that were given previously. The parameters specify what information, if any, you have to provide in order to use the new function. Another way to say this is that the parameters specify what the function needs to do its work. There can be any number of statements inside the function, but they have to be indented from the def. In the examples in this book, we will use the standard indentation of four spaces. Function definitions are the second of several compound statements we will see, all of which have the same pattern: A header line which begins with a keyword and ends with a colon. A body consisting of one or more Python statements, each indented the same amount – 4 spaces is the Python standard – from the header line.
764
1,878
msmarco_v2.1_doc_01_1669185184#3_2448216664
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
There can be any number of statements inside the function, but they have to be indented from the def. In the examples in this book, we will use the standard indentation of four spaces. Function definitions are the second of several compound statements we will see, all of which have the same pattern: A header line which begins with a keyword and ends with a colon. A body consisting of one or more Python statements, each indented the same amount – 4 spaces is the Python standard – from the header line. We’ve already seen the for loop which follows this pattern. In a function definition, the keyword in the header is def, which is followed by the name of the function and some parameters enclosed in parentheses. The parameter list may be empty, or it may contain any number of parameters separated from one another by commas. In either case, the parentheses are required. We need to say a bit more about the parameters.
1,372
2,297
msmarco_v2.1_doc_01_1669185184#4_2448218017
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
We’ve already seen the for loop which follows this pattern. In a function definition, the keyword in the header is def, which is followed by the name of the function and some parameters enclosed in parentheses. The parameter list may be empty, or it may contain any number of parameters separated from one another by commas. In either case, the parentheses are required. We need to say a bit more about the parameters. In the definition, the parameter list is more specifically known as the formal parameters. This list of names describes those things that the function will need to receive from the user of the function. When you use a function, you provide values to the formal parameters. The figure below shows this relationship. A function needs certain information to do its work.
1,878
2,665
msmarco_v2.1_doc_01_1669185184#5_2448219222
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
In the definition, the parameter list is more specifically known as the formal parameters. This list of names describes those things that the function will need to receive from the user of the function. When you use a function, you provide values to the formal parameters. The figure below shows this relationship. A function needs certain information to do its work. These values, often called arguments or actual parameters, are passed to the function by the user. This type of diagram is often called a black-box diagram because it only states the requirements from the perspective of the user. The user must know the name of the function and what arguments need to be passed. The details of how the function works are hidden inside the “black-box”. Suppose we’re working with turtles and a common operation we need is to draw squares.
2,298
3,136
msmarco_v2.1_doc_01_1669185184#6_2448220489
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
These values, often called arguments or actual parameters, are passed to the function by the user. This type of diagram is often called a black-box diagram because it only states the requirements from the perspective of the user. The user must know the name of the function and what arguments need to be passed. The details of how the function works are hidden inside the “black-box”. Suppose we’re working with turtles and a common operation we need is to draw squares. It would make sense if we did not have to duplicate all the steps each time we want to make a square. “ Draw a square” can be thought of as an a bstraction of a number of smaller steps. We will need to provide two pieces of information for the function to do its work: a turtle to do the drawing and a size for the side of the square. We could represent this using the following black-box diagram.
2,666
3,533
msmarco_v2.1_doc_01_1669185184#7_2448221796
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
It would make sense if we did not have to duplicate all the steps each time we want to make a square. “ Draw a square” can be thought of as an a bstraction of a number of smaller steps. We will need to provide two pieces of information for the function to do its work: a turtle to do the drawing and a size for the side of the square. We could represent this using the following black-box diagram. Here is a program containing a function to capture this idea. Give it a try. Load History 18 1 import turtle 2 ​ 3 def drawSquare(t, sz): 4 """Make turtle t draw a square of with side sz.""" 5 ​ 6 for i in range(4):
3,137
3,749
msmarco_v2.1_doc_01_1669185184#8_2448222860
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
Here is a program containing a function to capture this idea. Give it a try. Load History 18 1 import turtle 2 ​ 3 def drawSquare(t, sz): 4 """Make turtle t draw a square of with side sz.""" 5 ​ 6 for i in range(4): 7 t.forward(sz) 8 t.left(90) 9 ​ 10 ​ 11 wn = turtle. Screen() # Set up the window and its attributes 12 wn.bgcolor("lightgreen") 13 ​ 14 alex = turtle. Turtle() # create alex 15 drawSquare(alex, 50) # Call the function to draw the square passing the actual turtle and the actual side size 16 ​ 17 wn.exitonclick() 18 ​ Activity: 6.1.2 ActiveCode (ch04_1) This function is named drawSquare. It has two parameters — one to tell the function which turtle to move around and the other to tell it the size of the square we want drawn.
3,533
4,278
msmarco_v2.1_doc_01_1669185184#9_2448224104
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
7 t.forward(sz) 8 t.left(90) 9 ​ 10 ​ 11 wn = turtle. Screen() # Set up the window and its attributes 12 wn.bgcolor("lightgreen") 13 ​ 14 alex = turtle. Turtle() # create alex 15 drawSquare(alex, 50) # Call the function to draw the square passing the actual turtle and the actual side size 16 ​ 17 wn.exitonclick() 18 ​ Activity: 6.1.2 ActiveCode (ch04_1) This function is named drawSquare. It has two parameters — one to tell the function which turtle to move around and the other to tell it the size of the square we want drawn. In the function definition they are called t and sz respectively. Make sure you know where the body of the function ends — it depends on the indentation and the blank lines don’t count for this purpose! docstrings If the first thing after the function header is a string (some tools insist that it must be a triple-quoted string), it is called a docstring and gets special treatment in Python and in some of the programming tools. Another way to retrieve this information is to use the interactive interpreter, and enter the expression <function_name>.__doc__, which will retrieve the docstring for the function. So the string you write as documentation at the start of a function is retrievable by python tools at runtime.
3,749
5,002
msmarco_v2.1_doc_01_1669185184#10_2448225840
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
In the function definition they are called t and sz respectively. Make sure you know where the body of the function ends — it depends on the indentation and the blank lines don’t count for this purpose! docstrings If the first thing after the function header is a string (some tools insist that it must be a triple-quoted string), it is called a docstring and gets special treatment in Python and in some of the programming tools. Another way to retrieve this information is to use the interactive interpreter, and enter the expression <function_name>.__doc__, which will retrieve the docstring for the function. So the string you write as documentation at the start of a function is retrievable by python tools at runtime. This is different from comments in your code, which are completely eliminated when the program is parsed. By convention, Python programmers use docstrings for the key documentation of their functions. Defining a new function does not make the function run. To do that we need a function call. This is also known as a function invocation.
4,279
5,340
msmarco_v2.1_doc_01_1669185184#11_2448227327
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
This is different from comments in your code, which are completely eliminated when the program is parsed. By convention, Python programmers use docstrings for the key documentation of their functions. Defining a new function does not make the function run. To do that we need a function call. This is also known as a function invocation. We’ve already seen how to call some built-in functions like print, range and int. Function calls contain the name of the function to be executed followed by a list of values in parentheses, called arguments, which are assigned to the parameters in the function definition. So in the second to the last line of the program, we call the function, and pass alex as the turtle to be manipulated, and 50 as the size of the square we want. Once we’ve defined a function, we can call it as often as we like and its statements will be executed each time we call it. In this case, we could use it to get one of our turtles to draw a square and then we can move the turtle and have it draw a different square in a different location.
5,003
6,064
msmarco_v2.1_doc_01_1669185184#12_2448228813
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
We’ve already seen how to call some built-in functions like print, range and int. Function calls contain the name of the function to be executed followed by a list of values in parentheses, called arguments, which are assigned to the parameters in the function definition. So in the second to the last line of the program, we call the function, and pass alex as the turtle to be manipulated, and 50 as the size of the square we want. Once we’ve defined a function, we can call it as often as we like and its statements will be executed each time we call it. In this case, we could use it to get one of our turtles to draw a square and then we can move the turtle and have it draw a different square in a different location. Note that we lift the tail so that when alex moves there is no trace. We put the tail back down before drawing the next square. Make sure you can identify both invocations of the drawSquare function. Load History 24 1 import turtle 2 ​ 3 def drawSquare(t, sz): 4 """Make turtle t draw a square of with side sz."""
5,341
6,378
msmarco_v2.1_doc_01_1669185184#13_2448230294
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
Note that we lift the tail so that when alex moves there is no trace. We put the tail back down before drawing the next square. Make sure you can identify both invocations of the drawSquare function. Load History 24 1 import turtle 2 ​ 3 def drawSquare(t, sz): 4 """Make turtle t draw a square of with side sz.""" 5 ​ 6 for i in range(4): 7 t.forward(sz) 8 t.left(90) 9 ​ 10 ​ 11 wn = turtle. Screen() # Set up the window and its attributes 12 wn.bgcolor("lightgreen") 13 ​ 14 alex = turtle. Turtle() # create alex 15 drawSquare(alex, 50) # Call the function to draw the square 16 ​ 17 alex.penup() 18 alex.goto(100,100) 19 alex.pendown() 20 ​ 21 drawSquare(alex,75) # Draw another square 22 ​ 23 wn.exitonclick() 24 ​ Activity: 6.1.3 ActiveCode (ch04_1a) In the next example, we’ve changed the drawSquare function a little and we get tess to draw 15 squares with some variations.
6,065
6,943
msmarco_v2.1_doc_01_1669185184#14_2448231695
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
5 ​ 6 for i in range(4): 7 t.forward(sz) 8 t.left(90) 9 ​ 10 ​ 11 wn = turtle. Screen() # Set up the window and its attributes 12 wn.bgcolor("lightgreen") 13 ​ 14 alex = turtle. Turtle() # create alex 15 drawSquare(alex, 50) # Call the function to draw the square 16 ​ 17 alex.penup() 18 alex.goto(100,100) 19 alex.pendown() 20 ​ 21 drawSquare(alex,75) # Draw another square 22 ​ 23 wn.exitonclick() 24 ​ Activity: 6.1.3 ActiveCode (ch04_1a) In the next example, we’ve changed the drawSquare function a little and we get tess to draw 15 squares with some variations. Once the function has been defined, we can call it as many times as we like with whatever actual parameters we like. Load History 24 1 import turtle 2 ​ 3 def drawMulticolorSquare(t, sz): 4 """Make turtle t draw a multi-colour square of sz.""" 5 for i in ['red','purple','hotpink','blue']: 6 t.color(i) 7 t.forward(sz) 8 t.left(90) 9 ​ 10 wn = turtle.
6,378
7,295
msmarco_v2.1_doc_01_1669185184#15_2448233149
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
Once the function has been defined, we can call it as many times as we like with whatever actual parameters we like. Load History 24 1 import turtle 2 ​ 3 def drawMulticolorSquare(t, sz): 4 """Make turtle t draw a multi-colour square of sz.""" 5 for i in ['red','purple','hotpink','blue']: 6 t.color(i) 7 t.forward(sz) 8 t.left(90) 9 ​ 10 wn = turtle. Screen() # Set up the window and its attributes 11 wn.bgcolor("lightgreen") 12 ​ 13 tess = turtle. Turtle() # create tess and set some attributes 14 tess.pensize(3) 15 ​ 16 size = 20 # size of the smallest square 17 for i in range(15): 18 drawMulticolorSquare(tess, size) 19 size = size + 10 # increase the size for next time 20 tess.forward(10) # move tess along a little 21 tess.right(18) # and give her some extra turn 22 ​ 23 wn.exitonclick() 24 ​ Activity: 6.1.4 ActiveCode (ch04_2) Warning Even if a function call needs no arguments, the parentheses ( ) after the function name are required. This can lead to a difficult bug:
6,944
7,925
msmarco_v2.1_doc_01_1669185184#16_2448234633
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
Screen() # Set up the window and its attributes 11 wn.bgcolor("lightgreen") 12 ​ 13 tess = turtle. Turtle() # create tess and set some attributes 14 tess.pensize(3) 15 ​ 16 size = 20 # size of the smallest square 17 for i in range(15): 18 drawMulticolorSquare(tess, size) 19 size = size + 10 # increase the size for next time 20 tess.forward(10) # move tess along a little 21 tess.right(18) # and give her some extra turn 22 ​ 23 wn.exitonclick() 24 ​ Activity: 6.1.4 ActiveCode (ch04_2) Warning Even if a function call needs no arguments, the parentheses ( ) after the function name are required. This can lead to a difficult bug: A function name without the parenthesis is a legal expression referring to the function; for example, print and alex.penup, but they do not call the associated functions. Note This workspace is provided for your convenience. You can use this activecode window to try out anything you like. Load History Show CodeLens 3 1 ​ 2 ​ 3 ​ Activity:
7,295
8,266
msmarco_v2.1_doc_01_1669185184#17_2448236097
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
A function name without the parenthesis is a legal expression referring to the function; for example, print and alex.penup, but they do not call the associated functions. Note This workspace is provided for your convenience. You can use this activecode window to try out anything you like. Load History Show CodeLens 3 1 ​ 2 ​ 3 ​ Activity: 6.1.5 ActiveCode (scratch_05_01) Check your understanding func-1-6: What is a function in Python? A. A named sequence of statements. B. Any sequence of statements. C. A mathematical expression that calculates a value.
7,926
8,484
msmarco_v2.1_doc_01_1669185184#18_2448237097
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
6.1.5 ActiveCode (scratch_05_01) Check your understanding func-1-6: What is a function in Python? A. A named sequence of statements. B. Any sequence of statements. C. A mathematical expression that calculates a value. D. A statement of the form x = 5 + 4. Compare me Activity: 6.1.6 Multiple Choice (test_question5_1_1) func-1-7: What is one main purpose of a function? A. To improve the speed of execution B. To help the programmer organize programs into chunks that match how they think about the solution to the problem.
8,267
8,790
msmarco_v2.1_doc_01_1669185184#19_2448238040
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
D. A statement of the form x = 5 + 4. Compare me Activity: 6.1.6 Multiple Choice (test_question5_1_1) func-1-7: What is one main purpose of a function? A. To improve the speed of execution B. To help the programmer organize programs into chunks that match how they think about the solution to the problem. C. All Python programs must be written using functions D. To calculate values. Compare me Activity: 6.1.7 Multiple Choice (test_question5_1_2) func-1-8: Which of the following is a valid function header (first line of a function definition)? A. def drawCircle (t):
8,484
9,055
msmarco_v2.1_doc_01_1669185184#20_2448239031
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
C. All Python programs must be written using functions D. To calculate values. Compare me Activity: 6.1.7 Multiple Choice (test_question5_1_2) func-1-8: Which of the following is a valid function header (first line of a function definition)? A. def drawCircle (t): B. def drawCircle: C. drawCircle (t, sz): D. def drawCircle (t, sz) Compare me Activity: 6.1.8 Multiple Choice (test_question5_1_3) func-1-9: What is the name of the following function?
8,790
9,241
msmarco_v2.1_doc_01_1669185184#21_2448239902
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
B. def drawCircle: C. drawCircle (t, sz): D. def drawCircle (t, sz) Compare me Activity: 6.1.8 Multiple Choice (test_question5_1_3) func-1-9: What is the name of the following function? def drawSquare(t, sz): """ Make turtle t draw a square of with side sz.""" for i in range(4): t.forward(sz) t.left(90) A. def drawSquare (t, sz) B. drawSquare C. drawSquare (t, sz) D. Make turtle t draw a square with side sz. Compare me Activity:
9,055
9,487
msmarco_v2.1_doc_01_1669185184#22_2448240763
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
def drawSquare(t, sz): """ Make turtle t draw a square of with side sz.""" for i in range(4): t.forward(sz) t.left(90) A. def drawSquare (t, sz) B. drawSquare C. drawSquare (t, sz) D. Make turtle t draw a square with side sz. Compare me Activity: 6.1.9 Multiple Choice (test_question5_1_4) func-1-10: What are the parameters of the following function? def drawSquare(t, sz): """ Make turtle t draw a square of with side sz.""" for i in range(4):
9,241
9,685
msmarco_v2.1_doc_01_1669185184#23_2448241641
http://interactivepython.org/courselib/static/thinkcspy/Functions/functions.html
6.1. Functions — How to Think like a Computer Scientist: Interactive Edition
6.1. Functions ¶ 6.1. Functions ¶ docstrings Warning Note Check your understanding
6.1.9 Multiple Choice (test_question5_1_4) func-1-10: What are the parameters of the following function? def drawSquare(t, sz): """ Make turtle t draw a square of with side sz.""" for i in range(4): t.forward(sz) t.left(90) A. i B. t C. t, sz D. t, sz, i Compare me Activity: 6.1.10 Multiple Choice (test_question5_1_5) func-1-11: Considering the function below, which of the following statements correctly invokes, or calls, this function (i.e., causes it to run)? Assume we already have a turtle named alex. def
9,488
10,000
msmarco_v2.1_doc_01_1669196597#0_2448242584
http://interactivepython.org/courselib/static/thinkcspy/SimplePythonData/Typeconversionfunctions.html
2.3. Type conversion functions — How to Think like a Computer Scientist: Interactive Edition
2.3. Type conversion functions ¶ 2.3. Type conversion functions ¶ Check your understanding
2.3. Type conversion functions — How to Think like a Computer Scientist: Interactive Edition 2.3. Type conversion functions ¶ Sometimes it is necessary to convert values from one type to another. Python provides a few simple functions that will allow us to do that. The functions int, float and str will (attempt to) convert their arguments into types int, float and str respectively. We call these type conversion functions. The int function can take a floating point number or a string, and turn it into an int. For floating point numbers, it discards the decimal portion of the number - a process we call truncation towards zero on the number line. Let us see this in action:
0
678
msmarco_v2.1_doc_01_1669196597#1_2448243726
http://interactivepython.org/courselib/static/thinkcspy/SimplePythonData/Typeconversionfunctions.html
2.3. Type conversion functions — How to Think like a Computer Scientist: Interactive Edition
2.3. Type conversion functions ¶ 2.3. Type conversion functions ¶ Check your understanding
The functions int, float and str will (attempt to) convert their arguments into types int, float and str respectively. We call these type conversion functions. The int function can take a floating point number or a string, and turn it into an int. For floating point numbers, it discards the decimal portion of the number - a process we call truncation towards zero on the number line. Let us see this in action: print (3.14, int (3.14)) print (3.9999, int (3.9999)) # This doesn't round to the closest int! print (3.0, int (3.0)) print (-3.999, int (-3.999)) # Note that the result is closer to zero print ("2345", int ("2345")) # parse a string to produce an int print (17, int (17)) # int even works on integers print (int ("23bottles")) The last case shows that a string has to be a syntactically legal number, otherwise you’ll get one of those pesky runtime errors. Modify the example by deleting the bottles and rerun the program. You should see the integer 23. The type converter float can turn an integer, a float, or a syntactically legal string into a float.
266
1,335
msmarco_v2.1_doc_01_1669196597#2_2448245262
http://interactivepython.org/courselib/static/thinkcspy/SimplePythonData/Typeconversionfunctions.html
2.3. Type conversion functions — How to Think like a Computer Scientist: Interactive Edition
2.3. Type conversion functions ¶ 2.3. Type conversion functions ¶ Check your understanding
print (3.14, int (3.14)) print (3.9999, int (3.9999)) # This doesn't round to the closest int! print (3.0, int (3.0)) print (-3.999, int (-3.999)) # Note that the result is closer to zero print ("2345", int ("2345")) # parse a string to produce an int print (17, int (17)) # int even works on integers print (int ("23bottles")) The last case shows that a string has to be a syntactically legal number, otherwise you’ll get one of those pesky runtime errors. Modify the example by deleting the bottles and rerun the program. You should see the integer 23. The type converter float can turn an integer, a float, or a syntactically legal string into a float. print (float ("123.45")) print (type (float ("123.45"))) The type converter str turns its argument into a string. Remember that when we print a string, the quotes are removed. However, if we print the type, we can see that it is definitely str. print (str (17)) print (str (123.45)) print (type (str (123.45))) Check your understanding data-3-4: What value is printed when the following statement executes?
678
1,742
msmarco_v2.1_doc_01_1669196597#3_2448246799
http://interactivepython.org/courselib/static/thinkcspy/SimplePythonData/Typeconversionfunctions.html
2.3. Type conversion functions — How to Think like a Computer Scientist: Interactive Edition
2.3. Type conversion functions ¶ 2.3. Type conversion functions ¶ Check your understanding
print (float ("123.45")) print (type (float ("123.45"))) The type converter str turns its argument into a string. Remember that when we print a string, the quotes are removed. However, if we print the type, we can see that it is definitely str. print (str (17)) print (str (123.45)) print (type (str (123.45))) Check your understanding data-3-4: What value is printed when the following statement executes? print( int(53.785) ) Nothing is printed. It generates a runtime error. The statement is valid Python code. It calls the int function on 53.785 and then prints the value that is returned. 53 The int function truncates all values after the decimal and prints the integer value.
1,335
2,018
msmarco_v2.1_doc_01_1669196597#4_2448247946
http://interactivepython.org/courselib/static/thinkcspy/SimplePythonData/Typeconversionfunctions.html
2.3. Type conversion functions — How to Think like a Computer Scientist: Interactive Edition
2.3. Type conversion functions ¶ 2.3. Type conversion functions ¶ Check your understanding
print( int(53.785) ) Nothing is printed. It generates a runtime error. The statement is valid Python code. It calls the int function on 53.785 and then prints the value that is returned. 53 The int function truncates all values after the decimal and prints the integer value. 54 When converting to an integer, the int function does not round. 53.785 The int function removes the fractional part of 53.785 and returns an integer, which is then printed.
1,742
2,194
msmarco_v2.1_doc_01_1669199238#0_2448248857
http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures
3.3. Big-O Notation ¶ 3.3. Big-O Notation ¶ Self Check
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures 3.3. Big-O Notation ¶ When trying to characterize an algorithm’s efficiency in terms of execution time, independent of any particular program or computer, it is important to quantify the number of operations or steps that the algorithm will require. If each of these steps is considered to be a basic unit of computation, then the execution time for an algorithm can be expressed as the number of steps required to solve the problem. Deciding on an appropriate basic unit of computation can be a complicated problem and will depend on how the algorithm is implemented. A good basic unit of computation for comparing the summation algorithms shown earlier might be to count the number of assignment statements performed to compute the sum. In the function sumOfN, the number of assignment statements is 1 ( t h e S u m = 0 ) plus the value of n (the number of times we perform t h e S u m = t h e S u m + i ). We can denote this by a function, call it T, where T ( n) = 1 + n. The parameter n is often referred to as the “size of the problem, ” and we can read this as “T (n) is the time it takes to solve a problem of size n, namely 1+n steps.” In the summation functions given above, it makes sense to use the number of terms in the summation to denote the size of the problem. We can then say that the sum of the first 100,000 integers is a bigger instance of the summation problem than the sum of the first 1,000.
0
1,490
msmarco_v2.1_doc_01_1669199238#1_2448250771
http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures
3.3. Big-O Notation ¶ 3.3. Big-O Notation ¶ Self Check
A good basic unit of computation for comparing the summation algorithms shown earlier might be to count the number of assignment statements performed to compute the sum. In the function sumOfN, the number of assignment statements is 1 ( t h e S u m = 0 ) plus the value of n (the number of times we perform t h e S u m = t h e S u m + i ). We can denote this by a function, call it T, where T ( n) = 1 + n. The parameter n is often referred to as the “size of the problem, ” and we can read this as “T (n) is the time it takes to solve a problem of size n, namely 1+n steps.” In the summation functions given above, it makes sense to use the number of terms in the summation to denote the size of the problem. We can then say that the sum of the first 100,000 integers is a bigger instance of the summation problem than the sum of the first 1,000. Because of this, it might seem reasonable that the time required to solve the larger case would be greater than for the smaller case. Our goal then is to show how the algorithm’s execution time changes with respect to the size of the problem. Computer scientists prefer to take this analysis technique one step further. It turns out that the exact number of operations is not as important as determining the most dominant part of the T ( n) function. In other words, as the problem gets larger, some portion of the T ( n) function tends to overpower the rest.
642
2,050
msmarco_v2.1_doc_01_1669199238#2_2448252592
http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures
3.3. Big-O Notation ¶ 3.3. Big-O Notation ¶ Self Check
Because of this, it might seem reasonable that the time required to solve the larger case would be greater than for the smaller case. Our goal then is to show how the algorithm’s execution time changes with respect to the size of the problem. Computer scientists prefer to take this analysis technique one step further. It turns out that the exact number of operations is not as important as determining the most dominant part of the T ( n) function. In other words, as the problem gets larger, some portion of the T ( n) function tends to overpower the rest. This dominant term is what, in the end, is used for comparison. The order of magnitude function describes the part of T ( n) that increases the fastest as the value of n increases. Order of magnitude is often called Big-O notation (for “order”) and written as O ( f ( n)). It provides a useful approximation to the actual number of steps in the computation. The function f ( n) provides a simple representation of the dominant part of the original T ( n).
1,491
2,506
msmarco_v2.1_doc_01_1669199238#3_2448254012
http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures
3.3. Big-O Notation ¶ 3.3. Big-O Notation ¶ Self Check
This dominant term is what, in the end, is used for comparison. The order of magnitude function describes the part of T ( n) that increases the fastest as the value of n increases. Order of magnitude is often called Big-O notation (for “order”) and written as O ( f ( n)). It provides a useful approximation to the actual number of steps in the computation. The function f ( n) provides a simple representation of the dominant part of the original T ( n). In the above example, T ( n) = 1 + n. As n gets large, the constant 1 will become less and less significant to the final result. If we are looking for an approximation for T ( n), then we can drop the 1 and simply say that the running time is O ( n). It is important to note that the 1 is certainly significant for T ( n). However, as n gets large, our approximation will be just as accurate without it. As another example, suppose that for some algorithm, the exact number of steps is T ( n) = 5 n 2 + 27 n + 1005.
2,051
3,022
msmarco_v2.1_doc_01_1669199238#4_2448255383
http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures
3.3. Big-O Notation ¶ 3.3. Big-O Notation ¶ Self Check
In the above example, T ( n) = 1 + n. As n gets large, the constant 1 will become less and less significant to the final result. If we are looking for an approximation for T ( n), then we can drop the 1 and simply say that the running time is O ( n). It is important to note that the 1 is certainly significant for T ( n). However, as n gets large, our approximation will be just as accurate without it. As another example, suppose that for some algorithm, the exact number of steps is T ( n) = 5 n 2 + 27 n + 1005. When n is small, say 1 or 2, the constant 1005 seems to be the dominant part of the function. However, as n gets larger, the n 2 term becomes the most important. In fact, when n is really large, the other two terms become insignificant in the role that they play in determining the final result. Again, to approximate T ( n) as n gets large, we can ignore the other terms and focus on 5 n 2. In addition, the coefficient 5 becomes insignificant as n gets large.
2,506
3,484
msmarco_v2.1_doc_01_1669199238#5_2448256750
http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures
3.3. Big-O Notation ¶ 3.3. Big-O Notation ¶ Self Check
When n is small, say 1 or 2, the constant 1005 seems to be the dominant part of the function. However, as n gets larger, the n 2 term becomes the most important. In fact, when n is really large, the other two terms become insignificant in the role that they play in determining the final result. Again, to approximate T ( n) as n gets large, we can ignore the other terms and focus on 5 n 2. In addition, the coefficient 5 becomes insignificant as n gets large. We would say then that the function T ( n) has an order of magnitude f ( n) = n 2, or simply that it is O ( n 2). Although we do not see this in the summation example, sometimes the performance of an algorithm depends on the exact values of the data rather than simply the size of the problem. For these kinds of algorithms we need to characterize their performance in terms of best case, worst case, or average case performance. The worst case performance refers to a particular data set where the algorithm performs especially poorly. Whereas a different data set for the exact same algorithm might have extraordinarily good performance.
3,023
4,124
msmarco_v2.1_doc_01_1669199238#6_2448258241
http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures
3.3. Big-O Notation ¶ 3.3. Big-O Notation ¶ Self Check
We would say then that the function T ( n) has an order of magnitude f ( n) = n 2, or simply that it is O ( n 2). Although we do not see this in the summation example, sometimes the performance of an algorithm depends on the exact values of the data rather than simply the size of the problem. For these kinds of algorithms we need to characterize their performance in terms of best case, worst case, or average case performance. The worst case performance refers to a particular data set where the algorithm performs especially poorly. Whereas a different data set for the exact same algorithm might have extraordinarily good performance. However, in most cases the algorithm performs somewhere in between these two extremes (average case). It is important for a computer scientist to understand these distinctions so they are not misled by one particular case. A number of very common order of magnitude functions will come up over and over as you study algorithms. These are shown in Table 1. In order to decide which of these functions is the dominant part of any T ( n) function, we must see how they compare with one another as n gets large.
3,485
4,633
msmarco_v2.1_doc_01_1669199238#7_2448259779
http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures
3.3. Big-O Notation ¶ 3.3. Big-O Notation ¶ Self Check
However, in most cases the algorithm performs somewhere in between these two extremes (average case). It is important for a computer scientist to understand these distinctions so they are not misled by one particular case. A number of very common order of magnitude functions will come up over and over as you study algorithms. These are shown in Table 1. In order to decide which of these functions is the dominant part of any T ( n) function, we must see how they compare with one another as n gets large. Table 1: Common Functions for Big-O ¶ f (n) Name 1 Constant log ⁡ n Logarithmic n Linear n log ⁡ n Log Linear n 2 Quadratic n 3 Cubic 2 n Exponential Figure 1 shows graphs of the common functions from Table 1. Notice that when n is small, the functions are not very well defined with respect to one another. It is hard to tell which is dominant. However, as n grows, there is a definite relationship and it is easy to see how they compare with one another.
4,125
5,090
msmarco_v2.1_doc_01_1669199238#8_2448261170
http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures
3.3. Big-O Notation ¶ 3.3. Big-O Notation ¶ Self Check
Table 1: Common Functions for Big-O ¶ f (n) Name 1 Constant log ⁡ n Logarithmic n Linear n log ⁡ n Log Linear n 2 Quadratic n 3 Cubic 2 n Exponential Figure 1 shows graphs of the common functions from Table 1. Notice that when n is small, the functions are not very well defined with respect to one another. It is hard to tell which is dominant. However, as n grows, there is a definite relationship and it is easy to see how they compare with one another. Figure 1: Plot of Common Big-O Functions ¶ As a final example, suppose that we have the fragment of Python code shown in Listing 2. Although this program does not really do anything, it is instructive to see how we can take actual code and analyze performance. Listing 2 a=5 b=6 c=10 for i in range(n): for j in range(n):
4,633
5,412
msmarco_v2.1_doc_01_1669199238#9_2448262381
http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures
3.3. Big-O Notation ¶ 3.3. Big-O Notation ¶ Self Check
Figure 1: Plot of Common Big-O Functions ¶ As a final example, suppose that we have the fragment of Python code shown in Listing 2. Although this program does not really do anything, it is instructive to see how we can take actual code and analyze performance. Listing 2 a=5 b=6 c=10 for i in range(n): for j in range(n): x = i * i y = j * j z = i * j for k in range(n): w = a*k + 45 v = b*b d = 33 The number of assignment operations is the sum of four terms. The first term is the constant 3, representing the three assignment statements at the start of the fragment. The second term is 3 n 2, since there are three statements that are performed n 2 times due to the nested iteration. The third term is 2 n, two statements iterated n times.
5,090
5,833
msmarco_v2.1_doc_01_1669199238#10_2448263521
http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures
3.3. Big-O Notation ¶ 3.3. Big-O Notation ¶ Self Check
x = i * i y = j * j z = i * j for k in range(n): w = a*k + 45 v = b*b d = 33 The number of assignment operations is the sum of four terms. The first term is the constant 3, representing the three assignment statements at the start of the fragment. The second term is 3 n 2, since there are three statements that are performed n 2 times due to the nested iteration. The third term is 2 n, two statements iterated n times. Finally, the fourth term is the constant 1, representing the final assignment statement. This gives us T ( n) = 3 + 3 n 2 + 2 n + 1 = 3 n 2 + 2 n + 4. By looking at the exponents, we can easily see that the n 2 term will be dominant and therefore this fragment of code is O ( n 2). Note that all of the other terms as well as the coefficient on the dominant term can be ignored as n grows larger. Figure 2:
5,413
6,240
msmarco_v2.1_doc_01_1669199238#11_2448264740
http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures
3.3. Big-O Notation ¶ 3.3. Big-O Notation ¶ Self Check
Finally, the fourth term is the constant 1, representing the final assignment statement. This gives us T ( n) = 3 + 3 n 2 + 2 n + 1 = 3 n 2 + 2 n + 4. By looking at the exponents, we can easily see that the n 2 term will be dominant and therefore this fragment of code is O ( n 2). Note that all of the other terms as well as the coefficient on the dominant term can be ignored as n grows larger. Figure 2: Comparing T ( n) with Common Big-O Functions ¶ Figure 2 shows a few of the common Big-O functions as they compare with the T ( n) function discussed above. Note that T ( n) is initially larger than the cubic function. However, as n grows, the cubic function quickly overtakes T ( n). It is easy to see that T ( n) then follows the quadratic function as n continues to grow. Self Check Write two Python functions to find the minimum number in a list.
5,834
6,690
msmarco_v2.1_doc_01_1669199238#12_2448265994
http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures
3.3. Big-O Notation ¶ 3.3. Big-O Notation ¶ Self Check
Comparing T ( n) with Common Big-O Functions ¶ Figure 2 shows a few of the common Big-O functions as they compare with the T ( n) function discussed above. Note that T ( n) is initially larger than the cubic function. However, as n grows, the cubic function quickly overtakes T ( n). It is easy to see that T ( n) then follows the quadratic function as n continues to grow. Self Check Write two Python functions to find the minimum number in a list. The first function should compare each number to every other number on the list. O ( n 2). The second function should be linear O ( n). YouTube Runestone Interactive 1.29K subscribers Subscribe findmin Watch later Copy link Info Shopping Tap to unmute If playback doesn't begin shortly, try restarting your device. You're signed out Videos you watch may be added to the TV's watch history and influence TV recommendations.
6,241
7,113
msmarco_v2.1_doc_01_1669199238#13_2448267275
http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/BigONotation.html
3.3. Big-O Notation — Problem Solving with Algorithms and Data Structures
3.3. Big-O Notation ¶ 3.3. Big-O Notation ¶ Self Check
The first function should compare each number to every other number on the list. O ( n 2). The second function should be linear O ( n). YouTube Runestone Interactive 1.29K subscribers Subscribe findmin Watch later Copy link Info Shopping Tap to unmute If playback doesn't begin shortly, try restarting your device. You're signed out Videos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer. Cancel Confirm More videos More videos Switch camera Share Include playlist An error occurred while retrieving sharing information. Please try again later. Watch on 0:00 0:00 0:00 / 16:19 Live • Activity: 3.3.1 YouTube (findMinVid)
6,691
7,408
msmarco_v2.1_doc_01_1669207130#0_2448268412
http://interactivepython.org/runestone/static/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures
4.8. Converting Decimal Numbers to Binary Numbers ¶ 4.8. Converting Decimal Numbers to Binary Numbers ¶ Self Check
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures 4.8. Converting Decimal Numbers to Binary Numbers ¶ In your study of computer science, you have probably been exposed in one way or another to the idea of a binary number. Binary representation is important in computer science since all values stored within a computer exist as a string of binary digits, a string of 0s and 1s. Without the ability to convert back and forth between common representations and binary numbers, we would need to interact with computers in very awkward ways. Integer values are common data items. They are used in computer programs and computation all the time. We learn about them in math class and of course represent them using the decimal number system, or base 10. The decimal number 233 10 and its corresponding binary equivalent 11101001 2 are interpreted respectively as 2 × 10 2 + 3 × 10 1 + 3 × 10 0 and 1 × 2 7 + 1 × 2 6 + 1 × 2 5 + 0 × 2 4 + 1 × 2 3 + 0 × 2 2 + 0 × 2 1 + 1 × 2 0 But how can we easily convert integer values into binary numbers? The answer is an algorithm called “ Divide by 2 ” that uses a stack to keep track of the digits for the binary result.
0
1,209
msmarco_v2.1_doc_01_1669207130#1_2448270196
http://interactivepython.org/runestone/static/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures
4.8. Converting Decimal Numbers to Binary Numbers ¶ 4.8. Converting Decimal Numbers to Binary Numbers ¶ Self Check
Integer values are common data items. They are used in computer programs and computation all the time. We learn about them in math class and of course represent them using the decimal number system, or base 10. The decimal number 233 10 and its corresponding binary equivalent 11101001 2 are interpreted respectively as 2 × 10 2 + 3 × 10 1 + 3 × 10 0 and 1 × 2 7 + 1 × 2 6 + 1 × 2 5 + 0 × 2 4 + 1 × 2 3 + 0 × 2 2 + 0 × 2 1 + 1 × 2 0 But how can we easily convert integer values into binary numbers? The answer is an algorithm called “ Divide by 2 ” that uses a stack to keep track of the digits for the binary result. The Divide by 2 algorithm assumes that we start with an integer greater than 0. A simple iteration then continually divides the decimal number by 2 and keeps track of the remainder. The first division by 2 gives information as to whether the value is even or odd. An even value will have a remainder of 0. It will have the digit 0 in the ones place.
591
1,559
msmarco_v2.1_doc_01_1669207130#2_2448271728
http://interactivepython.org/runestone/static/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures
4.8. Converting Decimal Numbers to Binary Numbers ¶ 4.8. Converting Decimal Numbers to Binary Numbers ¶ Self Check
The Divide by 2 algorithm assumes that we start with an integer greater than 0. A simple iteration then continually divides the decimal number by 2 and keeps track of the remainder. The first division by 2 gives information as to whether the value is even or odd. An even value will have a remainder of 0. It will have the digit 0 in the ones place. An odd value will have a remainder of 1 and will have the digit 1 in the ones place. We think about building our binary number as a sequence of digits; the first remainder we compute will actually be the last digit in the sequence. As shown in Figure 5, we again see the reversal property that signals that a stack is likely to be the appropriate data structure for solving the problem. Figure 5:
1,209
1,956
msmarco_v2.1_doc_01_1669207130#3_2448272971
http://interactivepython.org/runestone/static/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures
4.8. Converting Decimal Numbers to Binary Numbers ¶ 4.8. Converting Decimal Numbers to Binary Numbers ¶ Self Check
An odd value will have a remainder of 1 and will have the digit 1 in the ones place. We think about building our binary number as a sequence of digits; the first remainder we compute will actually be the last digit in the sequence. As shown in Figure 5, we again see the reversal property that signals that a stack is likely to be the appropriate data structure for solving the problem. Figure 5: Decimal-to-Binary Conversion ¶ The Python code in ActiveCode 1 implements the Divide by 2 algorithm. The function divideBy2 takes an argument that is a decimal number and repeatedly divides it by 2. Line 7 uses the built-in modulo operator, %, to extract the remainder and line 8 then pushes it on the stack. After the division process reaches 0, a binary string is constructed in lines 11-13. Line 11 creates an empty string.
1,560
2,383
msmarco_v2.1_doc_01_1669207130#4_2448274297
http://interactivepython.org/runestone/static/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures
4.8. Converting Decimal Numbers to Binary Numbers ¶ 4.8. Converting Decimal Numbers to Binary Numbers ¶ Self Check
Decimal-to-Binary Conversion ¶ The Python code in ActiveCode 1 implements the Divide by 2 algorithm. The function divideBy2 takes an argument that is a decimal number and repeatedly divides it by 2. Line 7 uses the built-in modulo operator, %, to extract the remainder and line 8 then pushes it on the stack. After the division process reaches 0, a binary string is constructed in lines 11-13. Line 11 creates an empty string. The binary digits are popped from the stack one at a time and appended to the right-hand end of the string. The binary string is then returned. Load History 18 1 from pythonds.basic import Stack 2 ​ 3 def divideBy2(decNumber): 4 remstack = Stack() 5 ​ 6 while decNumber > 0: 7 rem = decNumber % 2 8 remstack.push(rem) 9 decNumber = decNumber // 2 10 ​ 11 binString = "" 12 while not remstack.isEmpty():
1,957
2,786
msmarco_v2.1_doc_01_1669207130#5_2448275669
http://interactivepython.org/runestone/static/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures
4.8. Converting Decimal Numbers to Binary Numbers ¶ 4.8. Converting Decimal Numbers to Binary Numbers ¶ Self Check
The binary digits are popped from the stack one at a time and appended to the right-hand end of the string. The binary string is then returned. Load History 18 1 from pythonds.basic import Stack 2 ​ 3 def divideBy2(decNumber): 4 remstack = Stack() 5 ​ 6 while decNumber > 0: 7 rem = decNumber % 2 8 remstack.push(rem) 9 decNumber = decNumber // 2 10 ​ 11 binString = "" 12 while not remstack.isEmpty(): 13 binString = binString + str(remstack.pop()) 14 ​ 15 return binString 16 ​ 17 print(divideBy2(42)) 18 ​ Converting from Decimal to Binary (divby2) The algorithm for binary conversion can easily be extended to perform the conversion for any base. In computer science it is common to use a number of different encodings. The most common of these are binary, octal (base 8), and hexadecimal (base 16). The decimal number 233 and its corresponding octal and hexadecimal equivalents 351 8 and E 9 16 are interpreted as 3 × 8 2 + 5 × 8 1 + 1 × 8 0 and 14 × 16 1 + 9 × 16 0 The function divideBy2 can be modified to accept not only a decimal value but also a base for the intended conversion. The “Divide by 2” idea is simply replaced with a more general “Divide by base.”
2,384
3,554
msmarco_v2.1_doc_01_1669207130#6_2448277453
http://interactivepython.org/runestone/static/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures
4.8. Converting Decimal Numbers to Binary Numbers ¶ 4.8. Converting Decimal Numbers to Binary Numbers ¶ Self Check
13 binString = binString + str(remstack.pop()) 14 ​ 15 return binString 16 ​ 17 print(divideBy2(42)) 18 ​ Converting from Decimal to Binary (divby2) The algorithm for binary conversion can easily be extended to perform the conversion for any base. In computer science it is common to use a number of different encodings. The most common of these are binary, octal (base 8), and hexadecimal (base 16). The decimal number 233 and its corresponding octal and hexadecimal equivalents 351 8 and E 9 16 are interpreted as 3 × 8 2 + 5 × 8 1 + 1 × 8 0 and 14 × 16 1 + 9 × 16 0 The function divideBy2 can be modified to accept not only a decimal value but also a base for the intended conversion. The “Divide by 2” idea is simply replaced with a more general “Divide by base.” A new function called baseConverter, shown in ActiveCode 2 , takes a decimal number and any base between 2 and 16 as parameters. The remainders are still pushed onto the stack until the value being converted becomes 0. The same left-to-right string construction technique can be used with one slight change. Base 2 through base 10 numbers need a maximum of 10 digits, so the typical digit characters 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 work fine. The problem comes when we go beyond base 10.
2,786
4,043
msmarco_v2.1_doc_01_1669207130#7_2448279283
http://interactivepython.org/runestone/static/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures
4.8. Converting Decimal Numbers to Binary Numbers ¶ 4.8. Converting Decimal Numbers to Binary Numbers ¶ Self Check
A new function called baseConverter, shown in ActiveCode 2 , takes a decimal number and any base between 2 and 16 as parameters. The remainders are still pushed onto the stack until the value being converted becomes 0. The same left-to-right string construction technique can be used with one slight change. Base 2 through base 10 numbers need a maximum of 10 digits, so the typical digit characters 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 work fine. The problem comes when we go beyond base 10. We can no longer simply use the remainders, as they are themselves represented as two-digit decimal numbers. Instead we need to create a set of digits that can be used to represent those remainders beyond 9. Load History 21 1 from pythonds.basic import Stack 2 ​ 3 def baseConverter(decNumber,base): 4 digits = "0123456789ABCDEF" 5 ​ 6 remstack = Stack() 7 ​ 8 while decNumber > 0: 9 rem = decNumber % base 10 remstack.push(rem) 11 decNumber = decNumber // base 12 ​ 13 newString = "" 14 while not remstack.isEmpty():
3,555
4,561
msmarco_v2.1_doc_01_1669207130#8_2448280837
http://interactivepython.org/runestone/static/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures
4.8. Converting Decimal Numbers to Binary Numbers ¶ 4.8. Converting Decimal Numbers to Binary Numbers ¶ Self Check
We can no longer simply use the remainders, as they are themselves represented as two-digit decimal numbers. Instead we need to create a set of digits that can be used to represent those remainders beyond 9. Load History 21 1 from pythonds.basic import Stack 2 ​ 3 def baseConverter(decNumber,base): 4 digits = "0123456789ABCDEF" 5 ​ 6 remstack = Stack() 7 ​ 8 while decNumber > 0: 9 rem = decNumber % base 10 remstack.push(rem) 11 decNumber = decNumber // base 12 ​ 13 newString = "" 14 while not remstack.isEmpty(): 15 newString = newString + digits[remstack.pop()] 16 ​ 17 return newString 18 ​ 19 print(baseConverter(25,2)) 20 print(baseConverter(25,16)) 21 ​ Converting from Decimal to any Base (baseconvert) A solution to this problem is to extend the digit set to include some alphabet characters. For example, hexadecimal uses the ten decimal digits along with the first six alphabet characters for the 16 digits. To implement this, a digit string is created (line 4 in Listing 6) that stores the digits in their corresponding positions. 0 is at position 0, 1 is at position 1, A is at position 10, B is at position 11, and so on. When a remainder is removed from the stack, it can be used to index into the digit string and the correct resulting digit can be appended to the answer.
4,044
5,335
msmarco_v2.1_doc_01_1669207130#9_2448282706
http://interactivepython.org/runestone/static/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures
4.8. Converting Decimal Numbers to Binary Numbers ¶ 4.8. Converting Decimal Numbers to Binary Numbers ¶ Self Check
15 newString = newString + digits[remstack.pop()] 16 ​ 17 return newString 18 ​ 19 print(baseConverter(25,2)) 20 print(baseConverter(25,16)) 21 ​ Converting from Decimal to any Base (baseconvert) A solution to this problem is to extend the digit set to include some alphabet characters. For example, hexadecimal uses the ten decimal digits along with the first six alphabet characters for the 16 digits. To implement this, a digit string is created (line 4 in Listing 6) that stores the digits in their corresponding positions. 0 is at position 0, 1 is at position 1, A is at position 10, B is at position 11, and so on. When a remainder is removed from the stack, it can be used to index into the digit string and the correct resulting digit can be appended to the answer. For example, if the remainder 13 is removed from the stack, the digit D is appended to the resulting string. Self Check Q-3: What is value of 25 expressed as an octal number? Compare me Activity: 4.8.3 Fill in the Blank (baseconvert1) Q-4:
4,561
5,575
msmarco_v2.1_doc_01_1669207130#10_2448284249
http://interactivepython.org/runestone/static/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures
4.8. Converting Decimal Numbers to Binary Numbers ¶ 4.8. Converting Decimal Numbers to Binary Numbers ¶ Self Check
For example, if the remainder 13 is removed from the stack, the digit D is appended to the resulting string. Self Check Q-3: What is value of 25 expressed as an octal number? Compare me Activity: 4.8.3 Fill in the Blank (baseconvert1) Q-4: What is value of 256 expressed as a hexidecimal number? Compare me Activity: 4.8.4 Fill in the Blank (baseconvert2) Q-5: What is value of 26 expressed in base 26? Compare me Activity:
5,336
5,759
msmarco_v2.1_doc_01_1669207130#11_2448285176
http://interactivepython.org/runestone/static/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures
4.8. Converting Decimal Numbers to Binary Numbers ¶ 4.8. Converting Decimal Numbers to Binary Numbers ¶ Self Check
What is value of 256 expressed as a hexidecimal number? Compare me Activity: 4.8.4 Fill in the Blank (baseconvert2) Q-5: What is value of 26 expressed in base 26? Compare me Activity: 4.8.5 Fill in the Blank (baseconvert3) YouTube Runestone Interactive 1.29K subscribers Subscribe Stack2 Watch later Copy link Info Shopping Tap to unmute If playback doesn't begin shortly, try restarting your device. You're signed out Videos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer. Cancel Confirm More videos More videos Switch camera Share Include playlist An error occurred while retrieving sharing information. Please try again later.
5,576
6,303
msmarco_v2.1_doc_01_1669207130#12_2448286423
http://interactivepython.org/runestone/static/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures
4.8. Converting Decimal Numbers to Binary Numbers ¶ 4.8. Converting Decimal Numbers to Binary Numbers ¶ Self Check
4.8.5 Fill in the Blank (baseconvert3) YouTube Runestone Interactive 1.29K subscribers Subscribe Stack2 Watch later Copy link Info Shopping Tap to unmute If playback doesn't begin shortly, try restarting your device. You're signed out Videos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer. Cancel Confirm More videos More videos Switch camera Share Include playlist An error occurred while retrieving sharing information. Please try again later. Watch on 0:00 0:00 0:00 / 6:05 Live • Activity: 4.8.6 YouTube (video_Stack2)
5,760
6,380
msmarco_v2.1_doc_01_1669214293#0_2448287571
http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html
4.9. Infix, Prefix and Postfix Expressions — Problem Solving with Algorithms and Data Structures
4.9. Infix, Prefix and Postfix Expressions ¶ 4.9. Infix, Prefix and Postfix Expressions ¶ 4.9.1. Conversion of Infix Expressions to Prefix and Postfix ¶ 4.9.2. General Infix-to-Postfix Conversion ¶ 4.9.3. Postfix Evaluation ¶ Self Check
4.9. Infix, Prefix and Postfix Expressions — Problem Solving with Algorithms and Data Structures 4.9. Infix, Prefix and Postfix Expressions ¶ When you write an arithmetic expression such as B * C, the form of the expression provides you with information so that you can interpret it correctly. In this case we know that the variable B is being multiplied by the variable C since the multiplication operator * appears between them in the expression. This type of notation is referred to as infix since the operator is in between the two operands that it is working on. Consider another infix example, A + B * C. The operators + and * still appear between the operands, but there is a problem. Which operands do they work on? Does the + work on A and B or does the * take B and C? The expression seems ambiguous. In fact, you have been reading and writing these types of expressions for a long time and they do not cause you any problem.
0
935
msmarco_v2.1_doc_01_1669214293#1_2448289137
http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html
4.9. Infix, Prefix and Postfix Expressions — Problem Solving with Algorithms and Data Structures
4.9. Infix, Prefix and Postfix Expressions ¶ 4.9. Infix, Prefix and Postfix Expressions ¶ 4.9.1. Conversion of Infix Expressions to Prefix and Postfix ¶ 4.9.2. General Infix-to-Postfix Conversion ¶ 4.9.3. Postfix Evaluation ¶ Self Check
Consider another infix example, A + B * C. The operators + and * still appear between the operands, but there is a problem. Which operands do they work on? Does the + work on A and B or does the * take B and C? The expression seems ambiguous. In fact, you have been reading and writing these types of expressions for a long time and they do not cause you any problem. The reason for this is that you know something about the operators + and *. Each operator has a precedence level. Operators of higher precedence are used before operators of lower precedence. The only thing that can change that order is the presence of parentheses. The precedence order for arithmetic operators places multiplication and division above addition and subtraction.
567
1,314
msmarco_v2.1_doc_01_1669214293#2_2448290505
http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html
4.9. Infix, Prefix and Postfix Expressions — Problem Solving with Algorithms and Data Structures
4.9. Infix, Prefix and Postfix Expressions ¶ 4.9. Infix, Prefix and Postfix Expressions ¶ 4.9.1. Conversion of Infix Expressions to Prefix and Postfix ¶ 4.9.2. General Infix-to-Postfix Conversion ¶ 4.9.3. Postfix Evaluation ¶ Self Check
The reason for this is that you know something about the operators + and *. Each operator has a precedence level. Operators of higher precedence are used before operators of lower precedence. The only thing that can change that order is the presence of parentheses. The precedence order for arithmetic operators places multiplication and division above addition and subtraction. If two operators of equal precedence appear, then a left-to-right ordering or associativity is used. Let’s interpret the troublesome expression A + B * C using operator precedence. B and C are multiplied first, and A is then added to that result. ( A + B) * C would force the addition of A and B to be done first before the multiplication. In expression A + B + C, by precedence (via associativity), the leftmost + would be done first.
936
1,750
msmarco_v2.1_doc_01_1669214293#3_2448291947
http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html
4.9. Infix, Prefix and Postfix Expressions — Problem Solving with Algorithms and Data Structures
4.9. Infix, Prefix and Postfix Expressions ¶ 4.9. Infix, Prefix and Postfix Expressions ¶ 4.9.1. Conversion of Infix Expressions to Prefix and Postfix ¶ 4.9.2. General Infix-to-Postfix Conversion ¶ 4.9.3. Postfix Evaluation ¶ Self Check
If two operators of equal precedence appear, then a left-to-right ordering or associativity is used. Let’s interpret the troublesome expression A + B * C using operator precedence. B and C are multiplied first, and A is then added to that result. ( A + B) * C would force the addition of A and B to be done first before the multiplication. In expression A + B + C, by precedence (via associativity), the leftmost + would be done first. Although all this may be obvious to you, remember that computers need to know exactly what operators to perform and in what order. One way to write an expression that guarantees there will be no confusion with respect to the order of operations is to create what is called a fully parenthesized expression. This type of expression uses one pair of parentheses for each operator. The parentheses dictate the order of operations; there is no ambiguity.
1,315
2,201
msmarco_v2.1_doc_01_1669214293#4_2448293462
http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html
4.9. Infix, Prefix and Postfix Expressions — Problem Solving with Algorithms and Data Structures
4.9. Infix, Prefix and Postfix Expressions ¶ 4.9. Infix, Prefix and Postfix Expressions ¶ 4.9.1. Conversion of Infix Expressions to Prefix and Postfix ¶ 4.9.2. General Infix-to-Postfix Conversion ¶ 4.9.3. Postfix Evaluation ¶ Self Check
Although all this may be obvious to you, remember that computers need to know exactly what operators to perform and in what order. One way to write an expression that guarantees there will be no confusion with respect to the order of operations is to create what is called a fully parenthesized expression. This type of expression uses one pair of parentheses for each operator. The parentheses dictate the order of operations; there is no ambiguity. There is also no need to remember any precedence rules. The expression A + B * C + D can be rewritten as ( (A + (B * C)) + D) to show that the multiplication happens first, followed by the leftmost addition. A + B + C + D can be written as ( ( (A + B) + C) + D) since the addition operations associate from left to right. There are two other very important expression formats that may not seem obvious to you at first. Consider the infix expression A + B. What would happen if we moved the operator before the two operands?
1,750
2,725
msmarco_v2.1_doc_01_1669214293#5_2448295059
http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html
4.9. Infix, Prefix and Postfix Expressions — Problem Solving with Algorithms and Data Structures
4.9. Infix, Prefix and Postfix Expressions ¶ 4.9. Infix, Prefix and Postfix Expressions ¶ 4.9.1. Conversion of Infix Expressions to Prefix and Postfix ¶ 4.9.2. General Infix-to-Postfix Conversion ¶ 4.9.3. Postfix Evaluation ¶ Self Check
There is also no need to remember any precedence rules. The expression A + B * C + D can be rewritten as ( (A + (B * C)) + D) to show that the multiplication happens first, followed by the leftmost addition. A + B + C + D can be written as ( ( (A + B) + C) + D) since the addition operations associate from left to right. There are two other very important expression formats that may not seem obvious to you at first. Consider the infix expression A + B. What would happen if we moved the operator before the two operands? The resulting expression would be + A B. Likewise, we could move the operator to the end. We would get A B +. These look a bit strange. These changes to the position of the operator with respect to the operands create two new expression formats, prefix and postfix . Prefix expression notation requires that all operators precede the two operands that they work on.
2,202
3,091
msmarco_v2.1_doc_01_1669214293#6_2448296571
http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html
4.9. Infix, Prefix and Postfix Expressions — Problem Solving with Algorithms and Data Structures
4.9. Infix, Prefix and Postfix Expressions ¶ 4.9. Infix, Prefix and Postfix Expressions ¶ 4.9.1. Conversion of Infix Expressions to Prefix and Postfix ¶ 4.9.2. General Infix-to-Postfix Conversion ¶ 4.9.3. Postfix Evaluation ¶ Self Check
The resulting expression would be + A B. Likewise, we could move the operator to the end. We would get A B +. These look a bit strange. These changes to the position of the operator with respect to the operands create two new expression formats, prefix and postfix . Prefix expression notation requires that all operators precede the two operands that they work on. Postfix, on the other hand, requires that its operators come after the corresponding operands. A few more examples should help to make this a bit clearer (see Table 2 ). A + B * C would be written as + A * B C in prefix. The multiplication operator comes immediately before the operands B and C, denoting that * has precedence over +. The addition operator then appears before the A and the result of the multiplication.
2,726
3,512