Recursive function call - Python

Asked

Viewed 1,598 times

3

I have a list of integers larger than zero. I need to identify the one with the largest number of divisors. For this I created three functions: one that lists, one that returns all divisors of all elements of a list and another that filters which element has more divisors. The problem is that I can’t get the function moreDivistors to directly receive a list of only the elements (without the splitters), you know? If I call the function2 (listingDivisors) within function 3 (moreDivisors) always gives way. However if I call manually, it works well. I’ve tried all possibilities and nothing. How do I call the first function in the second to make it work by getting the raw list?

function 1 (sort lists) def Qs(list): if list==[]: Return [] Else: pivot=list[0] Return (Qs([x for x in list if xpivor]))

function 2: returns divisors of a number

def listaDivisores(lista):
    if lista == []:
        return []
    else:
        lista=qs(lista)
        resultado=[]
        resultado.append((lista[0],[y for y in range(1,((lista[0])+1)) if (int(lista[0]))%y==0]))
        return resultado+listaDivisores(lista[1:])
    return listaDivisores(lista)

function 3 returns the number of one with the largest number of divisors
def maisDivisores(list):

    if len(lista)==[]:
        return "Nenhum número."

    else:
        **lista=listaDivisores(lista)**

when adding this command line the code does not execute if int(Len(list))==1: List Return[0] Elif int(Len(list[0][1]))

ERROR LOG

>>> maisDivisores(lista)
Traceback (most recent call last):
  File "<pyshell#499>", line 1, in <module>
    maisDivisores(lista)
  File "D:/Google Drive/CIn/Prog1/EE2.py", line 58, in maisDivisores
    return maisDivisores(lista)
  File "D:/Google Drive/CIn/Prog1/EE2.py", line 46, in maisDivisores
    lista=listaDivisores(lista)
  File "D:/Google Drive/CIn/Prog1/EE2.py", line 35, in listaDivisores
    resultado.append((lista[0],[y for y in range(1,((lista[0])+1)) if (int(lista[0]))%y==0]))
TypeError: can only concatenate tuple (not "int") to tuple
  • 1

    SOLVED!! Excludes the first function. I made only one. Hence what I did... from the raw list I took the first element destructively. With a list comprehension, I create a list with his divisors, if the list is different from empty I enter the function again, until I get all the elements then it will give me a list with the divisors of all. then just compare and return the element that has the largest number of splitters

2 answers

2


The code had a flaw. I fixed (rsrsrs)

GENERAL TASKS

def qs(lista): # função quickSort: ordena uma lista, revomendo as duplicatas
    if lista==[]:
        return []
    else:
        pivor=lista[0]
        return (qs([x for x in lista if x<pivor])+[pivor]+qs([x for x in lista if x>pivor]))


def maior (lista): # função maior: devolve o maior elemento de uma lista de tuplas compostas por um inteiro e uma lista de inteiros
    
    if lista == []:
        return 'Lista vazia.'
    elif len(lista)==1: 
        return lista[0]
    else:
        x = int(len(lista[0][1]))
        y = int(len(lista[1][1]))
        if x > y: # se o tamanho da lista do elemento 0 for maior que o tamanho da lista do elemento 1, o elemento 1 é excluído
            lista.pop(1)
        elif x==y: # no caso das listas dos elementos possuírem o mesmo tamanho, o critério de desempate será o inteiro que precede a lista
            if lista[0]>lista[1]:
                lista.pop(1)
            else:
                lista.pop(0)          
        else:
            lista.pop(0)
        return maior(lista)


def divisores(x):

    if x <= 0:
        return False
    else:
        return [y for y in range (1, x+1) if x%y==0] # retorna uma lista com todos os divisores inteiros de x

Construct a function moreDivisors( ) that takes as parameter a list of non-zero positive integers and returns, among these numbers, the one that has the largest number of integer divisors and which are these divisors. In the event of a tie (several numbers have the most divisors), the program must choose the largest of the tied numbers. A number x is divisor of a number y if the rest of the integer division of y by x is equal to 0. Your program cannot have loops (while, for), although it can use recursion and list comprehension. In addition, you should not use the operator in or functions such as max, min, sum, etc. It is explicitly allowed, however, to create as many functions as are accurate (find the divisors of a number, determine which number has the most divisors, etc.) or use functions from the previous question. Examples of use of maisDivisors( ) are given below.

-->Agents([24, 5, 9, 15, 42])

(24, [1, 2, 3, 4, 6, 8, 12, 24])

--> moreDivierships([ ])

"No number at all."

--> maisDivisores([1, 3, 5, 7, 11, 13, 17])

(17, [1, 17])

REPLY:

def maisDivisores(lista):

    if lista == []:
        return 'Nenhum número.'

    else:
        
        return maior(qs([(x,divisores(x)) for x in lista])) # retorna o inteiro com mais divisores de uma lista ordenada composta
                                                            # por tuplas  de inteiros e listas de divisores baseada na lista de 
                                                            # inteiros fornecida como parâmetro na função

1

CODE SOLVED!! Deletes the first function. I made only one. Hence what I did... from the raw list caught the first element in a destructive way. With a list comprehension, I create a list with his divisors, if the list is different from empty I enter the function again, until I get all the elements then it will give me a list with the divisors of all. then just compare and return the element that has the largest number of splitters

com apenas a função para ordenar e a outra pra filtrar o elemento com mais divisores

  • boa +1 @Márcio Arruda

Browser other questions tagged

You are not signed in. Login or sign up in order to post.