开发者

How do you randomly generate x amount of values and store them?

开发者 https://www.devze.com 2022-12-22 06:51 出处:网络
I found a suggestion on a Stack Overflow topic about problems beginners should do to learn a new language. A user posted a very nice list of problems from Beginner to advanced that should help you get

I found a suggestion on a Stack Overflow topic about problems beginners should do to learn a new language. A user posted a very nice list of problems from Beginner to advanced that should help you get to know a language. One of the problems is to create a phone book, with random phone numbers and random people on the phone book, and a user should be able to search a phone number and find the person, and vice-versa.

So how do you randomly g开发者_Python百科enerate x amount of values and store them, without a database, specifically focusing on Python and Ruby.


You need to define some more parameters before you can tackle this problem.

  • Are phone numbers unique to each person?
  • How will you store names? First name and last name in different strings? All in one string?
  • Do you want to support fuzzy matching?
  • do you want to offer reverse lookup functionality? (I.E. look up a person based on a phone number?)

In Python, you could do all of this with sets, lists, and/or dicts, but you might also look into the sqlite3 module.

To generate a random string of letters in Python you do:

import random
import string

minLength = 5 # the minimum length of the string.
maxLength = 15 # the maximum length of the string

randstring = string.join([random.choice(string.lowercase)
    for i in range(random.randrange(minlength,maxlength+1))], '')

To do the same with numbers, just replace random.lowercase with [1,2,3,4,5,6,7,8,9,0]


With Python, you can use the random module for generating random numbers. For storing phone numbers, names, contact etc, you can use a database, eg SQLite

0

精彩评论

暂无评论...
验证码 换一张
取 消