Updates from October, 2016 Toggle Comment Threads | Keyboard Shortcuts

  • loctv 11:02 am on October 21, 2016 Permalink | Reply
    Tags: ,   

    Problem: Faulty Keyboard 

    *Difficulty: Eazy
    Ritesh has found out a keyboard from his store room which is very unique. Unique because the keyboard contains only 10 keys (the numpad). In other words the keyboard has 10 keys, they are 1,2,3,4,5,6,7,8,9,0.

    Sharat has got the task to type all the natural number from 1 to N, using this keyboard. But the keyboard is in damaged condition, means, after pressing M keys in total from the keyboard, the keyboard completely stops working.

    Now you being his friend need to find out the greatest natural number he can type using the keyboard starting from 1. (You need to find the value of N).

    Input
    The first line of input contains the integer T, where T is the number of test cases. Then T test cases follow. Each test case contains an integer M, where M is maximum number of keys he can press in the keyboard before its completely damaged.

    Output:
    In each test case print a single integer N,where N is the greatest natural number he can type using the keyboard starting from 1.

    Constraints:
    0 < T < 105
    0 < M < 38890

    Example:

    Input:

    3
    5
    10
    15
    Output:
    5
    9
    12

    Explanation:
    (i)For the 1st test case M=5, he can type 1 2 3 4 5. Now after pressing 5 keys the keyboard is damaged.

    (ii)For the 2nd test case M=10, he can type 1 2 3 4 5 6 7 8 9, he has pressed 9 keys and can press only 1 more key but the next natural number he needs to type is 10, which is 2 digit, so he cant type 10, thus the greatest natural number he can type starting from 1 is 9.

    (iii)For the 3rd test case M=15, he can type 1 2 3 4 5 6 7 8 9 10 11 12, now he has pressed 15 keys and the keyboard is damaged. Thus the greatest natural number he can type starting from 1 is 12.

    Implementation: Python 2.7

    # there are 9 1-digit number
    # 90 2-digit number
    # 900 3-digit number
    # so on
    numbers = [0, 9, 90*2, 900*3, 9000*4]

    def find_n(number_of_keys):
    n = 9
    if number_of_keys <= numbers[1]:
    return number_of_keys
    elif number_of_keys <= numbers[2]+numbers[1]:
    number_of_keys -= 9
    n += number_of_keys/2
    elif number_of_keys <= numbers[3]+numbers[2]+numbers[1]:
    number_of_keys -= 9
    n += numbers[2]/2
    number_of_keys -= numbers[2]
    n += number_of_keys/3
    elif number_of_keys <= numbers[4]+numbers[3]+numbers[2]+numbers[1]:
    number_of_keys -= 9
    n += numbers[2]/2
    number_of_keys -= numbers[2]
    n += numbers[3]/3
    number_of_keys -= numbers[3]
    n += number_of_keys/4

    return n

    if __name__ == '__main__':
    t = input()
    for _ in xrange(t):
    m = input()
    print find_n(m)

    Advertisements
     
  • loctv 8:31 pm on October 20, 2016 Permalink | Reply
    Tags: ,   

    Problem: Prime Factors and their Powers 

    *Difficulty: Easy

    Given a number N, print all its unique prime factors and their powers in N.

    N = 100
    Factor Power
      2      2
      5      2
    
    N = 35
    Factor  Power
      5      1
      7      1
    

    Input:
    The first line of input contains an integer T denoting the number of test cases.
    The first line of each test case is N.

    Output:
    Print all prime factors and their powers separated by spaces.  The output should be printed in increasing order of prime factors.

    Constraints:
    1 ≤ T ≤ 200
    2 ≤ N ≤ 10000

    Example:
    Input:
    2
    100
    35

    Output:
    2 2 5 2
    5 1 7 1
    Implementation: Python 2.7, using Sieve Eratosthenes to generate a list of primes.

    from math import sqrt
    def sieve_eratosthenes(n):
        sieve = [True]*n
        sieve[0] = sieve[1] = False 
        for i in xrange(int(sqrt(len(sieve)))):
            if sieve[i]:
                for j in xrange(i+i, len(sieve), i):
                    sieve[j] = False 
        return [i for i in range(len(sieve)) if sieve[i]]
    
    primes = sieve_eratosthenes(10000)
    
    def prime_factors_and_powers(n):
        count, factors_powers = 0, {}
        while n > 2:
            power = 0
            while n % primes[count] == 0:
                power += 1
                n /= primes[count]
            if power > 0:
                factors_powers[primes[count]] = power
            count += 1
        return factors_powers
    
    if __name__ == '__main__':
        t = input()
        for _ in xrange(t):
            n = input()
            factors_and_powers = prime_factors_and_powers(n)
            for key in sorted(factors_and_powers):
                print key, factors_and_powers[key], 
            print
    
    
     
  • loctv 5:27 pm on October 20, 2016 Permalink | Reply
    Tags: ,   

    Problem: Happy Number 

    *Difficulty: Easy

    Given a no N your task is to find whether its a happy no or not . A number is called happy if it leads to 1 after a sequence of steps where in each step number is replaced by sum of squares of its digit that is if we start with Happy Number and keep replacing it with digits square sum, we reach 1.

    For eg:

    Input: n = 19
    Output: 1
    19 is Happy Number,
    1^2 + 9^2 = 82
    8^2 + 2^2 = 68
    6^2 + 8^2 = 100
    1^2 + 0^2 + 0^2 = 1
    As we reached to 1, 19 is a Happy Number.
    
    Input: n = 20
    Output: 0

    Input:
    The first line of input contains an integer T denoting the no of test cases. Then T test cases follow . The first line of each test case contains an integer N.

    Output:
    For each test case in a new line print 1 if the no is a happy else print 0.

    Constraints:
    1<=T<=100
    1<=N<=1000

    Example:
    Input

    2
    19
    20
    Output
    1
    0

    Implementation: Python 2.7

    capture

     
  • loctv 5:04 pm on October 20, 2016 Permalink | Reply
    Tags: ,   

    Problem: Longest Consecutive 1’s 

    *Difficulty: Easy

    Given a number N, Your task is to find the length of the longest consecutive 1’s in its binary representation.

    Input:
    The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N.

    Output:
    For each test case in a new line print the length of the longest consecutive 1’s in N’s binary representation.

    Constraints:
    1<=T<100
    1<=N<=1000
    Example:
    Input
    2
    14
    222
    Output
    3
    4

    Implementation: Python 2.7

    capture

     
  • loctv 8:48 pm on October 19, 2016 Permalink | Reply
    Tags: ,   

    Mini game: Memory Puzzle 

    This is a really simple game, but it’s hard to win in short amount of time. Your task is to find all of the pairs of icons that look the same. There are totally (10*7)/2 pairs, this means the board’s width is 10 and height is 7.

    Let’s get started.
    First, we need to import some necessary modules.

    import pygame, random, sys
    from pygame.locals import *
    

    and declare all instances that we are going to use later.

    FPS = 30 # frame per second
    WINDOW_WIDTH = 640 # size of the window's width in pixel
    WINDOW_HEIGHT = 480 # size of the window's height in pixel
    REVEAL_SPEED = 8 # speed boxes' sliding reveal and cover
    BOX_SIZE = 40 # size of box width and height in pixel
    GAP_SIZE = 10 # space gap between boxes in pixel
    BOARD_WIDTH = 10 # the number of column icons
    BOARD_HEIGTH = 7 # the number of row icons
    X_MARGIN = int( (WINDOW_WIDTH - (BOARD_WIDTH*(BOX_SIZE+GAP_SIZE))) / 2)
    Y_MARGIN = int( (WINDOW_HEIGHT - (BOARD_HEIGTH*(BOX_SIZE+GAP_SIZE))) / 2)
    
    #            R    G    B
    GRAY     = (100, 100, 100)
    NAVYBLUE = ( 60, 60 , 100)
    WHITE    = (255, 255, 255)
    RED      = (255, 0  , 0)
    GREEN    = ( 0 , 255, 0)
    BLUE     = ( 0 , 0  , 255)
    YELLOW   = (255, 255, 0)
    ORANGE   = (255, 128, 0)
    PURPLE   = (255, 0  , 255)
    CYAN     = ( 0 , 255, 255)
    
    BACKGROUND_COLOR = NAVYBLUE
    BOX_COLOR = WHITE
    HIGHLIGHT_COLOR = BLUE
    LIGHT_BACKGROUND_COLOR = GRAY
    
    DONUT = 'donut'
    SQUARE = 'square'
    DIAMOND = 'diamond'
    LINES = 'lines'
    OVAL = 'oval'
    
    ALL_COLORS = [RED, GREEN, BLUE, YELLOW, ORANGE, PURPLE, CYAN]
    ALL_SHAPES = [DONUT, SQUARE, DIAMOND, LINES, OVAL]
    CLOCK, DISPLAY_SURFACE = None, None
    

    We use instances instead of ‘magic numbers’. Magic number is a number in your code, for example, you create window game in pygame by using pygame.display.set_mode method:

    window_surface = pygame.display.set_mode((400, 400))
    

    This code create a Surface object, a special Surface to be exact, all things in your game will be displayed by this Surface. 400 is width and height of this Surface, but using those numbers make it hard to understand and if you want to change the window’s width and height you must find this exact line of code. These numbers are called ‘magic numbers’. So the appropriate and more effective way to do this is using instances.

    WINDOW_WIDTH = 400
    WINDOW_HEIGHT = 400
    window_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    

    There’re totally 7 different colors and 5 shapes.

    Next the main function, this function include all game logic, graphics, etc.

    def main():
        global CLOCK, DISPLAY_SURFACE
        pygame.init() # initialize pygame
        CLOCK = pygame.time.Clock()
        DISPLAY_SURFACE = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 0, 32)
    
        mousex = 0
        mousey = 0
        pygame.display.set_caption('Memory Game') # set window's title
    
        main_board = get_randomized_board()  # create the board, random placed items
        revealed_boxes = generate_revealed_boxes_data(False) # there is no box revealed yet
        first_selection = None # store the x,y of the first click
    
        DISPLAY_SURFACE.fill(BACKGROUND_COLOR) # set background color
        start_game_animation(main_board) # start the game, show all items
    
        while True: # game loop
            mouse_clicked = False
            DISPLAY_SURFACE.fill(BACKGROUND_COLOR)
            draw_board(main_board, revealed_boxes)
    
            for event in pygame.event.get(): # check event
                if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
                    pygame.quit()
                    sys.exit()
                elif event.type == MOUSEMOTION: # mouse hover event
                    mousex, mousey = event.pos
                elif event.type == MOUSEBUTTONUP: # mouse click event
                    mousex, mousey = event.pos
                    mouse_clicked = True
    
            box_x, box_y = get_box_at_pixel(mousex, mousey) # convert pixel coordinates to board coordinates
            if box_x != None and box_y != None:
                # the mouse is currently over a box
                if not revealed_boxes[box_x][box_y]: # if the box has not been revealed yet, highlight it
                    draw_highlight_box(box_x, box_y)
                if not revealed_boxes[box_x][box_y] and mouse_clicked: # click on an item
                    reveal_boxes_animation(main_board, [(box_x, box_y)]) # reveal that item
                    revealed_boxes[box_x][box_y] = True # temporarily mark this item revealed
    
                    if first_selection == None: # if this is the first box selected
                        first_selection = (box_x, box_y) # save it
                    else: # otherwise check if two revealed boxes are the sae
                        # get shape and color of two boxes
                        icon1_shape, icon1_color = get_shape_and_color(main_board, first_selection[0], first_selection[1])
                        icon2_shape, icon2_color = get_shape_and_color(main_board, box_x, box_y)
    
                        if icon1_shape != icon2_shape or icon1_color != icon2_color: # they are not the same
                            pygame.time.wait(1000) # wait 1 second
                            cover_boxes_animation(main_board, [(first_selection[0], first_selection[1]), (box_x, box_y)]) # then cover them
                            # remark them as they have not been revealed yet
                            revealed_boxes[first_selection[0]][first_selection[1]] = False
                            revealed_boxes[box_x][box_y] = False
                        # if they are the same, they remain revealed
                        elif has_won(revealed_boxes): # check for the win
                            game_won_animation(main_board) # start animation (just change the background color)
                            pygame.time.wait(2000) # then wait 2 seconds
    
                            main_board = get_randomized_board() # create new board
                            revealed_boxes = generate_revealed_boxes_data(False) # cover all the items
    
                            draw_board(main_board, revealed_boxes) # draw the board
                            pygame.display.update() # update game screen
                            pygame.time.wait(1000) # then wait 1 second
                            start_game_animation(main_board) # then start the game again
                        first_selection = None # after two item selected, reset this variable to None so that the next click will be the first item
    
            pygame.display.update() # final update each frame
            CLOCK.tick(FPS) # set frame per second
    
    

    Don’t panic, okey :> It’ll be crystal clear after I explain each line of code.
    First you use global keyword to access two global instances CLOCK and DISPLAY_SURFACE. Then you inititialize the game using pygame.init() method. Next, you create the game window, mousex and mousey to save the location of the mouse when player hover or click on a box, set window’s title, create game board. revealed_box is a 2d array, returned from function generate_revealed_boxes_data, with False as a argument. This means all of the values of revealed_boxes are False, just like there is no box that has been revealed yet. If first_selection is None, this is means the next time player click on a box, that box will be the first box in a pair. Fill the window with BACKGROUND_COLOR and start the game.

    The code in the game loop is already explained very clearly by comments, so check it out and free to ask me here if you’re stuck.

    Finally, I’m about to explain all the functions that are used in main function. First, generate_revealed_box_data, this function returns a 2-d array, with all values of each row equal val.
    The get_randomized_board function returns the game board, this function is like the main function, well commented so no need to explain more.
    The get_box_at_plixel converts game (or pixel) coordinates into board coordinates. What’s this mean? This means if you click or hover on a box on the screen, this function will convert that pixel value, for example (400, 200) to board coordinates , (boxx, boxy). This function is the reverse of lefttop_box, which converts game board coordinates to pixel coordinates.
    Then the draw_icon method, which takes 4 arguments, the game board, color, and boxx, boxxy. Convert boxx, boxy to pixel coordinates, then draw the icon (one of the five icons).
    Function draw_boxes_cover, draw icons, and if coverage > 0, draw the coverage over the items, this creates the animation effect.
    The reveal_boxes_animation and cover_boxes_animation makes use of draw_boxes_cover, with different coverage values.
    draw_board function draw the game board, if the box has been revealed, just draw the icon, if it’s not, draw the box cover it.
    start_game_animation, randomly reveal 8 boxes at a time. After quickly revealing those boxes will be covered it. This makes the game a little easier.
    The game_won_animation function makes the background change to LIGHT_BACKGROUND_COLOR and back to BACKGROUND_COLOR multiple times.
    has_won checks if all the values of revealed_box array are equal True.
    Here’s the code of all functions that’re explained above.

    def generate_revealed_boxes_data(val):
        # create a 2-D array of True or False values
        revealed_boxes = []
        for i in xrange(BOARD_WIDTH):
            revealed_boxes.append([val]*BOARD_HEIGTH)
        return revealed_boxes
    
    
    def get_randomized_board():
        # create game board
        # first we create an array saving all the possible combinations of shapes and colors
        icons = []
        for color in ALL_COLORS:
            for shape in ALL_SHAPES:
                icons.append((shape, color))
        random.shuffle(icons)
        num_icons_used = int(BOARD_WIDTH*BOARD_HEIGTH/2) # then we divide it by 2 because we just need half of them
        icons = icons[:num_icons_used]*2 # then we create a copy of current items, so we have even number of pairs of item
        random.shuffle(icons) # shuffle it
    
        # and convert into 2-D dimensional array
        board = []
        for x in xrange(BOARD_WIDTH):
            column = []
            for y in xrange(BOARD_HEIGTH):
                column.append(icons[0])
                del icons[0]
            board.append(column)
        return board
    
    def split_into_groups(group_size, list):
        # split a list into group
        result = []
        for i in xrange(0, len(list), group_size):
            result.append(list[i:i+group_size])
        return result
    
    def lefttop_box(boxx, boxy):
        # convert board coordinates to pixel coordinates
        left = boxx*(BOX_SIZE+GAP_SIZE) + X_MARGIN
        top = boxy*(BOX_SIZE+GAP_SIZE) + Y_MARGIN
        return (left, top)
    
    
    def get_box_at_pixel(x, y):
        # get the box on board where player click on
        for boxx in xrange(BOARD_WIDTH):
            for boxy in xrange(BOARD_HEIGTH):
                left, top = lefttop_box(boxx, boxy)
                box_rect = pygame.Rect(left, top, BOX_SIZE, BOX_SIZE)
                if box_rect.collidepoint(x, y):
                    return (boxx, boxy)
        return (None, None)
    
    
    def draw_icon(shape, color, boxx, boxy):
        # draw icon
        # these two variables are used to centralize the icon
        quarter = int(BOX_SIZE * 0.25)
        half = int(BOX_SIZE * 0.5)
    
        left, top = lefttop_box(boxx, boxy) # convert board coordinates to pixel coordinates
        if shape == DONUT:
            pygame.draw.circle(DISPLAY_SURFACE, color, (left+half, top+half), half-5)
            pygame.draw.circle(DISPLAY_SURFACE, BACKGROUND_COLOR, (left+half, top+half), quarter-5)
        elif shape == SQUARE:
            pygame.draw.rect(DISPLAY_SURFACE, color, (left+quarter, top+quarter, BOX_SIZE-half, BOX_SIZE-half))
        elif shape == DIAMOND:
            pygame.draw.polygon(DISPLAY_SURFACE, color, ((left+half, top), (left+BOX_SIZE-1, top+half), (left+half, top+BOX_SIZE-1),(left, top+half)))
        elif shape == LINES:
            for i in xrange(0, BOX_SIZE, 4):
                pygame.draw.line(DISPLAY_SURFACE, color, (left, top+i), (left+i, top))
                pygame.draw.line(DISPLAY_SURFACE, color, (left+i, top+BOX_SIZE-1), (left+BOX_SIZE-1, top+i))
        elif shape == OVAL:
            pygame.draw.ellipse(DISPLAY_SURFACE, color, (left, top + quarter, BOX_SIZE, half))
    
    
    def get_shape_and_color(board, boxx, boxy):
        # get shape and color of box with given coordinate
        return board[boxx][boxy][0], board[boxx][boxy][1]
    
    
    def draw_boxes_cover(board, boxes, coverage):
        # draw boxes with coverage
        # this create animation revealing and covering effect
        for box in boxes:
            left, top = lefttop_box(box[0], box[1])
            pygame.draw.rect(DISPLAY_SURFACE, BACKGROUND_COLOR, (left, top, BOX_SIZE, BOX_SIZE))
            shape, color = get_shape_and_color(board, box[0], box[1])
            # first we draw the icon
            draw_icon(shape, color, box[0], box[1])
            # then draw coverage on top of it
            if coverage > 0:
                pygame.draw.rect(DISPLAY_SURFACE, BOX_COLOR, (left, top, coverage, BOX_SIZE))
        pygame.display.update() # update the window
        CLOCK.tick(FPS) # slow down the animation
    
    
    def reveal_boxes_animation(board, boxes_to_reveal):
        # the box width will decrease each iteration until they reach 0
        for coverage in xrange(BOX_SIZE, -(REVEAL_SPEED)-1, -REVEAL_SPEED):
            draw_boxes_cover(board, boxes_to_reveal, coverage)
    
    
    def cover_boxes_animation(board, boxes_to_cover):
        # then they increase until they reach BOX_SIZE again
        for coverage in xrange(0, BOX_SIZE+REVEAL_SPEED, REVEAL_SPEED):
            draw_boxes_cover(board, boxes_to_cover, coverage)
    
    
    def draw_board(board, revealed):
        # draw the game board
        for boxx in xrange(BOARD_WIDTH):
            for boxy in xrange(BOARD_HEIGTH):
                left, top = lefttop_box(boxx, boxy) # convert board coordinates to game coordinates to draw
                if not revealed[boxx][boxy]: # if the box has not been revealed yet
                    # draw a box to cover it
                    pygame.draw.rect(DISPLAY_SURFACE, BOX_COLOR, (left, top, BOX_SIZE, BOX_SIZE))
                else: # otherwise, draw the icon
                    shape, color = get_shape_and_color(board, boxx, boxy)
                    draw_icon(shape, color, boxx, boxy)
    
    
    def draw_highlight_box(boxx, boxy):
        # draw a blue rect when player hover a box
        left, top = lefttop_box(boxx, boxy)
        pygame.draw.rect(DISPLAY_SURFACE, HIGHLIGHT_COLOR, (left-5, top-5, BOX_SIZE+10, BOX_SIZE+10), 4)
    
    
    def start_game_animation(board):
        covered_boxes = generate_revealed_boxes_data(False)
        boxes = []
        for x in xrange(BOARD_WIDTH):
            for y in xrange(BOARD_HEIGTH):
                boxes.append((x,y))
        random.shuffle(boxes)
        box_groups = split_into_groups(8, boxes)
    
        draw_board(board, covered_boxes)
        for box_group in box_groups:
            reveal_boxes_animation(board, box_group)
            cover_boxes_animation(board, box_group)
    
    
    def game_won_animation(board):
        covered_boxes = generate_revealed_boxes_data(True)
        color1 = LIGHT_BACKGROUND_COLOR
        color2 = BACKGROUND_COLOR
    
        for i in xrange(13):
            color1, color2 = color2, color1
            DISPLAY_SURFACE.fill(color1)
            draw_board(board, covered_boxes)
            pygame.display.update()
            pygame.time.wait(300)
    
    
    def has_won(revealed_boxes):
        for i in revealed_boxes:
            if False in i:
                return False
        else:
            return True
    

    Game play:

    Donate (I’ll very appreciate your donation, it will help a lot): https://www.paypal.me/TruongLoc

     
  • loctv 8:22 pm on October 14, 2016 Permalink | Reply
    Tags: ,   

    Problem: Least Prime Factor 

    • Difficulty: Easy

    Given a number N, print least prime factors for all numbers from 1 to N.  The least prime factor of an integer N is the smallest prime number that divides it. The least prime factor of all even numbers is 2. A prime number is its own least prime factor (as well as its own greatest prime factor).  Note : 1 needs to be printed for 1.

    Input: N = 6
    Output: 1 2 3 2 5 2
    

    The first line of input contains an integer T denoting the number of test cases.
    The first line of each test case is N.

    Output:
    Print least prime factors separated by space
    Constraints:
    1 ≤ T ≤ 200
    2 ≤ N ≤ 1000

    Example:
    Input:
    2
    6
    10

    Output:
    1 2 3 2 5 2
    1 2 3 2 5 2 7 2 3 2

    Implementation: Python 2.7

    from math import sqrt
    def sieve_eratosthenes(n):
        # create first n prime numbers
        sieve = [True] * (n+1)
        sieve[0] = False 
        sieve[1] = False 
        for i in xrange(2, int( sqrt(len(sieve)))):
            if sieve[i]:
                for j in xrange(i+i, len(sieve), i):
                    sieve[j] = False
        return [i for i in range(len(sieve)) if sieve[i]]
    
    primes = sieve_eratosthenes(1000)
    
    if __name__ == '__main__':
        t = input()
        for i in xrange(t):
            n = input()
            for _ in xrange(1,n+1):
                if _ == 1:
                    print 1,
                    continue
                index = 0
                while _ % primes[index] != 0:
                    index += 1
                print primes[index],
            print
    
     
  • loctv 8:06 pm on October 14, 2016 Permalink | Reply
    Tags: ,   

    Problem: Equilibrium point 

    • Difficulty: Easy

    Given an array A your task is to tell at which position the equilibrium first occurs in the array. Equilibrium position in an array is a position such that the sum of elements below it is equal to the sum of elements after it.

    Input:
    The first line of input contains an integer T denoting the no of test cases then T test cases follow. First line of each test case contains an integer N denoting the size of the array. Then in the next line are N space separated values of the array A.

    Output:
    For each test case in a new  line print the position at which the elements are at equilibrium if no equilibrium point exists print -1.

    Constraints:
    1<=T<=100
    1<=N<=100

    Example:
    Input:

    2
    1
    1
    5
    1 3 5 2 2

    Output:
    1
    3

    Explanation:
    1. Since its the only element hence its the only equilibrium point
    2. For second test case equilibrium point is at position 3 as elements below it (1+3) = elements after it (2+2)

    Implementation: Python 2.7

    def equilibrium_point(arr):
        if len(arr) == 1:
            return 1
        s = sum(arr)
        sum_so_far = arr[0]
        for i in xrange(1, len(arr)):
            #print s - (sum_so_far + arr[i])
            if s - (sum_so_far + arr[i]) == sum_so_far:
                return i+1
            sum_so_far += arr[i]
        else:
            return -1
    
    if __name__ == '__main__':
        t = input()
        for _ in xrange(t):
            n, (l) = input(), (map(int, raw_input().split()))
            print equilibrium_point(l)
    
     
  • loctv 12:07 pm on October 13, 2016 Permalink | Reply
    Tags: ,   

    Simple Sprites, Music, Sound Example in Pygame 

    I recommend you guys check out this post first, since this post reuse most of the code from that post.

    Let’s get started.

    Sprite is just an image that is drawn over and over again in a game. With Pygame, you can easily load and draw an image onto the screen. First you need to have a frame first, it’s usually  a Rect, then you load the image into the game by using pygame.image.load(path) method, next use the Surface’s method blit() to get the image cover the Rect.

    player = pygame.Rect(300,80,40,40)
    player_image = pygame.image.load(path)
    # draw the image over the Rect
    window_interface.blit(player_image, player)
    

    Music is loaded and play over and over again in a game. There’s always a music file in a game, because it’s consume lot of memory, if you have more than one music file in a game, your game probably surfer lagging.
    Here’s how you load music and play it in Pygame
    -1 means music loops forever

    pygame.mixer.music.load('path') # load music
    pygame.mixer.music.play(loops=-1, start=0.0) # play music with loops turned on and start at 0.0
    # if you can stop music while it playing
    pygame.mixer.music.stop()
    # ... and replay it again
    pygame.mixer.music.play(-1, 0.0)
    

    Sound is a short music file, literally. It’s played when an even occurs, like a button clicked, player collect new item, etc. You load sound and store its reference in a variable, then you can play it what ever you want.
    Example:

    # load sound and store reference in a variable
    sound = pygame.mixer.Sound(path)
    # game loop
    while True:
        for event in pygame.event.get():
            if event.type == KEYUP:
                if event.key == ord('m'):
                    sound.play()
    

    Apply those code into our previous example:

    import pygame, sys
    import random as rd
    from pygame.locals import *
    
    # set up pygame
    pygame.init()
    
    # set up window
    WINDOW_WIDTH = 400
    WINDOW_HEIGHT = 400
    window_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 0, 32)
    pygame.display.set_caption('Sprites and Sound')
    game_clock = pygame.time.Clock()
    
    # set up direction
    move_left = False
    move_up = False
    move_right = False
    move_down = False
    MOVEMENT_SPEED = 4
    
    # set up colors
    BLACK = (0, 0, 0)
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    BLUE = (0, 0, 255)
    SIZE = 20
    counter = 0
    
    bouncer = pygame.Rect(300, 80, 40, 40)
    # load and resize the image to fit the size of bouncer
    bouncer_image = pygame.transform.scale(pygame.image.load('player.png'), (40, 40))
    food_image = pygame.image.load('cherry.png')
    
    foods = []
    for i in xrange(20):
        foods.append(pygame.Rect(rd.randint(0, WINDOW_WIDTH), rd.randint(0, WINDOW_HEIGHT), SIZE, SIZE))
    
    # set up music
    pickup_sound = pygame.mixer.Sound('pickup.wav')
    pygame.mixer.music.load('background.mid')
    pygame.mixer.music.play()
    music_playing = True
    
    def check_overlap(rect1, rect2):
        """
        :param rect1: pygame rectangle
        :param rect2: pygame rectangle
        :return: True if rect1 overlap rect2
        """
        # check if one of four corners of rect1 is inside rect2
        for a, b in ([rect1, rect2], [rect2, rect1]):
            if is_point_inside_rect(a.left, a.top, b) \
            or is_point_inside_rect(a.left, a.bottom, b) \
            or is_point_inside_rect(a.right, a.top, b) \
            or is_point_inside_rect(a.right, a.bottom, b):
                return True
        else:
            return False
    
    def is_point_inside_rect(x, y, rect):
        return (x > rect.left and x < rect.right and y > rect.top and y < rect.bottom)
    
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
    
            if event.type == KEYDOWN:
                if event.key == K_LEFT or event.key == ord('a'):
                    move_left = True
                    move_right = False
                if event.key == K_RIGHT or event.key == ord('d'):
                    move_right = True
                    move_left = False
                if event.key == K_UP or event.key == ord('w'):
                    move_up = True
                    move_down = False
                if event.key == K_DOWN or event.key == ord('s'):
                    move_down = True
                    move_up = False
            if event.type == KEYUP:
                if event.key == K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                if event.key == K_LEFT or event.key == ord('a'):
                    move_left = False
                if event.key == K_RIGHT or event.key == ord('d'):
                    move_right = False
                if event.key == K_UP or event.key == ord('w'):
                    move_up = False
                if event.key == K_DOWN or event.key == ord('s'):
                    move_down = False
                # check if player want to mute music
                if event.key == ord('m'):
                    if music_playing:
                        pygame.mixer.music.stop()
                    else:
                        pygame.mixer.music.play(-1, 0.0)
                    music_playing = not music_playing
    
            if event.type == MOUSEBUTTONUP:
                foods.append(pygame.Rect(event.pos[0], event.pos[1], SIZE, SIZE))
    
    
        window_surface.fill(BLACK) # set background color of window to black
    
        # move the bouncer
        if move_down and bouncer.bottom < WINDOW_HEIGHT:
            bouncer.top += MOVEMENT_SPEED
        if move_up and bouncer.top > 0:
            bouncer.top -= MOVEMENT_SPEED
        if move_left and bouncer.left > 0:
            bouncer.left -= MOVEMENT_SPEED
        if move_right and bouncer.right < WINDOW_WIDTH:
            bouncer.right += MOVEMENT_SPEED
    
        # draw the bouncer
        #pygame.draw.rect(window_surface, GREEN, bouncer)
        window_surface.blit(bouncer_image, bouncer)
    
        # check collisions between foods and bouncer
        for food in foods[:]:
            if bouncer.colliderect(food):
                foods.remove(food)
                pickup_sound.play()
    
        # draw 'foods'
        for food in foods:
            #pygame.draw.rect(window_surface, BLUE, food)
            window_surface.blit(food_image, food)
        # after each 40 loops, we add new food
        counter += 1
        if counter > 20:
            counter = 0
            foods.append(pygame.Rect(rd.randint(0, WINDOW_WIDTH), rd.randint(0, WINDOW_HEIGHT), SIZE, SIZE))
    
        # draw the window onto the screen
        pygame.display.update()
        # sleep 0.02 second (around 50 frame per seconds)
        game_clock.tick(40) # 40 frame per second
    
    
    

    Files: Download
    Run to see how fun it is.
    Feel free to donate me, since I’m a poor coder (that’s why I’m still using free wordpress domain) 😦

     
  • loctv 10:21 am on October 13, 2016 Permalink | Reply
    Tags: ,   

    Simple Example For Handling Input In Pygame 

    If you haven’t read my post about collision detection in pygame, you must check it out to be able to continue with this tutorial. So check out  collision detection please.

    In this example, player will press one (or two) of eight buttons : key up, key down, key left, key right or w,s,a,d to move the box up, down, left, right, respectively. Player can also move the box diagonally. When the box hit the foods, the foods will disappear. When player clicks on the window, new food is created at that position. After each 20 loops, new food is created and placed randomly on the window. The code is almost the same as before, but we removed direction variables, and change them with move_up, move_down, move_left and move_right flags to check for input. If player hit key up or button ‘w’, move_up is true, move_down is false, the box will go up, same goes for the rest.

    Here’s the code

    import pygame, sys
    import random as rd
    from pygame.locals import *
    
    # set up pygame
    pygame.init()
    
    # set up window
    WINDOW_WIDTH = 400
    WINDOW_HEIGHT = 400
    window_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 0, 32)
    pygame.display.set_caption('Animation')
    game_clock = pygame.time.Clock()
    
    # set up direction
    move_left = False
    move_up = False
    move_right = False
    move_down = False
    MOVEMENT_SPEED = 4
    
    # set up colors
    BLACK = (0, 0, 0)
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    BLUE = (0, 0, 255)
    SIZE = 20
    counter = 0
    
    bouncer = pygame.Rect(300, 80, 50, 50)
    foods = []
    for i in xrange(20):
        foods.append(pygame.Rect(rd.randint(0, WINDOW_WIDTH), rd.randint(0, WINDOW_HEIGHT), SIZE, SIZE))
    
    def check_overlap(rect1, rect2):
        """
        :param rect1: pygame rectangle
        :param rect2: pygame rectangle
        :return: True if rect1 overlap rect2
        """
        # check if one of four corners of rect1 is inside rect2
        for a, b in ([rect1, rect2], [rect2, rect1]):
            if is_point_inside_rect(a.left, a.top, b) \
            or is_point_inside_rect(a.left, a.bottom, b) \
            or is_point_inside_rect(a.right, a.top, b) \
            or is_point_inside_rect(a.right, a.bottom, b):
                return True
        else:
            return False
    
    def is_point_inside_rect(x, y, rect):
        return (x > rect.left and x < rect.right and y > rect.top and y < rect.bottom)
    
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
    
            if event.type == KEYDOWN:
                if event.key == K_LEFT or event.key == ord('a'):
                    move_left = True
                    move_right = False
                if event.key == K_RIGHT or event.key == ord('d'):
                    move_right = True
                    move_left = False
                if event.key == K_UP or event.key == ord('w'):
                    move_up = True
                    move_down = False
                if event.key == K_DOWN or event.key == ord('s'):
                    move_down = True
                    move_up = False
            if event.type == KEYUP:
                if event.key == K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                if event.key == K_LEFT or event.key == ord('a'):
                    move_left = False
                if event.key == K_RIGHT or event.key == ord('d'):
                    move_right = False
                if event.key == K_UP or event.key == ord('w'):
                    move_up = False
                if event.key == K_DOWN or event.key == ord('s'):
                    move_down = False
            if event.type == MOUSEBUTTONUP:
                foods.append(pygame.Rect(event.pos[0], event.pos[1], SIZE, SIZE))
    
    
        window_surface.fill(BLACK) # set background color of window to black
    
        # move the bouncer
        if move_down and bouncer.bottom < WINDOW_HEIGHT:
            bouncer.top += MOVEMENT_SPEED
        if move_up and bouncer.top > 0:
            bouncer.top -= MOVEMENT_SPEED
        if move_left and bouncer.left > 0:
            bouncer.left -= MOVEMENT_SPEED
        if move_right and bouncer.right < WINDOW_WIDTH:
            bouncer.right += MOVEMENT_SPEED
    
        # draw the bouncer
        pygame.draw.rect(window_surface, GREEN, bouncer)
    
        # check collisions between foods and bouncer
        for food in foods[:]:
            if check_overlap(food, bouncer):
                foods.remove(food)
    
        # draw 'foods'
        for food in foods:
            pygame.draw.rect(window_surface, BLUE, food)
    
        # after each 40 loops, we add new food
        counter += 1
        if counter > 20:
            counter = 0
            foods.append(pygame.Rect(rd.randint(0, WINDOW_WIDTH), rd.randint(0, WINDOW_HEIGHT), SIZE, SIZE))
    
        # draw the window onto the screen
        pygame.display.update()
        # sleep 0.02 second (around 50 frame per seconds)
        game_clock.tick(40) # 40 frame per second
    
    
    

     

    Demo

     
  • loctv 5:11 pm on October 12, 2016 Permalink | Reply
    Tags: ,   

    Simple Collision Detection Example in Pygame 

    If you haven’t read Simple Animation In Pygame yet, go check it out. Because I’ll reuse many of the code in that post.

    Let’s get started by showing the code:

    import pygame, sys
    import random as rd
    from pygame.locals import *
    
    # set up pygame
    pygame.init()
    
    # set up window
    WINDOW_WIDTH = 400
    WINDOW_HEIGHT = 400
    window_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 0, 32)
    pygame.display.set_caption('Animation')
    game_clock = pygame.time.Clock()
    
    # set up direction
    DOWN_LEFT = 1
    DOWN_RIGHT = 2
    UP_LEFT = 3
    UP_RIGHT = 4
    directions = [DOWN_LEFT, DOWN_RIGHT, UP_LEFT, UP_RIGHT]
    MOVEMENT_SPEED = 4
    
    # set up colors
    BLACK = (0, 0, 0)
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    BLUE = (0, 0, 255)
    SIZE = 20
    counter = 0
    
    bouncer = {'rect': pygame.Rect(300, 80, 50, 80), 'dir':UP_RIGHT}
    foods = []
    for i in xrange(20):
        foods.append(pygame.Rect(rd.randint(0, WINDOW_WIDTH), rd.randint(0, WINDOW_HEIGHT), SIZE, SIZE))
    
    def check_overlap(rect1, rect2):
        """
        :param rect1: pygame rectangle
        :param rect2: pygame rectangle
        :return: True if rect1 overlap rect2
        """
        # check if one of four corners of rect1 is inside rect2
        for a, b in ([rect1, rect2], [rect2, rect1]):
            if is_point_inside_rect(a.left, a.top, b) \
            or is_point_inside_rect(a.left, a.bottom, b) \
            or is_point_inside_rect(a.right, a.top, b) \
            or is_point_inside_rect(a.right, a.bottom, b):
                return True
        else:
            return False
    
    def is_point_inside_rect(x, y, rect):
        return (x > rect.left and x < rect.right and y > rect.top and y < rect.bottom)
    
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
    
        window_surface.fill(BLACK) # set background color of window to black
    
        if bouncer['dir'] == DOWN_LEFT:
            bouncer['rect'].left -= MOVEMENT_SPEED
            bouncer['rect'].top += MOVEMENT_SPEED
        if bouncer['dir'] == DOWN_RIGHT:
            bouncer['rect'].left += MOVEMENT_SPEED
            bouncer['rect'].top += MOVEMENT_SPEED
        if bouncer['dir'] == UP_LEFT:
            bouncer['rect'].left -= MOVEMENT_SPEED
            bouncer['rect'].top -= MOVEMENT_SPEED
        if bouncer['dir'] == UP_RIGHT:
            bouncer['rect'].left += MOVEMENT_SPEED
            bouncer['rect'].top -= MOVEMENT_SPEED
    
        # check out of bound
        if bouncer['rect'].top < 0: # over the top of window
            if bouncer['dir'] == UP_LEFT:
                bouncer['dir'] = rd.choice(directions) #DOWN_LEFT
            if bouncer['dir'] == UP_RIGHT:
                bouncer['dir'] = rd.choice(directions) #DOWN_RIGHT
        if bouncer['rect'].bottom > WINDOW_HEIGHT: # below the bottom of window
            if bouncer['dir'] == DOWN_LEFT:
                bouncer['dir'] = rd.choice(directions) #UP_LEFT
            if bouncer['dir'] == DOWN_RIGHT:
                bouncer['dir'] = rd.choice(directions) #UP_RIGHT
        if bouncer['rect'].left < 0: # out of left side
            if bouncer['dir'] == DOWN_LEFT:
                bouncer['dir'] = rd.choice(directions) #DOWN_RIGHT
            if bouncer['dir'] == UP_LEFT:
                bouncer['dir'] = rd.choice(directions) #UP_RIGHT
        if bouncer['rect'].right > WINDOW_WIDTH: # out of right side
            if bouncer['dir'] == DOWN_RIGHT:
                bouncer['dir'] = rd.choice(directions) #DOWN_LEFT
            if bouncer['dir'] == UP_RIGHT:
                bouncer['dir'] = rd.choice(directions) #UP_LEFT
        # draw the bouncer
        pygame.draw.rect(window_surface, GREEN, bouncer['rect'])
    
        # check collisions between foods and bouncer
        for food in foods[:]:
            if check_overlap(food, bouncer['rect']):
                foods.remove(food)
    
        # draw 'foods'
        for food in foods:
            pygame.draw.rect(window_surface, BLUE, food)
    
        # after each 40 loops, we add new food
        counter += 1
        if counter > 20:
            counter = 0
            foods.append(pygame.Rect(rd.randint(0, WINDOW_WIDTH), rd.randint(0, WINDOW_HEIGHT), SIZE, SIZE))
    
        # draw the window onto the screen
        pygame.display.update()
        # sleep 0.02 second (around 50 frame per seconds)
        game_clock.tick(40) # 40 frame per second
    

    What we’re doing is we create a bouncer, and many boxes. Whenever the bouncer hit a box, the box will be removed from the screen.
    What we should focus here is the two important functions, check_overlap and is_point_inside_rect.

    Let’s go with is_point_inside_rect_first, since it’s used by check_overlap.
    This picture virtually how to check a point’s inside or outside of a rectangle:

    capture3

    A point (x,y) is inside a rectangle if its x is bigger than left and smaller than right side value of rectangle, same goes for top and bottom. In the above pictures, there are three point inside the rectangle.

    Now let’s go to the check_overlap function. This function check if four corners of a rect1 is inside rect2 [rect1, rect2] and vice versa [rect2, rect1].

    The code inside game loop has been changed a little bit. Line 63 to 74 move the bouncer, line 77 to 96 check if the bouncer hit one of the four sides of the window, if it is, randomly change the direction of it. The for loop at line 101 check if the bouncer collide with any food, and if it collide, it will eat the food, the food will disappear. Notice that we get food from food[:] not food. This is because in Python you should not remove or add a list while iterating through it. For example it’s difficult if you’re counting the number of jelly beans in a jar while someone’s adding or removing jelly beans, same thing goes for list.

    Line 111 check if counter > 20, if it is, add more food into foods. The last line , game_clock.tick(), I just simply understand that it kind of sets the frame rate of the game. No matter how fast or slow your computer is, the while loop will always run 40 times per second.

    Result of the code above:

    capture

    That’s it for this tutorial. Feel free to donate, many thanks.

     
c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel