We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
from collections import OrderedDict
d = OrderedDict()
for _ in range(int(input())):
item, space, quantity = input().rpartition(' ')
d[item] = d.get(item, 0) + int(quantity)
for item, quantity in d.items():
print(item, quantity)
from collections import OrderedDict
dct = OrderedDict()
for _ in range(int(input())):
i = input().rpartition(" ")
dct[i[0]] = int(i[-1]) + dct[i[0]] if i[0] in dct else int(i[-1])
for l in dct:
print(l, dct[l])
dct[i[0]] = int(i[-1]) + dct[i[0]] if i[0] in dct else int(i[-1])
B if A else C does a conditional evaluation: if A evaluates to truth, then the value of the expression is B, else it evaluates to C.
So what it's saying is: if i[0] (the name of the item) is a key in dct, then the value is int(i[-1]) + dct[i[0]]. If it is not a key in dct, then the value is int(i[-1])
if could still be used, but xpressed a bit shorter as
dct[i[0]] = int(i[-1]) + (dct[i[0]] if i[0] in dct else 0)
But DICT[SOMETHING] if SOMETHING in DICT else DEFAULT already has a function for it, because it happens so often: DICT.get(SOMETHING, DEFAULT)
line = ['banana', 'fries', '10']
line[:-1] returns the list upto the second last word ['banana', 'fries']
performing a join on it returns a string 'banana fries'
item maps to the name, which is a string
price maps to the price which is the last element in line, refered by line[-1]
There could be a problem. Suppose that the input were
Dancing___Monkeys___10
where each _ represents one space. You would getDancing_Monkeys as the item name, because the full split would get rid of all three spaces but you'd only put one back. rsplit(1) would get an item name of Dancing___Monkeys with three spaces.
get() returns the value associated with the key "item". If the key doesn't already exist, then it will return the "default" value (written on the right side of comma - 0) instead. So if it already exists, then it will add the previous price. Otherwise, it will add 0 to the new number.
it seems to form a tuple containing 3 parts:
1. the portion of string before the determined separator ( in this case the ' ' which is a space)
2. the determined separator itself
3. the portion of string after the determined separator
Based on the example, it seems like it will pick the separator that appeared last so in this case, it will choose the space before the integer :))
Hope I helped ans your qns lol
Traceback (most recent call last):
File "Solution.py", line 5, in
item,space,quantiy=input().rpartition(" ")
File "", line 1
BANANA FRIES 12
^
SyntaxError: invalid syntax
YOUR CODE IS GIVING THIS ERROR.CAN U PLZ TELL ME HOW TO REMOVE IT.
d.get(item,0) = means you have to search no(item) if you not get the the same no than 0 will be added. and if you get then it will be added in int(quantity)
I make 0 as a default case ..
you can also use orderdict if you can not mind it.
I tried printing d and d.items, the output looks the same but if i try to replace
for item, quantity in d.items():
to
for item, quantity in d:
it doesn't work.
Why?
This problem with Collections.OrderedDict() is instructive. I must say this is very useful for students. cheap CBD We all know the importance of maths in our education system. This section helps the students to learn maths in a very interesting way.
For this question, simple dictionary was fine. Because the items listed already in the order. OrderedDict will be usefull for other scenarios. rpartition helps me
When used rpartition and given sepererator as ' ', I know a tuple is created which also includes ' ', for instance BANANA FRIES 30, output will be ('BANANA FRIES', ' ', '30'), can someone explain why this does not appear in Ordered Dictonary?
Thanks! it worked! But why are we using rpartition? Why can't we use just input().split for item and quantity. The next input is anway in the next line and we are already using a for loop
Collections.OrderedDict()
You are viewing a single comment's thread. Return to all comments →
Just 7 lines:
me too but I think yours is more clear:
get() works much better.
can you please explain 5th line (if else on the same line)?
dct[i[0]] = int(i[-1]) + dct[i[0]] if i[0] in dct else int(i[-1])
B if A else C
does a conditional evaluation: if A evaluates to truth, then the value of the expression is B, else it evaluates to C.So what it's saying is: if
i[0]
(the name of the item) is a key in dct, then the value isint(i[-1]) + dct[i[0]]
. If it is not a key in dct, then the value isint(i[-1])
if
could still be used, but xpressed a bit shorter asdct[i[0]] = int(i[-1]) + (dct[i[0]] if i[0] in dct else 0)
But
DICT[SOMETHING] if SOMETHING in DICT else DEFAULT
already has a function for it, because it happens so often:DICT.get(SOMETHING, DEFAULT)
here is solution of problem Collections.OrderedDict() in python 2 and python 3 https://solution.programmingoneonone.com/2020/06/hackerrank-collections-ordereddict-problem-solution-python.html
here is problem solution in python programming. https://programs.programmingoneonone.com/2021/01/hackerrank-collections-ordereddict-solution-python.html
Updated solution is here
https://www.thecscience.com/2021/08/HackerRank-Collections.OrderedDict-in-python-problem-solution.html
this code is highly unreadble and way more complex than the answer needs to be. Will suggest people to avoid doing it this way
That's why I prefer clean, efficient and elegant solution which can be found here. Hackerrank OrderedDict clean solution
For easy solution and explanation please refer to this link. Have a good day https://codingsolutions4u.blogspot.com/2020/09/collections-ordereddict-hackerrank.html
For easy solution and explanation please refer to this link. Have a good day https://codingsolutions4u.blogspot.com/2020/09/collections-ordereddict-hackerrank.html
Found one critical bug, your site doesn't work in dark mode, thank me later
Your links don't work
rpartition is pretty handy. thanks
You can remove one more line by doing the print in 1 line:
No need for list inside of print, you can use a generator
Mera lauda
kitna bada h
from where u learn all thesae things bro
mera l****
lol
Nice coding!!
The print can be changed to:
[print(*i) for i in D.items()]
perhaps earning a variable:
lol i used re
import re; item,prize = re.split(r'\s+(?=\d+$)',input())
show off bro show off :P
I did pretty much the same but I didn't know about
rpartition
orrsplit
, so I went for this instead:me too, they are so geeky
bhag madharjaat
stop trying to be an asshole so hard. You are failing miserably.
please explain your code! or mention it here let me understand
line = ['banana', 'fries', '10'] line[:-1] returns the list upto the second last word ['banana', 'fries'] performing a join on it returns a string 'banana fries' item maps to the name, which is a string price maps to the price which is the last element in line, refered by line[-1]
bsdk pythojn docs me padh le
wah lauda tumne to bur me jhande gar diye
Randi kahana me paida hua h kya gali hi bakta h.....
There could be a problem. Suppose that the input were
Dancing___Monkeys___10
where each
_
represents one space. You would getDancing_Monkeys
as the item name, because the full split would get rid of all three spaces but you'd only put one back.rsplit(1)
would get an item name ofDancing___Monkeys
with three spaces.can anyone explain the 2nd line??
lst=input().split()
quantity=lst.pop()
item=' '.join(lst)
Sorry, can you explain how to use d.get(item,0)?
get() returns the value associated with the key "item". If the key doesn't already exist, then it will return the "default" value (written on the right side of comma - 0) instead. So if it already exists, then it will add the previous price. Otherwise, it will add 0 to the new number.
I could not understand use of space and can item as key can have space in it. It must be right as this is working perfectly. But
plz can u explain line by line
what rpartition does here?
http://python-reference.readthedocs.io/en/latest/docs/str/rpartition.html
it seems to form a tuple containing 3 parts: 1. the portion of string before the determined separator ( in this case the ' ' which is a space) 2. the determined separator itself 3. the portion of string after the determined separator
Based on the example, it seems like it will pick the separator that appeared last so in this case, it will choose the space before the integer :)) Hope I helped ans your qns lol
Thanks for rpartition, quite useful. Before it, I did:
After knowing learning about it, I arrived at pretty the same solution as you.
You can use simple unpacking for the item name like this:
how asterisk help to remove ....too many values to unpack this error
nice :D rpartition :))
You could use rsplit with limit 1 instead of rpartition.
same thing i thought
what d.get(item,0) does
+1 for
Get method is pretty awesome.
Can you please explain me this. I am new to python. I am unable to fathom the operations that are being performed here on tuples and dictionaries.
In your code of OrderedDict,
Can you tell me the work of** d.get(item, 0)**
Hey, can you plz tell why it is not taking first element as " " as we have no item with 9
superb way of thinking bro
why is 'space' used?
I don't get the "space" part?
can you please explain line 5 - d[item] = d.get(item, 0) + int(quantity)
I could not get "d.get(item, 0) " part
even working without OrderedDict no need to import collections
Could you please explain what is this line of code perfoming d[item] = d.get(item, 0) + int(quantity)
This get method returns the value for the given key, if present in the dictionary.
I made it in 6 :
can you please explai your code @jonmcclung
Try my method by using defaultdict
**from collections import*
a=defaultdict(list)
for q in range(int(input())):
item,space,quantiy=input().rpartition(" ")
a[item].append(int(quantiy))
for w,e in a.items():
print(w,sum(e))
**
Traceback (most recent call last): File "Solution.py", line 5, in item,space,quantiy=input().rpartition(" ") File "", line 1 BANANA FRIES 12 ^ SyntaxError: invalid syntax YOUR CODE IS GIVING THIS ERROR.CAN U PLZ TELL ME HOW TO REMOVE IT.
no men my code is perfectly working. i think you have make some type of the syntex error. Can you please send me your full code.
Great
can you explain line 5 ?
in line 5 you will append the item in the type of the list . if the item is same then the quantity will be added as a list of items .
and if the item is not same then then it will append the items as a simple list .
why have you used "space" identifier in 4th line
d[item] = d.get(item, 0) + int(quantity)
d.get(item,0) = means you have to search no(item) if you not get the the same no than 0 will be added. and if you get then it will be added in int(quantity)
I make 0 as a default case .. you can also use orderdict if you can not mind it.
yup,thanks for giving the suggestion
what is function of odereddict in this code, can anyone explain it??
good man
can u pls explain 5th line
I tried printing d and d.items, the output looks the same but if i try to replace for item, quantity in d.items(): to for item, quantity in d: it doesn't work. Why?
Can you please explain the 5th line !
can u please explain the function of _ in for loop
For _ in range(int(input())): '_' is just an placeholder variable.
This problem with Collections.OrderedDict() is instructive. I must say this is very useful for students. cheap CBD We all know the importance of maths in our education system. This section helps the students to learn maths in a very interesting way.
For this question, simple dictionary was fine. Because the items listed already in the order. OrderedDict will be usefull for other scenarios. rpartition helps me
When used rpartition and given sepererator as ' ', I know a tuple is created which also includes ' ', for instance BANANA FRIES 30, output will be ('BANANA FRIES', ' ', '30'), can someone explain why this does not appear in Ordered Dictonary?
In this case no need of orderdict, you have to print the output in the order of customers baught the item which is already in the order. Please refer the following link to get know about Ordered Dict https://docs.python.org/3/library/collections.html#collections.OrderedDict
rpartition(' ') whats this?
i.e It is spliting based on rightside occurance of string
use rplit instead of rpartition. this way you don't need to save space
Thanks! it worked! But why are we using rpartition? Why can't we use just input().split for item and quantity. The next input is anway in the next line and we are already using a for loop
genius!
Thanks bro, it helped me to learn about rpartition function and get func in dictinoary!