기본 콘텐츠로 건너뛰기

Word reversing Iterator implemented by Generator(yield)

def reverse(data):
    for index in range(len(data)-1, -1, -1):
    # repeat as many as the length of data,    # decrement -1 each time till the index becomes -1    #since index starts with 0        yield data[index]

for char in reverse('gold'):
    print(char)



Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data. Each time next() is called on it, the generator resumes where it left off (it remembers all the data values and which statement was last executed). An example shows that generators can be trivially easy to create.

Anything that can be done with generators can also be done with class-based iterators as described in the previous section. What makes generators so compact is that the __iter__() and __next__() methods are created automatically.

Another key feature is that the local variables and execution state are automatically saved between calls. This made the function easier to write and much more clear than an approach using instance variable like self.index and self.data

In addition to automatic method creation and saving program state, when generators terminate, they automatically raise StopIteration. In combination, these features make it easy to create iterators with no more effort than writing a regular function.

9.10. Generator Expressions

Some simple generators can be coded succinctly as expressions using a syntax similar to list comprehensions but when parantheses instead of square brackets. These expressions are designed for situations where the generator in used right away by an enclosing function. Generator Expressions are more compact but less versatile than full generator definitions and tend to be more memory friendly than equivalent list comprehensions.


#the sum() adds the items of an ITERABLE and returns the sum(it is numeric data typed.)


# print(sum(i*i for i in range(10)))
# print(type(sum(i*i for i in range(10))))# previous line returns int
xvec = [10, 20, 30]
yvec = [7, 5, 3]
print(sum(x*y for x,y in zip(xvec, yvec)))

댓글

이 블로그의 인기 게시물

JS 5.5 task6 Create an extendable calculator

<HTML>   <body>   </body>   <script> function Calculator() {   let methods = {     "-" : (a, b) => a - b,     "+" : (a, b) => a + b   };   //methods is an object which keeps key for operators   //and value to return the actual operation values   //each returns the result of operation that key(operator) does   this.calculate = function (str){     //calculate is one element in the function Calculator     //it takes the string and returns the value     //in the function element list is delimeted by , not ;     let split = str.split(" "),     a = +split[0],     op = split[1],     b = split [2]     if(!methods[op] || isNaN(a) || isNaN(b)) {       return NaN; // error handling     }     return methods[op](a,b);   }   this.addMethod = function(name, func){     methods[name] = func;     //this is how to add new key and ele to object   } } let powerCalc = new Calculator; powerCalc.addMethod("*&

JS 5.7 task5 Store read dates

<HTML>   <body>   </body>    <script>    let messages = [        {text: "Hello", from: "John"},        {text: "How goes?", from: "John"},        {text: "See you soon", from: "Alice"}    ];    let readMap = new WeakMap();    alert(readMap.size);    readMap.set(messages[0], new Date(2019, 3, 5));   </script> </HTML> <!-- task4 needed weakSet to save simply readmessage, this task needs to save THE TIME IT WAS READ along with the message itself the message out of the set or map means it hasn't been read I kinda feel good and bad at the same time to happen to read the solution but I do get to think more about the difference with tasks and be more available to understand the main contents so I think, its good? -->

How to set base url when deployed in Heroku? : base url and axios

https://stackoverflow.com/questions/47164330/axios-api-calls-in-heroku/47165888 baseUrl = process.env.baseURL || "http://localhost:5000" Even more stable way https://stackoverflow.com/questions/52129849/how-to-get-the-base-url-variable-on-a-deployed-heroku-node-app const production  = 'https://examplePage.com'; const development = 'http://localhost:3000/'; const url = (process.env.NODE_ENV ? production : development); process.env.NODE_ENV will resolve to undefined if you are running on localhost production mode. and return production if you have deployed the app production mode.