|
| 1 | +""" |
| 2 | +Write a function 'what_sign' which returns 'Positive' 'Zero' or 'Negative' when given a number |
| 3 | +""" |
| 4 | + |
| 5 | +def what_sign(n): |
| 6 | + if n > 0: |
| 7 | + return 'Positive' |
| 8 | + elif n < 0: |
| 9 | + return 'Negative' |
| 10 | + else: |
| 11 | + return 'Zero' |
| 12 | + |
| 13 | + |
| 14 | +def test_what_sign(n): |
| 15 | + assert what_sign(3) == 'Positive' |
| 16 | + assert what_sign(0) == 'Zero' |
| 17 | + assert what_sign(-3) == 'Negative' |
| 18 | + |
| 19 | +""" |
| 20 | +Write a function 'fizzbuzz' that prints the integers from 1 to 100. |
| 21 | +
|
| 22 | +But for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz". |
| 23 | +For numbers which are multiples of both three and five print "FizzBuzz". |
| 24 | +""" |
| 25 | + |
| 26 | +def fizzbuzz(): |
| 27 | + for num in xrange(1,101): |
| 28 | + msg = '' |
| 29 | + if num % 3 == 0: |
| 30 | + msg += 'Fizz' |
| 31 | + if num % 5 == 0: |
| 32 | + msg += 'Buzz' |
| 33 | + else: |
| 34 | + msg = str(num) |
| 35 | + print msg |
| 36 | + |
| 37 | +""" |
| 38 | +Write a function 'remove_indices' which removes one or more indicies from a list. |
| 39 | +
|
| 40 | +For example given the list: |
| 41 | +["John", "Bob", "Charles", "Trev"] |
| 42 | +and the indices: |
| 43 | +[1, 2] |
| 44 | +the resulting list will be: |
| 45 | +["John", "Trev"] |
| 46 | +""" |
| 47 | + |
| 48 | + |
| 49 | +def remove_indices(mylist, idxs): |
| 50 | + result = [] |
| 51 | + for i, l in enumerate(mylist): |
| 52 | + if i not in idxs: |
| 53 | + result.append(l) |
| 54 | + return result |
| 55 | + |
| 56 | + |
| 57 | +def test_remove_indices(): |
| 58 | + assert remove_indices(["John", "Bob", "Charles", "Trev"], [0]) == ["Bob", "Charles", "Trev"] |
| 59 | + assert remove_indices(["John", "Bob", "Charles", "Trev"], [1, 2]) == ["John", "Trev"] |
| 60 | + |
| 61 | + |
| 62 | +"""" |
| 63 | +Modify connect to handle failed connections |
| 64 | +""" |
| 65 | +import random |
| 66 | + |
| 67 | + |
| 68 | +def open_connection(): |
| 69 | + if random.randint(0, 3) != 0: |
| 70 | + raise ValueError('failed to connect') |
| 71 | + return True |
| 72 | + |
| 73 | + |
| 74 | +def connect(nretry=100): |
| 75 | + for _ in xrange(nretry): |
| 76 | + try: |
| 77 | + if open_connection(): |
| 78 | + return |
| 79 | + except ValueError: |
| 80 | + continue |
| 81 | + |
| 82 | + |
| 83 | +if "__main__" in __name__: |
| 84 | + connect() |
0 commit comments