val = dict()
def vote(val,person):
if person not in val:
val[person] = 1
else:
val[person] = val[person] + 1
def votes(val,person):
if person in val:
print val[person]
def result(val):
ex = sorted(val.items(), key = lambda val:val[1], reverse=True)
if len(ex) == 0:
print '***NONE***'
#Problem below
elif ex[0] == ex[1]:
print '***NONE***'
else:
print ex[0][0]
Output:
>>>vote(val,'Peter')
>>>vote(val,'Peter')
>>>votes(val,'Peter')
2
>>>vote(val,'Lisa')
>>>vote(val,'Lisa')
>>>votes(val,'Lisa')
2
>>>result(val)
Lisa
>>> print val
{'Lisa': 2, 'Peter': 2}
I want to try to find if 2 keys have the same values, and if they do I want to print "NONE" if that happens. Obviously it doesn't work since it prints "Lisa" instead, any tips on how to do it?
In your result function need to check the votes in the elif part.
elif ex[0][1] == ex[1][1]:
print ('***NONE***')
Related
testdeck = ['rock']
finaldeck = ['apple','banana','napalm','ice',5,6,7,8]
def deckhelp(testdeck,finaldeck):
testnumber = 0
testlength = len(testdeck)
for index, (card, item) in enumerate(zip(testdeck, finaldeck)):
if isinstance(item, int): #checks if item is an integer
finaldeck[index] = card
print(finaldeck)
testnumber += 1
if testnumber == testlength:
print('done')
pass
deckhelp(testdeck,finaldeck)
I want rock to replace the 5 located in finaldeck, can't seem to make it happen
This is not an appropriate use of zip() because you only want to iterate through testdeck when you reach the integers in finaldeck.
You also need to use return, not pass, to end the function when you reach the end of testdeck.
def deckhelp(testdeck, finaldeck):
testindex = 0
testlength = len(testdeck)
for index, item in enumerate(finaldeck):
if isinstance(item, int):
finaldeck[index] = testdeck[testindex]
testindex += 1
if testindex == testlength:
print('done')
return
Zip only works in testdeck and finaldeck have the same length. Instead, you can use something like this:
def deckhelp(testdeck, finaldeck):
replace_index = 0
for i, val in enumerate(finaldeck):
if isinstance(val, int):
finaldeck[i] = testdeck[replace_index]
replace_index += 1
if replace_index == len(testdeck):
print("done")
return
So I wrote this code with the help of Stack Overflow users that transfers points to an individual based on whether "++" or "--" appears behind an individual.
def get_name(input):
return input.replace("+", "").replace("-", "")
def keep(actions: list):
g = {}
for s in actions:
if '->' in s:
names = s.split('->')
g[names[1]] = g[names[0]]
g[names[0]] = 0
else:
name = get_name(s)
if name not in g:
g[name] = 0
if "++" in s:
g[name] += 1
if "--" in s:
g[name] -= 1
return {x:g[x] for x in g if g[x] != 0}
print(keep(["Jim++", "John--", "Jeff++", "Jim++", "John--", "John->Jeff",
"Jeff--", "June++", "Home->House"]))
So most of the program is alright, however, when I put "Home->House" into it, it returns a KeyError. I kinda understand why it does that, but I'm clueless as to how to fix that...
I tried browsing the internet for solutions but all they recommended was to use .get(), which doesn't really help me solve the issue.
How can I make my output just neglect if like an element doesn't have "++" or "--" in it... like how can I make sure if an input is just "Jim" instead of "Jim++" or "Jim--", the function would just neglect it...
So in my example, if the input for keep is
["Jim++", "John--", "Jeff++", "Jim++", "John--", "John->Jeff", "Jeff--", "June++", "Home->House "]
the output would be
{'Jeff': -2, 'June': 1, 'Jim': 2}
instead of KeyError
You get KeyError because g[names[1]] = g[names[0]] is trying to access element in dictionary that isn't there. You get the same issue with simple print(keep(["John->Jeff"])), because there are no ++ or -- actions executed first to initialise those keys ("John" and "Jeff" in g
Based on your desired output you want to ignore such actions that are for non existing keys.
Add if names[1] in g and names[0] in g: into your keep implementation i.e.
Edit: also g[names[1]] = g[names[0]] needs to change to g[names[1]] += g[names[0]] to product correct outcome.
def get_name(input):
return input.replace("+", "").replace("-", "")
def keep(actions: list):
g = {}
for s in actions:
if "->" in s:
names = s.split("->")
if names[1] in g and names[0] in g:
g[names[1]] += g[names[0]]
g[names[0]] = 0
else:
name = get_name(s)
if name not in g:
g[name] = 0
if "++" in s:
g[name] += 1
if "--" in s:
g[name] -= 1
return {x: g[x] for x in g if g[x] != 0}
In your code, when you get Home->House, it's the first appearence of both the keys. That's why you get KeyError when you try to execute g[names[1] = g[names[0]]: g[names[0]] is g['Home'], but this entry doesn't exist in your dict. You can simply solve swapping the order of the lines:
if '->' in s:
names = s.split('->')
g[names[0]] = 0
g[names[1]] = g[names[0]]
To neglect strings which haven't the "++" or the "--", you can simply add an if before performing get_name(s):
else:
if '++' in s or '--' in s:
name = get_name(s)
if name not in g:
g[name] = 0
if "++" in s:
g[name] += 1
if "--" in s:
g[name] -= 1
This code returns the expected output
Your code actually does ignore examples which do not include "++" or "--" in the else-section of your function.
The KeyError occurs because neither "Home" nor "House" appear in the List of input strings before you try to move the entry of "Home" into the entry of "House". Because the keys "Home" and "House" are not in your dictionary g you get a KeyError.
Below is a solution which does what you want.
def get_name(input):
return input.replace("+", "").replace("-", "")
def keep(actions: list):
g = {}
for s in actions:
if '->' in s:
names = s.split('->')
if names[0] in g.keys() and names[1] in g.keys():
g[names[1]] = g[names[0]] + g[names[1]]
g[names[0]] = 0
else:
name = get_name(s)
if name not in g:
g[name] = 0
if "++" in s:
g[name] += 1
if "--" in s:
g[name] -= 1
return {x:g[x] for x in g if g[x] != 0}
print(keep(["Jim++", "John--", "Jeff++", "Jim++", "John", "John--", "John->Jeff",
"Jeff--", "June++", "Home->House"]))
I added a check to make sure the keys exist in dict d when the input string includes a "->".
In order to get the output you indicated in your question, which includes 'Jeff': -2, you also need to make sure to add the value of the original key to the value of the new key. This is done in line
g[names[1]] = g[names[0]] + g[names[1]]
Otherwise the output will say 'Jeff': -3 as the input string "Jeff++" will be ignored.
I am trying to count the 'name' keys in this nested composed dict-list and i am getting 3 in place of 6 ,i think my problem is with the base case in the recursive function count_elem(tree)
def define_tree3():
tree3 ={'name':'GAS','grade':0.8,'children':[{'name':'CSA','grade':0.5,'children':[{'name':'MB','grade':0.1},{'name':'TA','grade':0.6}]},{'name':'IIW','grade':0.9,'children':[None,{'name':'IP','grade':0.99}]}]}
return tree3
#this fuction is to delete the given key from the given dict and retur the new dict
def delkey(dict1,key):
d=dict(dict1)
del d[key]
return d
#this function is to count the numbers of 'name'
def count_elem(tree):
if len(tree)==0:
return 0
else:
for i in tree:
if i == None:
return 0
elif i == 'name':
return 1+ count_elem(delkey(tree,i))
elif i == 'grade':
return count_elem(delkey(tree,i))
elif i == 'children':
for j in tree[i]:
if j == None:
continue
else:
return count_elem(j)
a=define_tree3()
print(count_elem(a))
This is not an answer to your question. I just tried to solve it and used a different approach. Might be useful as a reference.
tree3 = {'name':'GAS','grade':0.8,'children':[{'name':'CSA','grade':0.5,'children':[{'name':'MB','grade':0.1},{'name':'TA','grade':0.6}]},{'name':'IIW','grade':0.9,'children':[None,{'name':'IP','grade':0.99}]}]}
def count_name(entity):
count = 0
name = 'name'
# print('\n')
# print(count, entity)
if type(entity) == dict:
count += sum([key == name for key in entity.keys()])
for value in entity.values():
# print(count, value)
if type(value) == list:
count += sum([count_name(member) for member in value])
return count
count_name(tree3)
Here in this code else block is not printing the value Treasure locked
def counted(value):
if(value == 5):
return 1
else:
return 0
def numb(value1):
sam = 95
value = 0
stp = 97
h = {}
for i in range(0,26):
h.update({chr(stp) : (ord(chr(stp))-sam)})
sam = sam-1
stp = stp+1
for j in range(0,5):
value = h[value1[j]]+value
if(value > 80):
print('First lock-unlocked')
else:
print('Treasure locked')
string = input()
firstcheck = counted(len(string))
if(firstcheck == 1):
numb(string)
a good idea is to check what the condition is before entering the if statements, possibly check what value is printing before the if statement. the logic in def numb() has very little do with what's in def counted(). as long as one is 1 or 0 is being passed to numb() we know that function will run and seems like it.
else block is working properly. if you want to print Treasure Locked. you have to pass lower character string like 'aaaaa'. if value is > 80. then it always print First lock-unlocked.
I am new to this, and I am looking for help. I currently am stuck in a program I'm trying to complete. Here it is:
def searchStock(stockList, stockPrice, s):
for i in range(len(stockList)):
if s == stockList[i]:
s = stockPrice[i]
elif s != stockList[i]:
s = -1
return s
def mainFun():
stockList= []
stockPrice = []
l = 1
while l > 0:
stocks = str(input("Enter the name of the stock:"))
stockList += [stocks]
if stocks == "done"or stocks == 'done':
l = l * -1
stockList.remove("done")
else:
price = int(input("Enter the price of the stock:"))
stockPrice += [price]
l = l + 1
print(stockList)
print(stockPrice)
s = input("Enter the name of the stock you're looking for:")
s = searchStock(stockList, stockPrice, s)
Every time I run the program to the end, it never returns the variable s for some reason. If i replace return with print, it always prints -1 instead of the stockPrice if its on the list. I cant seem to get it to work. Can someone please help me?
Try adding this print to help you debug:
def searchStock(stockList, stockPrice, s):
output = -1
for i in range(len(stockList)):
if s == stockList[i]:
output = stockPrice[i]
print i, output, stockList[i], stockPrice[i]
elif s != stockList[i]:
output = -1
return output
Also I changed one of your variables, it seems better than modifying your input value and then returning it.