I wrote this block of code, but it doesn't work because of SyntaxError.
def char_freq(message):
d = dict()
for ch in message:
d[ch] += 1 if ch in d else d[ch] = 1
return d ^ SyntaxError: End of statement expected
I don't know how to rewrite the expression in order to keep if-else in one line and to get it to work.
I know it is possible to implement the function as a simple for loop, but I don't understand, why my if-else one-liner results in SyntaxError?
Turn d into a defaultdict and then you can just ignore the statement altogether
from collections import defaultdict
def char_freq(message):
d = defaultdict(int)
for ch in message:
d[ch] += 1
return d
It also looks like you're just counting characters so you could just use a counter
from collections import Counter
def char_freq(message):
return Counter(message)
As you asked to keep the if/else Do
d[ch] = (d[ch] + 1) if ch in d else 1
But the dict.get() syntax is nicer d[ch] = d.get(ch, 0) + 1
Or a collections.defaultdict with int factory
def char_freq(message):
d = defaultdict(int)
for ch in message:
d[ch] += 1
return d
In a certain condition I want to count up and return that value
but when I use recursion it reset the value
so I tried to use global variable
but it said
NameError: name 'count' is not defined
Here is my recursion code
def solution(relation):
global count
df = pd.DataFrame(relation)
for i in range(len(relation[0])):
for j in range(len(relation[0])):
if j != i:
temp = df[i] + df[j]
else:
temp = df[j]
if(len(temp)==len(set(temp))):
count +=1
for jj in range(len(relation)):
relation[jj] = relation[jj][1:]
return solution(relation)
return count
You must declare count also outside of function. Like this :
count = 0
def my_function(relation)
global count
# code here
Instead of using as global variable pass it to the recursion and then update it
By calling with updated count
for E.g
def solution(relation, count=0):
""" Your code logic"""
solution(relation, count=count)
If you really want to use it as a global variable, define it outside the function and it will work.
count = 0
def solution(relation):
df = pd.DataFrame(relation)
for i in range(len(relation[0])):
for j in range(len(relation[0])):
if j != i:
temp = df[i] + df[j]
else:
temp = df[j]
if(len(temp)==len(set(temp))):
count +=1
for jj in range(len(relation)):
relation[jj] = relation[jj][1:]
return solution(relation)
return count
But this is a bad practice since it will expose an internal variable to outside unnecessarily. So the best way is passing it as an argument as mentioned in the other solution.
def countFrequency(L):
fdict = {}
for x in range(0, len(L)):
for key, value in fdict:
if L[x] == fdict[str(x)]:
value = value + 1
else:
fdict[L[x]] = 1
return fdict
I'm trying to count the frequency of occurrences of a particular symbol in a given string and create a dictionary out of this. For some reason, the function just returns an empty dictionary. I think the problem arises with adding a new value to the dictionary, but not sure how to troubleshoot it/fix it.
input: countFrequency('MISSISSIPPI')
output: {}
Do this:
def countFrequency(L):
fdict = {}
for x in range(0, len(L)):
if str(L[x]) in fdict.keys():
fdict[str(L[x])] = fdict[str(L[x])] + 1
else:
fdict[str(L[x])] = 1
return fdict
The code in the inner loop:
if L[x] == fdict[str(x)]:
value = value + 1
else:
fdict[L[x]] = 1
is unreachable, because the dictionary is empty initally, and hence you will never add any value to fdict.
you can do it likes this:
def countFrequency(L):
fdict = {}
for symbol in L: #gets each letter in l
if symbol in fdict: #check if dhe dictionary already has an value for the symbol
fdict[symbol] += 1
else:
fdict[symbol] = 1
return fdic
Another issue is that the value value is never assigned to anything or used, so even if we were to go through the loop we would never increment a value in the dictionary.
I am developing a procedure add_to_index, that takes 3 inputs:
an index: [[,[url1,url2,...]],...]
a keyword: String
a url: String
If the keyword is already in the index, url is added to the list of urls associated with that keyword.
If the keyword is not in the index, a new element is to the index:
[keyword,[url]]
CODE
index = []
def add_to_index(index,keyword,url):
flag = 0
count = 0
for lists in index:
count += 1
if(lists[0]==keyword):
index[count][1].append(url)
if(flag ==0):
index.append([keyword,url])
#calling the function below
add_to_index(index,'google','http://google.com')
print index
output -> [['google', 'http://google.com']]
add_to_index(index,'computing','http://acm.org')
print index
output -> [['google', 'http://google.com'], ['computing', 'http://acm.org']]
add_to_index(index,'google','http://gmail.com')
print index
error->
index[count][1].append(url)
AttributeError: 'str' object has no attribute 'append'
Expected output:
[['google', ['http://google.com', 'http://gmail.com']],
['computing', ['http://acm.org']]]
You have done three mistakes, Firstly you have not used the flag and secondly you are adding the url as a string. And finally as Kaivosuketaja has mentioned in the comment, count should be incremented in the end. It can be done otherwise as
index = []
def add_to_index(index,keyword,url):
flag = 0
count = 0
for lists in index:
if(lists[0]==keyword):
flag = 1
index[count][1].append(url)
count += 1
if(flag ==0):
index.append([keyword,[url]])
# Take note of append away here
#calling the function below
add_to_index(index,'google','http://google.com')
print index
add_to_index(index,'computing','http://acm.org')
print index
add_to_index(index,'google','http://gmail.com')
print index
The output now is
[['google', ['http://google.com']]]
[['google', ['http://google.com']], ['computing', ['http://acm.org']]]
[['google', ['http://google.com', 'http://gmail.com']], ['computing', ['http://acm.org']]]
I think this is what you want:
index = []
def add_to_index(index,keyword,url):
flag = 0
count = 0
for lists in index:
if lists[0] == keyword:
lists[1].append(url)
flag = 1
count += 1
if flag == 0:
index.append([keyword, [url]])
#calling the function below
add_to_index(index,'google','http://google.com')
print index
I will suggest the use of dictionaries for this:
index = {}
def add_to_index(index, keyword, url):
if keyword not in index:
index[keyword] = [url]
else:
index[keyword].append(url)
>>> add_to_index(index,'computing','http://acm.org')
>>> add_to_index(index,'google','http://gmail.com')
>>> add_to_index(index,'google','http://gmail.com')
>>> index
{'computing': ['http://acm.org'], 'google': ['http://gmail.com', 'http://gmail.com']}
You could even make index a non global variable by implementing a simple class(ofcourse, this is possible with nested lists too):
class Index(object):
def __init__(self):
self.index = {}
def add_to_index(self, keyword, url):
if keyword not in index:
self.index[keyword] = [url]
else:
self.index[keyword].append(url)
First, you're trying to append to a string that is inside of the list you want to append to. Then, you forgot to say flag = 1 when you've found the keyword. Try the following:
index = []
def add_to_index(index,keyword,url):
flag = 0
count = 0
for lists in index:
if(lists[0]==keyword):
index[count][1].append(url)
flag = 1
count += 1
if(flag ==0):
index.append([keyword,url])
#calling the function below
add_to_index(index,'google','http://google.com')
add_to_index(index,'computing','http://acm.org')
add_to_index(index,'google','http://gmail.com')
print index
I think you'd be much better off using a defaultdict, though. It automatically searches for a keyword and adds the item to the existing keyword, or if it isn't found, creates a new keyword.
You could simplify things a little by getting rid of the flag and count variables.
index = []
def add_to_index(index, keyword, url):
for e in index:
if e[0] == keyword:
e[1].append(url)
return
else:
index.append([keyword,[url]])
I want a function called bebo_count that takes a list x as input and returns the count of the string “bebo” in that list.
For example, bebo_count(["bebo","buzz","bebo"]) should return 2
i have made a code like this
def bebo_count(x):
for a in x:
count = 0
if a == "bebo":
count += 1
return count
but it doesn't work it's always return 1 to me,can any one please modify this code to be working well?!
You keep resetting count = 0 in your loop, move it outside:
def bebo_count(x):
count = 0
for a in x:
if a == "bebo":
count += 1
return count
do not reinvent the wheel :-)
There is a built in method count
x = [ "bebo", "bv", "bebo" ]
x.count("bebo")
> 2
x.count("b")
> 0
You are setting count = 0 inside the for loop. That means that at each loop iteration, irrespective of what the value of count was before, it gets set back to zero. You should initialize count outside the loop. Note also that I have corrected your indentation.
def bebo_count(x):
count = 0
for a in x:
if a == "bebo":
count += 1
return count
For your reference, here is another way you might write this same function:
def bebo_count(x):
return len([a for a in x if a == "bebo"])
Your problem is: count = 0 is inside your for loop.
To fix your code :
def bebo_count(x):
count = 0 # initialize the count before you start counting
for a in x:
if a == "bebo":
count += 1
return count
However, a more pythonic way could be using list comprehension:
big_list = ["bebo", "something else", "bebo"]
def bebo_count(big_list) :
return len( [x for x in big_list if x=="bebo" ] )
print( bebo_count(big_list))