Sunday, December 23, 2018

codingdirectional: How good you really are in python

Today I have paid a visit to codewars after a few months of abandoned it, once I arrive at this site I immediately go to work by solving a python related question. This question goes by this, given three values of a color in a tuple, such as (0, 0, 0), I will need to convert them to their hex color code, and here is my solution to this question which earned me a few points later on.

def rgb(r, g, b):

    hex_value = [r, g, b]
    hex_str = ''
    plus_remainder = 0

    for i in range(len(hex_value)):
        if(hex_value[i] > 255):
            hex_str+='FF'
        elif(hex_value[i] < 0):
            hex_str += '00'
        else:
            # get the first hex color code
            h_value = int(hex_value[i]/16) 
            if(h_value > 15):
                plus_remainder = h_value - 15
                h_value = 'F'
            else:
                h_value = convert(h_value)

            # get the second hex color code, if the first value exceeds 15 then we need to add the remaining value to the n_remainder 

            if(hex_value[i] % 16 > 15):
                n_remainder  = 'F'
            else:
                n_remainder = convert((hex_value[i] % 16 + plus_remainder))

            hex_str+= (h_value) + (n_remainder) # concatenate both hex values
        

    return hex_str  # return hex string

def convert(value): # function to convert value to hex character

    if(value == 10):
        value = 'A'
    elif(value == 11):
        value = 'B'
    elif(value == 12):
        value = 'C'
    elif(value == 13):
        value = 'D'
    elif(value == 14):
        value = 'E'
    elif(value == 15):
        value = 'F'

    return str(value) 

As you can see although my solution is working but it is not that perfect, codewars is this type of site which you can really see how good you actually are in python by solving various python related questions, those python questions are not that simple to solve and it takes time and skill to accomplish those tasks, if you really want to master python then codewars is a must visit site for you, join them for free today!



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...