Python Forum
splitting a string numeically
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
splitting a string numeically
#11
I like this
def split_by_n( seq, n ):
    """A generator to divide a sequence into chunks of n units."""
    while seq:
        yield seq[:n]
        seq = seq[n:]

print(list(split_by_n("1234567890",4)))
Recommended Tutorials:
Reply
#12
@[metulburr]: that code is very inefficient, it will run in quadratic time relative to the length of the sequence. If you were iterating over a file with 10000 lines or something that would take much, much longer than it needs to.
Reply
#13
(Oct-07-2016, 08:32 PM)micseydel Wrote: @[metulburr]: that code is very inefficient, it will run in quadratic time relative to the length of the sequence. If you were iterating over a file with 10000 lines or something that would take much, much longer than it needs to.

Would you explain please, how to determine the efficiency of a code? In the Tutorials may be.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#14
My plan is to repost this this weekend, but here's the one metulburr already migrated: http://python-forum.io/Thread-Efficiency-Crash-Course
The idea is basically the same as the example. Slicing a string, like building a string with concatenation, will create a whole new one each time.

Also notable I suppose on top of efficiency is the API. I would argue an ideal API supports iterables, not just slicables.
Reply
#15
(Oct-07-2016, 09:48 PM)micseydel Wrote: Would you explain please, how to determine the efficiency of a code? In the Tutorials may be.
Here ya go http://python-forum.io/Thread-Efficiency...ourse--420
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  splitting file into multiple files by searching for string AlphaInc 2 816 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
  Splitting a string twice bazcurtis 2 5,466 Mar-09-2020, 02:54 PM
Last Post: perfringo
  splitting a string with 2 different delimiters Skaperen 4 2,650 Dec-30-2019, 04:49 AM
Last Post: BamBi25
  Splitting String into 2d list cclark135 2 2,757 Aug-26-2019, 01:46 PM
Last Post: ThomasL
  Strange behaviour while splitting string? naknak12 2 2,549 Feb-18-2019, 01:57 PM
Last Post: naknak12
  splitting a string by 2 characters Skaperen 8 8,822 Dec-27-2016, 06:14 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020