|
|
Line 1: |
Line 1: |
| Following are terse descriptions for Python3 operators. For more information, see your Python reading material.
| | The C assessment exam has used questions on specific topics, often those in the following list. |
| | # Simple and nested loops. |
| | # Functions |
| | # Bit operations |
| | # Linked list |
| | # Binary trees |
|
| |
|
| =Operators=
| | This page is an attempt to identify such a set of topics for Python. The focus is on fundamentals, not modules. No imports allowed. |
| The following are a basic set of operators that most will intuitively know what they do.
| | For each problem type, some topics are listed. Then example problems are given (or will be someday), and split into three categories: Easy, Medium, and Hard. A typical exam might use one each from the Easy and Hard categories, and three from the Medium category. |
| * '''Comments:''' <code>#</code> is used to demarcate comments - anything after a # on a line is ignored by the python interpreter.
| |
| * '''Arithmetic operators:''' <code>+ - * / //</code>
| |
| ** Note that / is floating point division (3/2 is 1.5), while // is integer division (3//2 is rounded down to 1).
| |
| * '''Assignment operators:''' <code> =</code>
| |
| * '''Comparison operators:''' <code> < <= == != >= ></code>
| |
| ** Note that == tests if two values are equal, != tests if they are not equal (3 != 2 will be True, 3 == 2 will be False).
| |
| * '''Logical operators:''' <code>and or not</code>
| |
| * '''Membership operators:''' <code>in, not in</code>
| |
|
| |
|
| ==More Operators== | | = Basic (BASIC) level programs = |
| The following are more operators. These may not be obvious. Some examples are given, but you may need to read through your Python text to understand these.
| | == Topics == |
| * '''Arithmetic operators:''' <code>% **</code>
| | # Basic data types: string, numeric (not Complex), Boolean |
| ** % is remainder (10 % 3 is 1, 17 % 3 is 2), and ** is exponentiation (10**3 is 1000, 2**3 is 8).
| | # Reading and writing: input and print. |
| * '''Assignment operators:''' <code> += -= *= /= //= %= **= &= |= ^= >>= <<=</code>
| | # Type conversions: string to/from numeric. |
| ** Each of these is shorthand. For example, <code>x += 3</code> is a shorthand for <code>x = x + 3</code>
| | # Algebraic expressions. Assignment statements. |
| * '''Identity operators:''' <code>is, is not</code>
| | == Problems == |
| ** Tests whether two objects are the same, not just whether the values are the same. For simple variables/expressions, <code>is</code> will be the same as ==, but for lists/tuples/dictionaries <code>is</code> only gives True if the two things being compared are actually the same object (not just the same values).
| | # Easy: Celsius to Fahrenheit conversion. |
| * '''Bitwise operators:''' <code>& | ^ ~ << >></code>
| | # Medium: Temperature conversion with inputs like: 30F, 40C, etc. |
| ** These operate on the bits of a number. You need to understand binary before you can understand these. Examples: 12 & 8 evaluates to 8, 12 | 7 evaluates to 15, 12 ^ 8 evaluates to 4, ~7 evaluates to -8 (same as -7-1), 3 << 2 evaluates to 12, 12 >> 1 evaluates to 6.
| | # Harder: Real solutions to quadratic equations. |
| * '''Brackets:''' <code>[ : ]</code>
| |
| ** Square brackets are used to pull individual elements from strings, lists, tuples, and dictionaries. If <code>A = (1, 2, 'hello', 'hi', 10, 5)</code> then <code>A[0]</code> is the first item (which is 1) and <code>A[1]</code> is the second (which is 2). The : is used inside of square brackets to obtain a ''slice'' of elements (some chunk of them). <code>A[2:4]</code> would be a tuple that starts with the third element of A and include 2 of the elements (so it would be ('hello', 'hi')).
| |
| * '''Parenthesis:''' <code> ( , )</code>
| |
| ** Parenthesis as part of math expressions are used for enforcing a desired order of operations.
| |
| ** Parenthesis immediately after a function name are used for either defining or calling a function. In both cases, the <code>,</code> is used to separate parameters.
| |
|
| |
|
| ==Expressions== | | = Fundamental Data Structures = |
| There are many rules to keep in mind for how expressions are evaluated by Python. The following are some of the rules you need to remember, and some examples to put into python to see what they evaluate to
| | List, tuple, set, frozenset, dictionary |
| * '''Operator precedence''' - inside of parenthesis first, then exponentiation, then multiplication/division/remainder, then addition/subtraction, then assignment. Full list of operator precedence - [https://docs.python.org/3/reference/expressions.html#operator-precedence at python.org].
| | == Topics == |
| ** <code>1 + 2 * 3</code>
| | # Creation of, and basic operations on, all five data structures. |
| ** <code>1 + 2 * 9 ** 0.5</code>
| | # Slicing. |
| ** <code>(1 + 2) * 3</code>
| | # Selecting the appropriate data structure. |
| * '''0-based indexing''' - index into string/list/tuple starts at 0
| | # Comprehensions. |
| ** <code>'hello'[0]</code>
| | == Problems == |
| ** <code>(1, 2, 3)[1]</code>
| | # Easy: Find words common to two lists, read from 2 column data .le. |
| * '''Slices''' - <code>x[i:j+1]</code> evaluates to a subsequence of x starting at index i and ending at index j
| | # Medium: Find words common to two of three lists. |
| ** <code>'hello'[1:3]</code>
| | i# Medium: Multiple choice? A few scenarios, pick the data structure: Example: Looking up words in a foxed list of words. Which of the five do we use? Or, looking up words in a changing list of words. Looking up and counting frequencies for a list of words. |
| ** <code>[1, 2, 3, 4, 5][2:4]</code>
| | # Harder (Code golf with comprehensions?) Sort, max, min problems. Example: Sort a list of words by the number of vowels in the word. Example: Find the number (in a list) with the most one bits in its binary representation. |
| * '''String constants''' - anything inside of single quotes or double quotes, and + for strings is concatenation
| |
| ** <code>'hi' + ' there'</code>
| |
| ** <code>"2" + '3'</code>
| |
| ** <code>str(2) + str(3)</code>
| |
| ** <code>2 + 3</code>
| |
| ** Triple single or double quotes can also be used, mainly to easily give string constants that are multiple lines long -
| |
| <pre>
| |
| message = '''
| |
| This message is more than one
| |
| line long.
| |
| '''
| |
| </pre>
| |
| * '''Boolean operators''' - note that <code>and</code> is higher precedence than <code>or</code> and that compound Boolean expression should be made out of complete Boolean expressions that are and'ed, or'ed together. To check whether a variable x is 'a' or 'A', you need <code>if x == 'a' or x == 'A':</code>. If you tried using <code>if x == 'a' or 'A':</code> this always evaluates to True (because the part after the or, 'A', is considered to be True [anything that is not 0, '', or None - is True]).
| |
| * '''Immutability''' - string and tuple variables are immutable, they cannot be changed. This also means that any string/tuple methods do not change the value of the string but only return a new string/tuple.
| |
| x = 'Hello'
| |
| x.upper()
| |
| print(x)
| |
| x = x.upper()
| |
| print(x)</code>
| |
|
| |
|
| ==Data Types and Literals== | | = Functions = |
| A "literal", when used in the context of programming, is a basic value that is contained within a program. The value of the literal is, literally, the value that it seems to be. The following are the basic data types in Python, and examples of literals for each.
| | == Topics == |
| * '''Integer''' - literals are numbers that do not have decimal points and are not contained in quotes. Note that integer arithmetic in Python is ''arbitrary precision'', meaning that Python integers have no maximum value (a very nice feature). Integers can be given in binary, octal, or hexadecimal using a leading <code>0b</code>, <code>0o</code>, or <code>0x</code>. <code>_</code> can be used within the digits to make grouping of digits easier to read. Examples of integer literals: <code>1234</code>, <code>-1234</code>, <code>16</code>, <code>0b10000</code>, <code>0o20</code>, <code>0x10</code>, <code>1_000_000_000</code>
| | # Basic definition. |
| * '''Floating point''' - literals are numbers that have a decimal point. Python does ''not'' use arbitrary precision with floating point arithmetic (meaning that there are limits to how large floating point numbers can be, and how many digits of precision). Scientific notation can be used. Examples of integer literals: <code>1234.0</code>, <code>3.14159</code>, <code>1_000_000.0</code>, <code>1e6</code>
| | # Test knowledge of builtin functions. |
| * '''String''' - text data, which is between matching <code>'single quotes'</code>, <code>"double quotes"</code>, <code><nowiki>'''triple single quotes'''</nowiki></code>, or <code>"""triple double quotes"""</code>. Optionally, a <code>r</code> or <code>f</code> can be given before the quotes, to give a ''raw string'' or ''format string''. raw strings treat escape characters literally, and format strings evaluate python expressions inside of <code>{ }</code>. Other examples of string literals: <code>'1234'</code>, <code>'True'</code>, <code>'x = 3'</code>, <code>r'\n is normally a newline but not in raw strings'</code>, <code>f'5*5 = {5*5}'</code>
| | # Recursion. |
| * '''Boolean''' - literals are <code>True</code> and <code>False</code>
| | # Decorators? Move this to classes? |
| * '''None''' - <code>None</code> is a special value in Python that is its own type.
| | == Problems == |
| * '''Tuple''' - a ''container type'', specified with matching (), that is ''immutable''. Examples: <code>('a', 'b', 'c')</code>, <code>('a', )</code>
| | # Easy: Defining simple functions. Position and named parameters. |
| * '''List''' - a container type, specified with matching [], that ''is'' mutable. Examples: <code>['a', 'b', 'c']</code>, <code>['a', ]</code>
| | # Medium: Recursion with memoization (functools not allowed). |
| * '''Dictionary''' - a container type where each item has a ''key'' used for looking up the item and a ''value'' that is stored with the key, specified with matching {} where each item is given as key:value. Examples: <code>{'name': 'Alice', 'age': 42}</code>, <code>{'h1': 97, 'h2': 100, 'exams': [95, 34, 77]}</code>
| | # Hard: Functions returning functions: return a linear or quadratic function given coefficients. |
| * '''Set''' - a container type where there are no duplicates of items, specified with matching {} where each item is just a value (not a key:value as in dictionaries). Examples: <code>{'orange', 'apple', 'banana'}</code>, <code>{99, 98, 96}</code>
| |
|
| |
|
| ==Other== | | = Iterators and Generators = |
| Here we give additional operators and punctuation that have meaning in python, but which we don't go into here because they are not commonly used in beginning python. For each of these you should just know that they exist and remember the description of what they mean. If you need to use them or need to understand code that uses them, you should ask the internet for examples and explanation.
| | == Topics == |
| * <code>\</code> can be used to break a long line into multiple lines while having python still regard them as a single logical line.
| | # Using iterators: for, next, iter. |
| * <code>@</code> is used to make decorator functions.
| | # Common iterators: lists, tuples, dictionaries, range, zip, enumerate, .le descriptors, et cetera. |
| * <code>:</code> and <code>-></code> can be used to annotate function definitions.
| | # Creating iterators: class-based iterations (move to classes?). |
| * <code>:=</code> can be used to assign a value within an expression.
| | == Problems == |
| | # Easy: nested loops, one of Rob’s patterns of characters. |
| | # Medium: nested loops, one of Rob’s harder patterns. |
| | # Medium: Given class definition: write a method to do something. |
| | # Hard: (generators) Construct generator for words from text .le. |
|
| |
|
| ==Assignment== | | = Classes = |
| A typical "assignment" is to require a student to be able to correctly evaluate arbitrary expressions involving the operators. You can think of this building up in complexity.
| | == Topics == |
| * Literal expressions - you should be able to identify the data type and value of any literal expression. The basic data types in Python are - integer, floating point, string, Boolean, tuple, list, dictionary, set, None.
| | # Basic definition. |
| * Binary operators - you should be able to evaluate an expression that has just two operands (e.g., 'hello' + 'cat').
| | # Dunder methods, class based iterators. |
| * Larger expressions - you should be able to evaluate larger expressions using the python rules for order of operations (e.g., '3' + '5' * 4)
| | # Inheritance. Decorators. |
| | | # Privacy conventions. |
| A practice quiz that you can take is here - '''[https://indstate.instructure.com/courses/12565/quizzes/228160?module_item_id=1145792 Python Operators and Expressions Quiz]'''.
| | == Problems == |
| | | # Easy: De.ne a Point class; add a few methods for distance, norms. |
| '''Pass rating check''' If you are assigned this quiz in a course, you should be able to score 100% on the quiz.
| | # Medium: Binary tree class, with the usual methods, a couple dunders (in, len, str, add, eq, invert). |
| | # Hard: Subset frequency counting trie. Given a big set, .nd all subsets that appear as subsets in at least r of the sets. |
The C assessment exam has used questions on specific topics, often those in the following list.
- Simple and nested loops.
- Functions
- Bit operations
- Linked list
- Binary trees
This page is an attempt to identify such a set of topics for Python. The focus is on fundamentals, not modules. No imports allowed.
For each problem type, some topics are listed. Then example problems are given (or will be someday), and split into three categories: Easy, Medium, and Hard. A typical exam might use one each from the Easy and Hard categories, and three from the Medium category.
Basic (BASIC) level programs
Topics
- Basic data types: string, numeric (not Complex), Boolean
- Reading and writing: input and print.
- Type conversions: string to/from numeric.
- Algebraic expressions. Assignment statements.
Problems
- Easy: Celsius to Fahrenheit conversion.
- Medium: Temperature conversion with inputs like: 30F, 40C, etc.
- Harder: Real solutions to quadratic equations.
Fundamental Data Structures
List, tuple, set, frozenset, dictionary
Topics
- Creation of, and basic operations on, all five data structures.
- Slicing.
- Selecting the appropriate data structure.
- Comprehensions.
Problems
- Easy: Find words common to two lists, read from 2 column data .le.
- Medium: Find words common to two of three lists.
i# Medium: Multiple choice? A few scenarios, pick the data structure: Example: Looking up words in a foxed list of words. Which of the five do we use? Or, looking up words in a changing list of words. Looking up and counting frequencies for a list of words.
- Harder (Code golf with comprehensions?) Sort, max, min problems. Example: Sort a list of words by the number of vowels in the word. Example: Find the number (in a list) with the most one bits in its binary representation.
Functions
Topics
- Basic definition.
- Test knowledge of builtin functions.
- Recursion.
- Decorators? Move this to classes?
Problems
- Easy: Defining simple functions. Position and named parameters.
- Medium: Recursion with memoization (functools not allowed).
- Hard: Functions returning functions: return a linear or quadratic function given coefficients.
Iterators and Generators
Topics
- Using iterators: for, next, iter.
- Common iterators: lists, tuples, dictionaries, range, zip, enumerate, .le descriptors, et cetera.
- Creating iterators: class-based iterations (move to classes?).
Problems
- Easy: nested loops, one of Rob’s patterns of characters.
- Medium: nested loops, one of Rob’s harder patterns.
- Medium: Given class definition: write a method to do something.
- Hard: (generators) Construct generator for words from text .le.
Classes
Topics
- Basic definition.
- Dunder methods, class based iterators.
- Inheritance. Decorators.
- Privacy conventions.
Problems
- Easy: De.ne a Point class; add a few methods for distance, norms.
- Medium: Binary tree class, with the usual methods, a couple dunders (in, len, str, add, eq, invert).
- Hard: Subset frequency counting trie. Given a big set, .nd all subsets that appear as subsets in at least r of the sets.