Posted 2 days ago

TopCoder Python Practice Room SRM 171 DIV 2, Problem 250

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

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

Problem Statement:
When playing many classic role playing games you often write die rolls in the form “ndx”, where n indicates the number of dice of size x to be rolled. A die of size x is an x-sided die that has a distinct number between 1 and x, inclusive, on each of its sides. For example, “2d8″ would mean “roll two eight sided dice”. Given a tuple (string) representing the dice to roll, return a tuple (integer) representing the minimum, maximum, and average die rolls (in that order). Round the value of the average die roll down to the highest integer less than or equal to the actual value. For example, the input {“1d8″,”3d4″,”2d6″} would have a minimum of 6 (if all the dice turned up ones), a maximum of 32 (if all the dice turned up their highest values), and an average of 19. The return value would be {6, 32, 19}.

My way:
Going through all the elements, I’ve created a list called result with three elements. Then, in each element of the dice tuple, split the dice, then, add to the result[0] the numbers of the left of the dice, to result[1] add the number in the left of the dice multiplying by the number at the right, and to result[2] add the number in the left multiplying by 1 + the numbeer in the right. At the end, get the average of result[2] dividing by 2. And then return result.

Here my code:

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

class RPG:
    def dieRolls(self, dice):
        result = [0, 0, 0]
        avg = 0.0
        for i in range(len(dice)):
            temp = dice[i].split('d')
            result[0] += int(temp[0])
            result[1] += int(temp[0]) * int(temp[1])
            avg += ((int(temp[0])) * (1 + int(temp[1])))
        result[2] = int(avg / 2)
        return result

Thank you very much

Posted 2 days ago

TopCoder Python Practice Room SRM 170 DIV 2, Problem 250

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

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

Problem Statement:
You are playing TopRPG, the latest and hottest new console-style RPG (role-playing game) to hit the market. Much like many RPGs, it features the main characters getting stronger as the game progresses by obtaining a nebulous sort of thing known as experience, which is typically acquired by killing monsters.
The strategy guide open in front of you tells you how much experience you’ll need to get to each level, represented as a tuple (integer) expNeeded. For example, if expNeeded were {150, 450, 900, 1800}, you would need a total of 150 experience to get to level 1 (from level 0), then another (450 – 150) = 300 experience to get to level 2, and so on.
You have 0 experience at the start, and you are about to go through an area where you will get a fixed amount of experience. You want to know how far you will be from the next level after you finish. Given a tuple (integer) expNeeded, where the ith element is the total amount of experience required to advance to level i, and an int received, indicating the amount of experience you will get, return an int which is the amount of experience it will take you to get to the next level after you receive the experience.

My way:
We need to go through the expNeeded tuple, checking if received is lesser than some element. If it is, then, store in the variable index the index of this element and break the loop. Then return expNeeded[i] – received.

Here my code:

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

class LevelUp:
    def toNextLevel(self, expNeeded, received):
        index = 0
        for i in range(len(expNeeded)):
            if received < expNeeded[i]:
                index = i
                break
        return expNeeded[i] - received

Thank you very much

Posted 6 days ago

Bitly API using Python

Hi, here I’ve been using Python to make a call to the Bitly API in order to get a shorten link from a long url.

Github Bitly API using Python

Bitly is a website where you can enter a long url, and they will give you a shorten link, then I’ve created something with Python where you can pass a url in the format (www.yoururl.com) and will return the shorten url from Bitly.

In the key part, you will need to register in Bitly and get your own api_key, then change for the key vcariable.

Here the code:

from urllib.request import urlopen
import json

API_KEY = 'key'

endpoint = 'https://api-ssl.bitly.com/v3/shorten?access_token='
endpoint += API_KEY
endpoint += '&uri=http://'
endpoint += input("Enter your url to shorten: ")
endpoint += '&format=json'

def getResponse(endpoint):
	return str(urlopen(endpoint).read().decode('utf-8'))

def loadJsonResponse(response):
	return json.loads(response)

response = getResponse(endpoint)
result = loadJsonResponse(response)
print("Shorted url: " + result['data']['url'])

Thank you very much

Posted 7 days ago

TopCoder Python Practice Room SRm 168 DIV 2, Problem 250

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

Github TopCoder Python Practice Room SRm 168 DIV 2, Problem 250

Problem Statement:
You are climbing a staircase. The staircase consists of some number of flights of stairs separated by landings. A flight is a a continuous series of stairs from one landing to another. You are a reasonably tall athletic person, so you can climb a certain number of stairs in one stride. However, after each flight, there is a landing which you cannot skip because you need to turn around for the next flight (which continues in the opposite direction).
You will be given the number of stairs in each flight in a tuple (integer) flights. Element 0 of flights represents the number of stairs in the first flight, element 1 is the number of stairs in the second flight, etc. You will also be given an integer stairsPerStride, which is how many continuous stairs you climb in each stride. If it takes two strides to turn around at a landing, return the number of strides to get to the top of the staircase. You do not need to turn at the top of the staircase.

My way:
First, initialize result to -2. Then go through the flights, then, while the elment is bigger than 0, substract starsPerStride and add +1 to the result. At the end of each element, add +2 to the result. At the end, return result.

Here my code:

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

class StairClimb:
    def stridesTaken(self, flights, stairsPerStride):
        result = -2
        for flight in flights:
            while flight > 0:
                flight -= stairsPerStride
                result += 1
            result += 2
        return result

Thank you very much

Posted 7 days ago

NPR Api using Python

Hi, here a small personal project about some working with NPR Api

NPR (National Public Radio) Api work using Python. Here you will find a small project, where we send a request to the NPR Api, in order to get the last 5 news in the topic od Science or Technology.

Github NPR Api using Python

Here we are building the url request, then getting the response from NPR Api in Json format, and then printing some data from the last topics.
All of this has been done after a course in www.codecademy.com

Is an easy example. To do this, you will need to register in the NPR Developer site, and get your own KEY, and then change where Y use myKey, for yours.

Here my code:

from urllib.request import urlopen
import json

#1007 Science topics
#1019 Technology topics

def main():
	url = 'http://api.npr.org/query?apiKey=' 
	urlKey = 'myKey'
	urlNumberResults = '&numResults=5'
	urlFormat = '&format=json'
	urlId = '&id=1019'
	urlRequireAssets = '&requireAssets=images,audio,text'

	url += urlKey + urlNumberResults + urlFormat + urlId + urlRequireAssets

	response = getResponse(url)
	json_obj = parseToJson(response)

	print(json_obj['list']['title']['$text'] + "\n")

	for story in json_obj['list']['story']:
		print(story['title']['$text'] + "\n")
		print(story['teaser']['$text'])
		print(story['storyDate']['$text'] + "\n")
		for paragraph in story['text']['paragraph']:
			print(paragraph['$text'] + "\n")
		print("-------------------------------" + "\n")

def getResponse(url):
	return str(urlopen(url).read().decode('utf-8'))

def parseToJson(response):
	return json.loads(response)

if __name__ == "__main__":
	main()

Thank you very much

Posted 1 week ago

TopCoder Python Practice Room SRM 626 DIV 2, Problem 500

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

This is the problem that I couldn´t solve in the SRM 626 because I made some silly mistakes, but I’ve solved right now.

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

Problem Statement:
Alice and Bob are playing a game. Alice has an a-sided die. Bob has a b-sided die. (The faces of an n-sided die have numbers 1 through n written on them.)
The game is simple: Each player rolls their die, and the player who rolls a strictly larger number wins. (It is possible that neither player wins.)
You are given the integers a and b. The players already rolled their dice. You do not know what numbers they rolled, but you know that Alice won the game. Compute and return the expected value of the number Alice rolled.

My way:
Here, I’ve decided to run a set of 5 games, then, go checking each of the cases where Alice wins Bob, and add to totalAlice that number of the Alice dice, and +1.0 to totalAliceWins. Then at the end, return totalAlice / totalWins. It’s important to return a float, not an int.

Here my code:

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

class FixedDiceGameDiv2:
    def getExpectation(self, a, b):
        games = 5
        totalAlice = 0.0
        totalWins = 0.0
        if b > a:
            b = a
        for i in range(games):
            for x in range(1, a + 1):
                temp = b
                for j in range(1, b + 1):
                    if x > j:
                        totalAlice += float(x)
                        totalWins += 1.0
        return totalAlice / totalWins

Thank you very much

Posted 1 week ago

TopCoder Python SRM 626 DIV 2, Problem 250

Hi, here the problem I’ve solved in the SRM 626 using Python!

This was my fist SRM using Python, and well.. was not so bad hehe. I did the 250, a little bit slowly, and made some silly mistakes in the 500, but.. I am happy because I knew how to solve both of them using Python.

Github TopCoder Python SRM 626 DIV 2, Problem 250

Problem Statement:
You are given a int[] array. At any moment, you may choose a nonempty contiguous subsequence of array. Whenever you do so, you will gain power equal to the sum of all elements in the chosen subsequence.
You chose each possible contiguous subsequence exactly once, each time gaining some power. Compute and return the total amount of power you gained.

My way:
I decided to use two for loops, in order to go through all the contiguous elements, then, go getting slicing the array from i to x and ge tthe sum. At the end, return the total sum.

Here my code:

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

class SumOfPower:
    def findSum(self, array):
        totalSum = 0
        lenght = len(array)
        for i in range(lenght):
            for x in range(i, lenght + 1):
                temp = array[i:x]
                totalSum += sum(temp)
        return totalSum

Thank you very much

Posted 1 week ago

Codeeval Python Prime Numbers (Vertical Brand Sponsored)

Hi, here a new problem I’ve solved working together with my friend Archit (@arcolife) which is a great developer! ;) Thank you my friend for work with me to solve this problem together!

Github Codeeval Python Prime Numbers (Vertical Brand Sponsored)
Codeeval Problem Statement

Our way:
We have created a method called isPrime, in order to check if a number os primer or not. Then, we go through the whole range from 1 to n, jumping +2 in each iteration, and then, if it’s prime, add to the result list. At the end, return the list converted to a string separated by ‘,’.

Here our code:

import fileinput
import sys
import math
 
def gen_primes(limit):
    assert limit < 4294967295
    if limit <= 2:
        return ""
    primes = [2]
    for n in range(1, limit, 2):
        if isPrime(n):
            primes.append(n)
    return ','.join(map(str, primes)) 

def isPrime(n):
    if n <= 1 or n % 2 == 0:
        return False
    if n == 2:
        return True
    m = int(math.sqrt(n))
    for i in range(3, m + 1, 2):
        if n % i == 0:
            return False
    return True
 
if __name__ == '__main__':
    for line in fileinput.input():
        print(gen_primes(int(line)))

Thank you very much

Posted 2 weeks ago

TopCoder Python Practice Room SRM 165 DIV 2, Problem 250

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

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

Problem Statement:
Prior to 1971, Britain used a system of coins that can be traced back to the time of Charlemagne. The three main units of coinage were the penny, the shilling, and the pound. There were 12 pennies in a shilling and 20 shillings in a pound. Given a number pence of pennies, convert this amount into pounds, shillings, and pennies by first converting as many pennies as possible into pounds, and then converting as many of the remaining pennies as possible into shillings. Return a tuple (integer) of size three containing the number of pounds, the number of shillings, and the number of pennies, in that order.

My way:
Here we only need to follow the instructions. Is pretty straighforward. ;)

Here my code:

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

class BritishCoins:
    def coins(self, pence):
        result = []
        result.append(int(pence / (20 * 12)))
        result.append(int((pence % (20 * 12)) / 12))
        result.append(int((pence % (20 * 12)) % 12))
        return result

Thank you very much

Posted 2 weeks ago

TopCoder Python Practice Room SRM 164 DIV 2, Problem 250

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

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

Problem Statement:
We have a collection of strings, and we want to right justify them. Create a class Justifier that contains a method justify that is given a tuple (string) textIn and returns a tuple (string) containing the same strings, right justified, in the same order as they appear in textIn.
The returned strings should be padded on the left with space characters so that they are all the same length as the longest string in textIn.

My way:
First we need to get the longest word. Then, go through the tuple, and while the length of the element is less than the longest, add a ” ” (whitespace) in the beginning. Then, add the result to a list, because tuples are inmmutable, and then return the result list.

Here my code:

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

class Justifier:
    def justify(self, textIn):
        longest = len(max(textIn, key=len))
        result = []
        for item in textIn:
        	while len(item) < longest:
        		item = " " + item
        	result.append(item)
        return result

Thank you very much

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