Posted 4 mins ago

Codechef Python July Cook Off 2014

Hi, here my performance in the July Cook Off 2014

Github Codechef Python July Cook Off 2014

Problem Statement Copy-Paste:
You had an array of integer numbers. You also had a beautiful operations called “Copy-Paste” which allowed you to copy any contiguous subsequence of your array and paste it in any position of your array. For example, if you have array [1, 2, 3, 4, 5] and copy it’s subsequence from the second to the fourth element and paste it after the third one, then you will get [1, 2, 3, 2, 3, 4, 4, 5] array. You remember that you have done a finite(probably zero) number of such operations over your initial array and got an array A as a result. Unfortunately you don’t remember the initial array itself, so you would like to know what could it be. You are interested by the smallest such array. So the task is to find the minimal size(length) of the array that A can be obtained from by using “Copy-Paste” operations.

Input

The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the number of elements in obtained array A. The second line contains N space-separated integers A1, A2, …, AN denoting the array.

Output

For each test case, output a single line containing the answer.

My way:
Here we only need to add all the elements to a set, and it will delete the repeated elements for us. Then, return the set.

Here my code:

cases = int(input())
for a in range(cases):
    n = int(input())
    numbers = input().split()
    res = set(numbers)
    print(len(res))

Problem Statement Sum Queries:
Andrii is good in Math, but not in Programming. He is asking you to solve following problem: Given an integer number N and two sets of integer A and B. Let set A contain all numbers from 1 to N and set B contain all numbers from N + 1 to 2N. Multiset C contains all sums a + b such that a belongs to A and b belongs to B. Note that multiset may contain several elements with the same values. For example, if N equals to three, then A = {1, 2, 3}, B = {4, 5, 6} and C = {5, 6, 6, 7, 7, 7, 8, 8, 9}. Andrii has M queries about multiset C. Every query is defined by a single integer q. Andrii wants to know the number of times q is contained in C. For example, number 6 is contained two times, 1 is not contained in C at all.
Please, help Andrii to answer all the queries.

Input

The first line of the input contains two integers N and M. Each of the next M line contains one integer q, the query asked by Andrii.

Output

Output the answer for each query in separate lines as in example.

My way:
Here we need to read each query, and then we have three posibilities. If query is less or equal n + 1, then print 0, else if query is less or equal 2 * n + 1, then print query – n – 1, otherwise, print 3 * n – query + 1.

Here my code:

temp = input().split()
n = int(temp[0])
queries = int(temp[1])
for i in range(queries):
    query = int(input())
    if query <= n + 1:
        print(0)
    elif query <= (2 * n + 1):
        print(query - n - 1)
    else:
        print(3 * n - query + 1)

Thank you very much

Posted 1 day ago

Ndepend Part 2 – Reports in html

Hi! Do you remember about NDepend? Is an analysis tool that I am using and you can download for free trial here: Ndepend download.

You can’t imagine how powerful this tool is.

Last time I write about it, I told you about Queries and Rules part, which is my favourite part, and today I would like to talk to you about another great feature.

As soon as you perform some analysis, a report in html will be opened in your browser really fast. Here you will be able to check several things, like:

Diagrams

Dependency graph (This explanations is from NDepend documentation):
This diagram represents the Graph of Dependencies beetween the .NET assemblies of your application.
This static diagram can be useful but it is just a coarse view of your application architecture.
It is recommended to use the NDepend interactive dependency Graph and interactive Dependency Matrix for an in-depth exploration of the actual architecture of your code.

Dependency Matrix (This explanations is from NDepend documentation):
This diagram represents the DSM (Dependency Structure Matrix) beetween the .NET assemblies of your application.
The Dependency Matrix is a compact way to represent and navigate across dependencies between components.
The number on cells of the Dependency Matrix included in the report, represent the number of types involved in the coupling
It is recommended to use the NDepend interactive dependency Graph and interactive Dependency Matrix for an in-depth exploration of the actual architecture of your code.

Treemap Matrix (This explanations is from NDepend documentation):
In this Metric View, the code base is represented through a Treemap.
Treemapping is a method for displaying tree-structured data by using nested rectangles.
In the present treemap, each rectangle represents a method and the area of a rectangle is proportional to the number of lines of code of the corresponding method.

Abstractness vs. Instability (This explanations is from NDepend documentation):
The Abstractness versus Instability Diagram helps to detect which assemblies are potentially painful to maintain (i.e concrete and stable) and which assemblies are potentially useless (i.e abstract and instable).
Abstractness: If an assembly contains many abstract types (i.e interfaces and abstract classes) and few concrete types, it is considered as abstract.
Stability: An assembly is considered stable if its types are used by a lot of types of tier assemblies. In this conditions stable means painful to modify.

Then, you will find all the metrics. With things like Code Coverage by Tests, Lines of code, Method complexity, etc…

This is an amazing feature, really. It’s really useful in the work environment! ;)

I trully recommend this tool, is one of the most useful tool I’ve never used in the job environment in order to analyse the code.

I would like to know your impressions too! ;)

Posted 1 day ago

Codeforces Python Problem A #443 Anton And Letters

Hi, here a new problem I’ve solved using Python!

Github Codeforces Python Problem A #443 Anton And Letters

Problem Statement:
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.

Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.

Input
The first and the single line contains the set of letters. The length of the line doesn’t exceed 1000. It is guaranteed that the line starts from an opening curved bracket and ends with a closing curved bracket. Between them, small English letters are listed, separated by a comma. Each comma is followed by a space.

Output
Print a single number — the number of distinct letters in Anton’s set.

My way:
Once we get the text, replacing the characters “,”, “{” and “}” for a “”, then split and store in a variable called temp. Then, create a list called result, and only, going through all the elements in temp, if result doesn’t contains the element, add it. At the end return the length of the list.

Here my code:

text = input().replace(",", "").replace("{", "").replace("}", "").split()

result = []
for i in range(len(text)):
    if text[i] not in result:
        result.append(text[i])
print(len(result))

Thank you very much

Posted 2 days ago

TopCoder Python Practice Room SRM 179 DIV 2, Problem 250

Hi, here a new problem I’ve solved using Python!

Github TopCoder Python Practice Room SRM 179 DIV 2, Problem 250

Problem Statement:
Proposals arrive at our office in a sequence. We give each one a score. We then calculate its “rank” based on comparison with the scores of the most recent submissions. Its rank is 1 + the number of recent scores that are greater than it. So a rank of 1 is the best possible rank and indicates that no recent score was greater. A rank of 2 would mean that exactly one recent score was greater. We need software that can calculate the rank of each score.
Create a class OnLineRank that contains a method calcRanks that is given k, the number of recent scores to use in each rank calculation, and tuple (integer) scores, the sequence of scores of the arriving proposals. The method should calculate the rank for each score and return the sum of all the ranks.
Each rank should be calculated based on the preceding k scores. If fewer than k scores have preceded this score, base the calculation on all the preceding scores. (The first proposal is thus guaranteed a rank of 1.)

My way:
Here, using a for loop starting from i = 1, start the rank to 1, then, with check the index where we need to start, i – k, and if it’s less than 0, then index equals 0. Then, with another for loop from a = index to i, if scores[a] is bigger than scores[i], add +1 to rank, and at the end of each iteration, add rank to the final result + 1 from the first element, which always have rank 1.

Here my code:

import math,string,itertools,fractions,heapq,collections,re,array,bisect,random

class OnLineRank:
    def calcRanks(self, k, scores):
        result = 1
        for i in range(1, len(scores)):
            rank = 1
            index = i - k
            if index < 0:
                index = 0
            for a in range(index, i):
                if scores[a] > scores[i]:
                    rank += 1
            result += rank
        return result

Thank you very much

Posted 3 days ago

Codeforces Python Problem A #448 Rewards

Hi, here a new problem I’ve solved using Python!

Github Codeforces Python Problem A #448 Rewards
Codeforces Problem Statement

My way:
First of all we need to get the sum of all the cups and all the trophies. Then, while shelves are bigger than 0, if totalCups are bigger than 0, substract 5 from cups, else if totalTrophies are bigger than 0, substract 10 from trophies. If at the end, totalCups or totalTrophies are bigger than 0, print “NO”, otherwise print “YES”.

Here my code:

sum1 = sum([int(n) for n in input().split()])
sum2 = sum([int(n) for n in input().split()])
shelves = int(input())
while shelves > 0:
    if sum1 > 0:
        sum1 -= 5
    elif sum2 > 0:
        sum2 -= 10
    shelves -= 1
if sum1 > 0 or sum2 > 0:
    print("NO")
else:
    print("YES")

Thank you very much

Posted 5 days ago

HackerRank Python Project Euler Challenge – Smallest Multiple

Hi, here a new problem I’ve solved using Python!

Github HackerRank Python Project Euler Challenge – Smallest Multiple
HackerRank Problem Statement

Problem Statement:
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible(divisible with no remainder) by all of the numbers from 1 to N?

Input Format
First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N.

Output Format
Print the required answer for each test case.

Constraints
1≤T≤10
1≤N≤40

My way:
Starting from n (i) (input) in each testcase, set a temporal to True, then, for 1 (a) to n, if i modulo a not equals 0 , then set temp equals False, and break the loop. Then, if temp equals True, print i and break the loop.

Here my code:

cases = int(input())
for i in range(cases):
    n = int(input())
    for i in range(n, 1000000):
        temp = True
        for a in range(1, n + 1):
            if i % a != 0:
                temp = False
                break
        if temp:
            print(i)
            break

Thank you very much

Posted 5 days ago

HackerRank Python Project Euler Challenge – Even Fibonacci Numbers

Hi, here a new problem I’ve solved using Python!

Github HackerRank Python Project Euler Challenge – Even Fibonacci Numbers
HackerRank Problem Statement

My way:
First, I store all the fibonacci sequence from 1 to 4^16 only once in the beginning. Then, in each case, only go through the fibonacci previously stored, and if fib[i] is bigger than n, break the loop, otherwise, check if it’s even, and if it is, then add to result. At the end of each case, print result.

Here my code:

cases = int(input())
fib = [1, 1]
index = 1
while fib[index] + fib[index - 1] <= 40000000000000000:
    fib.append(fib[index] + fib[index - 1])
    index += 1

for i in range(cases):
    n = int(input())
    result = 0
    for i in range(1, len(fib)):
        if fib[i] > n:
            break
        if fib[i] % 2 == 0:
            result += fib[i]
    print(result)

Thank you very much

Posted 6 days ago

TopCoder Python Practice Room SRM 178 DIV 2, Problem 250

Hi, here a new problem I’ve solved using Python!

Github TopCoder Python Practice Room SRM 178 DIV 2, Problem 250

Problem Statement:
A simple calculator accepts the following kinds of strings as input:
1) NUM+NUM
2) NUM-NUM
3) NUM*NUM
4) NUM/NUM
where NUM is a positive integer, between 1 and 10000 inclusive that can contain leading zeros. Return the value produced by the given expression. Here +,-,*, and / denote addition, subtraction, multiplication and division respectively. All operations are done on integers, so “5/3″ returns 1.

My way:
We only need to check the four possibilities. Then only if contains “+”, set result to the sum of the splitted parts, and this way with the other 3 different possibilities.

Here my code:

import math,string,itertools,fractions,heapq,collections,re,array,bisect,random

class SimpleCalculator:
    def calculate(self, input):
        result = 0
        splitted = []
        if "+" in input:
            splitted = input.split("+")
            result = int(splitted[0]) + int(splitted[1])
        elif "-" in input:
            splitted = input.split("-")
            result = int(splitted[0]) - int(splitted[1])
        elif "*" in input:
            splitted = input.split("*")
            result = int(splitted[0]) * int(splitted[1])
        elif "/" in input:
            splitted = input.split("/")
            result = int(splitted[0]) / int(splitted[1])
        return int(result)

Thank you very much

Posted 1 week ago

TopCoder Python Practice Room SRM 176 DIV 2, Problem 250

Hi, here a new problem I’ve solved using Python!

Github TopCoder Python Practice Room SRM 176 DIV 2, Problem 250

Problem Statement:
When doing any work with visual media it is often very useful to have the complement of a color on hand to create contrast and bring the focus of a picture to a particular place. To create the complement of a color on a computer, each of the red, green, and blue values of a color are inverted. Each of the red, green, and blue values of a color can range from 0 to 255, inclusive. If a particular component of one color is 50, then that component of its complement is 255-50=205. Although this generally works well, it doesn’t generate good complements for grey colors that have all three components right around 128. To fix this you will return an alternate complement for grey colors. If each component of a color and its corresponding component of the color’s complement differ by 32 or less, then make the complement of each component by either adding 128 to a component’s value, or by subtracting 128 from a component’s value, whichever one results in a legal value. For example, the color {120,130,140} would have the complement {125,105,115}, but each component in the color and the complement differ by 32 or less, so we make the complement {248,2,12}. Create a class RGBColor with a method getComplement that takes a tuple (integer) rgb representing the red, green, and blue values of a color, in that order, and returns a tuple (integer) representing the red, green, and blue values of the complement of that color, in that same order.

My way:
First we need to get the complement color, doing each of the rgb elements 255 – rgb[i]. Then, if all the rgb differs from <= 32 to each new color, then, add +128 or substact -128 to each element of the initial array while the number is a valid one. Then return rgb.

Here my code:

import math,string,itertools,fractions,heapq,collections,re,array,bisect,random

class RGBColor:
    def getComplement(self, rgb):
        newRgb = [255 - rgb[0], 255 - rgb[1], 255 - rgb[2]]
        if abs(rgb[0] - newRgb[0]) <= 32 and abs(rgb[1] - newRgb[1]) <= 32 and abs(rgb[2] - newRgb[2]) <= 32:
            if rgb[0] + 128 <= 255:
                newRgb[0] = rgb[0] + 128
            else:
                newRgb[0] = rgb[0] - 128
            if rgb[1] + 128 <= 255:
                newRgb[1] = rgb[1] + 128
            else:
                newRgb[1] = rgb[1] - 128
            if rgb[2] + 128 <= 255:
                newRgb[2] = rgb[2] + 128
            else:
                newRgb[2] = rgb[2] - 128
        return newRgb

Thank you very much

Posted 1 week ago

TopCoder Python Practice Room SRM 175 DIV 2, Problem 250

Hi, here a new problem I’ve solved using Python!

Github TopCoder Python Practice Room SRM 175 DIV 2, Problem 250

Problem Statement:
Let’s walk around the clock. We start at twelve o’clock and flip a coin. If it comes up heads, we step forward by one hour. If it’s tails, we step one hour backward. We flip the coin a second time, but now we step two hours forward in the case of heads, or two hours backward for tails. On the third flip, we step three hours forward or backward on the same principle. In general, then, the nth flip decides the direction in which we step n hours: we move forward on heads, and backward on tails.
You are given a string describing a sequence of coin flips such that the nth character is either ‘h’, meaning that the nth flip is heads, or ‘t’ to signify that the nth flip is tails. Return the hour at which we end up by following the above procedure.

My way:
Starting in result equals 0, and going through flips, if flip[i] equals ‘h’, then add to result i + 1, otherwise, substract i + 1. Then, while result is less or equals 0, add +12 to result, otherwise, result % (modulo) 12, and if it’s 0, add +12. Then return result.

Here my code:

import math,string,itertools,fractions,heapq,collections,re,array,bisect,random

class ClockWalk:
    def finalPosition(self, flips):
        result = 0
        for i in range(len(flips)):
            if flips[i] == 'h':
                result += (i + 1)
            else:
                result -= (i + 1)
        while result <= 0:
            result += 12
        else:
            result %= 12
            if result == 0:
                result = 12
        return result

Thank you very much

Visit Us On TwitterVisit Us On FacebookVisit Us On LinkedinCheck Our Feed