Re:Unpythonic Python
by acqq on Thursday April 10, 2014 @03:03AM
(#7564571)
And when you write C carefully, the C code looks like this (thanks seanjensengrey and rhth54656 for ideas):
The loosely similar Python:
[ Parent
| on HN ]
And my Visual C 6 compiles the above C to this x86 asm with a single conditional jump, just for the loop:
mov edi, DWORD PTR __imp__printf
mov esi, 1
L1:
mov eax, esi
cdq
mov ecx, 5
idiv ecx
mov eax, esi
mov ebx, 3
push esi
mov ecx, edx
neg ecx
sbb ecx, ecx
cdq
idiv ebx
inc ecx
neg edx
sbb edx, edx
inc edx
lea edx, DWORD PTR [edx+ecx*2]
mov eax, DWORD PTR arr[edx*4]
push eax
call edi
add esp, 8
inc esi
cmp esi, 101
jl SHORT L1
The magic is in the neg sbb combination: The neg changes reg to two's complement but also sets or clears the CF if the argument was != 0 then sbb reg,reg effectively moves CF to the reg avoiding conditional jump for != 0.Taking that a little further,
const char *fb[][2] = {{"%d\n", "Fizz\n"}, {"Buzz\n", "FizzBuzz\n"}};
int i;
for (i = 1; i <= 100; ++i)
printf(fb[i % 5 == 0][i % 3 == 0], i);
(It's a pity we have to specify the second dimension manually . . .)