programing

특정 길이까지 문자열 반복

luckcodes 2022. 11. 7. 22:33

특정 길이까지 문자열 반복

문자열을 일정 길이로 반복하는 효율적인 방법은 무엇입니까?예:repeat('abc', 7) -> 'abcabca'

현재 코드는 다음과 같습니다.

def repeat(string, length):
    cur, old = 1, string
    while len(string) < length:
        string += old[cur-1]
        cur = (cur+1)%len(old)
    return string

더 좋은 방법은 없을까?목록 이해력을 이용하는 건 어때?

Jason Scheirer의 답변은 맞지만 좀 더 설명을 해야 할 것 같습니다.

우선 문자열을 정수 횟수만큼 반복하려면 오버로드된 곱셈을 사용할 수 있습니다.

>>> 'abc' * 7
'abcabcabcabcabcabcabc'

따라서 원하는 길이만큼 문자열을 반복하려면 적절한 반복 횟수를 계산하여 곱셈 연산자의 오른쪽에 배치합니다.

def repeat_to_at_least_length(s, wanted):
    return s * (wanted//len(s) + 1)

>>> repeat_to_at_least_length('abc', 7)
'abcabcabc'

그런 다음 어레이 슬라이스를 사용하여 원하는 길이로 트리밍할 수 있습니다.

def repeat_to_length(s, wanted):
    return (s * (wanted//len(s) + 1))[:wanted]

>>> repeat_to_length('abc', 7)
'abcabca'

또는 pillmod의 답변에서 제시된 바와 같이, 어느 누구도 더 이상 알아채지 못할 정도로 아래로 스크롤하지 않을 것입니다.필요한 전체 반복 횟수와 추가 문자 수를 동시에 계산할 수 있습니다.

def pillmod_repeat_to_length(s, wanted):
    a, b = divmod(wanted, len(s))
    return s * a + s[:b]

어떤 게 더 나아요?벤치마킹합시다.

>>> import timeit
>>> timeit.repeat('scheirer_repeat_to_length("abcdefg", 129)', globals=globals())
[0.3964178159367293, 0.32557755894958973, 0.32851039397064596]
>>> timeit.repeat('pillmod_repeat_to_length("abcdefg", 129)', globals=globals())
[0.5276265419088304, 0.46511475392617285, 0.46291469305288047]

그래서 필모드의 버전은 40% 정도 느리지만 아쉽네요. 개인적으로 훨씬 읽기 쉽거든요.여기에는 몇 가지 가능한 이유가 있는데, 우선 바이트 코드 명령이 약 40% 더 많은 컴파일부터 시작합니다.

주의: 다음 예에서는 new-ish를 사용합니다.//정수 나눗셈을 잘라내는 연산자.이것은 종종 Python 3 기능으로 불리지만 PEP 238에 따르면 Python 2.2부터 도입되었습니다.Python 3(또는 Python 3을 탑재한 모듈)에서만 사용하면 됩니다.from __future__ import division)는, 어느쪽이든 사용할 수 있습니다.

def repeat_to_length(string_to_expand, length):
   return (string_to_expand * ((length/len(string_to_expand))+1))[:length]

python3의 경우:

def repeat_to_length(string_to_expand, length):
    return (string_to_expand * (int(length/len(string_to_expand))+1))[:length]

이것은 꽤 버마적인 표현이다.

newstring = 'abc'*5
print newstring[0:6]
def rep(s, m):
    a, b = divmod(m, len(s))
    return s * a + s[:b]
from itertools import cycle, islice
def srepeat(string, n):
   return ''.join(islice(cycle(string), n))

가장 효율적인 솔루션은 아니지만 분명 짧고 단순합니다.

def repstr(string, length):
    return (string * length)[0:length]

repstr("foobar", 14)

"foobarfoo barfo"를 지정합니다.이 버전의 한 가지 특징은 길이 < len ( string )의 경우 출력 문자열이 잘린다는 것입니다.예를 들어 다음과 같습니다.

repstr("foobar", 3)

"foo"를 표시합니다.

편집: 놀랍게도 이것은 적어도 짧은 문자열에서는 현재 받아들여지고 있는 솔루션('repeat_to_length' 함수)보다 빠릅니다.

from timeit import Timer
t1 = Timer("repstr('foofoo', 30)", 'from __main__ import repstr')
t2 = Timer("repeat_to_length('foofoo', 30)", 'from __main__ import repeat_to_length')
t1.timeit()  # gives ~0.35 secs
t2.timeit()  # gives ~0.43 secs

아마도 스트링이 길거나 길이가 매우 높은 경우(즉, 낭비가 심한 경우)string * length부품이 높으면 성능이 저하됩니다.실제로 위의 내용을 수정하여 확인할 수 있습니다.

from timeit import Timer
t1 = Timer("repstr('foofoo' * 10, 3000)", 'from __main__ import repstr')
t2 = Timer("repeat_to_length('foofoo' * 10, 3000)", 'from __main__ import repeat_to_length')
t1.timeit()  # gives ~18.85 secs
t2.timeit()  # gives ~1.13 secs

는 요?string * (length / len(string)) + string[0:(length % len(string))]

나는 이것을 사용한다:

def extend_string(s, l):
    return (s*l)[:l]

이 질문에 대한 답변이 충분하지 않은 것은 아니지만 반복 기능이 있습니다. 목록을 작성한 다음 출력에 참여하면 됩니다.

from itertools import repeat

def rep(s,n):
  ''.join(list(repeat(s,n))

예이 재귀!

def trunc(s,l):
    if l > 0:
        return s[:l] + trunc(s, l - len(s))
    return ''

영원히 확장되진 않겠지만 작은 현에도 괜찮습니다.그리고 예쁘다.

나도 방금 리틀 쉐머를 읽었는데 지금은 재귀가 좋아

것도 중 이렇게 하면 '목록 이해력'의 길이가 점점 .rpt문자열이 증가합니다.

def repeat(rpt, length):
    return ''.join([rpt for x in range(0, (len(rpt) % length))])[:length]

다른 FP 어프로치:

def repeat_string(string_to_repeat, repetitions):
    return ''.join([ string_to_repeat for n in range(repetitions)])
def extended_string (word, length) :

    extra_long_word = word * (length//len(word) + 1)
    required_string = extra_long_word[:length]
    return required_string

print(extended_string("abc", 7))
c = s.count('a')    
div=n//len(s)    
if n%len(s)==0:
    c= c*div
else:
    m = n%len(s)
    c = c*div+s[:m].count('a')
print(c)

★★★★★print(f"{'abc'*7}") 생성: 생성하다

abcabcabcabcabcabcabc

언급URL : https://stackoverflow.com/questions/3391076/repeat-string-to-certain-length