Archive

Posts Tagged ‘trick’

Sum the digits of a number until you get just one digit

Problem

Take a positive integer and sum its digits. Repeat this process until you get just one digit.

Example: 1472 🠖 1+4+7+2 = 14 🠖 1+4 = 5. The answer is 5.

Solution

# Python code
n = 1472
result = ((n-1) % 9) + 1

Credits

Thanks to my friend Mocsa who told me this math trick.

Categories: python Tags: , ,

creating a list of strings

February 5, 2017 1 comment

Have you aver written something like this?

>>> li = ["one", "two", "three", "four"]
>>> li
['one', 'two', 'three', 'four']

When I type in all those quotation marks and commas, I always feel sorry for my finger joints. Is there an easier way? Yes, there is:

>>> li = "one two three four".split()
>>> li
['one', 'two', 'three', 'four']
Categories: python Tags: ,

Print unicode text to the terminal

September 2, 2012 2 comments

Problem
I wrote a script in Eclipse-PyDev that prints some text with accented characters to the standard output. It runs fine in the IDE but it breaks in the console:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 11: ordinal not in range(128)

This thing bugged me for a long time but now I found a working solution.

Solution
Insert the following in your source code:

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

I found this trick here. “This allows you to switch from the default ASCII to other encodings such as UTF-8, which the Python runtime will use whenever it has to decode a string buffer to unicode.”

Related

Categories: python Tags: , , , ,