PDA

View Full Version : bug in python code


Krimble2000
07-17-2006, 01:35 PM
Hello, i have a problem with this rather simple piece of code.

bestand = open('weer.txt', 'r')

temperatuur = {}
totaal = 0
lijst = []

lijstgroter = []
lijstkleiner = []

for line in bestand :
if not line[0] == '#' :
l = line.split()
temperatuur[l[0]] = l[1]

## for calculating gemiddelde
getallen = l[1]
lijst.append(getallen)
totaal += int(getallen)
gemiddelde = totaal / len(lijst)

## if getal in l > gemiddelde then do something, else do something else
if int(l[1]) >= gemiddelde :
lijstgroter.append(l)
elif int(l[1]) < gemiddelde :
lijstkleiner.append(l)

print "De gemiddelde temperatuur = " + str(gemiddelde) + " graden." + "\n \n"
print "De steden met minstens de gemiddelde temperatuur: " + "\n" + str(lijstgroter) + "\n \n"
print "De steden met een temperatuur onder het gemiddelde:" + "\n" + str(lijstkleiner)

bestand.close()

my output is this:
De gemiddelde temperatuur = 15 graden.


De steden met minstens de gemiddelde temperatuur:
[['Athene', '19'], ['Istanbul', '19'], ['Las-Palmas', '17'], ['Lissabon', '18'], ['Mallorca', '14'], ['Marseille', '14'], ['Moskou', '16'], ['Rome', '15'], ['Bangkok', '37'], ['Curacao', '27'], ['Jakarta', '31'], ['Johannesburg', '17'], ['Los-Angeles', '15'], ['Mexico-Stad', '17'], ['Nairobi', '19'], ['Peking', '20'], ['Perth', '21'], ['Sydney', '20'], ['Tel-Aviv', '21']]


De steden met een temperatuur onder het gemiddelde:
[['Barcelona', '15'], ['Berlijn', '7'], ['Londen', '12'], ['Madrid', '6'], ['Milaan', '12'], ['Munchen', '6'], ['Parijs', '11'], ['Praag', '7'], ['Stockholm', '6'], ['Warschau', '8'], ['Wenen', '11'], ['Buenos-Aires', '9'], ['Chicago', '11'], ['New-York', '10'], ['Tokyo', '13'], ['Toronto', '5'], ['Vancouver', '14']]

in the upperlist are 2 mistakes: ['Mallorca', '14'] and ['Marseille', '14'] Why are those two not in the second list ?

Disko
07-17-2006, 08:11 PM
When you determine whether to put the new city and temperature in the list with temperatures above or under average, you are not using the average of all the temperatures but only the ones that are read so far.

Br,
/Disko

stew
07-17-2006, 08:46 PM
Your program is calculating the average temperature of the places counted so far and not of all the places. So when processing Mallorca and Marseille, it has so far visited ['Athene', '19'], ['Istanbul', '19'], ['Las-Palmas', '17'], ['Lissabon', '18'] which results in an anverage > 15.

CGTalk Moderation
07-17-2006, 08:46 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.