Strange behaviour of list.remove() - python-2.7

Consider the following piece of code.
def foo(a):
b = [a+9*i+j for i in xrange(0,3) for j in xrange(0,3)]
return b.remove(a)
The code doesn't work. It returns an null. But if I do the following, it works.
def foo1(a):
return [a+9*i+j for i in xrange(0,3) for j in xrange(0,3)]
b = foo1(a)
b = b.remove(a) # This works
Why does the first snippet fail when the second one works?

.remove(...) does not return any value. According to official documentation
You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. This is a design principle for all mutable data structures in Python.

Related

A function returning only one index instead of two or more | C++

inside Caleb Curry's C++ course I have stumbled upon a piece of code about classes with a function returning an index if found two objects with the same data members. Here's the function:
int indexuser(std::vector<User> &users, User user)
{
for(int i = 0; i < users.size(); i++)
{
if(users[i].fname == user.fname && users[i].lname == user.lname)
{
return i;
std::cout << "\n";
}
}
users.push_back(user);
return users.size()-1;
}
It seems to me that the function should return two indexes or more if found matching users, cause no matter what it should always return the last index of a vector. However the function returns only the first one it found. Can someone explain to me why does this happen? Thank you in advance.
The function checks if user(of type User) is present in the vector users. If found it will return index of the user found in vector and if not found, it will insert the user (usingusers.push_back(user)) in the vector and return its index (which will be users.size()-1).
And whenever (any) function finds return statement it returns to its calling statement terminating everything else.
If the function meets the return statement, it immediately returns to the code that called that function.
Subsequent code will not run.
In other words, the return command may exist several times in function, but at the first time the program meets return the function execution is finished, and only one value will be returned.
In c++ normal functions can return only 1 value. This value can be of any available type: an integer, its own structure or a standard container, or any other, but this value will be the only one. So the functions are simply executed until you execute the first operand return. As soon as they meet return, they return the corresponding value and complete their execution. Functions are absolutely indifferent to what happens after the first return, because they complete their execution. So in the function described below, only the number 42 will be returned. Moreover, the variable a will not be equal to the number 5, because the function ended before assign operator
int func(int &a)
{
return 42;
a = 5;
return 51;
return 1;
}

How to search by member accessor value with std::find_if()?

I am learning C++ at the moment and have an example program implemented with an array of objects data store. To make some other operations easier, I have changed the store to a vector. With this change I am now not sure of the best way to search the store to find an object based on a member accessor value.
Initially I used a simple loop:
vector<Composer> composers; // where Composer has a member function get_last_name() that returns a string
Composer& Database::get_composer(string last_name)
{
for (Composer& c : composers)
if (c.get_last_name().compare(last_name))
return c;
throw std::out_of_range("Composer not found");
}
This works just fine of course, but to experiment I wanted to see if there were vector specific functions that could also do the job. So far I have settled on trying to use find_if() (if there is a better function, please suggest).
However, I am not sure exactly the correct way to use find_if(). Based on code seen in online research I have replaced the above with the following:
vector<Composer> composers; // where Composer has a member function get_last_name() that returns a string
Composer& Database::get_composer(string last_name)
{
auto found = find_if(composers.begin(), composers.end(),
[last_name](Composer& c) -> bool {c.get_last_name().compare(last_name);});
if (found == composers.end())
throw out_of_range("Composer not found");
else
return *found;
}
This does not work. It does find a result, but it is the incorrect one. If an argument that matches, say the third composer's last name the function always returns the first item from the vector (if I pass an argument that doesn't match any last name the function correctly throws an exception)... what am I doing wrong?
You are on the right track, your lambda needs return statement. Also in such case you do not have to specify it's return type explicitly, it can be deduced:
find_if(composers.begin(), composers.end(),
[last_name](const Composer& c) { return c.get_last_name() == last_name);});
you original code should not compile or at least emit warning(s), you should pay attention to them.
Note: it is not clear how your original code worked if you tested it, it should be:
if (c.get_last_name().compare(last_name) == 0 )
or simply:
if (c.get_last_name() == last_name )
as std::string::compare() returns int -1 0 or 1, so your code searches for string that does not match variable last_name
With range-v3, you may use projection:
auto it = ranges::find(composers, last_name, &composers::get_last_name);

Using SelectFirst with a condition that relies on the input

I'm trying to find the first instance in a list, a, for which the element is not a member of another list, b. I'm thinking to use something similar to this:
a = {r,j,k};
b = {r,m,n};
firstnonmatch = SelectFirst[a,MemberQ[b,a_i]==False]
where firstnonmatch would return m. But I'm not sure how to refer to elements of the list in the conditions when using SelectFirst[]. Is there a good way to do this?
the crit argument needs to be a function, here you use a pure function:
a = {r,j,k};
b = {r,m,n};
SelectFirst[a,!MemberQ[b,#]&]
j

using Boost `ptree.find` doesn't work as expected

I have
const boost::property_tree::ptree& v
and I want to get <xmlattr>.Value, if it exists, otherwise the value.
I tried this code:
if(v.find("<xmlattr>.Value") != v.not_found())
value = v.get<std::string>("<xmlattr>.Value");
else
value = v.get_value<std::string>();
However, it doesn't work as expected. Even if the value is there, find() returns not_found().
This code works:
auto inValue = v.get_optional<std::string>("<xmlattr>.Value");
if(inValue.is_initialized())
value = inValue.get();
else
value = v.get_value<std::string>();
I guess I understood find() wrong. What exactly does it do? Is there another function I should use instead?
According to the documentation, find() (see here) finds a child with the given key (not path), or not_found() if there is none.
<xmlattr>.Value is a path (that works with get and get_optional).

Returning elements of a row in a list using Scala

I need to write a method that will return the contents of a particular row (index of it is inputted as method parameter). I have to use recursion and no loops.
So far I have attempted this uncompleted code (and I have no idea how to continue it):
class Sudoku(val grid: List[List[Int]]) {
def r(r: Int): Set[Int] = {
if (grid.isEmpty) Set()
else
}
}
I also do not know how Set works. Any help would be really appreciated. PS: I am not asking for complete code, an algorithm explanation would be more than enough!
This is the answer to the literal interpretation of the question:
class Sudoku(val grid: List[List[Int]]) {
def row(n: Int): List[Int] =
if (grid.size > n) grid(n) else Nil
}
The apply method on List, here applied on the value grid, which can be written either grid apply n, or simply grid(n) returns the n'th element of the list. If that element does not exist (e.g. grid(1000000)), it throws an exception, therefore we check the size of the list first.
I have no idea why you should return a Set, but you could simple call .toSet on the result. A Set is a collection with distinct elements (each element only occurs once) with no guarantee of ordering.
I also don't know why you would need recursion for this, so I reckon the question is part of a larger problem.