Practical programming


I have a bicycle. It is currently attached to my balcony railing with a combination lock/cable. It has been there for a while. The weather is nice now and I want to go for a ride, but I have forgotten the combination to the lock. So today I was playing around with the lock, trying to remember the combination. I’m pretty sure it had a 1 and a 4 in it. The combination is four digits long, and the digits can be any number from 1 to 6. So I was thinking I might have to try new combinations one by one until I found the right one. How many combinations could there be? Well, I could do the math, 6*6*6*6 = 1296 possible combinations. But that doesn’t really illustrate to me the reality of fiddling around with that thing. “What a great opportunity to write a program,” I thought. So I wrote a Python program to show me a list of all the possible combinations. It was very simple. Here it is:

combos.py   
x = 0
for a in range (0, 6):
    for b in range (0, 6):
        for c in range (0, 6):
            for d in range (0, 6):
                print a+1, b+1, c+1, d+1
                x = x+1
print "There are",x,"possible combinations."

How it works

First we give a value of 0 to the variable x. Then we set up 4 for loops, a through d, with each successive one inside the next. We let them run from 0 to 6. Inside the fourth loop, we tell Python to print the value that each loop is on in that particular cycle. We add 1 to the value of x to keep track of how many possible combinations there are. After all the loops are executed, we print a sentence telling us what the value of x is. That’s all there is to it! Now, write a comment in the comments section.

Related posts:

  1. Working on the bike problem with Python
  2. Programming with Python
  3. The bike saga continues
  4. Keep it simple
  5. Python Sudoku solver

2 thoughts on “Practical programming

  1. Without knowing the python language, it seems to me you should be looping from 0 to 5 to provide 6 possibilities for each position.

  2. With Python, the first value of a for loop is inclusive and the second value is exclusive, so you have to set up your loops to be one extra than the intuitive value. I reckon I could have set the values of the loop as 1 to 7, and I could just print a, b, c, d without the +1′s. But I’m used to starting loops at 0, so I stuck with it.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>