Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7003995
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T21:08:29+00:00 2026-05-27T21:08:29+00:00

I have been studying this code to generate random text: from collections import defaultdict,

  • 0

I have been studying this code to generate random text:

from collections import defaultdict, Counter
from itertools import ifilter
from random import choice, randrange

def pairwise(iterable):
    it = iter(iterable)
    last = next(it)
    for curr in it:
        yield last, curr
        last = curr

valid = set('abcdefghijklmnopqrstuvwxyz ')

def valid_pair((last, curr)):
    return last in valid and curr in valid

def make_markov(text):
    markov = defaultdict(Counter)
    lowercased = (c.lower() for c in text)
    for p, q in ifilter(valid_pair, pairwise(lowercased)):
        markov[p][q] += 1
    return markov

def genrandom(model, n):
    curr = choice(list(model))
    for i in xrange(n):
        yield curr
        if curr not in model:   # handle case where there is no known successor
            curr = choice(list(model))
        d = model[curr]
        target = randrange(sum(d.values()))
        cumulative = 0
        for curr, cnt in d.items():
            cumulative += cnt
            if cumulative > target:
                break

model = make_markov('The qui_.ck brown fox')
print ''.join(genrandom(model, 20))

However i am having trouble understanding the last bit, from target = randrange(sum(d.values())) onwards.
An explanation would be greatly appreciated! Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T21:08:30+00:00Added an answer on May 27, 2026 at 9:08 pm

    target = randrange(sum(d.values()))

    d.values() Since model is a dictionary mapping letters to counter object, and a counter object is a dictionary, d.values() is a list of all the counts for each key in the dictionary (but doesn’t return the keys). This means sum(d.values()) will return the total of all the counts. randrange() choose a value within [0, result) where result was the value of sum(d.values()).

    d.items() returns key, value pairs for every item in the given counts dictionary. The code is trying to assign a probability to each letter and then choose a letter. If the counts are (‘a’, 5), (‘b’, 7), and (‘c’, 2), then the total number of counts is 14. The code chooses a random number between 0 and 13 (inclusive). If the result is in [0, 5), it will return ‘a’, if the result is in [5, 12), it will return ‘b’, and if the result is in [12, 14), it will return ‘c’. The relative probabilities are determined by the width of those ranges, and the width of the ranges are determined by the counts determined in make_markov.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Actually I am studying this algorithm and I have been exploring his code (which
I have been studying .NET 4.0 Code Contracts and looking on stackoverflow as well
Okay, I have been studying text input in SDL (how to turn the keystrokes
Well I have been studying a little C this winter break and in my
Have been studying the file system related classes of Adobe AIR 1.5, but so
I have been studying SOAP and WSDL in preparation for implementing a web service.
I have been studying DDD in-depth on my own time; reading everything about it
I have been studying unicode and its Python implementation now for two days, and
Recently I have been studying recursion; how to write it, analyze it, etc. I
Over the last few weeks I have been studying the MVC design pattern for

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.