'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.
Related
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.
def myNames():
b = []
while True:
a = input("whats the name: ")
if a != "done":
b.append(a)
elif a == "done":
break
return b
x = myNames()
print (x)
def getAverageLength(myNames):
total = 0
for i in myNames: #This line of code gives me an error and I cant figure it out
total = total + len(i)
average = float(total) / float(len(myNames))
return average
getAverageLength(myNames)
It takes my first function (myNames) as an argument. Ive been trying to figure this error out but have no idea what to do here
Your last line: getAverageLength(myNames), like you said in your description, is using myNames as a parameter which is only present as a function in the current scope.
This means when you reach your for loop, you end up trying to iterate over a function, since that is what was passed into getAverageLength
Maybe you meant getAverageLength(x)?
Or perhaps getAverageLength(myNames()) since myNames() passes the result of the function as opposed to the function itself.
To correctly calculate the average length of the strings, you could use the following:
averageLength = sum(map(len, x)) / len(x)
I'm trying to get user's input through the entry widget into an array, keep note that the user's input is a number. How can I get the users input as an integer.
I tried changing the entry values to int with int(g.get())
but it gives me this line:
...
ValueError: invalid literal for int() with base 10: ''
...
So I tried putting it as a string first with int(str(g.get())
But that gave me the same error line.
Tried it outside the loop to get the values in the array, inside the loop, both, nothing worked.
I'm also not sure if my input into an array algorithm works, I'm thinking I might need to put the widget inside the array(?).
x = 6
ind = np.arange(N)
arr = []
G = tk.Entry(self, textvariable="")
G.pack
while x >= 0:
arr[x] = int(str(G.get()))
arr.append(x)
x = x - 1
I expect to have an array of numbers that the user inputted into the entry widget, for example, arr = [6,4,6,3,7]
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.
player_list= {'peter':0, 'karel':0}
naam = input("Welke speler moet een score + 1 krijgen?")
for key, value in player_list.items():
player_list[naam] = value + 1
print(player_list)
Can someone explain me I why get the correct value whenever I enter "peter" but not when I enter "karel"?
I assume, that you'd like to increment dict value of the key which is same as the string that user provides via input. Ask yourself, do you really need to iterate over dict items to do such thing? Dict is key-value structure, and you can access value of the key whenever you provide this key directly.
>>> player_list = {'peter':0, 'karel':0}
>>> player_list['peter']
0
Setting value to the existing dict key is easy. All you need to do is:
>>> player_list['peter'] = 3
>>> player_list['peter']
3
If you'd like to increment value for 'peter' you need to take whatever is stored under 'peter' and add one, but there is no need to iterate over dict items to do that. Like with any other variable, dict element is kind of placeholder for some space of memory that you can access via that placeholder. So in case of any variable you'd do something as:
>>> x = 1
>>> x = x + 1 # or x += 1 for short
...and in case of dict element, you can do the same:
>>> player_list['peter'] = player_list['peter'] + 1 # or:
>>> player_list['peter'] += 1
If you're curious why your current code doesn't work as you expected, run your code using debugger or just add print function:
for key, value in player_list.items():
print("Current key: {}, current value: {}".format(key, value))
player_list[naam] = value + 1
In fact, it's always good to use some debugging tools whenever you don't know why your code execution is different than your expected result.