[Tutor] Problem with task, please help!

Alan Gauld alan.gauld at yahoo.co.uk
Sun Oct 28 05:27:29 EDT 2018


On 27/10/2018 20:41, michiel nijs wrote:
> I am an engineering student and we have to use Python. 
> We don't have lessons so we all have to learn it on our own.

What, no lessons at all?!
Or just no lessons on Python?
Have you done any kind of programming before?


> We got a task and I am stuck on this:
> "Count the number of parcels for forrest ground and > count the number of parcels for orchard ground".

When starting out on a problem its always good
to consider how you would solve it without a
computer, just using pen and paper.

Can you write down the algorithm steps you would
use to do this manually?

> I think I have to use the for-loop but I don't know how.

Do you mean you don't know how to use a for loop?

In that case read any Python tutorial on looping.
(Try mine in the .sig if you like)

Or do you mean you don't know how to apply it here?
If the latter then you have already written the code
to read the data from the file.
Now you need to loop over that data analysing each line.

Can you write a function (isForest() ) that extracts
the data you want from a line and returns true if it
is a forest?
And another similar (isOrchard() ) that returns true
if an orchard?

Now, in your loop, you just need to test whether it's
a forest and increment the counter if it is.
And if it's not, test if it's an orchard and increment
the other counter is it is.

It will look something like:

forests, orchards = 0,0
for line in getLandUse():
    if isForest(line): forests += 1
    if isOrchard(line) orchards += 1
print (forests, orchards)

That's not the most efficient solution but it should
be easy to understand and debug.


> import numpy as np
> import csv
> from matplotlib import pyplot as plt

You only really need csv for this task.

> def getlanduse():
>     with open('LandUse.csv', encoding='latin-1') as csvfile:
>         readCSV = csv.DictReader(csvfile, delimiter=';')
>         return list(readCSV)
HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list