Array: Difference between revisions

2,207 bytes added ,  15 years ago
no edit summary
(Clarify the contrast between numerically indexed and associative arrays)
No edit summary
Line 103:
end.
</pascal>
 
=={{header|Python}}==
Example: open a text file and compute letter frequency.
<python>
import string
if hasattr(string, ''ascii_lowercase''):
letters = string.ascii_lowercase # Python 2.6 and later
else:
letters = string.lowercase # Earlier versions
offset = ord('a')
def countletters(file_handle):
"""Traverse a file and compute the number of occurences of each letter
"""return results as a simple 26 element list of integers.
results = [0] * len(letters)
for line in file_handle:
for char in line:
char = char.lower()
if char in letters:
results[offset - ord(char)] += 1
# Ordinal of 'a' minus ordinal of any lowercase ASCII letter -> 0..25
return results
 
if __name__ == "__main__":
sourcedata = open(sys.argv[1])
lettercounts = countletters(sourcedata)
for i in range(len(lettercounts)):
print "%s=%d" % (chr(i + ord('a'), lettercounts[i]),
 
</python>
 
This example defines the function and provides a sample usage. The ''if ... __main__...'' line allows it to be cleanly imported into any other Python code while also allowing it to function as a standalone script. (A very common Python idiom).
 
Using a numerically indexed array (list) for this is artificial and clutters the code somewhat. The more Pythonic approach would be:
 
<python>
...
def countletters(file_handle):
"""Count occurences of letters and return a dictionary of them
"""
results = dict()
for line in file_handle:
for char in line:
if char.lower() in letters:
c = char.lower()
results[c] = results.get(c,0) + 1
return results
</python>
 
Which eliminates the ungainly fiddling with ordinal values and offsets. More importantly it allows the results to be more simply printed using:
 
<python>
lettercounts = countletters(sourcedata)
for letter,count in lettercounts.items():
print "%s=%s" % (letter, count),
</python>
 
Again eliminating all fussing with the details of converting letters into list indices.
 
 
==Computational metrics==
Anonymous user