praveenp
BAN USERPython solution: O(n)
# Code to get -->
# a. All possible subsets of a given list
# b. All possible subsets/no of subsets of a given list whose sum is equals to target number
# c. All possible subsets/no of subsets of a given list whose sum is equals to 0
# Recursive approach
def powerset(arr):
x=[]
l = len(arr)
s = ['']*len(arr)
helper(arr,s,0,x)
#print(x)
# Looping through the subsets to find target number
cnt = 0
for i in x:
if sum(i) == 0 and len(i) != 0:
cnt +=1
#print subsets that corresponds to target number
print(i)
# print no of subsets that corresponds to target number
print(cnt)
def helper(arr,s,n,x):
if n == len(arr):
temp =[]
for i in s:
if i != '':
temp.append(i)
x.append(temp)
#print(x)
else:
s[n] = ''
helper(arr,s,n+1,x)
s[n] = arr[n]
helper(arr,s,n+1,x)
powerset([-1,-2,1,2,0])
Python solution :
nums = [188930, 194123, 201345, 154243, 154243]
k = 3
for i in range(len(nums)-k+1):
i_ln,d_ln,i_cnt,d_cnt = 1,1,0,0
s = nums[i:k+i]
#Increasing order
for j in range(len(s)-1):
if s[j] < s[j+1]:
i_ln += 1
else:
i_cnt += int(((i_ln-1)*i_ln)/2)
i_ln = 1
if i_ln > 1:
i_cnt += ((i_ln-1)*i_ln)/2
#Decreasing order
for j in range(len(s)-1):
if s[j] > s[j+1]:
d_ln += 1
else:
d_cnt += int(((d_ln-1)*d_ln)/2)
d_ln = 1
if d_ln > 1:
d_cnt += ((d_ln-1)*d_ln)/2
print(int(i_cnt),int(d_cnt),int(i_cnt-d_cnt))
Python solution : O(n)
A = [0, 2, 6, 7, 10, 3 , 1 , 4 , 11 , 8 , 1]
# new list B to get max index value of A[i] + 1th item
B = list(reversed(A))
# list of tuples to hold index values (i,j)
l = []
for i in A:
if (i+1) in A and A.index(i+1) > A.index(i):
l.append((A.index(i), (len(A)-B.index(i+1)-1)))
print((i,i+1), l[len(l)-1])
print(l)
Python Solution:
- praveenp November 10, 2017