<br><br><div class="gmail_quote">On Sun, Aug 22, 2010 at 1:31 PM, Dirk Nachbar <span dir="ltr"><<a href="mailto:dirknbr@gmail.com">dirknbr@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
Here is a function which takes any list and creates a freq table,<br>
which can be printed unsorted, sorted by cases or items. It's supposed<br>
to mirror the proc freq in SAS.<br>
<br>
Dirk<br>
<br>
def freq(seq,order='unsorted',prin=True):<br>
#order can be unsorted, cases, items<br>
<br>
freq={}<br>
for s in seq:<br>
if s in freq:<br>
freq[s]+=1<br>
else:<br>
freq[s]=1<br></blockquote><div><br></div><div>The above code can be replaced with this:</div><div> freq = {}</div><div> for s in seqn:</div><div> freq[s] = freq.get(s,0) + 1</div><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
if prin==True:<br>
print 'Items=',len(seq),'Cases=',len(freq)<br>
print '------------------------'<br>
if order=='unsorted':<br>
for k in freq.keys():<br>
print k,freq[k],float(freq[k])/len(seq)<br>
elif order=='cases':<br>
#<a href="http://blog.client9.com/2007/11/sorting-python-dict-by-
value.html" target="_blank">http://blog.client9.com/2007/11/sorting-python-dict-by-<br>
value.html</a><br>
freq2=sorted(freq.iteritems(), key=lambda (k,v):<br>
(v,k),reverse=True)<br>
for f in freq2:<br>
print f[0],f[1],float(f[1])/len(seq)<br>
elif order=='items':<br>
for k in sorted(freq.iterkeys()):<br>
print k,freq[k],float(freq[k])/len(seq)<br>
print '------------------------'<br>
return freq<br>
<br>
#test<br>
<br>
import random<br>
<br>
rand=[]<br>
for i in range(10000):<br>
rand.append(str(int(100*random.random())))<br>
<br>
fr=freq(rand)<br>
fr2=freq(rand,order='items')<br>
fr2=freq(rand,order='cases')<br>
<font color="#888888">--<br></font></blockquote><div><br></div><div>I feel the code you wrote is bloated a bit. You shall definately give another try to improvise it.</div><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<font color="#888888">
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</font></blockquote></div><br><br clear="all"><br>-- <br>~l0nwlf<br>