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.
Related
I wrote a code to calculate an average, but it takes only the first item in the list.
I want to input a list of key=value and it should add all the values and then divide by the total number, so it gives me the average.
def average_price_petrol(**args):
result = 0
total = 0
for key,value in args.items():
result += value
total +=1
return result/total
average_price_petrol(aral = 1.799, bft = 1.629, esso = 1.799, shell = 1.829, jet = 1.719)
In addition to the already mentioned indentation issue for return which causes the function to return on the very first loop iteration, you do not need to iterate over args.items() as you don't care about the keys.
def average_price_petrol(**args):
result = 0
total = 0
for value in args.values():
result += value
total += 1
return result / total
And this can be simplified to:
def average_price_petrol(**args):
return sum(args.values()) / len(args)
You need to indent the code properly.
def average_price_petrol(**args):
result = 0
total = 0
for key,value in args.items():
result += value
total +=1
return result/total
Python uses spaces to determine scopes so your code would loop through the first argument and then return the average before the loop has finished
I am trying to write a function that will take in a string and use a dictionary to calculate and return the most common letter in that string. I believe that my code is close to working; however, I get a "cant assign to function call" error on line 5.
Here is my code so far:
def mostCommon(myString):
charCount = []
for c in myString.lower():
if c in charCount:
charCount(c) += 1
else:
charCount(c) = 1
myVal = 0
myKey = 0
for key, value in charCount.lower():
if value > myVal:
myVal = value
myKey = key
return charCount
Here's your function with the errors corrected.
def mostCommon(myString):
charCount = {}
for c in myString.lower():
if c in charCount:
charCount[c] += 1
else:
charCount[c] = 1
myVal = 0
myKey = 0
for key, value in charCount.items():
if value > myVal:
myVal = value
myKey = key
return myKey
Here's a much simpler way of doing it
from collections import Counter
def mostCommon(myString):
return Counter(myString).most_common(1)[0][0]
Well you defined charCount as a list, and then tried to call it like a function. If you want charCount to just be a number, just set it to 0 before your for loop.
Or to use a dict
charCount = {}
for c in myString.lower():
if c in charCount:
charCount[c] += 1
I think you intended charCount to be a dict not a list. Here is a simple solution using the max function:
def mostCommon2(myString):
charCount = {}
for c in myString.lower():
if c in charCount:
charCount[c] += 1
else:
charCount[c] = 1
return max(charCount, key=charCount.get)
here after a few things that can help.
The correct syntax to declare a dictionary is charCount = {}
you cannot create an item with charCount(c), you better do charcount[c] = 'c'
To add element to a dictionnary: Add new keys to a 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 am trying to use codeacademy to learn python. the assignment is to "Write a function called fizz_count that takes a list x as input and returns the count of the string “fizz” in that list."
# Write your function below!
def fizz_count(input):
x = [input]
count = 0
if x =="fizz":
count = count + 1
return count
i think the code above the if loop is fine since the error message ("Your function fails on fizz_count([u'fizz', 0, 0]); it returns None when it should return 1.") only appears when i add that code.
i also tried to make a new variable (new_count) and set that to count + 1 but that gives me the same error message
I would appreciate your assistance very much
The problem is that you have no loop.
# Write your function below!
def fizz_count(input):
count = 0
for x in input: # you need to iterate through the input list
if x =="fizz":
count = count + 1
return count
There is a more concise way by using the .count() function:
def fizz_count(input):
return input.count("fizz")
Get rid of x = [input], that just creates another list containing the list input.
i think the code above the if loop is fine
ifs don't loop; you're probably looking for for:
for x in input: # 'x' will get assigned to each element of 'input'
...
Within this loop, you would check if x is equal to "fizz" and increment the count accordingly (as you are doing with your if-statement currently).
Lastly, move your return-statement out of the loop / if-statement. You want that to get executed after the loop, since you always want to traverse the list entirely before returning.
As a side note, you shouldn't use the name input, as that's already assigned to a built-in function.
Putting it all together:
def fizz_count(l):
count = 0 # set our initial count to 0
for x in l: # for each element x of the list l
if x == "fizz": # check if x equals "fizz"
count = count + 1 # if so, increment count
return count # return how many "fizz"s we counted
def fizz_count(x): #DEFine func
count = 0 #set counter to zero
for item in x:
if item == "fizz" :
count += 1 #iterate counter +1 for each match
print count #print result
return count #return value
fizz_count(["fizz","buzz","fizz"]) #call func
Try this:
# Write your function below!
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count = count + 1
return count
def fizz_count(input)
count = 0
for x in input:
count += 1 if x=="fizz" else 0
return count
I have a class of the form:
class data:
person.models.foreignKey("people.person")
place.models.foreignKey("places.place")
and I'm trying to create a dict containing places that have the same person associated with how many connections they have. IE:
dict={[place1:place2]:count}
so the dict might look like this:
dict={[place1:place2]:3, [place1:place3]:2, ect}
so far I have:
dict={}
datas=data.objects.all()
for data1 in datas:
for data2 in datas:
# if dict is empty
if not dict and data1.person == data2.person and data1.place != data2.place:
dict[(data1.place, data2.place)]=1
elif data1.person == data2.person and data1.place != data2.place:
for assoc, count in dict.items():
if assoc == (data1.place, data2.place) or assoc == (data2.place, data1.place):
count +=1
else:
dict[(data1.place, data2.place)]=1
else:
dict[(data1.place, data2.place)]=1
this is currently returning completely erroneous relations and never increments count. What am i doing wrong?
Do not use predefined names like dict for your variables. Think that your problem is that you try to increase count variable while you have to increase dict[key] - e.g. dict[key] += 1
dct = {}
datas = data.objects.all()
for data1 in datas:
for data2 in datas:
# if dict is empty
if not dct and data1.person == data2.person and data1.place != data2.place:
dct[(data1.place, data2.place)] = 1
elif data1.person == data2.person and data1.place != data2.place:
if (data1.place, data2.place) in dct:
dct[(data1.place, data2.place)] += 1
elif (data2.place, data1.place) in dct:
dct[(data2.place, data1.place)] += 1
else:
dct[(data1.place, data2.place)] = 1
else:
dct[(data1.place, data2.place)] = 1
Use annotations. I don't have you model layout, so this is an approximation of the logic. You'll need to tweak it to map to the correct stuff based on your implementation:
from django.db.models import Count
places = Place.objects.filter(people=thisguy).annotate(connections=Count('people'))
Then you can get the connections count via an attribute on each place:
places[0].connections