Key error while adding a new key to the dictionary - python-3.x

This is my code:
nums = sorted(nums)
n = len(nums)
maps = { 0 : [nums[0]]}
maps[2] = ["shot"]
dp = [1 for _ in nums]
for i in range(1 , n):
for j in range(i , -1 , -1):
if nums[i] % nums[j] == 0:
dp[i] = dp[j]+1
print(maps)
if i not in maps.keys():
maps[i] = maps[j].append(nums[i])
The error message:
KeyError: 1
maps[i] = maps[j].append(nums[i])
Line 15 in largestDivisibleSubset (Solution.py)
ret = Solution().largestDivisibleSubset(param_1)
Line 41 in _driver (Solution.py)
_driver()
Line 52 in <module> (Solution.py)
The input: nums = [1,2,3,5,7]

You can only use the append method to insert a value to a key, that is already existing.
So either you do something like this:
maps[i] = nums[i]
Or:
maps[i] = nums[j]

This is your problem stanza:
if i not in maps.keys():
maps[i] = maps[j].append(nums[i])
Here you are asking 'if i is not in the maps dictionary, then get the value at index i from the nums array and append it to the value referenced by the key j in the maps dictionary, then assign the result of that function back to the value of the key i in the dictionary'.
append() returns None, which means you'll just be putting None at the key i. But your error is actually saying that the key 1 doesn't exist in the object you're looking into. Presumably that is maps, because you are attempting to dereference maps[j] - and j is not one of the keys in maps. Since that can't be fetched, and would be None if you did, you can't append anything to it.
A definitive solution can't be given here, since it's unclear what you want to end up with. Given an input array of [1,2,3,5,7] what do you expect maps to look like at the end of this function?
One thing that might help is something like:
if i not in maps.keys():
ls = maps.get(j, [])
ls.append(nums[i])
maps[i] = ls
Here, we get the list at index j and return a default empty list [] if j is not inside the map already. Then we assign the modified list to the key i. I'm not sure if this is actually what you're looking for, though.

Related

List Index Error - Combining list elements via index

'Original String = 1234 A 56 78 90 B'
def func_1(one_dict):
global ends
ends = []
for x in original_string:
if x in one_dict:
ends.append(one_dict[x])
return ends
The above returns:
['B', 'A']
My next function is supposed to then combine them into 1 string and get value from dictionary. I've tried this with/without the str in mult_ends with the same result.
def func_2(two_dict):
global mult_ends
mult_ends = str(ends[0] + ends[1])
for key in mult_ends:
if key in two_dict:
return two_dict[key]
The results confuse me since I use pretty identical processes in other functions with no issue.
IndexError: list index out of range
Why would the list index be out of range when there is clearly a 0 and 1? I've also added global ends to func_2 and I still received the same error.
*** RESTRUCTURED FUNCTIONS INTO 1 ***
def func_1(one_dict):
global ends
ends = []
for x in original_string:
if x in one_dict:
ends.append(one_dict[x])
mult_ends = ends[0] + ends[1]
for key in two_dict:
if key in mult_ends:
return ends_final_dict[key]
return None
Now, it actually does what I want it to do and returns the correct dictionary key in the event log:
A B
However, it does not return when I try to insert it back into my GUI for the user and it still throws the IndexError: list index out of range.

IndexError: list index out of range while using nested loops

A = [34,23,1,24,75,33,54,8]
K = 60
solution=[]
for i in range(len(A)):
for j in range(i+1,len(A)):
v=solution[(A[i]+A[j])]
print(v)
Hi, I am trying to get the list with result of individual sums like: 34+23 34+1 34+24 and so on then next 23+1,23+24 and so on.
Your code fails since it's trying to set v to the (A[i]+A[j])th element of solution, which is empty, so that value doesn't exist.
If I understand what you're trying to do, then this should give the desired result.
A = [34,23,1,24,75,33,54,8]
v = [[A[x] + A[i] for i in range(x + 1, len(A))] for x in range(len(A))]
As you can see here,
List index starts from 0 to the (n-1), where n is the len(list).
So A(len(A)) doesn't exist. Which results in the error.
So to fix this replace
len(A)
by
len(A) - 1
inside all instances of range function.

how can i print the right value in the code?

I'm new to python, and I'm having trouble resolving this code. I just have to print the position of the string when j equals r. But it prints nothing.
class List():
def __init__(self, l_red, l_erd, r):
self.l_red = "ABCEFGC"
self.l_erd = "DBFEGAC"
self.r = l_red[0]
def posicao(self):
j = self.l_red[0];
while self.l_erd[j] != self.r:
j = j + 1
print(j)
This is a bit hard to understand but I will give it a go.
To begin with you really need to consider using a different name for the class; List is already in python.
To instantiate and use this class you would need to use:
a_variable = List() # or whatever you are going to use
a_variable.posicao()
l_red is a string which can act like a character list, and l_erd is the same. Lists take an integer number (0, 1, 2, 3 ...) and return what was in that place. So what you need to do is something more like:
def posicao(self):
letter_of_interest = "A"
j = 0
for j in range(0, len(self.l_erd):
if letter_of_interest == self.r:
print(j)
break
Now what I have written is just for a single character, and you would use a loop to go through each character of interest, but I will leave that to you.
If you want it to find all the positions where that character exists just remove that break.
There are better methods of doing this, look into just using "ABCDE".index('A') this works.

Why the interpreter shows that there should be a colon?

I try to find the key of the biggest number in the values of dictionary:
def compare(dictionary):
varb0 = 0
for i in dictionary:
if dictionary[i] >= varb0:
sha = dictionary[i]
for j in dictionary:
if dictionary[j] = varb0:
return j
but the interpreter report an error of lack of colon:
the screensnap
so, is there anyone who could tell me why this error occured? or any idea of better solution for my stupid question?
If you use = you are assigning a value to a variable.
If you use == you are comparing the values inside variables for equality.
Therefore:
def compare(dictionary):
varb0 = 0
for i in dictionary:
if dictionary[i] >= varb0:
sha = dictionary[i]
for j in dictionary:
if dictionary[j] == varb0:
return j

When I try to run my code, I seem to run with an IndexError

When I try to run my code, I seem to run with an IndexError.
def _init_trellis(self, observed, forward=True, init_func=identity):
trellis = [ [None for j in range(len(observed))]
for i in range(len(self.real_states) + 1) ]
if forward:
v = lambda s: self.transition(0, s) * self.emission(s, observed[1])
else:
v = lambda s: self.transition(s, self.end_state)
init_pos = 1 if forward else -1
for state in self.state_nums():
trellis[state][init_pos] = init_func( v(state) )
return trellis
ERROR:
v = lambda s: self.transition(0, s) * self.emission(s, observed[1]) IndexError: list index out of range
Add assertions to your code.
assert(len(observed) > 1)
will ensure that the array is long enough.
Update:
This happens when you try to access a list with an index, but the list does not have that many elements to show.
For example:
a_list = ['a', 'b', 'c']
print(a_list[0] # Prints a.
print(a_list[2] # Prints c.
print(a_list[3] # Gives IndexError.
'''Index of 3 means the 4th element of the list is being accessed.
Since the list only has 3 elements, it gives an index error.'''
In this case, observed[1] giving an index error means observed has only 1 element.
That is, len(observed) is 1.
Original Answer:
Based on the error, ensure that observed is an iterable with a minimum length of 2.

Resources