I need to write a function called updateHand(hand, word) which does this:
Assumes that 'hand' has all the letters in word. In other words, this
assumes that however many times a letter appears in 'word', 'hand' has
at least as many of that letter in it.
Updates the hand: uses up the letters in the given word and returns
the new hand, without those letters in it.
Has no side effects: does not modify hand.
word: string hand: dictionary (string -> int) returns: dictionary
(string -> int)
I wrote the code and everything is working except the fact that when 'hand' is returned, it is not in the same order:
updateHand({'u': 1, 'q': 1, 'a': 1, 'm': 1, 'l': 2, 'i': 1}, 'quail')
{'u': 0, 'i': 0, 'm': 1, 'a': 0, 'l': 1, 'q': 0}
Could someone give me the solution or even just a hint to this problem because I don't understand...
A dict will not returns the items by insertion order.
What you need is OrderedDict:
from collections import OrderedDict
my_dict = OrderedDict()
my_dict['a'] = 1
...
This concerns only python version < 3.6. From python 3.6, the insertion order is kept.
Related
I have a function that counts DNA bases within a sequence and returns a count of them separately. The function is
def baseCounts(DNA):
for base in DNA:
numofAs = DNA.count('A')
numofCs = DNA.count('C')
numofGs = DNA.count('G')
numofTs = DNA.count('T')
return numofAs, numofCs, numofGs, numofTs
Now, I need to alter the function so it is not restricted to just the DNA alphabet of A, C, G and T.
I know I need to add the alphabet argument to the function
BaseCounts(DNA, alphabet):
However, I don't know what or how to code the rest of the for loop for any character? Keep in mind they have to be added separately?
You can use counter:
from collections import Counter
DNA = 'ATCGBBHHTTCCGGHH'
c = Counter(DNA)
print(c)
Output:
Counter({'C': 3, 'B': 2, 'H': 4, 'A': 1, 'G': 3, 'T': 3})
will return a Counter object which is a specialized dictionary where the keys correspond to the values encountered in the sequence DNA, and constitute your alphabet, and the values are the count of these values in DNA
So I was wondering if anybody wants to help me with this. I don't even understand where to begin? Any help would be appreciated.
Write a function called count_bases that counts the number of times each letter occurs in a given string. The results should be returned as a dictionary, with letters in upper case as keys and the number of occurrences as (integer) values
For example when the function is called with the string 'ATGATAGG', it should return {'A': 3, 'T': 2, 'G': 3, 'C': 0}. Please ensure your function uses return, not print(). The order of the keys in the dictionary does not need to follow this order (2 marks).
Make sure that your function works when passed any lower and/or uppercase DNA characters in the sequence string. (2 marks)
DNA sequences sometimes contain letters other than A, C, G to T to indicate degenerate nucleotides. For example, R can represent A or G (the purine bases). If the program encounters any letter other than A, C, G or T, it should also count the frequency of that letter and return within the dictionary object. (2 marks).
Use following code:
def count_bases(input_str):
result = {}
for s in input_str:
try:
result[s]+=1
except:
result[s] = 1
return result
print(count_bases('ATGATAGG'))
Output:
{'A': 3, 'T': 2, 'G': 3}
Try it:
def f(input):
d = {}
for s in input:
d[s] = d.get(s,0)+1
return d
from collections import Counter
def count_bases(sequence):
# since you want to count both lower and upper case letters,
# it'd be better if you convert the input sequence to either upper or lower.
sequence = sequence.upper()
# Counter (from collections) does the counting for you. It takes list as input.
# So, list(sequence) will separate letters from your sequence into a list of letters ('abc' => ['a', 'b', 'c'])
# It returns you a Counter object. Since you want a dictionary, cast it to dict.
return dict(Counter(list(sequence)))
count_bases('ATGATAGGaatdga')
{'A': 6, 'T': 3, 'G': 4, 'D': 1}
I got this code from the book Automate the boring stuff with Python, and I don't understand how the setdefault() method counts the number of unique characters.
Code:
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
According to the book, the setdefault() method searches for the key in the dictionary and if not found updates the dictionary, if found does nothing.
But I don't understand the counting behaviour of setdefault and how it is done?
Output:
{' ': 13, ',': 1, '.': 1, 'A': 1, 'I': 1, 'a': 4, 'c': 3, 'b': 1, 'e': 5, 'd': 3, 'g': 2,
'i': 6, 'h': 3, 'k': 2, 'l': 3, 'o': 2, 'n': 4, 'p': 1, 's': 3, 'r': 5, 't': 6, 'w': 2, 'y': 1}
Please explain this to me.
In your example setdefault() is equivalent to this code...
if character not in count:
count[character] = 0
This is a nicer way (arguably) to do the same thing:
from collections import defaultdict
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = defaultdict(int)
for character in message:
count[character] = count[character] + 1
print(count)
It works because the default int is 0.
An even nicer way is as follows:
from collections import Counter
print(Counter(
'It was a bright cold day in April, '
'and the clocks were striking thirteen.'))
It would be better to use defaultdict in at least this case.
from collections import defaultdict
count = defaultdict(int)
for character in message:
count[character] += 1
A defaultdict is constructed with a no argument function which creates an instance of whatever default value should be. If a key is not there then this function provides a value for it and inserts the key, value in the dictionary for you. Since int() returns 0 it is initialized correctly in this case. If you wanted it initialized to some other value, n, then you would do something like
count = defaultdict(lambda : n)
I am using the same textbook and I had the same problem. The answers provided are more sophisticated than the example in question, so they don't actually address the issue: the question above is - how does the code understand that it should count the number of occurrences. It turns out, it doesn't really "count". It just keeps changing the values, until it stops. So here is how I explained it to myself after a long and painful research:
message='It was a bright,\
cold day in April,\
and the clocks were \
striking thirteen.'
count={} # "count" is set as an empty dictionary, which we want to fill out
for character in message: # for each character, do the following:
count.setdefault(character,0) # if the character is not there,
# take it from the message above
# and set it in the dictionary
# so the new key is a letter (e.g. 'a') and value is 0
# (zero is the only value that we can set by default
# otherwise we would gladly set it to 1 (to start with the 1st occurrence))
# but if the character already exists - this line will do nothing! (this is pointed out in the same book, page 110)
# the next time it finds the same character
# - which means, its second occurrence -
# it won't change the key (letter)
# But we still want to change the value, so we write the following line:
count[character]=count[character]+1 # and this line will change the value e.g. increase it by 1
# because "count[character]",
# is a number, e.g. count['a'] is 1 after its first occurrence
# This is not an "n=n+1" line that we remember from while loops
# it doesn't mean "increase the number by 1
# and do the same operation from the start"
# it simply changes the value (which is an integer) ,
# which we are currently processing in our dictionary, by 1
# to summarize: we want the code to go through the characters
# and only react to the first occurence of each of them; so
# the setdefault does exactly that; it ignores the values;
# second, we want the code to increase the value by 1
# each time it encounters the same key;
# So in short:
# setdefault deals with the key only if it is new (first occurence)
# and the value can be set to change at each occurence,
# by a simple statement with a "+" operator
# the most important thing to understand here is that
# setdefault ignores the values, so to speak,
# and only takes keys, and even them only if they are newly introduced.
print(count) # prints the whole obtained dictionary
answer by #egon is very good and it answers the doubts raised here. I just modified the code little bit and hope it will be easy to understand now.
message = 'naga'
count = {}
for character in message:
count.setdefault(character,0)
print(count)
count[character] = count[character] + 1
print(count)
print(count)
and the output will be as follows
{'n': 0} # first key and value set in count
{'n': 1} # set to this value when count[character] = count[character] + 1 is executed.
{'n': 1, 'a': 0} # so on
{'n': 1, 'a': 1}
{'g': 0, 'n': 1, 'a': 1}
{'g': 1, 'n': 1, 'a': 1}
{'g': 1, 'n': 1, 'a': 1}
{'g': 1, 'n': 1, 'a': 2}
{'g': 1, 'n': 1, 'a': 2}
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {} #This is an empty dictionary. We will add key-value pairs to this dictionary with the help of the following lines of code (The for-loop and its code block).
for character in message: #The loop will run for the number of single characters (Each letter & each space between the words are characters) in the string assigned to 'message'.
#That means the loop will run for 73 times.
#In each iteration of the loop, 'character' will be set to the current character of the string for the running iteration.
#That means the loop will start with 'I' and end with '.'(period). 'I' is the current character of the first iteration and '.' is the current character of the last iteration of the for-loop.
count.setdefault(character, 0) #If the character assigned to 'character' is not in the 'count' dictionary, then the character will be added to the dictionary as a key with its value being set to 0.
count[character] = count[character] + 1 #The value of the key (character added as key) of 'count' in the running iteration of the loop is incremented by one.
#As a result of a key's value being incremented, we can track how many times a particular character in the string was iterated.
#^It's because the existing value of the existing key will be incremented by 1 for the number of times the particular character is iterated.
#The accuracy of exactly how many times a value should be incremented is ensured because already existing keys in the dictionary aren't updated with new values by set.default(), as it does so only if the key is missing in the dictionary.
print(count) #Prints out the dictionary with all the key-value pairs added.
#The key and its value in each key-value pair represent a specific character from the string assigned to 'message' and the number of times it's found in the string, respectively.
I need to write a function that takes a a dictionary and a string as input, and returns the updated dictionary as follows:
>>> dct = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
>>> updateHand(dct, 'quail')
returns {'a':0, 'q':0, 'l':1, 'm':1, 'u':0, 'i':0}
I'm writing the following code, but I don't know somehow it mutates the dictionary ( it shouldn't ).
def updateHand(dct, s)
for char in s :
dct[char] = dct.get(char,0) - 1
return dct
I get the following message, when I run the above example:
Original dct was {'a': 1, 'i': 1, 'm': 1, 'l': 2, 'q': 1, 'u': 1}
but implementation of updateHand mutated the original hand!
Now the dct looks like this: {'a': 0, 'q': 0, 'u': 0, 'i': 0, 'm': 1, 'l': 1}
What is meant by mutating a dictionary ? And how do I overcome it ?
And on the side note, doesn't Python maintain random ordering of elements, like Java ?
Use the copy of the original dictionary using dict.copy:
def updateHand(dct, s)
dct = dct.copy() # <----
for char in s :
dct[char] = dct.get(char,0) - 1
return dct
What is meant by mutating a dictionary ?
The code changes the dictionary passed instead of returning new one.
And on the side note, doesn't Python maintain random ordering of elements, like Java ?
The insertion order is not maintained in dictionary.
This question already has answers here:
Why dict.get(key) instead of dict[key]?
(14 answers)
Closed 4 years ago.
sentence = "The quick brown fox jumped over the lazy dog."
characters = {}
for character in sentence:
characters[character] = characters.get(character, 0) + 1
print(characters)
I don't understand what characters.get(character, 0) + 1 is doing, rest all seems pretty straightforward.
The get method of a dict (like for example characters) works just like indexing the dict, except that, if the key is missing, instead of raising a KeyError it returns the default value (if you call .get with just one argument, the key, the default value is None).
So an equivalent Python function (where calling myget(d, k, v) is just like d.get(k, v) might be:
def myget(d, k, v=None):
try: return d[k]
except KeyError: return v
The sample code in your question is clearly trying to count the number of occurrences of each character: if it already has a count for a given character, get returns it (so it's just incremented by one), else get returns 0 (so the incrementing correctly gives 1 at a character's first occurrence in the string).
To understand what is going on, let's take one letter(repeated more than once) in the sentence string and follow what happens when it goes through the loop.
Remember that we start off with an empty characters dictionary
characters = {}
I will pick the letter 'e'. Let's pass the character 'e' (found in the word The) for the first time through the loop. I will assume it's the first character to go through the loop and I'll substitute the variables with their values:
for 'e' in "The quick brown fox jumped over the lazy dog.":
{}['e'] = {}.get('e', 0) + 1
characters.get('e', 0) tells python to look for the key 'e' in the dictionary. If it's not found it returns 0. Since this is the first time 'e' is passed through the loop, the character 'e' is not found in the dictionary yet, so the get method returns 0. This 0 value is then added to the 1 (present in the characters[character] = characters.get(character,0) + 1 equation).
After completion of the first loop using the 'e' character, we now have an entry in the dictionary like this: {'e': 1}
The dictionary is now:
characters = {'e': 1}
Now, let's pass the second 'e' (found in the word jumped) through the same loop. I'll assume it's the second character to go through the loop and I'll update the variables with their new values:
for 'e' in "The quick brown fox jumped over the lazy dog.":
{'e': 1}['e'] = {'e': 1}.get('e', 0) + 1
Here the get method finds a key entry for 'e' and finds its value which is 1.
We add this to the other 1 in characters.get(character, 0) + 1 and get 2 as result.
When we apply this in the characters[character] = characters.get(character, 0) + 1 equation:
characters['e'] = 2
It should be clear that the last equation assigns a new value 2 to the already present 'e' key.
Therefore the dictionary is now:
characters = {'e': 2}
Start here http://docs.python.org/tutorial/datastructures.html#dictionaries
Then here http://docs.python.org/library/stdtypes.html#mapping-types-dict
Then here http://docs.python.org/library/stdtypes.html#dict.get
characters.get( key, default )
key is a character
default is 0
If the character is in the dictionary, characters, you get the dictionary object.
If not, you get 0.
Syntax:
get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
If d is a dictionary, then d.get(k, v) means, give me the value of k in d, unless k isn't there, in which case give me v. It's being used here to get the current count of the character, which should start at 0 if the character hasn't been encountered before.
I see this is a fairly old question, but this looks like one of those times when something's been written without knowledge of a language feature. The collections library exists to fulfill these purposes.
from collections import Counter
letter_counter = Counter()
for letter in 'The quick brown fox jumps over the lazy dog':
letter_counter[letter] += 1
>>> letter_counter
Counter({' ': 8, 'o': 4, 'e': 3, 'h': 2, 'r': 2, 'u': 2, 'T': 1, 'a': 1, 'c': 1, 'b': 1, 'd': 1, 'g': 1, 'f': 1, 'i': 1, 'k': 1, 'j': 1, 'm': 1, 'l': 1, 'n': 1, 'q': 1, 'p': 1, 's': 1, 't': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1})
In this example the spaces are being counted, obviously, but whether or not you want those filtered is up to you.
As for the dict.get(a_key, default_value), there have been several answers to this particular question -- this method returns the value of the key, or the default_value you supply. The first argument is the key you're looking for, the second argument is the default for when that key is not present.