learning with python question (HtTLaPP)

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Apr 28 02:45:12 EDT 2008


En Sat, 26 Apr 2008 20:50:57 -0300, <umpsumps at gmail.com> escribió:

> ok.. I finally made something that works.. Please let me know what you
> think:
>
>>>> def lines(letters):
> 	fin = open('words.txt')
> 	count = 0
> 	rescount = 0  # count the number of results
> 	results = ""  # there are words that contain the letters
> 	for line in fin:
> 		needs = 0
> 		x = str(line.strip())
> 		for ch in letters:
> 			if ch not in x:
> 				pass
> 			else:
> 				needs = needs + 1
> 		if needs == len(letters):
> 			rescount += 1
> 			results = results + '\n' + x
> 		count += 1
> 	print count, 'lines searched'
> 	print results, '\n'
> 	print 'result count is: ', rescount

That's pretty good. Some improvements:

- The "natural" way to collect the results is using a list, appending words to it. Later you can print it one word per line or in any other format you want. Also, we don't need the "rescount" variable: it's just the length of the list.

> 		needs = 0
> 		for ch in letters:
> 			if ch not in x:
> 				pass
> 			else:
> 				needs = needs + 1
> 		if needs == len(letters):

The overall idea is to test whether ALL letters are in the word `x`, ok? So as soon as we find a letter that isn't in the word, we are sure the test failed and we can break out of the loop. And if we get up to the last step, that means that all the letters were in the word (else we would not have got so far). So we don't have to count the letters; instead, we can use the "else" clause of the for loop (it means "the loop was exhausted completely".)

- I don't like the names "x" nor "ch"; I'm using "word" and "letter" instead. This is the revised version:

def lines(letters):
	fin = open('words.txt')
	count = 0
	results = []  # there are words that contain the letters
	for line in fin:
		word = line.strip()
		for letter in letters:
			if letter not in x:
				break
		else:
			results.append(word)
		count += 1
	print count, 'lines searched'
	print '\n'.join(results), '\n'
	print 'result count is: ', len(results)

That "\n".join(...) means "concatenate all the items in the list using \n as a separator between items" and it's a pretty common idiom in Python.

-- 
Gabriel Genellina




More information about the Python-list mailing list