Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this piece of code doing, python

I am self learning python and I was doing an exercise, the solution to which was posted in this thread. Could anyone translate into english what this piece of code means? When I learned if statements I never came across this syntax.

 consonants = 'bcdfghjklmnpqrstvwxz'
 return ''.join(l + 'o' + l if l in consonants else l for l in s)
like image 486
Aeleon Avatar asked May 03 '15 00:05

Aeleon


People also ask

What is a code object in Python?

Code objects are a low-level detail of the CPython implementation. Each one represents a chunk of executable code that hasn’t yet been bound into a function. Though code objects represent some piece of executable code, they are not, by themselves, directly callable.

Is Python interpreted or compiled?

Conditional Statements Exception Handling Dictionaries Modules Taking Input From The User Download and Install Python Python is a interpreted language which means that the code is translated (interpreted) to binary code while the program runs. That is different from compiled languages (C++ etc.) where the code is first compiled to binary code.

What is Python interpreter?

Taking Input From The User Download and Install Python Python is a interpreted language which means that the code is translated (interpreted) to binary code while the program runs. That is different from compiled languages (C++ etc.) where the code is first compiled to binary code. To run Python code you need to have a Python interpreter.

What are list comprehensions in Python and how to use them?

List comprehensions in Python are super helpful and powerful. They reduce the code length to a great length and make it more readable. In the following code, we can see that we are checking multiples of 6, and then multiples of 2 and 3 using the if-else conditions inside the list, which reduced the code to a great extent.


1 Answers

It's a longer piece of code, written as a generator. Here is what it would look like, more drawn out.

consonants = 'bcdfghjklmnpqrstvwxz'

ls = []
for l in s:
    if l in consonants:
        ls.append(l + 'o' + l)
    else:
        ls.append(l)

return ''.join(ls)

It loops through s and checks if l is in the string consonants. If it is, it pushes l + 'o' + l to the list, and if not, it simply pushes l.

The result is then joined into a string, using ''.join, and returned.

More accurately (as a generator):

consonants = 'bcdfghjklmnpqrstvwxz'

def gencons(s):
    for l in s:
        if l in consonants:
            yield l + 'o' + l
        else:
            yield l

return ''.join(gencons(s))

Where gencons is just a arbitrary name I gave the generator function.

like image 51
Zach Gates Avatar answered Oct 23 '22 05:10

Zach Gates