Write a module named randStr.py that has 3 functions. Each function has an optio
ID: 3585561 • Letter: W
Question
Write a module named randStr.py that has 3 functions. Each function has an optional second parameter to set a particular seed.
1) randWord accepts a string and will return a random word from that string (return value is string).
2) strMixer will randomly change words inside the string and returns a string
-- If the string is only one word, then it will mix the letters of the word and return the mixed word as a string
3) randIntForWord accepts a word and then returns a random integer between 0 and 100,000; the same word should return the same random integer.
Import the 3 functions in the main file and call each of them 5 times (with and without seed).
If the module is called directly, print the following message:
"Sorry, but this module can only be imported!"
code needed in Python V3.x
Explanation / Answer
############ randStr.py #######################
import random
from random import shuffle
import numpy as np
def randWord(text, seedValue=None):
if(seedValue!=None):
random.seed(seedValue)
words=text.split()
index=random.randint(1,len(words))
return words[index-1]
def strMixer(text, seedValue=None):
if(seedValue!=None):
random.seed(seedValue)
words=text.split()
if(len(words)==1):
return ''.join(random.sample(words[0],len(words[0])))
else:
return ' '.join(random.sample(words, len(words)))
def randIntForWord(text, seedValue=None):
seedValue=sum(map(ord, text))
random.seed(seedValue)
index=random.randint(0,100000)
return index
if __name__ == "__main__":
print("Sorry, but this module can only be imported!")
########## main.py ###################
from randStr import *
print(randWord("I love programming."))
print(randWord("I love programming."))
print(randWord("I love programming."))
print(randWord("I love programming."))
print(randWord("I love programming."))
print(randWord("I love programming.",50))
print(randWord("I love programming.",50))
print(randWord("I love programming.",50))
print(randWord("I love programming.",50))
print(randWord("I love programming.",50))
print(strMixer("I love programming."))
print(strMixer("I love programming."))
print(strMixer("I love programming."))
print(strMixer("I love programming."))
print(strMixer("I love programming."))
print(strMixer("I love programming.",50))
print(strMixer("I love programming.",50))
print(strMixer("I love programming.",50))
print(strMixer("I love programming.",50))
print(strMixer("I love programming.",50))
print(randIntForWord("hello"))
print(randIntForWord("hello"))
print(randIntForWord("hello"))
print(randIntForWord("hello"))
print(randIntForWord("hello"))
print(randIntForWord("hello",50))
print(randIntForWord("hello",50))
print(randIntForWord("hello",50))
print(randIntForWord("hello",50))
print(randIntForWord("hello",50))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.