I’m in an introductory Python course. I’m taking a practice final and I don’t know exactly what to do for a question. It asks:
Complete the following method that places odd numbers found in the string s in consecutive elements of the list x.
def assign(s):
length = _____
x = _____*[0]
index = 0
for j in range(_____):
digit = int(s[j]) #convert to int digit
if _____: #test for odd number
x[_____] = digit
__________
print("The odd numbers are")
for j in range(index):
print(x[j])
I don’t know if it’s the way it’s worded but I have no clue how to go about answering this. My best guess would be:
def assign(s):
length = len(s)
x = length*[0]
index = 0
for j in range(s):
digit = int(s[j]) #convert to int digit
if _____: #test for odd number
x[_____] = digit
__________
print("The odd numbers are")
for j in range(index):
print(x[j])
I have no clue how to continue, or if I’m even starting it off right. I can’t change anything that’s already there, I can only fill in the blanks, and they all have to be filled in. Anyone know how to do this?
Here is the solution:
You got the beginning right. An key point is that variable
indexpoints to the next odd number that should be added to listx.Note, however, that the template that was provided to you is horrible: it completely goes against the spirit of Python. It looks like C code forced into Python; this is not good practice, as Python offers much more powerful data structures than C. Here is a Pythonic version:
The main difference is that you have fewer variables: the code is more legible, one has to keep fewer variables in mind when reading the code. The variables that have disappeared are essentially indexes: they are often not needed (indexes are important in C because C is “close to the metal”: it is close to machine language, which requires indexes). As a consequence, the need for keeping track of the
lengthof the input string disappears.You also have less cruft: in the original version, list
xcontained many0that were essentially useless (slower code, which is also harder to make sense of). Essentially, Python listxwas forced to be like a C array: the variable number of odd digits in the string call for a list (variable size), not for an array (fixed size).Also, the fact that the code is shorter makes is faster to read, and to write!
As suggested by Jon, an even more Pythonic version consists in using list comprehensions:
This is a good example of why Python code is so much faster to write and read than C code.