Learn Python and Algorithm Using TopCoder - 2(KiwiJuiceEasy)

Hong Sun
Hong Sun
Aug 9, 2017 · 2 min read

Today we will continue the “KiwiJuiceEasy”. There are many ways to solve this problem but I will show you two similar ways and one python TIP. (I suppose you have thought about this practice problem for solving.)

Problem StatementTaro has prepared delicious kiwi fruit juice. He poured it into N bottles numbered from 0 to N-1. The capacity of the i-th bottle is capacities[i] liters, and he poured bottles[i] liters of kiwi juice into this bottle. Now he wants to redistribute juice in the bottles. In order to do this, he will perform M operations numbered from 0 to M-1 in the order in which he will perform them. For the i-th operation, he will pour kiwi juice from bottle fromId[i] to bottle toId[i]. He will stop pouring when bottle fromId[i] becomes empty or bottle toId[i] becomes full, whichever happens earlier. Return an that contains exactly N elements and whose i-th element is the amount of kiwi juice in the i-th bottle after all pouring operations are finished.
  • Editor: you can change a language
  • After writing code, compile and test. Then you can check the result before submitting.
  • + Compile 👉 Submit 👉 Run System Tests

Code

I think that reading others’ code help me develop myself. If you think me, you read two code above and think the code compared to your code.


PYTHON TIP

This tip is from book EFFECTIVE PYTHON.(Item 11: Use zip to Process Iterators in Parallel) In our practice problem fromId and toId are related.

for i in range(len(fromId)):
juice_sum = bottles[fromId[i]] + battles[toId[i]]
...

This code’s problem is that this whole loop statement is visually noisy.(EFFECTIVE PYTHON-Brett Slatkin)

for f,t in zip(fromId, toId):
juice_sum = bottles[f] + battles[t]
...

Zip function makes an iterator aggregates elements from each of the iterables.(more detail) There are two problems with this function. First, in python2 zip is not a generator, so this could use a lot of memory and cause your program to crash.(but we used python3) Second, when the input iterators are of different lengths, the problem arises. If you aren’t confident that the lengths of the lists, consider using the zip_longest function from the itertools built-in module instead.


The next practice problem is InterestingParty. Let’s have a Party!


source

Brett Slatkin, EFFECTIVE PYTHON: 59 Specific Ways to Write Better Python
最强最速アルゴリズマ-養成講座 プログラミングコンテストTOPCODER攻略ガイド/高橋直大

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade