Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending tuple of tuples

Good afternoon, I got a question for an assignment in python it's almost correct but the last part which I can't figure out

def create_line(letters,x,numElems):
    sizeofLetters=len(letters)
    another_list = []
    i=0

    while(i!=numElems):
        if(i+x*numElems==sizeofLetters):
            break
        another_list.append(letters[i+x*numElems])
        i +=1

    return another_list

def create_key(letters):
    sizeofList = len(letters) 
    conjLetters = []
    x=0
    i=0

    raiz = sqrt(sizeofList)
    numTuples=raiz

    if(isinstance(raiz,float)==True):
        numTuples = int(raiz)+1
        raiz = int(raiz)+1

    numElems=sizeofList/raiz


    while(x!=numTuples-1):
        line = tuple(create_line(letters,x,numElems))
        x+=1        
        conjLetters.append(line)
    return tuple(conjLetters)

create_key receives a tuple of chars (E.g: ('A','B','C','D'). Transforms it into a tuple of tuples. The number of tuples is the square root of the size, rounded up always (4,1=5). The number of elements per tuple is assigned by dividing the len of tuple per number of tuples.

create_line appends each letter received to a list returning it with the condition of each list returned has a max of numElems per list.

create_key after that appends all lists (meanwhile transformed into a tuple) into a tuple of tuples returning it.

So my problem is when I do this code, if letters = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', ' ', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Z', '.')

my output was supposed to be (('A', 'B', 'C', 'D', 'E'), ('F', 'G', 'H', 'I', 'J'), (' ', 'L', 'M', 'N', 'O'), ('P', 'Q', 'R', 'S', 'T'), ('U', 'V', 'X', 'Z', '.'), ()) without the final tuple, this only happens when the root is int (for example 25,36 etc)

Appreciate the help! João

like image 636
João Portugal Avatar asked Dec 20 '25 17:12

João Portugal


1 Answers

The result of sqrt will always be a float (in case of 25, it's 5.0). That's why you always add 1 to the integer representation, which misrepresents the numbers in case the number is whole. Instead, use math.ceil, which returns the next-highest integer, or the same number, if it's a whole number already:

from math import sqrt, ceil

...

def create_key(letters):
    sizeofList = len(letters) 
    conjLetters = []
    x = 0
    i = 0

    raiz = ceil(sqrt(sizeofList))
    numTuples = raiz

    numElems = sizeofList // raiz  # Python 3 compatibility


    while x != numTuples-1:
        line = tuple(create_line(letters, x, numElems))
        x += 1        
        conjLetters.append(line)
    return tuple(conjLetters)
like image 185
L3viathan Avatar answered Dec 23 '25 06:12

L3viathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!