How to compress code in python 3?

0

I wanted to leave this little bit of code in a single line ...

i = int(input())
for j in range(1,i+1):
  if(i%j==0):
    print(j)

Is it possible?

    
asked by anonymous 13.08.2018 / 21:30

3 answers

1

To do this, let's use lambda functions, but you can rest assured that it's something simple.

We can do it by parts:

The variable i will leave it at the end.

  • We first compressed if and print

    (lambda x,j: print(j) if x%j == 0 else None)
    
  • Then we compress the cycle for , where it says "Func", imagine that it is a function whatsoever

    [ Func(xa,ja) for xa in range(1, ja+1)]
    
  • Now we need to put the lambda function we create inside the for zipped cycle. So just replace "Func" with lambda

    [ (lambda x,j: print(j) if x%j == 0 else None)(ja, xa) for xa in range(1, ja+1)]
    
  • But we still have to pass our input argument, i , the input . Let's build a new lambda function for this

    (lambda ja: [ (lambda x,j: print(j) if x%j == 0 else None)(ja,xa) for xa in range(1, ja+1)])
    
  • Now we just need to add an input to it

    (lambda ja: [ (lambda x,j: print(j) if x%j == 0 else None)(ja, xa) for xa in range(1, ja+1)])(int(input('Digite uma entrada : ')))
    
  • p>

    Some sources that may aid you in your studies:

    14.08.2018 / 22:23
    5

    What you can do is to reduce and simplify your code with list comprehension :

    i = int(input('Calcular divisores de: '))
    divisores = [j for j in range(1, i+1) if i % j == 0]
    print('Divisores:', divisores)
    

  • But given its comment :

      

    I wanted to see if I could shorten the code execution time ...

    I make my Isac : Number of lines has no direct relation to code execution time.

        
  • 13.08.2018 / 21:45
    1

    You can use "one line converter" , convert any python code to one line only automatically:

    link

    Your code looks like this:

    (lambda __y, __print, __g: [(lambda __after, __items, __sentinel: __y(lambda __this: lambda: (lambda __i: [(lambda __after: (__print(j), __after())[1] if ((i % j) == 0) else __after())(lambda: __this()) for __g['j'] in [(__i)]][0] if __i is not __sentinel else __after())(next(__items, __sentinel)))())(lambda: None, iter(range(1, (i + 1))), []) for __g['i'] in [(int(input()))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), __import__('__builtin__', level=0).__dict__['print'], globals())
    

    The interesting thing is that this is to prove that a line is only nonsense in python, the language favors readable codes and not number of lines.

        
    14.08.2018 / 20:47