Lesson 2 - part C


Working Program

Firstly, what kind of inputs do we want to have for this program? Let's see. We would like to have an input statement to take in the string which we will produce a list of anagrams for. Secondly, we would like to choose the rows and columns for the table.

word = input(“Enter a word: “)

tablerow = int(input(“Enter the row: “))

tablecolumn = int(input(“Enter the column: “))

We just have to use three different input statement for different inputs.



Mountain View


If you think that this is a complete working program. Think again. There are a few improvement that can done on this program. Let's say you put in a string with 4 unique characters. Then, you type 5 as your row and 10 as your column. What do you see? An error! What happened?

Relax. What happened was that the program was trying to remove an element from an emptylist. This happened because the number of time of removal of element is more than original number of empty list.

In this case, the program was supposed to remove one element in each time column loop 50 times. But there are only 24 numbers of string in the list. So, how do we solve this problem?

Well, we can just use a if statement to determine whether the list is empty. If yes, then we end the function. Look at the code below.



if len(words) == 0:

return

This return statement return nothing. Sounds weird right? But this is the way return statement work. It could return anything. A list, a string, an integer, a function or even nothing at all. So return statement can be used to stop a function once a certain condition is met. In this case we say that is the number of element in the list words is 0, then stop the function. That way, we wouldn't not remove an element from an empty list.

The next question is where do we placed this piece of code. We can place it in a few places. I personally prefer to place it directly after the words.pop(0) statement. So, what will happen is that every time after the program remove an element from the list words, it will check whether there's any element left. If yes, then continue with the program. If there's no more element, then the function is stopped using the return statement.

This is the not only flaw of this program. There are a few more flaws. One of the main flaws is that when the input string have more than 7 or 8 characters, the program works in a very slow rate. However, this is an unavoidable issue. The only way is to use a totally different algorithm to solve this problem.

I will let you try out the code and find out the flaws by yourself. Who knows? You may find some other flaws that I do not know about.


Go to Lesson 3

Back to Lesson 2 Part B

Back to Index