Function returning incomplete value - python

def sum_2_array(list1):
item = 10
numlist = list()
for i in list1:
num = list1.pop()
diff = item-num
if diff in list1:
return num, diff
print sum_2_array([2,3,5,8,7])
This function computes the minimum absolute diff between the elements of an array.The error is that it is returning just one value .
Can anayone please check and tell me where I am going wrong

Please run below code & see if it works. I have Used simple logic
def sum_2_array(list1):
item = 10
j = 0
for i in list1:
print "this is value of J = ", j
num = list1[j]
print "this is value of num = ", num
diff = item - num
print "this is vale of diff = ", diff
if diff in list1:
print num
print diff
j += 1
print sum_2_array([2, 3, 5, 8, 7])
Code you were running in that when it comes to third item in the list i.e 5. At the same time it pops out this item from the list. Because you are using list1.pop(). So it unable to find 5 in the list that's why you are getting only two values. Use code I gave & check if it works.
I got following result from that
this is value of J = 0
this is value of num = 2
this is vale of diff = 8
2
8
this is value of J = 1
this is value of num = 3
this is vale of diff = 7
3
7
this is value of J = 2
this is value of num = 5
this is vale of diff = 5
5
5
this is value of J = 3
this is value of num = 8
this is vale of diff = 2
8
2
this is value of J = 4
this is value of num = 7
this is vale of diff = 3
7
3

Related

smallest difference of a sequence of a list

I am new to python. I am working on program to find the smallest difference of sequence of element. for example I have a input A=[7,8,9],M=3. Difference of all elements of sequence should be in this form S=(|7-7|,|7-8|,|7-9|,|8-7|,|8-8|,|8-9|,|9-7|,|9-8|,|9-9|).S=[0,1,2,1,0,1,2,1,0]. we get 9 different element in list. So the output of M smallest element of s is 0. since 0 is 3 smallest element. Does anyone know what I am doing wrong
enter code here
F=[]
A = [7, 8, 9]
M = 3
S=0
for i in range(len(A)):
for j in range(len(A)):
S = S + (abs(A[i] - A[j]))
t = F.append(S)
t.sort()
for k in range(len(t)):
if k == M:
break
print(t[k])
The right code is here:
A = [7, 8, 9]
M = 3
S=[] #
for i in range(len(A)):
for j in range(len(A)):
S.append(abs(A[i] - A[j]))
# t = F.append(S) # t is not defined before
S.sort()
print(S[M-1]) # S is sorted
Ask me if you have any questions.
Here, you can try this:
x=[7,8,9]
y=[abs(j-k) for j in x for k in x]
print(y)
What you are doing is basically a nested loop.
Here is how it goes:
for i in x:
for j in x:
#==== This is what your program needs =====
i=7
|__j=7
|__j=8
|__j=9
i=8
|__j=7
|__j=8
|__j=9
i=9
|__j=7
|__j=8
|__j=9
Now if you print the how it looks like:
x=[7,8,9]
for i in x:
print(f'The main number is {i}.')
for j in x:
print(f"{i} - {j} = {abs(i-j)}")
And that does exactly what you need
The main number is 7.
7 - 7 = 0
7 - 8 = 1
7 - 9 = 2
The main number is 8.
8 - 7 = 1
8 - 8 = 0
8 - 9 = 1
The main number is 9.
9 - 7 = 2
9 - 8 = 1
9 - 9 = 0

how to print greatest sum each rows in python?

i confused how to print every greatest per rows in array 2d python. my code so far walking properly but i can't get the right result. the program wants output like:
input:
2 - for how much array need to create
2 -> for how much size array(rows default = 3)
1 2 3
4 5 6
3
0 0 0
2 3 4
5 6 7
so far i get this right on input. and output:
in array 1 is : 2(represent row) -> (4+5+6) is greatest than (1+2+3)
in array 2 is : 3 (represent row) -> (5+6+7) is greatest
only (in array 1 is : 2 (and so on depending on the number of arrays or matrices created))` which will be displayed on the screen
i confused how to implementing that.
this my code:
import sys
print("Enter the number of arrays:")
K = int(input())
array = []
for i in range(K):
print("Enter the number of rows and columns you want:")
rows = int(input())
columns = 3
matrix = []
print("Start entering the rows:")
for j in range(rows):
matrix.append(list(map(int, input().split())))
array.append(matrix)
rows2 = len(matrix)
column2 = len(matrix[0])
idx = -1
maxi = -sys.maxsize
for r in range(0, rows2):
rowtotal=0
for s in range(0, column2):
rowtotal=rowtotal+int(matrix[r][s])
if (rowtotal > maxi):
maxi = rowtotal
idx = i
where should i put print to get the output and do i have to loop again?. and what is the syntax for displaying the output?. thanks.
You do not need array outside the for loop, since you just need to evaluate row-wise in matrix.
As user inputs the row, you can already just calculate the sum of the row using sum(). If that row's sum is bigger than the previously biggest sum (or sentinel value -999999), we set it as the biggest_row_sum and remember the biggest_row_index. At the end of the building of a full matrix, we just print out biggest_row_sum and biggest_row_index.
print("Enter the number of arrays:")
K = int(input())
for i in range(K):
print("Enter the number of rows you want:")
rows = int(input())
columns = 3
matrix = []
biggest_row_sum = -999999
biggest_row_index = -1
print("Start entering the rows:")
for j in range(rows):
this_row = list(map(int, input().split()))
matrix.append(this_row)
this_row_sum = sum(this_row)
if this_row_sum > biggest_row_sum:
biggest_row_index = j
biggest_row_sum = this_row_sum
print(matrix)
print("in array " + str(i+1) + " is : " + str(biggest_row_index+1))
Output:
Enter the number of arrays:
2
Enter the number of rows you want:
2
Using default number of columns = 3
Start entering the rows:
1 2 3
4 5 6
[[1, 2, 3], [4, 5, 6]]
in array 1 is : 2
Enter the number of rows you want:
3
Using default number of columns = 3
Start entering the rows:
0 0 0
2 3 4
5 6 7
[[0, 0, 0], [2, 3, 4], [5, 6, 7]]
in array 2 is : 3
Updated with OP's comment below
To only print out at the end of user input for all matrixes, we can simply store the final results into a list of tuples containing (matrix_no, matrix_greatest_sum) in answers, then print out at the end:
print("Enter the number of arrays:")
K = int(input())
answers = []
for i in range(K):
print("Enter the number of rows you want:")
rows = int(input())
columns = 3
matrix = []
biggest_row_sum = -999999
biggest_row_index = -1
print("Start entering the rows:")
for j in range(rows):
this_row = list(map(int, input().split()))
matrix.append(this_row)
this_row_sum = sum(this_row)
if this_row_sum > biggest_row_sum:
biggest_row_index = j
biggest_row_sum = this_row_sum
answers.append((i+1, biggest_row_index+1))
# Print final answer
for matrix_no, matrix_greatest_sum in answers:
print("in array " + str(matrix_no) + " is : " + str(matrix_greatest_sum))
import sys
print("Enter the number of arrays:")
K = int(input())
array = []
for i in range(K):
print("Enter the number of rows and columns you want:")
rows = int(input())
columns = 3
matrix = []
print("Start entering the rows:")
for j in range(rows):
matrix.append(list(map(int, input().split())))
array.append(matrix) # we also do not need this line
# we do not need to save matrix to array just for calculating the max row
# we can do it inside the loop using the matrix variable
greatest_row = 0 # initially let's say the greatest row is the first row
current_sum = 0 # initial sum 0
for j in range(rows):
a_row_sum = sum(matrix[j])
if a_row_sum > current_sum:
current_sum = a_row_sum
greatest_row = j
# everything is 0 based indexed
# so we add one while outputting the result
print("in array {0} is : {1}".format(i + 1, greatest_row + 1))
output
Enter the number of arrays:
2
Enter the number of rows and columns you want:
2
Start entering the rows:
1 2 3
4 5 6
in array 1 is : 2
Enter the number of rows and columns you want:
3
Start entering the rows:
0 0 0
2 3 4
5 6 7
in array 2 is : 3

how does result = k + tri_recursion(k-1) give me an output of triangular numbers?

I'm currently learning about functions and I came across a recursions example on w3schools.com. This code is giving me a list of triangular numbers for an argument k > 0. My question is how exactly is it printing out a list of triangular numbers with "result" defined as result = k + tri_recursion(k-1) in the body of the code. The output for an input of k = 6, for example, gives me 1, 3, 6, 10, 15, 21 but I just don't understand how I'm getting a list of triangular numbers from such a simple setting of the return variable. Help would be much appreciated :)
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nexample result")
tri_recursion(6)
you need create a list to storage numbers:
tri_list = []
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k-1)
tri_list.append(result)
print(result)
else:
result = 0
return result
print("\n\nexample result")
tri_recursion(6)
print(tri_list)
Then you have:
k = 6
6 + tri_recursion(5)
5 + tri_recursion(4)
4 + tri_recursion(3)
3 + tri_recursion(2)
2 + tri_recursion(1)
1 + tri_recursion(0)
1 + 0 = 1
2 + 1 = 3
3 + 3 = 6
4 + 6 = 10
5 + 10 = 15
6 + 15 = 21
This happens because you are printing the sum of the previous numbers in each return of each recursion

I am having a problem with understanding this python code

I want to learn Python and I took a test. I the test I came across this code and I needed to get it's output.
I put the correct answer which was 6, but I didn't understand the code, I just put it in an online python compiler!
Why does this code output a 6?
def func(x):
res = 0
for i in range(x):
res += i
return res
print(func(4))
I thing this will solve your problem buddy
def func(x):
res = 0
for i in range(x):
print "x",i
print "res",res
res += i
print "res out", res
return res
print(func(4))
result:
x 0
res 0
res out 0
x 1
res 0
res out 1
x 2
res 1
res out 3
x 3
res 3
res out 6
6
you're passing number 4 as variable x into the function and printing the result in the end.
in the for loop, i is a temporary variable representing each number in range 0 to 4.
so the steps in the code look like this
for 0 in range 0 to 4
add 0 to variable res = 0 + 0 = 0
now res = 0
next step/loop for 1 in range 0 to 4
add 1 to variable res = 0 + 1 = 1
now res = 1
next step/loop for 2 in range 0 to 4
add 2 to variable res = 1 + 2 = 3
now res = 3
next step/loop for 3 in range 0 to 4
add 3 to variable res = 3 + 3 = 6
now res = 6
and the loop is done, giving you the result 6
You assign the value of i to the res and then res value is added to the value of i and your output is assign to the value of res that is when x=3, res become 3 and added with the value 3 is equal to 6 boom
def is used to define function and range means from start to the end point you want so in your case you passed 4 as variable x into your function that means your loop start with the value of 0 and end when value is 4.

Why is Poisonous plants stack solution giving TLE?

Trying to solve hackerrank problem.
There are plants in a garden. Each of these plants has been added with some amount of pesticide. After each day, if any plant has more pesticide than the plant at its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each plant. Print the number of days after which no plant dies, i.e. the time after which there are no plants with more pesticide content than the plant to their left.
I have used stacks to solve this problem. Example below:
a = 6 5 8 4 7 10 9
10 > 9 a = 6 5 8 4 7 10 b = 9
7 > 10 a = 6 5 8 4 7 b = 9
4 > 7 a = 6 5 8 4 b = 9
8 > 4 a = 6 5 8 b = 9 4
5 > 8 a = 6 5 b = 9 4
6 > 5 a = 6 5 b = 9 4
after this just make a new list with a = a + b.reverse(). Start the process again and exit when list is sorted in reverse order.
This still is giving me time exceeded. Any idea?
n = int(input())
first_list = input().split()
first_list = [int(i) for i in first_list]
count = 0
second_list = []
data_1, data_2 = 0, 0
while True:
b = []
if sorted(first_list, reverse=True) == first_list:
break
data_1 = first_list.pop()
for i in range(len(first_list)-1):
data_2 = first_list.pop()
if data_1 > data_2:
pass
elif data_1 < data_2:
second_list.append(data_1)
elif data_1 == data_2:
second_list.append(data_1)
second_list.append(data_2)
data_1 = data_2
if len(first_list)>=1 and data_1 < first_list[0]:
first_list.append(data_1)
second_list.reverse()
first_list = first_list + second_list
count += 1
print(count)
Edited code:
n = int(input())
input = [int(i) for i in input().split()]
count, t_length = 0, 0
cmp = input[0]
while True:
length = len(input)
for i in range(1, length):
if input[i] == -1:
t_length += 1
continue
if input[i] > cmp:
cmp = input[i]
input[i] = -1
else:
t_length += 1
cmp = input[i]
if t_length+1 == length:
break
count += 1
cmp, t_length = input[0], 0
print(count)
I agree with Woot4Moo that something doesn't look right, and I suggest you focus more on stack use (instead of doubly linked lists). See this link to the Stock Span problem which helps detail an O(N) solution for tracking differences in a list of prices. This can be extended with a condition for pesticide.
For example, it'd be filling in the gaps of:
import sys
ps = [int(s) for s in list(sys.stdin)[1].strip().split()]
stack = [ps[0]]
max_days = 0
for i in range(1, len(ps)):
days[i] = 1 if ps[i] > ps[i-1] else 0
# TODO - Logic to update days[i]
while len(stack) > 0 and ps[i] <= stack[-1][1]:
(ps_other, days_other) = stack.pop()
stack.append((ps[i], days[i])
max_days = max(max_days, days[i])
print(max_days)
I quickly implemented in O(N^2), and found 80% of tests pass (the rest timing out), so more cleverly using the stack according to the link above should do the job.
import collections
import sys
ps = [int(s) for s in list(sys.stdin)[1].strip().split()]
ps_prev = []
days = 0
while collections.Counter(ps_prev) != collections.Counter(ps):
ps_prev = ps[:]
i = len(ps) - 1
while i > 0:
if ps[i] > ps[i-1]:
ps.pop(i)
i -= 1
days += 1
print(days - 1)
Edit: note that the sketchy sys.stdin use is to cater for the HackerRank test input.
Sorting is N log N and your data structure seems wrong to me. Why would you not use a doubly linked list since the requirement is that it is the left most neighbor. You would simply dereference the pointers that died.

Categories

Resources