HELP Newbie solve this Problem
Mark Hathaway
hathawa2 at marshall.edu
Fri Mar 24 19:06:25 EST 2000
>> On Fri, 24 Mar 2000 03:43:38 GMT, race9047 at my-deja.com declaimed the
>> following in comp.lang.python:
>>
>> 7 a
>> 12 b
>> 16 c
>> . . .
>> 3 z
>> But the real challenge is to invert the list to look like this:
>> a 7
>> b 12
>> c 16
>> . . .
>> z 3
>>
> Dennis Lee Bieber wrote:
>
> I must be from a different world then... The second part is what
> I'd find easy... even in FORTRAN (maybe too easy in FORTRAN)
>
> integer counts(26) / 26 * 0 / ! or is it 0 * 26?
> character line*132 ! set for the longest line the
> ! the data file can contain
> open(10, file="data", status="old")
> read(10, '(a132)', iostat=ios) line
> 10 continue
> if (ios .eq. 0) then
> do 20 i=1, 132 ! or the line length max
> if (line(i:i) .ge. 'a' .and. line(i:i) .le. 'z') then
> inx = ichar(line(i:i)) - ichar('a') + 1
> counts(inx) = counts(inx) + 1
> elseif (line(i:i) .ge. 'A' .and. line(i:i) .le. 'Z')
> x then
> inx = ichar(line(i:i)) - ichar('A') + 1
> counts(inx) = counts(inx) + 1
> else
> continue ! just my style
> endif
> 20 continue
> read(10, '(a132)', iostat=ios) line
> goto 10
> endif
> close(10)
> do 30 i=1, 26
> print *, char(i), ' ', counts(i)
> 30 continue
> stop
>
> It would look much cleaner in Python, and I'd use case
> conversion modules rather than the duplicates in the IF statements...
I can't really believe the Fartran code takes that much space.
I suspect it's given as a set-up, so the Python code to follow
will be all the more impressive. Well, here's a Python version.
import string
lines = open('file.txt').readlines()
for each in lines:
eachlist = string.split(each)
str = eachlist[1] + " " + eachlist[0]
print str
If you'd wanted the output printed back to a file then you could
add something other than the final 'print str' statement.
Amazing isn't it? When a language doesn't get in your way the code
is brief and more readable. It's all the niggling little details
that a language like Fortran or C require that makes them very ugly.
Mark Hathaway
e-mail: hathawa2 at marshall.edu
More information about the Python-list
mailing list