Why the interpreter shows that there should be a colon? - python-3.x

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

Related

Issues with list comprehensions

My goal was to create a method that would take an array as parameter, and output the sum of the min() value of each of its subarrays. However, I really don’t understand what’s wrong with my list comprehension.
class Solution(object):
def sumSubarrayMins(self, arr):
s = 0
self.subarrays = [arr[i:j] for i in range(j-1,len(arr))for j in range(1,len(arr)+1)]
for subarray in self.subarrays:
s += min(subarray)
return s
sol = Solution()
sol.sumSubarrayMins([3,1,2,4])
I often try debugging with python tutor but it is really no help in this case.
Your subarray calculation logic is wrong. You are trying to use j in the first loop, before you define it. Try this:
self.subarrays = [arr[i:j] for i in range(0, len(arr)) for j in range(i+1, len(arr)+1)]

Key error while adding a new key to the dictionary

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.

I am trying to update dictionary by taking user input but getting error

I am trying to update dictionary by taking input from the user, pls help me in doing that.
Below is the code i am trying to implement.
n = int(input("enter a n value:"))
d = {}
for i in range(n):
keys = input() # here i have taken keys as strings
values = int(input()) # here i have taken values as integers
d[keys] = values
print(d)
c = {}
key = input()
valu = int(input())
c[key] = valu
d.update({c})
There's a bug in the last line of your code. {c} tries to create a set using c as its element which is not allowed as dict object is not hashable. Change you last line to: d.update(c) and it should work.

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.

Common values in a Python dictionary

I'm trying to write a code that will return common values from a dictionary based on a list of words.
Example:
inp = ['here','now']
dict = {'here':{1,2,3}, 'now':{2,3}, 'stop':{1, 3}}
for val in inp.intersection(D):
lst = D[val]
print(sorted(lst))
output: [2, 3]
The input inp may contain any one or all of the above words, and I want to know what values they have in common. I just cannot seem to figure out how to do that. Please, any help would be appreciated.
The easiest way to do this is to just count them all, and then make a dict of the values that are equal to the number of sets you intersected.
To accomplish the first part, we do something like this:
answer = {}
for word in inp:
for itm in word:
if itm in answer:
answer[itm] += 1
else:
answer[itm] = 1
To accomplish the second part, we just have to iterate over answer and build an array like so:
answerArr = []
for i in answer:
if (answer[i] == len(inp)):
answerArr.append(i)
i'm not certain that i understood your question perfectly but i think this is what you meant albeit in a very simple way:
inp = ['here','now']
dict = {'here':{1,2,3}, 'now':{2,3}, 'stop':{1, 3}}
output = []
for item in inp:
output.append(dict[item])
for item in output:
occurances = output.count(item)
if occurances <= 1:
output.remove(item)
print(output)
This should output the items from the dict which occurs in more than one input. If you want it to be common for all of the inputs just change the <= 1 to be the number of inputs given.

Resources