Short String Exercise in python language
java programming and c, c++, Matlab, Python, HTML, CSS programming language, and new techniques news and any history.
Short String Exercise in python language
Compound Boolean Expressions
Recall that a Rectangle is specified in its constructor by two diagonally oppose Points. This example gives the first use in the tutorials of the Rectangle methods that recover those two corner points, getP1 and getP2. The program calls the points obtained this way pt1 and pt2. The x and y
java programming and c, c++, Matlab, Python, HTML, CSS programming language, and new techniques news and any history.
Short String Exercise in python language
Write a program short.py with a function printShort with a heading:
def printShort(strings):
'''Given a list of strings,
print the ones with at most three characters.
>>> printShort(['a', 'long', one'])
a
one
'''
In your main program, test the function, calling it several times with different lists of strings. Hint: Find the length of each string with the lens function.
The function documentation here models a common approach: illustrating the behavior of the function with a Python Shell interaction. This begins with a line starting with >>>. Other exercises and examples will also document behavior in the Shell.
Even Print Exercise
Write a program even1.py with a function printEven with a heading:
def printEven(nums):
'''Given a list of integers nums,
print the even ones.
>>> printEven([4, 1, 3, 2, 7])
4
2
'''
In your main program, test the function, calling it several times with different lists of integers. Hint: A number is even if its remainder, when dividing by 2, is 0.
Even List Exercise
Write a program even2.py with a function choose even with a heading:
def chooseEven(nums):
'''Given a list of integers, nums,
return a list containing only the even ones.
>>> chooseEven([4, 1, 3, 2, 7])
[4, 2]
'''
In your main program, test the function, calling it several times with different lists of integers and printing the results. Hint: Create a new list, and append the appropriate numbers to it.
Unique List Exercise
* The madlib2.py program has its getKeys function, which first generates a list of each occurrence of a cue in the story format. This gives the cues in order, but likely includes repetitions. The original version of getKeys uses a quick method to remove duplicates, forming a set from the list. There is a disadvantage in the conversion, though: Sets are not ordered, so when you iterate through the resulting set, the order of the cues will likely bear no resemblance to the order they first appeared in the list. That issue motivates this problem:
Copy madlib2.py to madlib2a.py, and add a function with this heading:
def uniqueList(aList):
''' Return a new list that includes the first occurrence of each value
in aList, and omits later repeats. The returned list should include
the first occurrences of values in aList in their original order.
>>> vals = ['cat', 'dog', 'cat', 'bug', 'dog', 'ant', 'dog', 'bug']
>>> uniqueList(vals)
['cat', 'dog', 'bug', 'ant']
'''
A useful Boolean operator is in, checking membership in a sequence:
>>> vals = ['this', 'is', 'it]
>>> 'is' in vals
True
>>> 'was' in vals
False
It can also be used with not, as not in, to mean the opposite:
>>> vals = ['this', 'is', 'it]
>>> 'is' not in vals
False
>>> 'was' not in vals
True
In general the two versions are:
item in sequence
item not in sequence
Hint: Process aList in order. Use the new syntax to only append elements to a new list that are not already in the new list.
After perfecting the uniqueList function, replace the last line of getKeys, so it uses uniqueList to remove duplicates in keyList.
Check that your madlib2a.py prompts you for cue values in the order that the cues first appear in the Madlib format stringCompound Boolean Expressions
To be eligible to graduate from Loyola University Chicago, you must have 120 credits and a GPA of at least 2.0. This translates directly into Python as a compound condition:
credits >= 120 and GPA >=2.0
This is true if both credits >= 120 is true and GPA >= 2.0 is true. A short example program using this would be:
credits = float(input('How many units of credit do you have? '))
GPA = float(input('What is your GPA? '))
if credits >= 120 and GPA >=2.0:
print('You are eligible to graduate!')
else:
print('You are not eligible to graduate.')
The new Python syntax is for the operator and:
condition1 and condition2
The compound condition is true if both of the component conditions are true. It is false if at least one of the conditions is false.
In the last example in the previous section, there was an if-elif statement where both tests had the same block to be done if the condition was true:
if x < xLow:
dx = -dx
elif x > xHigh:
dx = -dx
There is a simpler way to state this in a sentence: If x < xLow or x > xHigh, switch the sign of dx. That translates directly into Python:
if x < xLow or x > xHigh:
dx = -dx
The word or makes another compound condition:
condition1 or condition2
is true if at least one of the conditions is true. It is false if both conditions are false. This corresponds to one way the word “or” is used in English. Other times in English “or” is used to mean exactly one alternative is true.
Warning
When translating a problem stated in English using “or”, be careful to determine whether the meaning matches Python’s or.
It is often convenient to encapsulate complicated tests inside a function. Think of how to complete the function starting:
def isInside(rect, point):
'''Return True if the point is inside the Rectangle rect.'''
pt1 = rect.getP1()
pt2 = rect.getP2()
coordinates of pt1, pt2, and the point can be recovered with the methods of the Point type, getX() and getY().
Suppose that I introduce variables for the x coordinates of pt1, point, and pt2, calling these x-coordinates end1, Val, and end2, respectively. On the first try, you might decide that the needed mathematical relationship to test is
end1 <= val <= end2
Unfortunately, this is not enough: The only requirement for the two corner points is that they be diagonally opposite, not that the coordinates of the second point are higher than the corresponding coordinates of the first point. It could be that end1 is 200; end2 is 100, and val is 120. In this latter case val is between end1 and end2, but substituting into the expression above
200 <= 120 <= 100
is False. The 100 and 200 need to be reversed in this case. This makes a complicated situation. Also, this is an issue which must be revisited for both the x and y coordinates. I introduce an auxiliary function isBetween to deal with one coordinate at a time. It starts:
def isBetween(val, end1, end2):
'''Return True if val is between the ends.
The ends do not need to be in increasing order.'''
Clearly this is true if the original expression, end1 <= val <= end2, is true. You must also consider the possible case when the order of the ends is reversed: end2 <= val <= end1. How do we combine these two possibilities? The Boolean connectives to consider are and or. Which applies? You only need one to be true, so or is the proper connective:
A correct but redundant function body would be:
if end1 <= val <= end2 or end2 <= val <= end1:
return True
else:
return False
Check the meaning: if the compound expression is True, return True. If the condition is False, return False - in either case return the same value as the test condition. See that a much simpler and neater version is to just return the value of the condition itself!
return end1 <= val <= end2 or end2 <= val <= end1
Not: -In general, you should not need an if-else statement to choose between true and false values! Operate directly on the boolean expression
A side comment on expressions like
end1 <= val <= end2
Other than the two-character operators, this is like standard math syntax, chaining comparisons. In Python any number of comparisons can be chainedin this way, closely approximating mathematical notation. Though this is good Python, be aware that if you try other high-level languages like Java and C++, such an expression is gibberish. Another way the expression can be expressed (and which translates directly to other languages) is:
end1 <= val and val <= end2
So much for the auxiliary function isBetween. Back to the isInside function. You can use the isBetween function to check the x coordinates,
isBetween(point.getX(), p1.getX(), p2.getX())
and to check the y coordinates,
isBetween(point.getY(), p1.getY(), p2.getY())
Again the question arises: how do you combine the two tests?
In this case, we need the point to be both between the sides and between the top and bottom, so the proper connector is and.
Sometimes you want to test the opposite of a condition. As in English, you can use the word not. For instance, to test if a Point was not inside Rectangle Rect, you could use the condition
not isInside(rect, point)
In general,
not condition
is True when the condition is False, and False when a condition is True.
The example program chooseButton1.py, shown below, is a complete program using the isInside function in a simple application, choosing colors. Pardon the length. Do check it out. It will be the starting point for a number of improvements that shorten it and make it more powerful in the next section. First a brief overview:
The program includes the functions isBetween and isInside that have already been discussed. The program creates a number of colored rectangles to use as buttons and also as picture components. Aside from specific data values,
the code to create each rectangle is the same, so the action is encapsulated in a function, makeColoredRect. All of this is fine, and will be preserved in later versions.
The present main function is long, though. It has the usual graphics starting code, draws buttons and picture elements, and then has a number of code sections prompting the user to choose a color for a picture element. Each code section has a long if-elif-else test to see which button was clicked, and sets the color of the picture element appropriately.
'''Make a choice of colors via mouse clicks in Rectangles --
A demonstration of Boolean operators and Boolean functions.'''
from graphics import *
def isBetween(x, end1, end2):
'''Return True if x is between the ends or equal to either.
The ends do not need to be in increasing order.'''
return end1 <= x <= end2 or end2 <= x <= end1
def isInside(point, rect):
'''Return True if the point is inside the Rectangle rect.'''
pt1 = rect.getP1()
pt2 = rect.getP2()
return isBetween(point.getX(), pt1.getX(), pt2.getX()) and \
isBetween(point.getY(), pt1.getY(), pt2.getY())
def makeColoredRect(corner, width, height, color, win):
''' Return a Rectangle drawn in win with the upper left corner
and color specified.'''
corner2 = corner.clone()
corner2.move(width, -height)
rect = Rectangle(corner, corner2)
rect.setFill(color)
rect.draw(win)
return rect
def main():
win = GraphWin('pick Colors', 400, 400)
win.yUp() # right side up coordinates
redButton = makeColoredRect(Point(310, 350), 80, 30, 'red', win)
yellowButton = makeColoredRect(Point(310, 310), 80, 30, 'yellow', win)
blueButton = makeColoredRect(Point(310, 270), 80, 30, 'blue', win)
house = makeColoredRect(Point(60, 200), 180, 150, 'gray', win)
door = makeColoredRect(Point(90, 150), 40, 100, 'white', win)
roof = Polygon(Point(50, 200), Point(250, 200), Point(150, 300))
roof.setFill('black')
roof.draw(win)
msg = Text(Point(win.getWidth()/2, 375),'Click to choose a house color.')
msg.draw(win)
pt = win.getMouse()
if isInside(pt, redButton):
color = 'red'
elif isInside(pt, yellowButton):
color = 'yellow'
elif isInside(pt, blueButton):
color = 'blue'
else :
color = 'white'
house.setFill(color)
msg.setText('Click to choose a door color.')
pt = win.getMouse()
if isInside(pt, redButton):
color = 'red'
elif isInside(pt, yellowButton):
color = 'yellow'
elif isInside(pt, blueButton):
color = 'blue'
else :
color = 'white'
door.setFill(color)
win.promptClose(msg)
main()
The only further new feature used is in the long return statement in isInside.
return isBetween(point.getX(), pt1.getX(), pt2.getX()) and \
isBetween(point.getY(), pt1.getY(), pt2.getY())
Recall that Python is smart enough to realize that a statement continues to the next line if there is an unmatched pair of parentheses or brackets. Above is another situation with a long statement, but there are no unmatched parentheses on a line. For readabili ,ty it is best not to make an enormous long line that would run off your screen or paper. Continuing to the next line is recommended. You can make the final character on a line be a backslash (\) to indicate the statement continues on the next line. This is not particularly neat, but it is a rather rare situation. Most statements fit neatly on one line, and the creator of Python decided it was best to make the syntax simple in the most common situation. (Many other languages require a special statement terminator symbol like ‘;’ and pay no attention to newlines). Extra parentheses here would not hurt, so an alternative would be
return (isBetween(point.getX(), pt1.getX(), pt2.getX()) and
isBetween(point.getY(), pt1.getY(), pt2.getY()) )
The chooseButton1.py program is long partly because of repeated code. The next section gives another version involving lists.
Comments
Post a Comment