Adding Specific Number from a Matrix within a List - python-3.x

I have a list initialized:
best_selected = [[2, 3, 0, 1], [1, 3, 0, 2], [1, 2, 3, 0], [1, 0, 2, 3]]
0 1 2 3
finalList = [[0, 1308, 17410, 16098], [1246, 0, 17557, 16244], [17675, 18002, 0, 5618], [16257, 16584, 5508, 0]]
0 1 2 3
The finalList as a matrix looks like this:
[[ 0 1308 17410 16098]
[ 1246 0 17557 16244]
[17675 18002 0 5618]
[16257 16584 5508 0]]
What I'm trying to do is to iterate in every list of best_selected and add them depending on which index it is in on the other list. And lets say in the first iteration is [2, 3, 0, 1] in best_selected list. The first element in the list is 2 so I'm going to start in :
[[ 0 1308 17410 16098]
[ 1246 0 17557 16244]
--> [17675 18002 0 5618]
[16257 16584 5508 0]]
Since the next number of 2 is 3 respectively in the first iteration of the best_selected, so I would get 5618 as the first value to be in the index. Since it stopped at 3 I would now check next at:
[[ 0 1308 17410 16098]
[ 1246 0 17557 16244]
[17675 18002 0 5618]
--> [16257 16584 5508 0]]
As the next element of 3 is 0*, then I would try to add 16257 in the variable 'index' that contained the value 5618 so the index would now contain the value of 16257 + 5618. I'm trying to do that in each of every iteration of best_selected and so far I'm having errors
The code I'm trying to work out:
count = len(best_selected)
index = 0
j = 0
val = best_selected[0]
while count != 0:
index = index + finalList[best_selected[val]]
if counter == 1:
pass
else:
val = best_selected[j+1]
j = j + 1
counter = counter - 1
print(index)
Any fix or an easy solution would highly be appreciated!

If I understand you correctly, you want a sliding window of the current item and the next item in the sublist. You could just iterate over the sublists and then over the range range(len(sublist)-1), so that you can assign the first index to i = sublist[indx] and the second to j = sublist[indx+1].
index = 0
for sublist in best_selected:
for indx in range(len(sublist)-1):
i = sublist[indx]
j = sublist[indx+1]
index += finalList[i][j]
The nicer variant would be to zip the sublist with sublist[1:] to get tuples with the indices which you can immediately unpack in the head of the loop:
for sublist in best_selected:
for i, j in zip(sublist, sublist[1:]):
index += finalList[i][j]
Here's the solution with the separate sublist sums:
sums = []
for sublist in best_selected:
sublist_sum = 0
for i, j in zip(sublist, sublist[1:]):
sublist_sum += finalList[i][j]
sums.append(sublist_sum)
print(sums)
print(sum(sums))

Related

what is wrong with my code? leetcode - 189. Rotate Array

The code works perfectly fine for the first test case but gives wrong answer for the second one. Why is that?
arr = [1,2,3,4,5,6,7]
arr2 = [-1,-100,3,99]
def reverse(array, start, end):
while start < end:
array[start], array[end] = array[end], array[start]
start += 1
end -= 1
return array
def rotate(array, k):
reverse(array, 0, k)
reverse(array, k+1, len(array)-1)
reverse(array, 0, len(array)-1)
return array
print(rotate(arr, 3)) # output: [5, 6, 7, 1, 2, 3, 4]
# print(reverse(arr, 2, 4))
rotate(arr2, 2)
print(arr2) # output: [99, -1, -100, 3] (should be [3, 99, -1, -100])
Your existing logic does the following -
Move k + 1 item from front of the list to the back of the list.
But the solution needs to move k elements from back of the list to the front. Or another way to think is move len(array) - k element from front to the back.
To do so, two changes required in the rotate() -
Update k to len(array) - k
Change your logic to move k instead of k + 1 element from front to back
So, your rotate() needs to be changed to following -
def rotate(array, k):
k = len(array) - k
reverse(array, 0, k-1)
reverse(array, k, len(array)-1)
reverse(array, 0, len(array)-1)
return array
I think there are better ways to solve this but with your logic this should solve the problem.

Printing fibonacci series using lists in python

I am relatively a noobie in programming and trying to learn python. I was trying to implement a Fibonacci series into a list within 10.
fibo= [0,1]
for k in range(11):
i= fibo[-1]
j = fibo[-2]
k= fibo[i]+fibo[j]
fibo.append(k)
k=+1
print(fibo)
Not sure what I did wrong? Any help is really appreciated!
Output:
[0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
You can use this code to print fibonacci series upto N.
N = int(input()) # Length of fibonacci series
fibo = [0, 1]
a = fibo[0]
b = fibo[1]
for each in range(2, N):
c = a + b
a, b = b, c
fibo.append(c)
print(fibo[:N])
OUTPUT
N = 10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
I can see few issues here:
fibo = [0,1]
# Your loop should start at index 2, otherwise
# you will try to access fibo[-2] and fibo[-1] with k=0
# and fibo[-1] and fibo[0] with k=1
# Also, if you only want 10 values, you should change 11
# to 10 since fibo already has two values.
# for k in range(11):
for k in range(2, 10):
# You don't want the content of fibo, but the indexes!
# i = fibo[-1]
# j = fibo[-2]
i = k - 1
j = k - 2
# You are already using k, so you need to use an other variable
# k = fibo[i] + fibo[j]
v = fibo[i] + fibo[j]
fibo.append(v)
# You don't need k+=1 because it will be incremented
# according to range(2, 10). The loop will start with
# k = 2 and it will stop when k = 9
# k += 1
print(fibo)
Your code did not crash because you technically can access fibo[-1] and fibo[-2]. It will respectively return the last value of your array, and the value before the last one.

Start counting indexes from 1 instead of 0 of a list

I created a program to get the the max value of a list and the position of its occurrences (list starting at indexing with 1 not 0) but I can't manage to find any useful solutions.
The input is always a string of numbers divided by zero.
This is my code:
inp = list(map(int,input().split()))
m = max(inp)
count = inp.count(m)
print(m)
def maxelements(seq): # #SilentGhost
return [i for i, j in enumerate(seq) if j == m]
print(maxelements(inp))
I expect to output the maximum value and then all the positions of its occurrences. (also is it possible to do without brackets as in the example below?)
Input: 4 56 43 45 2 56 8
Output: 56
2 6
If you want to shift index values, you could just do
return [i + 1 for i, j in enumerate(seq) if j == m]
more generally any transformation of i or j!
def f(i, j):
# do whatever you want, and return something
return i + 1
return [f(i, j) for i, j in enumerate(seq) if j == m]
Without brackets, as a string:
return " ".join(str(i + 1) for i, j in enumerate(seq) if j==m)
Specifiy start=1 with enumerate():
>>> l = [4, 56, 43, 45, 2, 56, 8]
>>> max_num = max(l)
>>> [i for i, e in enumerate(l, start=1) if e == max_num]
[2, 6]
By default enumerate() uses start=0, because indices start at 0.

How to find median of a list using indexing

I am trying to define a function, median, that consumes a list of numbers and returns the median number from the list. If the list is empty, then I want to return None. To calculate the median, I need to find the middle index of the list after it has been sorted. Do not use a built-in function.
SURVEY_RESULTS = [1.5, 1, 2, 1.5, 2, 3, 1, 1, 1, 2]
def median(SURVEY_RESULTS):
length = 0
order = sorted(SURVEY_RESULTS)
I'm not sure how to use indexing to now determine the median.
Here is my implementation:
def QuickSort(myList,start,end):
if start < end:
i,j = start,end
base = myList[i]
while i < j:
while (i < j) and (myList[j] >= base):
j = j - 1
myList[i] = myList[j]
while (i < j) and (myList[i] <= base):
i = i + 1
myList[j] = myList[i]
myList[i] = base
QuickSort(myList, start, i - 1)
QuickSort(myList, j + 1, end)
return myList
def median(l):
half = len(l) // 2
return (l[half] + l[~half])/2 # Use reverse index
SURVEY_RESULTS = [1.5, 1, 2, 1.5, 2, 3, 1, 1, 1, 2]
# Sort first
QuickSort(SURVEY_RESULTS, 0, len(SURVEY_RESULTS)-1)
result = median(SURVEY_RESULTS)
print (result)

Python find indexes of list of lists

I'm trying to find the indexes of all the elements in a python list of lists. The list would look something like this:
list = [[x,y,x],
[x,y,y],
[y,y,y]]
To do this I have tried to use a nested loop like this:
for lst in list:
print(list.index(lst))
for x in lst:
print(lst.index(x))
This however prints out a long list with almost seemingly random numbers.
screenshot of output for a slightly different list
What I'm tring to achieve is an output looking something like this:
0
1
0
2
0
3
1
0
1
0
Is there anyone who can help out a python beginner?
You can enumerate to print indexes
x = 22
y = 34
l = [[x,y,x],
[x,y,y],
[y,y,y]]
indexes = [(i, j) for i, nl in enumerate(l) for j, nle in enumerate(nl)]
print(*indexes, sep="\n")
# output
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)
https://docs.python.org/3/library/functions.html#enumerate
You can easily access index and value with the use of by looping thorugh the list using enumerate. I added some printing with text to show what number is what.
myList = [[1,2,3],
[4,5,6],
[7,8,9]]
for lstIdx, lst in enumerate(myList):
print("list idx: " + str(lstIdx))
for idx, item in enumerate(lst):
print("item idx in list: " + str(idx))
output:
list idx: 0
item idx in list: 0
item idx in list: 1
item idx in list: 2
list idx: 1
item idx in list: 0
item idx in list: 1
item idx in list: 2
list idx: 2
item idx in list: 0
item idx in list: 1
item idx in list: 2

Resources