Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
fact[0] := 1;
fact[n_?Positive] := n*fact[n - 1];int fact(int n);
int fact1(int n)
{
return 1;
}
int factN(int n)
{
return fact(n - 1) * n;
}
typedef int (*fact_fn_t)(int);
fact_fn_t fact_fn[] = {fact1, factN};
int fact(int n)
{
int i = (bool)(n - 1);
return fact_fn[i](n);
}
int main(int argc, char* argv[])
{
cout << fact(5) << endl;
}def fac(n):
return not n or n * fac(n - 1)
А зачем для проверки пустоты приведение к int? «if l» вместо «if len(l) != 0» — действительно, писать удобно (хотя по мнению некоторых и непитонично).Оно и не приводится к int, оно приводится к логическому типу. К тому же, кроме «питоничности» и лучшей читаемости, вариант "
if l:" скорее всего ещё и быстрее.Но когда переменная будет то ли bool, то ли int — это ИМХО нехорошо.Добро пожаловать в язык с утиной типизацией ) Хотя вроде в любой момент понятно, какой тип имеет переменная и в чему он будет приведён: 0, "", [] — False, остальное — True
int Rec(int n)
{
int a = -isPos(n);
return a&(n*Rec(n-1))+1-isPos(n);
}
смещение_правила_в_таблице_правил = текущее_состояние*длина_алфавита + текущий_символ;
новое_состояние = правила[смещение_правила_в_таблице_правил][0];
новый_символ = правила[смещение_правила_в_таблице_правил][1];
движение = правила[смещение_правила_в_таблице_правил][2];
{"cake":"Yummy!!!"}.get(raw_input(), "The cake is a lie :(")print (lambda x:reduce(lambda x, y:x*y, [i for i in range(1, max(x, 2))]))(int(raw_input())+1)<?php isCake(input) and print('Yummy, thanks!') or print('You are still lying to me!'); ?>package ru.nullpointer.cake;
/**
*
* @author Alexander Yastrebov
*/
public class App {
public static void main(String[] args) throws Exception {
taste("pie");
taste("cake");
taste("cookie");
}
private static void taste(String s) {
Confectionery c = new Confectionery();
try {
s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
Class clazz = Class.forName(App.class.getName() + "$" + s);
c = (Confectionery) clazz.newInstance();
} catch (Exception ex) {
}
c.taste();
}
static class Confectionery {
protected void taste() {
System.out.println("Not so tasty as I wish :(");
}
}
static class Cake extends Confectionery {
protected void taste() {
System.out.println("Mmm, very tasty!");
}
}
}
public class App {
public static void main(String[] args) {
taste("pie");
taste("cake");
taste("cookie");
}
private static void taste(String s) {
try {
s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
Class.forName(App.class.getName() + "$" + s);
System.out.println("Mmm, very tasty!");
} catch (Exception ex) {
System.out.println("Not so tasty as I wish :(");
}
}
static class Cake { }
}
double min(double a, double b)
{
double c = b - a;
int less = -(*(long long *)(&c) >> 63);
return (1 - less) * a + less * b;
}
/* Вызов: extern void sort_array(uint32_t *arr,uint32_t N); */
.text
.globl sort_array
sort_array:
pushl %ebp
movl %esp, %ebp
pushl %edi
pushl %esi
pushl %ebx
pushl $31
pushl 12(%ebp)
pushl 8(%ebp)
call sort_array_asm_recursive
addl $12,%esp
popl %ebx
popl %esi
popl %edi
popl %ebp
ret
sort_array_asm_recursive:
movl 12(%esp),%ecx
movl 8(%esp),%eax
decl %eax
neg %eax
shrl $31,%eax
jmp *jump_tab3(,%eax,4)
go_sort_process:
movl 4(%esp),%ebx
xorl %eax,%eax
movl 8(%esp),%edx
decl %edx
go_sort_again:
movl %eax,%esi
subl %edx,%esi
shrl $31,%esi
jmp *jump_tab0(,%esi,4)
process_one:
movl (%ebx,%eax,4),%esi
shrl %cl,%esi
andl $1,%esi
shll $1,%esi
movl (%ebx,%edx,4),%edi
shrl %cl,%edi
andl $1,%edi
orl %edi,%esi
jmp *jump_tab1(,%esi,4)
sw_j0:
incl %eax
jmp go_sort_again
sw_j1:
incl %eax
decl %edx
jmp go_sort_again
sw_j2:
movl (%ebx,%eax,4),%esi
xchgl (%ebx,%edx,4),%esi
movl %esi,(%ebx,%eax,4)
incl %eax
decl %edx
jmp go_sort_again
sw_j3:
decl %edx
jmp go_sort_again
get_out_of_loop:
movl (%ebx,%eax,4),%esi
shrl %cl,%esi
andl $1,%esi
xorl $1,%esi
addl %esi,%eax
decl %ecx
movl %ecx,%esi
shrl $31,%esi
jmp *jump_tab2(,%esi,4)
recurs_go:
movl 8(%esp),%esi
subl %eax,%esi
leal (%ebx,%eax,4),%edi
pushl %ecx
pushl %esi
pushl %edi
pushl %ecx
pushl %eax
pushl %ebx
call sort_array_asm_recursive
addl $12,%esp
call sort_array_asm_recursive
addl $12,%esp
recurs_end:
ret
jmp recurs_end
.data
jump_tab0:
.long get_out_of_loop
.long process_one
jump_tab1:
.long sw_j0
.long sw_j1
.long sw_j2
.long sw_j3
jump_tab2:
.long recurs_go
.long recurs_end
jump_tab3:
.long recurs_end
.long go_sort_process
<?php
$word = 'cake';
$cake = 0;
$$word++;
$buff = array('The cake is a lie :(', 'Yummy!!!');
echo $buff[$cake];

$word = "cake";
$results = array("The cake is a lie!", "Yummy!");
echo $results[$word];
<?php
$emotions = array( $_GET['eat'] => ' :( '); // на что угодно переданное - плохая реакция
$emotions['cookie'] = 'thank you'; // а за печеньку спасибо
print $emotions[$_GET['eat']];
?>
Один знакомый заявил мне, что любая программа может быть написана без использования if/else.
int res;
for( res = strcmp(input, "cake"); res == 0; )
{
puts("Yummy!!!");
// Здесь бы не помешал goto для избежания избыточной проверки,
// но раз уж объявили goto вредным - кушаем так.
break;
}
while( res != 0 )
{
puts("The cake is a lie :(");
break;
}
System.out.println((char)(x*'s'));
#include "stdio.h"
static char * cake_message = "cake";
const char * match_message = "Yummy!!!";
const char * error_message = "The cake is a lie :(";
int test( char * str )
{
int result;
unsigned long * cake_ptr32, * arg_ptr32;
unsigned long diff;
char ch = str[4];
const char * result_message = match_message;
// Длина входящей строки не более 4-байт
result = (int) ((unsigned char) (str[4] | -str[4]) >> 7);
// Сравниваем слова как 32-х битные значения
cake_ptr32 = (unsigned long *) cake_message;
arg_ptr32 = (unsigned long *) str;
diff = *cake_ptr32 - *arg_ptr32;
result |= (int) (( diff | -diff ) >> 31);
result_message += result * (error_message - match_message);
puts(result_message);
return result;
}
int main(int argc, char * argv[])
{
test("on");
test("cake");
test("cakecake");
return 0;
}
* This source code was highlighted with Source Code Highlighter.
Программирование без использования условных конструкций