How to call a function to process list - python

i have created a function to find the column sums of a hard coded 2d lists so im trying to have it print out only the values of the hard coded column sums. I basically added column indexes and added their sums to an emptylist. then i returned that empty list. when i try to print the values of the empty list i get an error, any help?
#Function that returns column sums for list1
def columnsumsfunction(a) :
rowsize = len(list1)
columnsize = len(list1[0])
csum =[]
c = 0
while c < columnsize :
totalsum = 0
r = 0
while r < rowsize :
mysum = list1[r][c]
totalsum = totalsum + mysum
r = r + 1
c = c + 1
csum.append(totalsum)
return csum
for a in list1 :
csum = columnsumsfunction(a)
print csum
#main
list1 = [[1, 2, 3],
[4, 5, 6] ]
Im just not really sure on how to call on the function to process list1. li
im just trying to call on the function to print
5 7 9

The code in your question is a little out of order, but if you fix that and change all the instances of list to a within the function you'll be set:
#Function that returns column sums for list1
def columnsumsfunction(a) :
rowsize = len(a)
columnsize = len(a[0])
csum =[]
c = 0
while c < columnsize :
totalsum = 0
r = 0
while r < rowsize :
mysum = a[r][c]
totalsum = totalsum + mysum
r = r + 1
c = c + 1
csum.append(totalsum)
return csum
list1 = [[1, 2, 3],
[4, 5, 6] ]
csum = columnsumsfunction(list1)
print csum

def columnsumsfunction():
index = 0
rowsize = len(list1)
columnsize = len(list1[0])
csum =[]
c = 0
while c < columnsize :
totalsum = 0
r = 0
while r < rowsize :
mysum = list1[r][c]
totalsum = totalsum + mysum
r = r + 1
c = c + 1
csum.append(totalsum)
return csum
#main
list1 = [[1, 2, 3],
[4, 5, 6] ]
csum = columnsumsfunction()
print csum
If you are trying to print 5 7 9 this code works fine.
You don't need list2 at all. Call the columnsfunction() after list1 has been defined.
The for loop is also not required.

Related

How to find sum of product of min value and length of sub list

I have a list of n numbers. I want to divide the list into sub lists, such as the sub list consists of continuous increasing numbers or continuous decreasing numbers. Then take the product of each sub list's min value and it's length. Finally take the sum of all this product's
Input:
l = [1,2,6,4,2,3,1,8,9,7]
Output:
32
Details:
[1,2,6],[6,4,2],[2,3],[3,1],[1,8,9],[9,7]
(1*3) +(2*3) + (2*2)+(1*2)+(1*3)+ (7*2) = 32
Code so far:
n = 10
l = [1,2,6,4,2,3,1,8,9,7]
tot = 0
count = 0
inc=dec=False
min_val = 1001 # max value in list won't exceed 1000
for idx, e in enumerate(l):
if idx+1<=n:
if e > l[idx+1]:
count+=1
if min_val > l[idx+1]:
min_val=l[idx+1]
inc=True
dec=False
elif e < l[idx+1]:
count+=1
if min_val > e:
min_val=e
dec=True
# if not inc
inc=False
*Note: No Two adjacent value will be equal in the list.
Update-1:
itemp = [1001]
dtemp = [1001]
result=0
for e in l:
# if not itemp or not dtemp:
# itemp.append(e)
# dtemp.append(e)
if e > itemp[-1]:
if not dtemp:
itemp.append(e)
else:
result+=(min(dtemp)*(len(dtemp)-1))
dtemp=[1001]
itemp.append(e)
elif e < dtemp[-1]:
dtemp.append(e)
if not itemp:
dtemp.append(e)
else:
result+=(min(itemp)*(len(itemp)-1))
itemp=[1001]
dtemp.append(e)
print(result)
This results 0 as output. Can some one help?
l = [1,2,6,4,2,3,1,8,9,7]
local_max= [i for i in range(1, len(l)-1) if l[i-1]<l[i]>l[i+1]]
local_min= [i for i in range(1, len(l)-1) if l[i-1]>l[i]<l[i+1]]
idx= sorted(local_max+local_min +[0,len(l)-1])
idx_pairs = zip(idx[:-1],idx[1:])
sum(min(l[i_1],l[i_2])*(i_2+1-i_1) for i_1,i_2 in idx_pairs)
You could identify the breaking positions (peaks and bottoms) using zip to detect changes of increasing/decreasing values between each sequence of 3 elements. Then use these breaks to form the sub-lists and apply the calculation in a comprehension.
L = [1,2,6,4,2,3,1,8,9,7]
breaks = [i+1 for i,(a,b,c) in enumerate(zip(L,L[1:],L[2:])) if (a<b)==(b>c)]
subL = [ L[s:e+1] for s,e in zip([0]+breaks,breaks+[len(L)]) ]
result = sum(min(s)*len(s) for s in subL)
print(breaks) # [2, 4, 5, 6, 8] indices of peaks and bottoms
# [1,2,6,4,2,3,1,8,9,7]
# ^ ^ ^ ^ ^
# 0 1 2 3 4 5 6 7 8 9
print(subL) # [ [1, 2, 6], [6, 4, 2], [2, 3], [3, 1], [1, 8, 9], [9, 7]]
# 0..2+1 2..4+1 4..5+1 5..6+1 6..8+1 8..len(L)
# | | | | | | | | | | | |
# [0] | + [2, | 4, | 5, | 6, | 8] |
# [2, 4, 5, 6, 8] + [len(L)]
print(result) # 32
tot = start = m = n = 0
direc = -1
for n, x in enumerate(lis):
if n == 0:
m = x
else:
old = lis[n - 1]
if (x > old and direc == 0) or (x < old and direc == 1):
tot += m * (n - start)
start = n - 1
m = min(old, x)
direc ^= 1
else:
direc = 1 if x > old else 0
m = min(m, x)
ln = n - start + 1
if ln > 1:
tot += m * ln

Python: I cannot get the right Merge Sort

I wrote the following programming; after running it, the result is not correct.
So what is wrong with my code?
def mergesort(list1):
if len(list1) > 1:
mid = len(list1) // 2
left_list = list1[:mid]
right_list = list1[mid:]
mergesort(left_list)
mergesort(right_list)
i = 0 # left
j = 0 # right
k = 0 # total
while len(list1) > 1 and i < len(left_list) and j < len(right_list):
if left_list[i] < right_list[j]:
list1[k] = left_list[i]
k += 1
i +=1
else:
list1[k] = right_list[i]
k += 1
j += 1
if len(list1) > 1 and i < len(left_list):
list1[k] = left_list[i]
i += 1
k += 1
if len(list1) > 1 and j < len(right_list):
list1[k] = right_list[j]
k += 1
j += 1
return list1
ex = [3, 5, 9, 0, 8, 7]
mergesort(ex)
result: [0, 3, 5, 7, 7, 9]
I found three problems
you didn't get result from mergesort(left_list) mergesort(right_list) (but this could even work because it replaces values in original list)
you used i instead of j in one place
you used if istead of while in two places
def mergesort(list1):
if len(list1) > 1:
mid = len(list1) // 2
left_list = list1[:mid]
right_list = list1[mid:]
left_list = mergesort(left_list) # 1. get result
right_list = mergesort(right_list) # 1. get result
i = 0 # left
j = 0 # right
k = 0 # total
while len(list1) > 1 and i < len(left_list) and j < len(right_list):
if left_list[i] < right_list[j]:
list1[k] = left_list[i]
k += 1
i +=1
else:
list1[k] = right_list[j] # 2. use `j` instead of `i`
k += 1
j += 1
while len(list1) > 1 and i < len(left_list): # 3. use `while`
list1[k] = left_list[i]
i += 1
k += 1
while len(list1) > 1 and j < len(right_list): # 3. use `while`
list1[k] = right_list[j]
k += 1
j += 1
return list1
ex = [3, 5, 9, 0, 8, 7]
print(mergesort(ex))
There are 3 distinct steps in merge sort: the base case, the recursive step, and the merge step. The merge step is often written as a separate function, but here I have incorporated it into the merge_sort function to stay consistent with your code. Your biggest problem was that you did not take you recursively-sorted sub-lists and merge them.
def mergesort(list1):
#base case
if len(list1) <= 1:
return list1
#recursive step
mid = len(list1) // 2
left_list = list1[:mid]
right_list = list1[mid:]
sorted_left = mergesort(left_list)
sorted_right = mergesort(right_list)
#merge step
result = []
while len(sorted_left) > 0 and len(sorted_right) > 0:
if sorted_left[0] <= sorted_right[0]:
result.append(sorted_left.pop(0))
elif sorted_right[0] <= sorted_left[0]:
result.append(sorted_right.pop(0))
else:
result.append(sorted_left.pop(0))
result.append(sorted_right.pop(0))
result = result + sorted_left + sorted_right
return result
print(mergesort([3,5,1,9,7])) #output: [1, 3, 5, 7, 9]

I kept getting "ModuleNotFoundError: No module named 'error'"

I was given an outline of this code from my teacher, however I kept getting ModuleNotFoundError: No module named 'error'. I know that I need a module named error, however when I couldn't find a code for a module named error.
I am trying to solve this question:
Solve the tridiagonal equations Ax = b by Doolittle’s decomposition method, where:
A = [6 2 0 0 0
−1 7 2 0 0
0 −2 8 2 0
0 0 3 7 −2
0 0 0 3 5]
b = [2
−3
4
−3
1].
Here is the code that I was using:
from numpy import argmax, dot, zeros, array, asarray, tril, triu
def swapRows(v,i,j):
if len(v.shape) == 1: v[i],v[j] = v[j],v[i]
else:
temp = v[i].copy()
v[i] = v[j]
v[j] = temp
def swapCols(v,i,j):
temp = v[:,j].copy()
v[:,j] = v[:,i]
v[:,i] = temp
import error
def LUdecomp(a,tol=1.0e-9):
n = len(a)
seq = array(range(n))
# Set up scale factors
s = zeros(n)
for i in range(n):
s[i] = max(abs(a[i,:]))
for k in range(0,n-1):
# Row interchange, if needed
p = argmax(abs(a[k:n,k])/s[k:n]) + k
if abs(a[p,k]) < tol: error.err('Matrix is singular')
if p != k:
swapRows(s,k,p)
swapRows(a,k,p)
swapRows(seq,k,p)
# Elimination
for i in range(k+1,n):
if a[i,k] != 0.0:
lam = a[i,k]/a[k,k]
a[i,k+1:n] = a[i,k+1:n] - lam*a[k,k+1:n]
a[i,k] = lam
return a,seq
def LUsolve(a,b,seq):
n = len(a)
# Rearrange constant vector; store it in [x]
x = b.copy()
for i in range(n):
x[i] = b[seq[i]]
# Solution
for k in range(1,n):
x[k] = x[k] - dot(a[k,0:k],x[0:k])
x[n-1] = x[n-1]/a[n-1,n-1]
for k in range(n-2,-1,-1):
x[k] = (x[k] - dot(a[k,k+1:n],x[k+1:n]))/a[k,k]
return x
A = asarray( [ [ 6, 2, 0, 0, 0 ],
[ -1, 7, 2, 0, 0 ],
[ 0, -2, 8, 2, 0 ],
[ 0, 0, 3, 7, -2 ],
[ 0, 0, 0, 3, 5 ] ], dtype=float ) A_orig = A.copy() b = asarray( [ 2, -3, 4, -3, 1 ], dtype=float ) b_orig = b.copy()
A,seq = LUdecomp(A) # A is overwritten as L\U L = tril( A, -1 ) # extract L for ii in range(L.shape[0]): L[ii,ii] = 1.0 # add in 1's on the diagonal U = triu( A, 0 ) # extract U print ("L = ") print (L) print ("U = ") print (U) if False:
print ("A[seq,:]= ")
print (A_orig[seq,:])
print ("LU= ")
print (dot(L,U))
x = LUsolve(A,b,seq) print ("Solution= ", x)
If your intention is to throw an error at some point, then you can reach that without the import error statement. Raising an exception might be a solution.
See the documentation on errors and exceptions.
You can remove import error and edit
if abs(a[p,k]) < tol: error.err('Matrix is singular')
in LUdecomp() as follows:
if abs(a[p,k]) < tol:
raise Exception('Matrix is singular')

Python List IndexError: list index out of range

I try to search in an list the maximal frequency of an element.
Now I have the problem that the last checked element of the list (a[i+1]) I get an IndexError. How can I solve this problem?
With len(a)-1 the last element a[i+1] is never used thus the result of maxMode(a4) is wrong.
a1 = [5,3,6,7,2,7,3,6,2,8,7]
a2 = [5,3,6,7,2,7,3,6,2,8,7,5,2]
a3 = [5,3,6,7,2,7,3,6,2,8,2,5,2]
a4 = [5,3,6,7,2,7,3,6,2,7,2,5,1]
def maxMode(a):
cnt = 1
maxCnt = 0
res = 0
for i in range(len(a)-1):
if a[i] == a[i+1]:
cnt += 1
else:
if cnt >= maxCnt:
maxCnt = cnt
res = a[i]
cnt = 1
return res
a1.sort()
a2.sort()
a3.sort()
a4.sort()
print(a1)
print(maxMode(a1))
print(a2)
print(maxMode(a2))
print(a3)
print(maxMode(a3))
print(a4)
print(maxMode(a4))
As BluCode points out, your code runs fine for the 4 test cases you provide (or at least, it doesn't crash and returns a mode although as you point out, for the 4th test, it's not the max mode). Also, as you alluded to, you're not counting your last element (or really, you're not checking if the last batch could be the maximal), and so if a4 was instead: [1, 2, 2, 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7], it wrongly prints out 2 (because it finds 3 2's and 3 7's and doesn't do a final check for the 7s being as good or better)
The following worked with my 4 updated test cases:
a1 = [5,3,6,7,2,7,3,6,2,8,7]
a2 = [5,3,6,7,2,7,3,6,2,8,7,5,2]
a3 = [5,3,6,7,2,7,3,6,2,8,2,5,2]
a4 = [5,3,6,7,2,7,3,6,2,7,2,5,1,7]
def maxMode(a):
cnt = 1
maxCnt = 0
res = 0
for i in range(len(a)-1):
if a[i] == a[i+1]:
cnt += 1
else:
if cnt >= maxCnt:
maxCnt = cnt
res = a[i]
cnt = 1
if cnt >= maxCnt:
maxCnt = cnt
res = a[i]
return res
a1.sort()
a2.sort()
a3.sort()
a4.sort()
print(a1)
print(maxMode(a1))
print(a2)
print(maxMode(a2))
print(a3)
print(maxMode(a3))
print(a4)
print(maxMode(a4))

Quicksort implement in Python run with none stop

This is my quicksort algorithms. Very simple
x = 0
def swap(list, a, b):
temp = list[a]
list[a] = list[b]
list[b] = temp
return list
def quicksort2(list, left, right):
if right > left:
global x
x = x + 1
print x , list, left, right
l = left+1
r = right
while l <= r :
while list[l] < list[left]:
l = l + 1
while list[r] > list[left]:
r = r - 1
if l < r:
list = swap(list, l, r)
list = swap(list, left, r)
list = quicksort2(list, left, r-1);
return quicksort2(list, r+1, right);
return list
But when i run my testcase
b = list([1, 2, 2, 3, 4, 5, 6, 12, 6, 32])
quicksort2(b, 0, len(b)-1)
the result is
1 [1, 2, 2, 3, 4, 5, 6, 12, 6, 32] 0 9
2 [1, 2, 2, 3, 4, 5, 6, 12, 6, 32] 1 9
and stop at this...
Anybody have any reason ...
Have you tried to trace the program execution under a debugger...?
The while l <= r loop runs forever, because after several decrements of r
left == 1
l == 2
r == 2
and
l is not incremented, because list[2] is not less than list[1]
r is not decremented any longer, because list[2] is not greater than list[1]
no swap is done, because l is not less than r
and loop will continue, because l is still equal to r.......
I simply modified your code a bit.. Found several mistakes, some already mentioned by others. The rest I am not going to go through.
However, you do not have to return a modified list, as lists in python are always passed by reference.
This should be working:
def quicksort2(list, low, high):
global x
x = x + 1
print x , list, low, high
l = low
r = high
mid = list[(r + l) / 2]
while l <= r:
while list[l] < mid: l += 1
while list[r] > mid: r -= 1
if l <= r:
list[l], list[r] = list[r], list[l] #swap(r,l)
l += 1
r -= 1
if r > low: quicksort2(list, low, r);
if l < high: quicksort2(list, l, high);
if __name__ == '__main__':
x = 0
b = [1, 2, 2, 3, 4, 5, 6, 12, 6, 32]
quicksort2(b, 0, len(b)-1)
print b

Categories

Resources