Arithmetic

  1. Sum of Series
    Find the sum of all odd numbers between 1 and 99 (inclusive).
    [Reveal]
    
        print(sum(range(1,100,2)))
    							
  2. Time Calculator
    Write a function that takes an input x (number of seconds), and returns 4 numbers, namely the number of days, hours, minutes, and seconds that is represented by the input.
    [Reveal]
    
        def dhms(x):
            days = x//86400
            hours = (x%86400)//3600
            minutes = (x%3600)//60
            seconds = x%60
            return days,'days',hours,'hours',minutes,'minutes',seconds,'seconds'
    							
  3. Tip Calculator
    Write a function that takes an input price and service quality and calculate the price after tips. Assume tips are 20% if service is good, 10% if medium and 0% if service is bad.
    [Reveal]
    
        def tip_calculator(price, service):
            if service == "good":
                return price * 1.2 #apply 20% tips
            elif service == "medium":
                return price * 1.1 #apply 10% tips
            elif service == "bad":
                return price * 1.0 #apply 0% tips
    							
  4. Mean
    Write a function that computes the mean (average) of an input list of numbers.
    [Reveal]
    
        def mean(A):
            return 1.0 * sum(A) / len(A)
    							
  5. Median
    Write a function that computes the median of an input list of numbers.
    [Reveal]
    
        def median(A):
            A = sorted(A)
            if len(A) % 2 == 0:
                return 0.5 * (A[int(len(A)/2) - 1] + A[int(len(A)/2)])
            else:
                return A[int(len(A)/2)]
    							
  6. Mode
    Write a function that computes the mode of an input list of numbers (assume unique).
    [Reveal]
    
        def mode(A):
            count = {}
            for i in range(len(A)):
                if A[i] in count:
                    count[A[i]] = count[A[i]] + 1
                else:
                    count[A[i]] = 1
    
            highest_count = 0
            M = None
            for n in count:
                if count[n] > highest_count:
                    highest_count = count[n]
                    M = n
            return M
    							
  7. Standard Deviation
    Write a function that computes the standard deviation of an input list of numbers.
    [Reveal]
    
        import math
        def standard_deviation(A):
            mean_of_A = 1.0 * sum(A) / len(A)
            S = 0.0
            for i in range(len(A)):
                S = S + (A[i] - mean_of_A)**2
            return math.sqrt(S / len(A))
    							

Loops

  1. Cards
    Print out the rank and suit of all the cards in a standard 52-card deck.
    [Reveal]
    
        for number in list(range(1,11))+['J','Q','K', 'A']:
            for suit in ['clubs','diamonds','hearts','spades']:
                print(number, suit)
    							
  2. Population Growth
    The population of a town starts at 100. Each year, the population grows by 50% (rounded down to the nearest integer). Calculate the number of years it takes for the population to exceed 2000.
    [Reveal]
    
        population = 100
        years = 0
        while True:
            if population > 2000:
                print(years, 'years')
                break
            else:
                population = int(population * 1.5)
                years += 1
    							
  3. Number Guessing Game
    Write a program for the number guessing game. The program picks a random number between 1 and 100 (inclusive) and the user has to guess the number. The program continuously prompts the user for an input and prints "Too high" or "Too low" if the guess is incorrect.
    [Reveal]
    
        import random
        secret_number = random.randint(0,100)
        while True:
            print('Guess a number:')
            a = int(input())
            if a > secret_number:
                print('Too high')
            elif a < secret_number:
                print('Too low')
            else:
                print('Success')
                break
    							

Strings

  1. Capitalize
    Write a function to capitalize the first letter of each word of an input sentence.
    (e.g. "hello world" becomes "Hello World")
    [Reveal]
    
        def capitalize_letters(s):
            t = s.split()
            for i in range(len(t)):
                t[i] = t[i][0].upper() + t[i][1:]
            return ' '.join(t)
    							
  2. Typing Speed
    Write a program that measures the typing speed of the user.
    (e.g. Measure the time taken to type the sentence "quick brown fox jumps over the lazy dog")
    [Reveal]
    
        import time
        words_to_type = "quick brown fox jumps over the lazy dog"
        print('Press ENTER to start')
        input()
        print('Type the following:',words_to_type)
        t1 = time.time()
        a = input()
        t2 = time.time()
        if a==words_to_type:
            print('Time taken is',t2-t1,'seconds')
        else:
            print('Incorrect input')
    							
  3. Anagrams
    Given a query word and a list of valid words, write a function that prints all the anagrams of the query word.
    [Reveal]
    
        def anagrams(query, words):
            for w in words:
                if sorted(w)==sorted(query):
                    print(w)
    							

NumPy

  1. Sum of Arrays
    Using NumPy, add the numbers in the following two lists:
    L1: odd numbers between 1 and 31 (inclusive)
    L2: even numbers between 32 and 62 (inclusive)
    [Reveal]
    
        import numpy
        L1 = numpy.array(list(range(1, 32, 2)))
        L2 = numpy.array(list(range(32, 63, 2)))
        L3 = L1 + L2
        print(L3)
    							
  2. Count Positive Numbers
    Using NumPy, count the number of positive numbers in each of the following lists:
    L1 = [5, -10, 4, 9, -3, -1, 3, 9, 4, 6]
    L2 = [[-8, -8, 9], [-1, -3, 4], [ 1, -5, -9]]
    L3 = [[[-4, 3], [-1, -1]], [[ 6, 1], [-4, -7]]]
    [Reveal]
    
        import numpy
        print((numpy.array(L1)>0).sum())
        print((numpy.array(L2)>0).sum())
        print((numpy.array(L3)>0).sum())
    							
  3. Clip Values
    Using NumPy, modify the following array to clip (limit) values between 0 and 100:
    L1 = [[[ 63, 91, 61],
    [-27, 19, -11],
    [ 41, 74, 3]],
    [[ 82, -12, -35],
    [142, -35, 84],
    [ 75, 8, 47]],
    [[114, 115, -36],
    [123, 108, 147],
    [-43, 111, 140]]]
    [Reveal]
    
        import numpy
        L1 = numpy.array(L1)
        L1[L1<0] = 0
        L1[L1>100]=100
        print(L1)
    							
  4. Flip Image
    Given an input image in the form of a 3-dimensional NumPy array, write a function that flips the image in the horizontal direction.
    [Reveal]
    
        def flip_image(I):
            return I[:,::-1,:]
    							

PyGame

  1. Tic-Tac-Toe
    Implement Tic-Tac-Toe.
    [Reveal]
    
        import pygame
        from pygame.locals import *
    
        #initialize game window
        screen = pygame.display.set_mode((600,600))
    
        #import image resources
        board = pygame.image.load('board.png')
        circle = pygame.image.load('circle.png')
        cross = pygame.image.load('cross.png')
    
        #display board
        screen.blit(board,(0,0))
        pygame.display.flip()
    
        #variables that store the state of the game
        game_over = False
        which_symbol = 'circle'
        board_state = [[' ',' ',' '],
                       [' ',' ',' '],
                       [' ',' ',' ']]
        line_width = 10
        line_color = (0,0,0)
    
        #function to check for matches in a straight line
        def check_match():
            #horizontal match
            for i in range(3):
                if not board_state[i][0]==' ' and board_state[i][0]==board_state[i][1]==board_state[i][2]:
                    line_start = (0, i*200+95)
                    line_end = (599, i*200+95)
                    pygame.draw.line(screen,line_color,line_start,line_end,line_width)
                    return True
            #vertical match
            for i in range(3):
                if not board_state[0][i]==' ' and board_state[0][i]==board_state[1][i]==board_state[2][i]:
                    line_start = (i*200+95, 0)
                    line_end = (i*200+95, 599)
                    pygame.draw.line(screen,line_color,line_start,line_end,line_width)
                    return True
            #left diagonal
            if not board_state[0][0]==' ' and board_state[0][0]==board_state[1][1]==board_state[2][2]:
                line_start = (0,0)
                line_end = (599,599)
                pygame.draw.line(screen,line_color,line_start,line_end,line_width)
                return True
            #right diagonal
            if not board_state[2][0]==' ' and board_state[2][0]==board_state[1][1]==board_state[0][2]:
                line_start = (599,0)
                line_end = (0,599)
                pygame.draw.line(screen,line_color,line_start,line_end,line_width)
                return True
            return False
    
        #game loop
        clock = pygame.time.Clock()
        while True:
            clock.tick(30)
            if not game_over:
                for event in pygame.event.get():
                    if event.type == MOUSEBUTTONUP:
                        mouse = pygame.mouse.get_pos()
                        grid_x = mouse[0] // 200
                        grid_y = mouse[1] // 200
                        print(board_state)
                        if board_state[grid_y][grid_x] == ' ':
                            if which_symbol=='circle':
                                board_state[grid_y][grid_x] = 'o'
                                X = grid_x * 200 + 25
                                Y = grid_y * 200 + 25
                                print('draw a circle at location',X,Y)
                                screen.blit(circle,(X,Y))
                                pygame.display.flip()
                                game_over = check_match()
                                pygame.display.flip()
                                which_symbol = 'cross'
                            elif which_symbol=='cross':
                                board_state[grid_y][grid_x] = 'x'
                                X = grid_x * 200 + 25
                                Y = grid_y * 200 + 25
                                print('draw a cross at location',X,Y)
                                screen.blit(cross,(X,Y))
                                game_over = check_match()
                                pygame.display.flip()
                                which_symbol = 'circle'
    							
  2. Snake
    Implement Snake.
    [Reveal]
    
        import pygame
        print(pygame.__version__)
        from pygame.locals import *
        import random
    
        screen = pygame.display.set_mode((500,500))
        grass_image = pygame.image.load('grass.png')
        grass_image = pygame.transform.scale(grass_image, (500,500))
    
        apple_x = random.randint(0,400)
        apple_y = random.randint(0,400)
        apple_size = 50
        apple = pygame.image.load('apple.png')
        apple = pygame.transform.scale(apple, (apple_size,apple_size))
    
        snake_x = random.randint(0,400)
        snake_y = random.randint(0,400)
        snake_direction = 'right'
        snake_size = 100
        snake = pygame.image.load('cobra.png')
        snake = pygame.transform.scale(snake, (snake_size,snake_size))
    
        def move_snake():
            screen.blit(grass_image, (0,0))
            screen.blit(apple, (apple_x,apple_y))
            screen.blit(snake, (snake_x,snake_y))
            pygame.display.flip()
    
        clock = pygame.time.Clock()
        while True:
            clock.tick(30)
            move_snake()
            if snake_direction == 'right':
                snake_x = snake_x + 5
            elif snake_direction == 'left':
                snake_x = snake_x - 5
            elif snake_direction == 'up':
                snake_y = snake_y - 5
            elif snake_direction == 'down':
                snake_y = snake_y + 5
    
            if snake_x > apple_x - snake_size and snake_x < apple_x + apple_size and snake_y > apple_y - snake_size and snake_y < apple_y + apple_size:
                print('apple consumed')
                apple_x = random.randint(0,400)
                apple_y = random.randint(0,400)
    
            for event in pygame.event.get():
                if event.type == KEYDOWN:
                    if event.key == K_UP:
                        snake_direction = 'up'
                    elif event.key == K_DOWN:
                        snake_direction = 'down'
                    elif event.key == K_LEFT:
                        snake_direction = 'left'
                    elif event.key == K_RIGHT:
                        snake_direction = 'right'