Do this activity with a partner. You don't have to turn anything in.
myString = 'hi there!' len(myString) myList = myString.split() len(myList[1]) x = 10 y = 15 str(x) + str(y) [x]+[y] range(1,11) range(3,10)[0] #this is tricky negNums = range(-7,1) negNums[3:5] (x == 10) and (str(y) == 'fifteen') (x < 4) or (y*0.1 < 4) if len(myList[1]) > 10: print myList[1],'has length > 10' else: print myList[1],'has length <= 10'
In this task, we're going to move away from text for a bit and practice our loops and conditionals. The premise is this: Suppose you were a farmer and you have a lot of grassland, and a lot of sheep. Sheep eat grass, but in order for the grass to have time to grow back, you want to confine the sheep to a particular section of your land, so that they can't get to the grass in other places. Then, when they have eaten all the grass in that area, you'll move them to another section of your land, and repeat the process.
The question is this: To fence off your land, you need a fence. Supposing that you have n meters of wire. How big of a piece of land can you fence off? We'll make the problem a little easier by adding a constraint -- you may only fence off rectangular (or square) pieces of land. For example, if you have 24 meters of wire, you may either fence off an area of 3x9m (since 3+3+9+9=24), or an area of 5x7m (since 5+5+7+7=24). The former would give you 27m2 of eatable grass, the latter would give you 35m2
Download grass.py
. The output of your program should look something like:
You have 24 meters of wire. Therefore, the possible sections are: Length: 11 m, Width: 1 m, Area: 11 meters square. Length: 10 m, Width: 2 m, Area: 20 meters square. Length: 9 m, Width: 3 m, Area: 27 meters square. Length: 8 m, Width: 4 m, Area: 32 meters square. Length: 7 m, Width: 5 m, Area: 35 meters square. Length: 6 m, Width: 6 m, Area: 36 meters square.Note that we do not need to calculate the answers for
length <= 5m
. Why?
Hint: You will need to use the built-in Python function range(x,y)
, that generates a list with the given beginning and end values.
In this task, you will write a program that will print out the words that make up the first n non-space characters of a text, rounded up to the next word. For example, the first 30 characters of the poem "Tiger, Tiger", would be:
Tiger, tiger, burning bright In theThat's exactly 30 characters, not counting the spaces. If we wanted 45 characters, then we would need:
Tiger, tiger, burning bright In the forests of the nightThat's 47 non-space characters -- the 45th character falls right in the middle of "night", so instead of chopping the word in the middle, we take in the whole word.
The same programming pattern that we used to find the maximum value of a list can be used for this problem. Download firstN.py
and finish the program.