I'm trying to write a version of cumulative sum in python using the reduce function. Here is my code so far:
<script src="https://unpkg.com/vue@2.5.10/dist/vue.min.js"></script>
<div id="app">
<input type="text" v-model="myid" placeholder="My ID" />
<button type="button" @click="click">Submit</button>
</div>
But the problem is that in my lambda function, python doesn't know that a (my accumulator parameter) is a list object, and that I want my reduce function to return a list. In other functional programming languages, it might ask me to specify the type of from functools import reduce
def my_cum_sum(arg):
return reduce(lambda a, x: (a.append(a[-1] + x)) if len(a) > 0 else a.append(x), arg, [])
assert(my_cum_sum([1, 1, 1, 1]) == [1, 2, 3, 4]))
and a
. But I'm new to python, and haven't quite figured out how it handles types and stuff. What is the pythonic way of solving this problem?
答案 0 :(得分:1)
import android.databinding.BindingAdapter;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import java.util.List;
/**
* Created by admin on 14-12-2017.
*/
public class RewardAdapter extends RecyclerView.Adapter<RewardAdapter.ViewHolder> {
private List<SampleModel> model;
public RewardAdapter(List<SampleModel> model) {
this.model = model;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()),
R.layout.rewarded_item, parent, false);
return new ViewHolder(binding);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
ViewDataBinding viewDataBinding = holder.getViewDataBinding();
// viewDataBinding.setVariable(BR.image,model.get(position));
viewDataBinding.setVariable(BR.recipeName, model.get(position));
viewDataBinding.setVariable(BR.imageUrl, model.get(position));
}
@Override
public int getItemCount() {
return (null != model ? model.size() : 0);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ViewDataBinding viewBinding;
public ViewHolder(ViewDataBinding binding) {
super(binding.getRoot());
viewBinding = binding;
viewBinding.executePendingBindings();
}
public ViewDataBinding getViewDataBinding() {
return viewBinding;
}
}
}
returns append
, so you cannot get the list back into None
like this.
Just use the addition between the list and a list made of a single element, or just a list made of initial element if list is empty:
reduce
result:
from functools import reduce
def my_cum_sum(arg):
return reduce(lambda a, x: a + [a[-1]+x] if a else [x], arg, [])
print (my_cum_sum([1, 1, 1, 1]))
(note that [1, 2, 3, 4]
is better written if len(a)>0
as well)