import this
The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
The operator for exponentiation is two astericks - **
.
a = 3
b = 5
print a**2 + b**2
34
Notice how we can assign multiple values to variables at the same time.
Since the problem says 'inclusively', we need to add 1 to the slice end points.
s = 'HumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheKingsmenCouldntputHumptyDumptyinhisplaceagain.'
a, b, c, d = 22, 27, 97, 102
print s[a:b + 1] + ' ' + s[c:d + 1]
Humpty Dumpty
Again, the word 'inclusively' means we need to add 1 to the range
end point.
a, b = 100, 200
total = 0
for i in range(a, b + 1):
if i % 2 == 1:
total += i
print total
7500
A more experienced Python programmer might use a generator expression.
sum(i for i in range(a, b + 1) if i % 2 == 1)
7500
Strings have a split()
method that splits the string at any whitespace and returns a list of the resulting pieces.
s = 'We tried list and we tried dicts also we tried Zen'
counts = {}
for word in s.split():
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
for word in counts:
print word, counts[word]
and 1 We 1 tried 3 dicts 1 Zen 1 list 1 we 2 also 1
A more experienced Python programmer might use a special kind dictionary object from the collections
module called Counter
.
from collections import Counter
counts_two = Counter(s.split())
Let's check that this gives the same answer as the other way.
print counts == counts_two
True