J.P. Morgan Interview Question

How would you write a function that prints "bar" every 4th time, and "foo" every other time?

Interview Answers

Anonymous

Sep 15, 2016

Sorry if ( count == 3) { //for every 4

3

Anonymous

Apr 30, 2018

You can add a while loop to make it run a certain number of times. Be careful in python not to exceed the maximum recursion depth which I believe is around 1000. count=0 def fooBar(): global count count = count+1 if count==0: print('bar ',count) while count < 999: return fooBar() elif(count%4 == 0): print('foo ',count) while count < 999: return fooBar() else: print('bar ',count) while count < 999: return fooBar() fooBar()

Anonymous

Apr 30, 2018

Why not: count=0 def fooBar(): global count count = count+1 if count==0: print('bar ',count) elif(count%4 == 0): print('foo ',count) else: print('bar ',count) fooBar()

Anonymous

Sep 15, 2016

recursion? printFooBar(int count) { if ( count == 2) { print("Bar"); count = 0; } else { print("Foo"); count = count + 1; } printFoorbar(count) } main() { printFoorbar(0); }

Anonymous

Jun 1, 2016

The simplest way...pass in number and set up a modulator

8