Posted 2 mins ago

HackerRank Python MazimizingXOR

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

Github HackerRank Python MazimizingXOR
HackerRank Problem Statement

My way:
Here only using a couple of for loops, with all the combinations of two elements, get the max between result and a ^ b. Then, return result.

Here my code:

def main():
	l = int(input())
	r = int(input())
	result = 0
	for i in range(l, r + 1):
		for a in range(i, r + 1):
			result = max(result, i ^ a)
	print(result)

if __name__ == "__main__":
	main()

Thank you very much

Posted 43 mins ago

HackerRank Python The Love Letter Mistery

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

Github HackerRank Python The Love Letter Mistery
HackerRank Problem Statement

My way:
Here I’ve used a string initialized like the alphabet in lowercase, in order to check if the index of a letter if bigger than the other. Then, starting from 0 to len(word) / 2, add to the result the absolute value of substraction of both indices. Continue doing this until the middel of the word. Then return result.

Here my code:

def main():
	cases = int(input())
	for a in range(cases):
		abc = "abcdefghijklmnopqrstuvwxyz"
		result = 0
		word = input()
		j = -1
		for i in range(int(len(word) / 2)):
			result += abs(abc.index(word[i]) - abc.index(word[j]))
			j -= 1
		print(result)

if __name__ == "__main__":
	main()

Thank you very much

Posted 1 day ago

TopCoder Python Practice Room SRM 145 DIV 2, Problem 500

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

Github TopCoder Python Practice Room SRM 145 DIV 2, Problem 500

Problem Statement:
You are writing firmware for an exercise machine. Each second, a routine in your firmware is called which decides whether it should display the percentage of the workout completed. The display does not have any ability to show decimal points, so the routine should only display a percentage if the second it is called results in a whole percentage of the total workout.
Given a string time representing how long the workout lasts, in the format “hours:minutes:seconds”, return the number of times a percentage will be displayed by the routine. The machine should never display 0% or 100%.

Constraints:
time will be a string formatted as “HH:MM:SS”, HH = hours, MM = minutes, SS = seconds.
The hours portion of time will be an integer with exactly two digits, with a value between 00 and 23, inclusive.
The minutes portion of time will be an integer with exactly two digits, with a value between 00 and 59, inclusive.
The seconds portion of time will be an integer with exactly two digits, with a value between 00 and 59, inclusive.
time will not be “00:00:00″.

My way:
First, we need to get the total seconds, and then, get the last two elements in seconds. Then, with a for loop in range(99), initialize a new temporal variable called completed to 0, then add those two elements in seconds to completed each time, and check if ismodulo 100 equals 0, if it is, add +1 to the total result. At the end, return totalTimes.

Here my code:

class ExerciseMachine:
    def getPercentages(self, time):
        totalTimes = 0
        seconds = 0
        temp = time.split(":")
        seconds += int(temp[0]) * 3600
        seconds += int(temp[1]) * 60
        seconds += int(temp[2])
        stepPercentage = int(str(seconds)[-2:])
        completed = 0
        for i in range(99):
            completed += stepPercentage
            if completed % 100 == 0:
                totalTimes += 1
        return totalTimes

Thank you very much

Posted 1 day ago

TopCoder Python Practice Room SRM 180 DIV 2, Problem 250

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

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

Problem Statement:
The dinky is a small fish that breeds monogamously and regularly. Within days of its birth, the male of the species seeks out a mate and bonds with her for life, never dallying with another. At the end of every month, the couple issues exactly two offspring, of which one is a boy and the other a girl. Each of these, in turn, goes off on its amorous quest. Inbreeding is not uncommon in the confines of a fish tank, so a pair of cousins or even siblings may end up mating. If there are more females than males, the excess number who cannot secure a mate will not give birth in that month.
Despite their diminutive dimensions and peaceful nature, a population of dinkies must not be allowed to multiply ad infinitum. Experts recommend that one allot at least half a liter of water per dinky fish. Anything less than that, and the tank is said to be crowded. The solution is either to buy a larger tank or to catch some dinkies for breakfast.
Given the volume of a tank in liters, the number of male dinkies currently inhabiting the tank, and the number of females present, you are to calculate the number of months that can elapse before the tank becomes crowded. Bear in mind that all couples reproduce simultaneously at the end of every month. If the input values are such that the tank is already crowded, the correct answer is 0. If the tank will become crowded at the end of the first month, the answer is 1.

Constraints:
tankVolume is between 1 and 1000000 (one million), inclusive
maleNum is between 1 and 1000, inclusive
femaleNum is between 1 and 1000, inclusive

My way:
Here, we only need to check each time that nameNum plus femaleNum are lesser or equal than tankCap * 2, then get the minimum of the fishes, add that num to both sex, and then add +1 month. At the ends, return the number of months.

Here my code:

class DinkyFish:
    def monthsUntilCrowded(self, tankVolume, maleNum, femaleNum):
        months = 0
        while maleNum + femaleNum <= (tankVolume * 2):
            minFishes = min(maleNum, femaleNum)
            maleNum += minFishes
            femaleNum += minFishes
            months += 1
        return months

Thank you very much

Posted 1 week 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 week 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 week 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 1 week 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 1 week 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 2 weeks 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

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