Category Archives: for loop

STARTING WITH PYTHON3 – The very beginning – part 5

Journal: uffmm.org,
ISSN 2567-6458, July 18-19, 2019
Email: info@uffmm.org
Author: Gerd Doeben-Henisch
Email:
gerd@doeben-henisch.de

CONTEXT

This is the next step in the python3 programming project. The overall context is still the python Co-Learning project.

SUBJECT

After a first clearing of the environment for python programming we have started with the structure of the python programming language, and in this section will continue dealing with the object type sequences and string and more programming elements are shown in a simple example of a creative actor.

Remark: for general help information go directly to the python manuals, which you can find associated with the entry for python 3.7.3 if you press the Windows-Button, look to the list of Apps (= programs), and identify the entry for python 3.7.3. If you open the python entry by clicking you see the sub-entry python 3.7.3 Manuals. If you click on this sub-entry the python documentation will open. In this documentation you can find nearly everything you will need. For Beginners you even find a small tutorial.

SZENARIO

For the further discussion of additional properties of python string and sequence objects I will assume again a simple scenario. I will expand the last scenario with the simple input-output actor by introducing some creativity into the actor. This means that the actor receives again either one word or sequences of words but instead of classifying the word according to some categories or instead of giving back the list of the multiple words as individual entities the actor will change the input creatively.
In case of a single word the actor will re-order the symbols of the string and additionally he can replace one individual symbol by some random symbol out of a finite alphabet.
In case of multiple words the actor will first partition the sequence of words into the individual words in a list, then he will also re-order these items of the list, will then re-order the letters in the words, and finally he can replace in every word one individual symbol by some random symbol out of a finite alphabet. After these operations the list is again concatenated to one sequence of words.
In this version of the program one can repeat in two ways: either (i) input manually new words or (ii) redirect the output into the input that the actor can continue to change the output further.
Interesting feature Cognitive Entropy: If the user selects always the closed world option then the set of available letters will not be expanded during all the repetitions. This reveals then after some repetitions the implicit tendency of all words to become more and more equal until only one type of word ‘survived’. This depends on the random character of the process which increases the chances of the bigger numbers to overrun the smaller ones. The other option is the open world option. This includes that in a repetition a completely new letter can be introduced in a single word. This opposes the implicit tendency of cognitive entropy to enforce the big numbers against the smaller ones.

How can this scenario be realized?

ACTOR STORY

1. There is a user (as executive actor) who can enter single or multiple words into the input interface of an assisting interface.
2. After confirming the input the assisting actor will respond in a creative manner. These creativity is manifested in changed orders of symbols and words as well as by replaced symbols.
3. After the response the user can either repeat the sequence or he can stop. If repeating then he can select between two options: (i) enter manually new words as input or (ii) redirect the output of the system as new input. This allows a continuous creative change of the words.
4. The repeated re-direction offers again two options: (i) Closed world, no real input, or (ii) Open world; some real new input

IMPLEMENTATION

Download here the python source code. This text appears as an HTML-document, because the blog-software does not allow to load a python program file directly.

stringDemo2.py

DEMOS

Single word in a closed world:

PS C:\Users\gerd_2\code> python stringDemo2.py
Single word = ‘1’ or Multiple words = ‘2’
1
New manual input =’1′ or Redirect the last output = ‘2’
1
Closed world =’1′ or Open world =’2′
1
Input a single word
abcde
Your input word is = abcde
New in-word order with worder():
ebaca
STOP = ‘N’, CONTINUE != ‘N’
y
Single word = ‘1’ or Multiple words = ‘2’
1
New manual input =’1′ or Redirect the last output = ‘2’
2
Closed world =’1′ or Open world =’2′
1
The last output was = ebaca
New in-word order with worder():
ccbaa
STOP = ‘N’, CONTINUE != ‘N’
y
Single word = ‘1’ or Multiple words = ‘2’
1
New manual input =’1′ or Redirect the last output = ‘2’
2
Closed world =’1′ or Open world =’2′
1
The last output was = ccbaa
New in-word order with worder():
ccccb
STOP = ‘N’, CONTINUE != ‘N’
y
Single word = ‘1’ or Multiple words = ‘2’
1
New manual input =’1′ or Redirect the last output = ‘2’
2
Closed world =’1′ or Open world =’2′
1
The last output was = ccccb
New in-word order with worder():
ccccc
STOP = ‘N’, CONTINUE != ‘N’

The original word ‘abcde’ has been changed to ‘ccccc’ in a closed world environment. If one introduces an open world scenario then this monotonicity can never happen.

Multiple words in a closed world

PS C:\Users\gerd_2\code> python stringDemo2.py
Single word = ‘1’ or Multiple words = ‘2’
2
New manual input =’1′ or Redirect the last output = ‘2’
1
Closed world =’1′ or Open world =’2′
1
Input multiple words
abc def geh
Your input words are = abc def geh
List version of sqorder input =
[‘abc’, ‘def’, ‘geh’]
New word order in sequence with sqorder():
def geh geh
List version of input in mcworder()=
[‘def’, ‘geh’, ‘geh’]
New in-word order with worder():
fef
New in-word order with worder():
hee
New in-word order with worder():
ege
New word-sequence order :
fef hee ege
STOP = ‘N’, CONTINUE != ‘N’
y
Single word = ‘1’ or Multiple words = ‘2’
2
New manual input =’1′ or Redirect the last output = ‘2’
2
Closed world =’1′ or Open world =’2′
1
The last output was = fef hee ege
List version of sqorder input =
[‘fef’, ‘hee’, ‘ege’]
New word order in sequence with sqorder():
fef fef ege
List version of input in mcworder()=
[‘fef’, ‘fef’, ‘ege’]
New in-word order with worder():
fff
New in-word order with worder():
fee
New in-word order with worder():
eee
New word-sequence order :
fff fee eee
STOP = ‘N’, CONTINUE != ‘N’
y
Single word = ‘1’ or Multiple words = ‘2’
2
New manual input =’1′ or Redirect the last output = ‘2’
2
Closed world =’1′ or Open world =’2′
1
The last output was = fff fee eee
List version of sqorder input =
[‘fff’, ‘fee’, ‘eee’]
New word order in sequence with sqorder():
eee fee fee
List version of input in mcworder()=
[‘eee’, ‘fee’, ‘fee’]
New in-word order with worder():
eee
New in-word order with worder():
eef
New in-word order with worder():
eee
New word-sequence order :
eee eef eee
STOP = ‘N’, CONTINUE != ‘N’
y
Single word = ‘1’ or Multiple words = ‘2’
2
New manual input =’1′ or Redirect the last output = ‘2’
2
Closed world =’1′ or Open world =’2′
1
The last output was = eee eef eee
List version of sqorder input =
[‘eee’, ‘eef’, ‘eee’]
New word order in sequence with sqorder():
eee eee eee
List version of input in mcworder()=
[‘eee’, ‘eee’, ‘eee’]
New in-word order with worder():
eee
New in-word order with worder():
eee
New in-word order with worder():
eee
New word-sequence order :
eee eee eee
STOP = ‘N’, CONTINUE != ‘N’

You can see that the cognitive entropy replicates with the closed world assumption in the multi-word scenario too.

EXERCISES

Here are some details of objects and operations.

Letters and Numbers

With  ord(‘a’) one can get the decimal code of the letter as ’97’ and the other way around one can translate a decimal number ’97’ in a letter with  chr(97) to ‘a’.  For ord(‘z’) one gets ‘122’, and then one can use the numbers to compute characters which has been used in the program to find random characters to be inserted in a word.

Strings and Lists

There are some operations only available for list-objects and others only for string-objects.  Thus to change and re-arrange a string directly is not possible, but translating a string in a list, then apply some operations, and then transfer the changed list back into a string, this works fine. Thus translate a word w into a list wl by wl = list(w) allows the re-order of these elements by appending: wll.append(wl[r]). Afterwords I have translated the list again in a string by constructing a new string wnew by concatenating all letters step by step: wnew=wnew+wl[i]. If yould try to transfer the list directly like in the following example, then you will get as a result again  list:

>> w=’abcd’
>>> wl=list(w)
>>> wl
[‘a’, ‘b’, ‘c’, ‘d’]
>>> wn=str(wl)
>>> wn
“[‘a’, ‘b’, ‘c’, ‘d’]”

Immediate Help

If one needs direct information about the operations which are possible with a certain object like here the string object ‘w’, then one can ask for all possible operation like this:

>> dir(w)
[‘__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__getnewargs__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mod__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rmod__’, ‘__rmul__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘capitalize’, ‘casefold’, ‘center’, ‘count’, ‘encode’, ‘endswith’, ‘expandtabs’, ‘find’, ‘format’, ‘format_map’, ‘index’, ‘isalnum’, ‘isalpha’, ‘isascii’, ‘isdecimal’, ‘isdigit’, ‘isidentifier’, ‘islower’, ‘isnumeric’, ‘isprintable’, ‘isspace’, ‘istitle’, ‘isupper’, ‘join’, ‘ljust’, ‘lower’, ‘lstrip’, ‘maketrans’, ‘partition’, ‘replace’, ‘rfind’, ‘rindex’, ‘rjust’, ‘rpartition’, ‘rsplit’, ‘rstrip’, ‘split’, ‘splitlines’, ‘startswith’, ‘strip’, ‘swapcase’, ‘title’, ‘translate’, ‘upper’, ‘zfill’]
>>>

In the case that ‘w’ is a sequence of strings/ words like w=’abc def’, then does the list operations be of no help, because one gets a list of letters, not of words:

>> wl2=list(w)
>>> wl2
[‘a’, ‘b’, ‘c’, ‘ ‘, ‘d’, ‘e’, ‘f’]

For the program one needs a list of single words. Looking to the possible operations with string objects with Dir() above, one sees the name ‘split’. We can ask, what this ‘split’ is about:

>>> help(str.split)
Help on method_descriptor:

split(self, /, sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string.

sep
The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.

This sounds as if it could be of help. Indeed, that is the mechanism I have used:

>> w=’abc def’
>>> w
‘abc def’
>>> wl=w.split()
>>> wl
[‘abc’, ‘def’]

Function Definition

As you can see in the program text the minimal structure of a function definition is as follows:

def fname(Input-Arguments):
     some commands
    [return VarNames]

The name is needed for the identification of the command, the input variables to get some values from the outside to work on and finally, but optionally, you can return the values of some variables back to the outside of the function.

The For-Loop

Besides the loop organized with the while-command there is the other command with a fixed number of repetitions indicated by the for-command:

for i in range(n):
commands

The operator ‘range()’ delivers a sequence of numbers from ‘0’ to ‘n-1’ and attaches these to the variable ‘i’. Thus the variable i takes one after the other all the numbers from range(). During one repetition all the commands will be executed which are listed after the for-command.

Random Numbers

In this program very heavily I have used random numbers. To be able to do this one has before this usage to import the random number library. I did this with the call:

import random as rnd

This introduces additionally an abbreviation ‘rnd’. Thus if one wants to call a certain operation from the random object one can write like this:

r=rnd.randrange(0,n)

In this example one uses  the randrange() operation from random with the arguments (0,n) this means that an integer random number will be generated in the intervall [0,n-1].

If-Operator with Combined Conditions

In the program you can find statements like

if opt==’1′ and opt2==’1′ and opt3==’1′:

Following the if-keyword you see three different conditions

opt==’1′
opt2==’1′
opt3==’1′

which are put together to one expression by the logical operator ‘and’. This means that all three conditions must simultaneously be true, otherwise this combined condition will not work.

Introduce the Import Module Mechanism

See for this the two files:

stringDemo2b.py
stringDemos.py

StringDemo2b.py is the same as stringDemo2.py discussed above but all the supporting functions are now removed from the main file and stored in an extra file called ‘stringDemos.py’ which works for the main file stringDemo2b.py as a module file. That this works there must be a special

import stringDemos as sd

command and at each occurence of a function call with functions from the imported module in the main module stringDemo2b.py one has to add the prefix ‘sd.’ indicating, that these functions are now located in a special place.

This import call does work only if the special path for the import module ‘stringDemos.py’ is visible to the python modulecall mechanisms. In this case the Path with the modul stringDemos.py is given as C:\Users\gerd_2\code. If one wants know what the actual path names are which are known to the python system one can use a system call:

>> import sys
>>> sys.path
>>> …

If the wanted path is not yet part of these given paths one can append the new path like this:

>> sys.path.append(‘C:\\Users\\gerd_2\\code’)

If this has all done rightly one can work with the program like before. The main advantage of this splitting of the main program and of the supporting functions is (i) a greater transparency of the main code and (ii) the supporting functions can now easily be used from other programs too if needed.

A next possible continuation you can find HERE.