lilzz
Posts: 411
Joined: Sat Nov 30, 2013 5:27 pm

How does the following codes do

Fri Jul 31, 2015 11:14 pm

Code: Select all

for x in range(1, self.max_x):
            for y in range(1, self.max_y):
                if x in (3, 10):
                    if y % 2 == 1:
                        self.b_tiles[(x, y)] = ["0" * 42 for i in range(16)]
                    else:
                        self.t_tiles[(x, y)] = ["0" * 42 for i in range(16)]
                else:
                    self.l_tiles[(x, y)] = ["0" * 54 for i in range(16)]
1)What's "0"*42 for i in range(16)?

Code: Select all

 match = re.match(r"input(\d)_(\d)", netname)
2)Why need to have 2 (\d)?

Code: Select all

 netname="ram/ADDR_%d" % (idx1*4 + idx2)
3)What's the 2 nd purpose of %?

Code: Select all

import re, sys
match = re.match(r"ram/DATA_(\d+)", netname)
4)what's the difference between (\d+) and (\d)?
5)What's re.match?

ghp
Posts: 1498
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: How does the following codes do

Sat Aug 01, 2015 5:02 am

Hello,
many questions.
(1) "0"*42 just builds a string of 42 zeroes. And the trailing for statement builds 16 elements of this. Note the [] brackets around this. When I find expressions like this, I pack them in a print statement and execute.

Code: Select all

print ( ["0" * 4 for i in range(3)] )
['0000', '0000', '0000']
I reduced the number of repeats to make it a little bit shorter.

(5) re is a package in python which handles 'regular expressions'. It provides some functions like re.match() or re.find(). The re.match() is a very powerful string function, which allows to find out whether a certain string matches a pattern. See https://docs.python.org/2/library/re.html for some explanation. It uses the r"something" as a first parameter, which describes the pattern, and a second string which is checked whether it matches the pattern or not.

(4) patterns describe the data you want to check. The '\d' is for "one digit". But sometimes there are multiple digits needed. The '+'-sign after a char, escape sequence or group says 'match at least one or more'. As the brackets () also are special characters in this syntax, the pattern r"ram/DATA_(\d+)" would match "ram/DATA_1", "ram/DATA_000" and all other combinations like this. But not "ram/DATA_ABC" (and of course not "cookie").

(2) With answer(4), you will see that r"input(\d)_(\d)" matches something like "input2_4".

(3) the Percent sign between Strings is a 'insert the following data into the formatting definitions of the string left". In first String is a %d, and at runtime the code formats the value of (idx1*4 + idx2) as a decimal.

Code: Select all

print ( "ram/ADDR_%d" % 23 )
ram/ADDR_23
Regards,
Gerhard

Return to “Python”