Feeds:
Posts
Comments

Remove duplicate elements

How to remove duplicate elements from a list or array

#Python 2.5, 2.6
cad = ["Buying","prepaid", "debit", "card", "debit", "these", "prepaid"]
no_duplicate = set(cad)
print list(no_duplicate)

#output ['card', 'these', 'prepaid', 'Buying', 'debit']
#Ruby
cad = ["Buying","prepaid", "debit", "card", "debit", "these", "prepaid"]
puts cad.uniq

Factorial

Many books recommend and show the factorial function recursively, but not always good to use recursion. You may lock the computer!. Think different.

 
#Python 2.5
def fact(x): 
  a = 1 
  for i in xrange(1,x+1): 
    a = a*i 
  return a

#Python 2.6
import math 
math.factorial(8)
 
#Ruby: 
#8! or 8 factorial
(1..8).inject{|x,y| x*y}

Show your code at WordPress

This example is very clear.
There is more information here

[sourcecode language= ‘python’]
print ‘hola mundo’
[/sourcecode]

print 'hola mundo'
Follow

Get every new post delivered to your Inbox.