When to use list with sum in python - python-3.x

Here are two examples:
sum(list(map(lambda x:x,range(10))))
and
sum(range(10))
The second example does not require a list(), but the first one does. Why?
How do I know when is list() a necessity? Similarly using list() for min() and max().
I am running python 3.3.5 with ipython 2.2.0. Here is what I see:
print(sum) results in <built-in function sum> from python console and <function sum at 0x7f965257eb00> from ipythonNotebook. Looks like an issue with hidden imports in notebook.

Neither of the examples require the use of list. The sum builtin function works with any iterable, so converting the result of map to a list isn't necessary.
Just in case, make sure you are indeed using the builtin sum function. Doing something like from numpy import * would override that. (you can simply print sum and see what you get).

I guess the 1st one just enforces and expects the output of the map function to be a list because if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables.
But either way base on your example, it would still work.

Related

How to initilise a list that contains custom functions without python running those functions during initialisation?

Short version:
How do you store functions in a list and only have them be executed when they are called using their index position in the list?
Long Version:
So I am writing a program that rolls a user-chosen number of six-sided dice, stores the results in a list and then organizes the results/ data in a dictionary.
After the data is gathered the program gives the user options from 0-2 to choose from and asks the user to type a number corresponding to the option they want.
After this input by the user, a variable, lets say TT, is assigned to it. I want the program to use TT to identify which function to run that is contained within a list called "Executable_options" by using TT as the index posistion of this function within the list.
The problem I am having is that I have to have the list that contains the functions on a line after the functions have been defined and when I initialize the list it goes through and executes all functions within it in order when I don't want it to. I just want them to be in the list for calling at a later date.
I tried to initialise the list without any functions in and then append the functions individually, but every time a function is appened to the list it is also executed.
def results():
def Rolling_thunder():
def roll_again():
The functions contains things, but is unnecessary to show for the question at hand
Executable_options = []
Executable_options.append(results())
Executable_options.append(Rolling_thunder())
Executable_options.append(roll_again)
options = len(Executable_options)
I am relatively new to Python so I am still getting my head around it. I have tried searching for the answer to this on existing posts, but couldn't find anything so I assume I am just using the wrong key words in my search.
Thank you very much for taking the time to read this and for the answers provided.
Edit: Code now works
The () on the end of the function name calls it - i.e. results() is the call to the results method.
Simply append to the list without the call - i.e:
Executable_options.append(results)
You can then call it by doing e.g.:
Executable_options[0]()
as per your given data the code will look like this:
def results():
def Rolling_thunder():
def roll_again():
Executable_options = []
Executable_options.append(results)
Executable_options.append(Rolling_thunder)
Executable_options.append(roll_again)
for i in range(0,len(Executable_options)):
Executable_options[i]()
this will work for you.

np.std change ddof within groupby

I was running a manual (I wrote a function) std dev versus numpy's built in.
There was a slight difference in the returned values.
I looked it up and numpy uses ddof=0 by default.
I am trying to figure out how to pass that within a groupby and I am failing.
My groupby is simply this: grouped = houses.groupby('Yr Sold').agg({'SalePrice': np.std})
If I use: np.std(ddof=1) it errors out saying I am missing the required positional argument 'a'.
I looked that up and I see what it is, but it seems to me that 'a' is my 'SalePrice' column.
I have tried a few different ways but every single thing I try results in a syntax error.
Using the groupby syntax above, how do I pass the ddof=1 parameter to adjust numpy's default behavior?
I figured out how to solve my problem, just not by directly using the syntax above.
std_dev_dict = {}
for id, group in houses.groupby('Yr Sold'):
std_dev_dict[id] = np.std(group['SalePrice'], ddof=1)
print(std_dev_dict)

modgrammar import lists to use as disjunct literals?

I'd like to be able to have files that contain lists of terms that I can read and use in a modgrammar grammar, but OR() doesn't work on a Python list as far as I can tell...
from modgrammar import *
with open(termfile) as f:
terms = [x.strip() for x in f.readlines()]
class SomeGrammar(Grammar):
grammar = (OR(terms))
Trying to parse strings that begin with anything but the first term in the list throws an exception. Is there a way to do this cleanly?
Modgrammar will interpret a list as a series of terms to match in order, so OR(terms) is interpreted as "match these in order OR (nothing else)", which isn't what you're looking for.
Fortunately, Python has a built-in syntax to take a list and pass it as multiple arguments for a function (like OR). You should be able to use OR(*terms) to do what you want instead.

Zip Function without using built in

I'm trying to create a function (without using a built in function) that turns this
([f,u,n],[1,2,3,4])
into this [(f,1),(u,2),(n,3)]
Basically taking the first element of both lists and turning them into a tuple, then the second element of both lists, etc.
I have this so far:
>> def zipup(lista,listb):
>> for x in range(len(lista)):
>>for y in range(len(listb)):
>>return [(lista[x],listb[y])]
But I keep getting this: [(f,1)]
Help?!
The error message is saying that the variable i is not defined, it is not even in the code snippet that you showed ... that a look at the line that the error shows.
As for the zip, take a look at the docs for the standard library for the izip, there is a equivalent python implementation that you can use as a guide.

How to format a flat string with integers in it in erlang?

In erlang, I want to format a string with integers in it and I want the result to be flattened. But I get this:
io_lib:format("sdfsdf ~B", [12312]).
[115,100,102,115,100,102,32,"12312"]
I can get the desired result by using the code below but it is really not elegant.
lists:flatten(io_lib:format("sdfsdf ~B", [12312])).
"sdfsdf 12312"
Is there a better formatting strings with integers in them, so that they are flat? Ideally, using only one function?
You flatten a list using lists:flatten/1 as you've done in your example.
If you can accept a binary, list_to_binary/1 is quite efficient:
1> list_to_binary(io_lib:format("sdfsdf ~B", [12312])).
<<"sdfsdf 12312">>
However, question why you need a flat list in the first place. If it is just cosmetics, you don't need it. io:format/1,2,3 and most other port functions (gen_tcp etc) accept so called deep IO lists (nested lists with characters and binaries):
2> io:format([115,100,102,115,100,102,32,"12312"]).
sdfsdf 12312ok
There is an efficiency reason that io_lib:format returns deep lists. Basically it saves a call to lists:flatten.
Ask yourself why you want the list flattened. If you are going to print the list or send it to a port or write it to a file, all those operations handle deep lists.
If you really need a flattened list for some reason, then just flatten it. Or you can create your own my_io_lib:format that returns flattened lists if you think it important.
(If you only want to flatten the list for debugging reasons then either print your strings with ~s, or create a flattener in an erlang module named user_default. Something like this:
-module(user_default).
-compile(export_all).
%% either this:
fl(String) ->
lists:flatten(String).
%% or this:
pp(String) ->
io:format("~s~n", [String]).
Then you can use fl/1 and print/1 in the Erlang shell (as long as user_default.beam is in your path of course).)

Resources