简体   繁体   中英

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:

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

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.

One good way to return the factors from the method and then iterate the list as string value.

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)
    return factors


number5 = int(input('Choose a number:'))
factors = decompose(number5)
print(f"The decomposition of {number5} in prime factor is " + '*'.join(
    [str(i) for i in factors]))

Output:

Choose a number:45
The decomposition of 45 in prime factor is 3*5

There are different ways to do this, the following explanation is just one way.

In this line:

factors = str(factors)

You are turning the list itself into a string. You need to turn each item in the list into strings if you want to join them. You can do this by using a list comprehension:

factors = [str(x) for x in factors]

Then I would change the line where you print the decomposition to this:

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

So with input 45 the output should be (amongst other things) "The decomposition of 45 in prime factor is 3*5".

EDIT: You might want to look at the rest of your code, 3*5 is not the prime decomposition of 45.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM