Function to sum and compare two sides of an array - python

For example this is array = [1,2,3,4,3,2,1]
i want computer to choose i=4 and sum both left of the four and right of the four and then compare if they are equal to each other, program prints i value to the screen.
Now i write it in here and it works as long as the i value is 0 but if i want to make this search for i>0 then i gets complicated.
this is my main program:
# importing "array" for array creations
import array as arr
# Function to find sum
# of array exlcuding the
# range which has [a, b]
def sumexcludingrange(li, a, b): # I FOUND THIS FUNCTION ONLINE BUT ALSO DIDN`T WORK EITHER.
sum = 0
add = True
# loop in li
for no in li:
# if no != a then add
if no != a and add == True:
sum = sum + no
# mark when a and b are found
elif no == a:
add = False
elif no == b:
add = True
# print sum
return sum
#lis = [1, 2, 4, 5, 6]
#a = 2
#b = 5
#sumexcludingrange(arr, 0, i-1)
def my(arr):
for i in range(len(arr)):
if i == 0: #this works when array is like [1,0,0,1] and i equals zero
sum_left = arr[0]
sum_right = sum(arr) - arr[0]
while sum_left == sum_right:
print(i)
break
elif i > 0 : # i 1 2 3 4 5 6 7 8 9..
#sumleft and sumright are not right.. what is the issue here?
sum_left = sumexcludingrange(arr, 0, i-1) #result is 16, sumexcludingrange function didn`t
#work.
print (sum_left)
#print(i)
sum_right == sum(arr) - sum_left
#print(sum_right)
#break
while sum_left == sum_right:
print(sum_left)
print(sum_right)
print("they are equal now")
break
else:
print("index cannot be a negative number.")
something = arr.array('i', [1,2,3,4,3,2,1]) # len(arr) = 7
my(something)
After seeing that i need another function to compare two sides of the array, i created a new file and write it in here and somehow it outputs this:
1
13
13
2
10
10
#array[i] array[i+1] .. + array[length-1]
array = [1,2,3,4,5,6,7] # 7 element so length=7,
for i in range(len(array)):
if i > 0 :
ln = len(array) + 1
sum_right = sum(array[i+1:ln])
sum_left = sum(array) - sum_right
print(i)
print(sum_right)
print(sum_right)
the way i think is this:
# array[i] i>0 i={1,2,3,4..}
sum_total = sum(arr) = array[0] + ..+ array[i-1] + array[i] + array[i+1] + ... + array[length-1]
sum_right = array[i+1] + .. + array[length-1]
sum_left = sum_total - sum_right
Is there a better way to accomplish that?

If I understand your question correctly, the solution could be something like this:
array = [1,2,3,4,5,6,7]
a1 = array[:4] # first 4 numbers
a2 = array[-4:] # last 4 numbers
total = sum(array)
diff = total-sum(a2)

Related

Find middle index of a matrix inside a matrix python

i'm trying to find the start and stop of a matrix inside a matrix
For example theres a matrix of W and B, B is a square inside the whole matrix:
5 6
WWBBBW
WWBBBW
WWBBBW
WWWWWW
WWWWWW
i want to get the middle of:
BBB
BBB
BBB
which should output me:
2 4
because the matrix is in another matrix
My idea was to take the square and make the middle B1
then index it inside of the whole matrix.
I've tried the code as following which i made.
def middle(m):
# for getting the middle of BlackPart
n = len(m)//2
n1 = len(m[n])//2
m[n][n1] = "B1"
return m
def find(matrix, list1):
# for getting B list
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == "B":
list1.append("B")
return list1
def q2():
# for getting matrix
nope = input("").split(" ")
counter1 = 0
m = []
while counter1 < int(nope[0]):
a = input("")
m.append(list(a))
counter1 += 1
# for getting matrix
# below is for getting a square matrix
l = []
find(m, l)
n = int(len(l) ** (1 / 2))
counter = 0
for i in range(len(l) // 3):
l += [l[counter * n: counter * n + n]]
counter += 1
middle(m)
q2()
But it was too complicated and confused me, then i ended up noting it as a failure.
Please tell me if there is an easier way to do this.
Thanks
There you go, I figured it out:
matrix = """WWBBBW
WWBBBW
WWBBBW
WWWWWW
WWWWWW"""
bstart = 0
bend = 0
bfound = False
bposition_x = 0
bposition_y = 0
bstartline = 0
bfoundinlines = []
matrix = matrix.split("\n")
for linenum, line in enumerate(matrix):
bfound = False
for index, x in enumerate(line):
if x == "B" and bfound == False:
bstart = index
bfound = True
bfoundinlines.append(linenum)
elif x == "W" and bfound == True:
bend = index - 1
bstartline += 1
bposition_x = int((bstart + bend)/2 + 1)
bposition_y = int(round(len(bfoundinlines)/2)) # 1 already added (counting from 1)
if len(bfoundinlines) == 1: bposition_y = 2 #python rounds 0.5 to 0
print("from top:",bposition_y,"from left",bposition_x)

Can someone help me replace the **for loop** to **while loop** I'm struggling to figure it out?

Can someone help me replace the for loop to while loop I'm struggling to figure it out?
The question specifically asks us not to use for loop. That's why I need to replace it with the while loop
I have listed below:
my code
Sample testing of the input and the output
the conditions we have to follow:
def matrix_equal(matrix1, matrix2):
"""
-------------------------------------------------------
Compares two matrices to see if they are equal - i.e. have the
same contents in the same locations.
Use: equal = matrix_equal(matrix1, matrix2)
-------------------------------------------------------
Parameters:
matrix1 - the first matrix (2D list of ?)
matrix2 - the second matrix (2D list of ?)
Returns:
equal - True if matrix1 and matrix2 are equal,
False otherwise (boolean)
------------------------------------------------------
"""
equal = True
if((len(matrix1) != len(matrix2)) or (len(matrix1[0]) != len(matrix2[0]))):
equal = False
for x in range(len(matrix1)):
if(equal == False):
break
for y in range(len(matrix1[0])):
num1 = matrix1[x][y]
num2 = matrix2[x][y]
if(num1 != num2):
equal = False
break
return equal
Sample testing:
First matrix:
0 1 2
0 c a t
1 d o g
2 b i g
Second matrix:
0 1 2
0 c a t
1 d o g
2 b i g
Equal matrices: True
The conditions we have to follow:
1. should not call input in the function
2. should not call print in the function
3. should not have multiple returns
This should solve your problem, this is a solution using while loop :
def matrix_equal(mat1,mat2):
equal = True
if(len(mat1[0]) == len(mat2[0]) and len(mat1) == len(mat2)):
i = 0
n = len(mat1[0])
m = len(mat1)
while(i < m):
j = 0
while(j < n):
if(mat1[i][j] != mat2[i][j]):
equal = False
break
j+=1
if(equal==False):
break
i+=1
else:
equal = False
return equal
Change
for x in range(len(matrix1)):
to
x = 0
while x < len(matrix1):
x += 1
Cheers!
You can transform :
for i in range(mat.shape[0]):
{do stuff...}
into
i = 0
while i < mat.shape[0]:
{do stuff...}
# increment i with 1
i += 1
so here you would get :
def mat_eq_while(matrix1, matrix2):
i = 0
j = 0
equal = True
if(not (mat1.shape == mat2.shape) ):
equal = False
while i < mat1.shape[0]:
if(equal == False):
break
while j < mat1.shape[1]:
num1 = matrix1[i, j]
num2 = matrix2[i, j]
if(num1 != num2):
equal = False
break
j += 1
i += 1
return equal
test it with
import numpy as np
mat1 = np.matrix(range(9)).reshape(3,3)
mat2 = np.matrix(range(1, 10)).reshape(3,3)
print( mat_eq_while(mat1, mat1) )
print( mat_eq_while(mat1, mat2) )

Max Sub Array (non-adjacent)

I'm working on a HackerRank Max Array Sum problem. I see some simple and smart solutions but I wanna know why my code failing.
Here is my code. It takes next 4 elements from array and choose index0 or index1 and shift 2 or 3 elements.
if I can find max subset elements instead of sum of elements I can see my mistake.
HackerRank Problem Link
def Calc(arr):
result = 0
i = 0
while i < len(arr):
tempar = [i if i > 0 else 0 for i in arr[i:i+4]]
if len(tempar) == 4:
tmax = max(tempar[0] + tempar[2], tempar[0] + tempar[3], tempar[1] + tempar[3])
if tempar[0] + tempar[2] == tmax or tempar[0] + tempar[3] == tmax:
result += tempar[0]
i += 2
elif tempar[1] + tempar[3] == tmax:
result += tempar[1]
i+=3
if len(tempar) == 3:
if tempar[0] + tempar[2] > tempar[1]:
result += tempar[0] + tempar[2]
else:
result += tempar[1]
i+=3
if len(tempar) == 2:
result += max(tempar)
i+=2
if len(tempar) == 1:
result += tempar[0]
i+=1
return result
input()
ar = list(map(int, input().split()))
print(Calc(ar))
I didn't read your algorithm and the problem carefully, so I can't say whether your algorithm is right or not.
But it seems that your code allows choosing an empty set when all elements are negative. (tempar = [i if i > 0 else 0 for i in arr[i:i+4]])
For example, your program will output 0 for the input
5
-1 -1 -1 -1 -1
Your algorithm doesn't work.
for simple input
5
-1 -1 3 -2 5
I suggest you use the following approach:
def Calc(arr):
result = 0
prev_result=0
is_last_included=False
i = 0
while i < len(arr):
if arr[i] > 0:
if is_last_included==False:
prev_result=result
result=result+arr[i]
is_last_included=True
elif (prev_result+arr[i])>result:
temp=result
result=prev_result+arr[i]
prev_result=temp
is_last_included=True
else:
prev_result=result
is_last_included=False
i=i+1
return result

Python List Index Error

Here is my version of the code right now and I keep getting list index error.
n = 0
y = len(list1)-1
while n < y:
for k in list1:
if list1[n]+ k == g:
print("The 2 prime numbers that add up to ",g,"are ", list1[n]," and ",k,".")
break
else:
n = n+1
You are incrementing n in the for loop but testing its contraint in the outer while loop.
Perhaps this is what you wanted:
n = 0
y = len(list1)-1
found = 0
while n < y:
for k in list1:
if list1[n]+ k == g:
print("The 2 prime numbers that add up to ",g,"are ", list1[n]," and ",k,".")
found = 1
break # for loop
if found:
break # while loop
n = n + 1
A much better way to do it is using itertools.combinations_with_replacement:
import itertools
for (v1,v2) in itertools.combinations_with_replacement(list1, 2):
if v1 + v2 == g:
print("blah blah blah")
break
combinations_with_replacement(list1,2) will return all the unordered combinations of two elements of list1. For instance, combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
You left a few bits of information out, but I gather that you are trying to find 2 primes that match a target. In order to access a list in this manner, you need to enumerate it.
y = len(list1) - 1
while n < y:
for n, k in enumerate(list1):
if list1[n]+ k == g :
print("The 2 prime numbers that add up to ",g,"are ", list1[n]," and ",k,".")
break
However, you don't really need the index, two for loops would accomplish the same thing.
target = 8
primes = [2, 3, 5, 7, 11, 13, 17, 19]
message = 'The 2 prime numbers that add up to {target} are {value1} and {value2}'
for index1, value1 in enumerate(primes):
for value2 in primes[index1 + 1:]:
if value1 + value2 == target:
print(message.format(target=target, value1=value1, value2=value2))

Collatz conjecture sequence

The Collatz conjecture
what i am trying to do:
Write a function called collatz_sequence that takes a starting integer and returns the sequence of integers, including the starting point, for that number. Return the sequence in the form of a list. Create your function so that if the user inputs any integer less than 1, it returns the empty list [].
background on collatz conjecture:
Take any natural number n. If n is even, divide it by 2 to get n / 2, if n is odd multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process indefinitely. The conjecture is that no matter what number you start with, you will always eventually reach 1.
What I have so far:
def collatz_sequence(x):
seq = [x]
if x < 1:
return []
while x > 1:
if x % 2 == 0:
x= x/2
else:
x= 3*x+1
return seq
When I run this with a number less than 1 i get the empty set which is right. But when i run it with a number above 1 I only get that number i.e. collatz_sequence(6) returns [6]. I need this to return the whole sequence of numbers so 6 should return 6,3,10,5,16,8,4,2,1 in a list.
You forgot to append the x values to the seq list:
def collatz_sequence(x):
seq = [x]
if x < 1:
return []
while x > 1:
if x % 2 == 0:
x = x / 2
else:
x = 3 * x + 1
seq.append(x) # Added line
return seq
Verification:
~/tmp$ python collatz.py
[6, 3, 10, 5, 16, 8, 4, 2, 1]
def collatz_sequence(x):
seq = [x]
while seq[-1] > 1:
if x % 2 == 0:
seq.append(x/2)
else:
seq.append(3*x+1)
x = seq[-1]
return seq
Here's some code that produces what you're looking for. The check for 1 is built into while statement, and it iteratively appends to the list seq.
>>> collatz_sequence(6)
[6, 3, 10, 5, 16, 8, 4, 2, 1]
Note, this is going to be very slow for large lists of numbers. A cache won't solve the speed issue, and you won't be able to use this in a brute-force solution of the project euler problem, it will take forever (as it does every calculation, every single iteration.)
Here's another way of doing it:
while True:
x=int(input('ENTER NO.:'))
print ('----------------')
while x>0:
if x%2==0:
x = x/2
elif x>1:
x = 3*x + 1
else:
break
print (x)
This will ask the user for a number again and again to be put in it until he quits
def collatz(x):
while x !=1:
print(int(x))
if x%2 == 0:
x = x/2
else:
x = 3*x+1
this is what i propose..
seq = []
x = (int(input("Add number:")))
if (x != 1):
print ("Number can't be 1")
while x > 1:
if x % 2 == 0:
x=x/2
else:
x = 3 * x + 1
seq.append (x)
print seq
This gives all the steps of a single number. It has worked with a 50-digit number in 0,3 second.
collatz = []
def collatz_sequence(x):
while x != 1:
if x % 2 == 0:
x /= 2
else:
x = (3*x + 1)/2
collatz.append(int(x))
print(collatz)
collatz_sequence()
Recursion:
def collatz(n):
if n == 1: return [n]
elif n % 2 == 0: return [n] + collatz(int(n/2))
else: return [n] + collatz(n*3+1)
print(collatz(27))
steps=0
c0 = int(input("enter the value of c0="))
while c0>1:
if c0 % 2 ==0 :
c0 = c0/2
print(int(c0))
steps +=1
else:
c0 = (3 * c0) + 1
print(int(c0))
steps +=1
print("steps= ", steps)
import numpy as np
from matplotlib.pyplot import step, xlim, ylim, show
def collatz_sequence(N):
seq = [N]
m = 0
maxN = 0
while seq[-1] > 1:
if N % 2 == 0:
k = N//2
seq.append(N//2)
if k > maxN:
maxN = k
else:
k = 3*N+1
seq.append(3*N+1)
if k > maxN:
maxN = k
N = seq[-1]
m = m + 1
print(seq)
x = np.arange(0, m+1)
y = np.array(seq)
xlim(0, m+1)
ylim(0, maxN*1.1)
step(x, y)
show()
def collatz_exec():
print('Enter an Integer')
N = int(input())
collatz_sequence(N)
This is how you can use it:
>>> from collatz_sequence import *
>>> collatz_exec()
Enter an Integer
21
[21, 64, 32, 16, 8, 4, 2, 1]
And a plot that shows the sequence:
seq = []
def collatz_sequence(x):
global seq
seq.append(x)
if x == 1:
return
if (x % 2) == 0:
collatz_sequence(x / 2)
else:
collatz_sequence((x * 3) + 1)
collatz_sequence(217)
print seq
def collataz(number):
while number > 1:
if number % 2 == 0 :
number = number //2
print(number)
elif number % 2 ==1 :
number = 3 * number + 1
print(number)
if number == 1 :
break
print('enter any number...!')
number=int(input())
collataz(number)

Categories