Skip to content

Instantly share code, notes, and snippets.

@ethanhs
Created October 20, 2017 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ethanhs/5a83f9267bdfa4e6e92681156a48dcb8 to your computer and use it in GitHub Desktop.
Save ethanhs/5a83f9267bdfa4e6e92681156a48dcb8 to your computer and use it in GitHub Desktop.
Because we need a C version
MAX = 250
nums = range(MAX + 1)
signs = '+-*/'
if_template = '''
if (a == {0} && b == '{1}' && c == {2})
puts("{0} {1} {2} = {3}");
'''
main_template = '''
int main( int argc, char** argv) {
if (argc != 4) {
printf("Incorrect number of arguments, usage `calc <num> <sign> <num>`");
exit(1);
}
int a = atoi(argv[1]);
char b = *argv[2];
int c = atoi(argv[3]);
'''
with open('calc.c', 'w+') as f:
print('#include <stdio.h>', file=f)
print('#include <stdlib.h>', file=f)
print(main_template, file=f)
for sign in signs:
for num1 in nums:
for num2 in nums:
eq = f'{num1} {sign} {num2}'
try:
ans = eval(eq)
except ZeroDivisionError:
ans = 'Infinity'
print(if_template.format(num1, sign, num2, ans), file=f)
print('}', file=f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment