Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Join element between each item of a list – python

I want to join an element in this case it’s "*" between each element of the list but not at the first position and not in the last position

How can I do this ?

Code :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import math
def decompose(n:int):
    
    factors = []
    
    
    if n < 2:
        return False
    
    for d in range(2, int(math.sqrt(n)) +1):
        
        if n % d == 0:
            factors.append(d)
            print(factors)
            
    factors = str(factors)
    
            
    print(f"The decomposition of {number5} in prime factor is" + '*'.join(str(factors)))       
    return True
    
number5 = int(input('Chose a number:'))


print(decompose(number5))

it prints this :

Decomposition of 45 in prime factor is [*3*,* *5*]

But that’s not what I want, I want numbers without commas and without the * in first and last position

>Solution :

This way:

def decompose(n: int):
    factors = []

    if n < 2:
        return False

    d = 2
    while d <= n:
        while n % d == 0:
            factors.append(str(d))
            n //= d
        d += 1
    if n > 1:
        factors.append(str(n))

    print(f"The decomposition of {number5} in prime factor is " + '*'.join(factors))
    return True


number5 = int(input('Chose a number:'))

print(decompose(number5))

What I’ve changed:

  • The algorithm of factorization. Now it counts multiple multipliers.
  • factors now is a List[str], so join could be performed easily.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading