def Sum(self,I):
        j = len(sorted(I))
        result = []
        for x in range(j):
            for y in range (1,j):
                for z in range (2,j):
                    if I[x]+I[y]+I[z] == 0:
                        result.append([I[x], I[y], I[z]])

        res = list(set(tuple(sorted(sub)) for sub in result))
        print(res)
Exemple #2
0
def loadFile():
with open('electronics.csv') as csvfile: #Opens and reads the dataset
reader = csv.reader(csvfile)
data = list(reader)
for x in range(0,len(data)):
del data[x][0] # Removing transaction
Number from the dataset
transactionNumber = len(data) # Counts the number of
lines or number of transactions in a dataset.
return data,transactionNumber
def flatList(currentItemSet): # Function converts Array
of array list into a flat list of data [[1],[2]] => [1,2]
itemList = [([x] if isinstance(x,str) else x) for x in currentItemSet]
flatList=list(itertools.chain(*itemList)) # Helps in reading entire
string rather than a character from a string.
flatList=set(flatList) # Removes duplicate
elements from the list by using set
flatList=list(flatList) # Converting a SET to LIST
of values.
return flatList
def formatData(data): # Function used to remove
unwanted spaces in the data for a CSV file.
flatList = [item for sublist in data for item in sublist] # converts a
data into flatlist.

while '' in flatList:
flatList.remove('')
return flatList
def findSupportItem(supportValue,support,transactionNumber): # Function
identifies the SUPPORT% of each item.
currentItemSet=[]
currentRemoveList=[]

for key, value in supportValue.iteritems(): # Reads a
dictionary list by reading its key and value.
transactionNumber=Decimal(transactionNumber)

if ((value/transactionNumber)*100>=support): #Condition to
check minimum SUPPORT %
finalItemSet[key]=value #Frequent Item
dictionary dataset
currentItemSet.append(key) # Maintains
current item data set.
else:
finalRemoveList[key]=value # Maintains
all remove list dataset
currentRemoveList.append(key) # Current item
remove list.
return finalItemSet,finalRemoveList,currentItemSet,currentRemoveList
def findSupportValue(flatListData): #find the counts of each item
counts=dict(Counter(flatListData)) # Dictionary COUNTER identifies
number of counts for each item.
return counts
def combinationListValue(currentItemSet,x): # Function helps in
identifying combinations of data
combinationList=list(itertools.combinations(currentItemSet,x)) #
Creates a list from COMBINATIONS of data.
return combinationList
def findSupportOccurances(combinationList1,data,supportOccurances): #
Finds the occurrences of subset of data for finding support values.
for x in range(0,len(data)):
for y in range(0,len(combinationList1)):
if (set(combinationList1[y]).issubset(set(data[x]))==True):
#Checks that if the current data is subset of Main Combination list
supportOccurances.append(combinationList1[y])
return supportOccurances
def calculateConfidence(finalSupportSet,confidence,mainKey,subKey): #
Fucntion to calculate % Value of confidence from a set of values.
associationList = [e for e in mainKey if e not in subKey]
if(float(finalSupportSet.get(mainKey))*100/finalSupportSet.get(subKey)>=flo
at(confidence)): #To identify or filter %values with the accepted
confidence.
#print str(subKey) +' -> '+ str(associationList) +'
'+str(float(finalSupportSet.get(mainKey))*100/finalSupportSet.get(subKey))

finalKey=str(subKey) +' -> '+ str(associationList)
# Designing the data based on association rules generated.
finalConfidence=round((finalSupportSet.get(mainKey)/float(finalSupportSet.g
et(subKey)))*100,1) #Gets the data directly from Final frequent dataset
item to calculate the values
finalSupport=round((finalSupportSet.get(mainKey)/float(transactionNumber))*
100,1)
finalList=[]
finalList.append(finalSupport)
finalList.append(finalConfidence)
#Creating final list of support and confidence values.
finalResult[finalKey]=finalList

def findConfindence(finalSupportSet,confidence): # Function to
create confidence sets and identify the confidence values.
finalConfidenceList=dict()
finalSupportList=dict()
for mainKey, mainValue in finalSupportSet.iteritems(): #Iterating
finalSupportItemSet dictionary to identify the confidence.
if not isinstance(mainKey, str):
for subKey,subValue in finalSupportSet.iteritems():
#Iterating finalSupportItemSet dictionary to search for subset values to
identify the confidence,
if isinstance(subKey,str): # To
check identify whether current item is a string or a list 'ORANGE' is a
string , [[ORANGE,APPLE]] is a list.
key=[]
key.append(subKey)
subKey=key
if(set(subKey).issubset(set(mainKey))):
calculateConfidence(finalSupportSet,confidence,mainKey,subKey[0])
else:
if(set(subKey).issubset(set(mainKey)) and subKey !=
mainKey): # Identifies the subset values for lists, and identifies
confidence set.
calculateConfidence(finalSupportSet,confidence,mainKey,subKey) # Calling
function to calculate confidence.

if __name__ == '__main__':
support = input("Enter % Support\n") #Enter Support Percentage
(eg:20)
confidence=input("Enter % Confidence\n") #Enter Confidence % (eg : 50)
data,transactionNumber=loadFile() # Call function to Load
file
flatListData=formatData(data) # call function to
format Data
supportValue=findSupportValue(flatListData) #Call function identify
the SUPPORT for initial set of data.
itemSet1,removelist1,currentItemSet,currentRemoveList=findSupportItem(suppo
rtValue,support,transactionNumber) #Returning results of current Item
set.
print "\nFREQUENT 1-ITEM SET "
print "``````````````````````"

print str(currentItemSet)+"\n"

x=2
while True:
#Loops until the current frequent items is Zero or Null
currentItemSet=flatList(currentItemSet)
combinationList=combinationListValue(currentItemSet,x)
# Find combination list of item.
supportOccurances=[]
supportOccurances=findSupportOccurances(combinationList,data,supportOccuran
ces) # find the number of occurrences of support
datasets.
counts=findSupportValue(supportOccurances)
finalSupportSet,removelist1,currentItemSet,currentRemoveList=findSupportIte
m(counts,support,transactionNumber) # Returns value of final data set and
current data set.
print "FREQUENT "+str(x)+"-ITEM SET "
print "``````````````````````````"
print str(currentItemSet)+"\n"
if (len(currentItemSet)<=1):
#If currentItemSet has no data or just one data it will exit the loop.
break
x=x+1
print "\nFREQUENT ITEM SETS"
print "````````````````````"
print str(finalSupportSet)+"\n"
findConfindence(finalSupportSet,confidence)
with open('output.csv', 'w+') as csvfile: #
Export the results in the csv file.
fieldnames = ['ASSOCIATION RULE', 'SUPPORT','CONFIDENCE'] #
Creating title of the csv file.
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
print "\n ASSOCIATION RULE "
print "``````````````````````"

for key,value in finalResult.iteritems():
# Writes finalItemSet results to csv file.
chars_to_remove = ['[', ']', "'"]
print key.translate(None, ''.join(chars_to_remove)) + ' : ' +
str(value)
writer.writerow({'ASSOCIATION RULE': key.translate(None,
''.join(chars_to_remove)), 'SUPPORT': value[0],'CONFIDENCE': value[1]}) #
Writes data to csv file
Exemple #3
0
iter(object[, sentinel])
Python len()  : Returns Length of an Object.
Syntax:
len(s)
Python max() : returns largest element.
Syntax:
max(iterable, *iterables[,key, default])
max(arg1, arg2, *args[, key])
Python min() : returns smallest element.
Syntax:
min(iterable, *iterables[,key, default])
min(arg1, arg2, *args[, key])
Python map() :  Applies Function and Returns a List.
Syntax:
map(function, iterable, ...)
Python set() : returns a Python set.
Syntax:
set([iterable])
Python sorted() : returns sorted list from a given iterable.
Syntax:
sorted(iterable[, key][, reverse])
Python sum() : Add items of an Iterable.
Syntax:
sum(iterable, start)
Python zip() : Returns an Iterator of Tuples.
Syntax:

zip(*iterables)
EXAMPLE PROGRAM
x={"Mon","Tue","Wed","Thu","Fri","Sat","Sun"}
y={"Jan","Feb","Mar","Wed"}
Exemple #4
0
#create a set

set1={'khadak','ram','surakshya','amar','khadak'}
print(set1)


print('You can also create a set from a list as follows:')



#convert list to 

album_list = ["Michael jackson", "Thriller", 1986, "00:42:19",\
				"Pop, Rock, R&B", 46.0, 65, "30-Nov-82", None, 10.0]
album_set = set(album_list)
print(album_set)


print('Now let us create a set of genres:')
#Convert list to set

music_genres = set(["pop","pop","rock", "folk rock", "hard rock", "soul",\
				"Progressive rock", "soft rock", "R&B", "disco"])
print(music_genres)


#Set Operations
print('Let us go over set operations, as these can be used to change \nthe set. Consider the set A:')
#Sample set
Exemple #5
0
SET: 
A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.

Creating Python Sets
A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or by using the built-in set() function.
It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements.
# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
Output
{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}
Try the following examples as well.
# set cannot have duplicates
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)

# we can make set from a list
# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)

# set cannot have mutable items
Exemple #6
0
   The order of selection does not matter.  The numbers in each ticket is not guaranteed to be sorted in any way.

----------------------------------------------------------------------------------------------------------------------------------------
# 2 12 16 29 54 6
GRAND_PRIZE = "$242,000,000"
WHITE = [2, 12, 16, 29, 54]
RED = 6

z = []
while True:
    totalBalls = input("Enter 6 ball numbers:").split()
    for i in totalBalls:
        z.append(int(i))
    w = z[:-1]
    r = z[5]
    dupeCheck = len(w) == len(set(w))
    c = 0
    for x in w:
        if int(x) >= 1 and int(x) <= 69:
            c+= 1
    p = len(w) == c
    s = r >= 1 and r <= 26
    a_set = set(w)
    b_set = set(WHITE)

    q = len(a_set.intersection(b_set))
    matchRed = int(RED == r)
    if (len(totalBalls) == 6 and dupeCheck and p and s):
        if(matchRed == 1 and q == 0): print("$4")
        elif (matchRed == 1 and q == 1): print("$4")
        elif (matchRed == 1 and q == 2): print("$7")
Exemple #7
0
Mathematically a set is a collection of items not in any particular order. A Python set is similar to this mathematical definition with below additional conditions.

The elements in the set cannot be duplicates.
The elements in the set are immutable(cannot be modified) but the set as a whole is mutable.
There is no index attached to any element in a python set. So they do not support any indexing or slicing operation.
Set Operations
The sets in python are typically used for mathematical operations like union, intersection, difference and complement etc. We can create a set, access it’s elements and carry out these mathematical operations as shown below.

Creating a set
A set is created by using the set() function or placing all the elements within a pair of curly braces.

 
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
Months={"Jan","Feb","Mar"}
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)
 
When the above code is executed, it produces the following result. Please note how the order of the elements has changed in the result.

 
set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])
set(['Jan', 'Mar', 'Feb'])
set([17, 21, 22])
 
Accessing Values in a Set
We cannot access individual values in a set. We can only access all the elements together as shown above. But we can also get a list of individual elements by looping through the set.

 
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
 def generatePalindromes(self, s):
     d = collections.Counter(s)
     m = tuple(k for k, v in d.iteritems() if v % 2)
     p = ''.join(k*(v/2) for k, v in d.iteritems())
     return [''.join(i + m + i[::-1]) for i in set(itertools.permutations(p))] if len(m) < 2 else []