0

The loop variant is supposed to be a strictly decreasing natural number, defined by the arguments in the loop. I find it a bit difficult in python since the index isn't used. For example, what is the loop variant in the below sentence?

P = [int(x) for x in list('{0:b}'.format(12))]
2
  • any pointer on the web to what you call "loop variant" ? I didn't find anything for python Commented Nov 13, 2013 at 11:30
  • en.wikipedia.org/wiki/Loop_variant Commented Nov 13, 2013 at 11:41

3 Answers 3

1

I think your definition is overly restrictive; not all loops have a numeric loop variant in the language they're written in, certainly not necessarily a decreasing one. In your example, x is a loop variant, but not in the form you seek.

Under the covers, there is an index into the string representing the binary form of 12, and it will vary from 0 to 3. So the loop variant, in the sense of your linked Wikipedia article, would be a function that subtracts that index from 3.

Sign up to request clarification or add additional context in comments.

2 Comments

What does it mean that it's overly restrictive?
Yes that I know, but am I supposed to add index to the for loop just to be able to describe the loop variant?
1

In order to understand you need to decompose.

Binary representation of 12

format allows you to give the binary representation of 12:

>>> '{0:b}'.format(12)
'1100'

You could also use bin but '0b' is append at the beginning:

>>> bin(12)
'0b1100'

However, you could write bin(12)[2:] (as suggested in another answer).

Iteration over a string

You can iterate over each character of a string using a loop by doing:

for x in '1100':

The x in this for loop will take the successive characters of the string: '1', '1', '0', '0'.

List comprehension

And finally, [... for x in ...] is a list-comprehension. That will create a new list using the for.

[int(x) for x in '1100']

is equivalent to:

list(map(int, '1100'))

and:

list(map(int, ['1', '1', '0', '0']))

or:

l = []
for x in '1100':
    l.append(int(x))

Loop variant?

Your question is actually: what is the loop variant here?

Well, in Python, the for is in fact more a foreach. Let's take as an example for x in [3, 2, 10]. x will successively take the values 3, 2 and 10.

If we want something close to the C-style for-loop:

// C for-loop:
for (int i = 0; i < 10; i++)

We write:

# Python for-loop:
for i in range(10):

range(10) returns something iterable and i will take the successive values given by range.

Back to your example, there is no "loop variant" but if you need one, you can use enumerate:

for i, x in enumerate('1100'):
    print(i, x)

Will give:

(0, '1')
(1, '1')
(2, '0')
(3, '0')

2 Comments

Using map() will actually solve my problem since I don't have to use a for loop :). Do you know the worst time complexity of map?
I think map will be faster in that specific case (not function call, only a cast to int). However, I think that list-comprehension is becoming the recommended way of doing it.
1

It's called a list-comprehension.

And what you are doing can be written as:

P = []
for x in list('{0:b}'.format(12)):
    P.append(int(x))

It seems that the code formats the number 12 into binary (1100) and then each character is turned into an integer and added to P.


You can do this much easier by using the bin() builtin:

>>> map(int, bin(12)[2:])  # in Python 3+ call list() on the map
[1, 1, 0, 0]

bin(12)[2:] is much faster than "{0:b}".format(12) - Timing:

>>> timeit.Timer('bin(12)[2:]').repeat()
[0.19629462759158045, 0.15594946498989515, 0.1560687067152564]
>>> timeit.Timer('"{0:b}".format(12)').repeat()
[0.45589523752218497, 0.4375863126642727, 0.43800530974230867]

5 Comments

I don't see how bin(12)[2:] is easier than '{0:b}'.format(12). (but it's good to give that other alternative)
Check the timing, it is between 2 and 3 times faster.
That's an excellent point! Also, you may want to add a list() around your map for Python3.
Who said we are using Python3?
list(map(...)) will work for both Python2 and Python3. It's time to write code that will work on both when possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.