编程时,我经常发现自己需要计算如下内容:
x = (y / n) + (y % n ? 1 : 0);
或者更明确地说:
x = y / n;
if (y % n != 0) {
x = x + 1;
}
Run Code Online (Sandbox Code Playgroud)
是否有更优雅的方式来实现这一价值?可以在不使用条件表达式的情况下实现吗?
基本上我想要以下通用功能:
public string StringOrNull<T> (T value)
{
if (value != null)
{
return value.ToString();
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用约束,例如T:class,但T可以是基本类型,Nullable <>或类.有没有通用的方法来做到这一点?
编辑
结果我跳了枪.这实际上工作得很好,如下例所示:
class Program
{
static void Main(string[] args)
{
int i = 7;
Nullable<int> n_i = 7;
Nullable<int> n_i_asNull = null;
String foo = "foo";
String bar = null;
Console.WriteLine(StringOrNull(i));
Console.WriteLine(StringOrNull(n_i));
Console.WriteLine(StringOrNull(n_i_asNull));
Console.WriteLine(StringOrNull(foo));
Console.WriteLine(StringOrNull(bar));
}
static private string StringOrNull<T>(T value)
{
if (value != null)
{
return value.ToString();
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud) 假设我有一系列数字:{n,n + 1,n + 2,... n + m}
如果不提前存储数字,我想创建一个函数f(),给定序列{1,2,3,... m}将以随机(或至少伪随机)顺序吐出原始集合.
例如假设我的序列是{10,11,12,13,14,15,16,17}
f(1) could yield 14 f(2) could yield 17 f(3) could yield 13 f(4) could yield 10 f(5) could yield 16 f(6) could yield 15 f(7) could yield 11 f(8) could yield 12
在过去的某个时刻,一位同事向我展示了一种能够做到这一点的数学算法,但是我已经忘记了除了存在之外几乎所有关于它的事情.我记得你必须事先得到序列,并从函数中使用的序列中生成一些常量.对于那些想知道的人,我遗憾地失去了与那位同事的联系.
这个问题的答案看起来很接近我想要的,但我不确定答案是否允许我提前将输出约束到特定序列.
编辑:
为了澄清一点,我不想存储原始序列或混洗序列.我想从原始序列生成函数f().
令人沮丧的是,我已经看到了这一点,我只是记不起来,谷歌再次找到它.
Fisher-Yates算法非常适合置换或改组卡座,但它不是我想要的.
我一直在玩这个,但是看不出明显的解决方案.我想从XinY_Go函数中删除递归.
def XinY_Go(x,y,index,slots):
if (y - index) == 1:
slots[index] = x
print slots
slots[index] = 0
return
for i in range(x+1):
slots[index] = x-i
XinY_Go(x-(x-i), y, index + 1, slots)
def XinY(x,y):
return XinY_Go(x,y,0,[0] * y)
Run Code Online (Sandbox Code Playgroud)
该函数正在计算将X弹珠放入Y槽的方法数.这是一些示例输出:
>>> xy.XinY(1,2) [1, 0] [0, 1] >>> xy.XinY(2,3) [2, 0, 0] [1, 1, 0] [1, 0, 1] [0, 2, 0] [0, 1, 1] [0, 0, 2]
我想定义一个支持__getitem__但不允许迭代的类.例如:
class B:
def __getitem__(self, k):
return k
cb = B()
for x in cb:
print x
Run Code Online (Sandbox Code Playgroud)
我可以在课堂B上添加什么来强制for x in cb:失败?