![]() ![]() Revised code def random_ints_with_sum(n): (And if you need a list, it's trivial to build one, by passing your generator to the function list.)Ģ. It's often convenient to process these items one by one, and a generator function allows you to do this without having to construct an intermediate list in memory. When you're writing a function that produces a sequence of items, it's usually a good idea in Python to make it into a generator function that yields the items one by one (rather than a normal function that builds and returns a list of all the items). The Python style guide (PEP8) says, "Avoid extraneous whitespace immediately before a comma, semicolon, or colon." (So use sort or multiply, rather than sorter or multiplier.) (iii) "Generator" has a specialized meaning in Python (referring to a generator), so best not to use it unless that's what you mean. (ii) If you're going to name a function after its action, use the imperative form of the verb. ![]() You could choose a better name for the function than generater_random_list. What does this function do and how do you call it? ![]() Python allows you just to write return as a shorthand for return None if you really have nothing worth returning, but here you do have something to return, namely the list of random numbers you just constructed. (The caller could set rand_list = before the second call to generater_random_list, but it would be really annoying to have to keep remembering to do that.)Īnd second, what's the point of returning 0? That's no use to anyone. First, if you call generater_random_list twice, rand_list now contains the concatenation of the first and second lists: > generater_random_list(10) This is a poor design of interface for two reasons. The function stores its results in the global variable rand_list and always returns 0. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |