Python: How to print my simple poem [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I would like to know how I could print out sentences using my triplet poem program.
My program randomly picks a list of nouns to use.
My program:
import random
def nouns():
nounPersons = ["cow","crowd","hound","clown"];
nounPlace = ["town","pound","battleground","playground"];
rhymes = ["crowned","round","gowned","found","drowned"];
nounPersons2 = ["dog","frog","hog"];
nounPlace2 = ["fog","Prague","smog"];
rhymes2 = ["log","eggnog","hotdog"];
nounList1 = [nounPersons,nounPlace,rhymes]
nounList2 = [nounPersons2,nounPlace2,rhymes2]
nounsList = [nounList1, nounList2]
randomPick = random.choice(nounsList)
return(randomPick)
verbs = ["walked","ran","rolled","biked","crawled"];
nouns()
For example, I could have "The cow walked to the town. But then it was drowned." And just replace the nouns/rhyme(cow, town,drowned) and verb(walked) with my randomizer.
Would I use random.randint in some way?
I just basically need a general print statement like the example I showed using my randomizer to randomly pick between the nouns/rhymes.

As usual (for me), there may be a more Pythonic approach, but to get what you have working, I did three things:
assigned your call to the nouns() function to 'chosen_list' variable. That way the returned 'randomPick' gets used.
built in a selection step to get individual words from the lists in 'chosen_list' and your verb list
added a final print statement with formatting to assemble the words in to a sentence
the code:
import random
def nouns():
nounPersons = ["cow","crowd","hound","clown"];
nounPlace = ["town","pound","battleground","playground"];
rhymes = ["crowned","round","gowned","found","drowned"];
nounPersons2 = ["dog","frog","hog"];
nounPlace2 = ["fog","Prague","smog"];
rhymes2 = ["log","eggnog","hotdog"];
nounList1 = [nounPersons,nounPlace,rhymes]
nounList2 = [nounPersons2,nounPlace2,rhymes2]
nounsList = [nounList1, nounList2]
randomPick = random.choice(nounsList)
return randomPick
verbs = ["walked","ran","rolled","biked","crawled"]
# this is change 1.
chosen_list = nouns()
# select single words from lists - this is change 2.
noun_subj = random.choice(chosen_list[0])
noun_obj = random.choice(chosen_list[1])
rhyme_word = random.choice(chosen_list[2])
verb_word = random.choice(verbs)
# insert words in to text line - this is change 3.
print ("The {} {} to the {}. But then it was {}.".format(noun_subj, verb_word, noun_obj, rhyme_word))

Related

How would I add the results of a 'for' loop into a dictionary? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I am required to take 52 random outputs of cards. I got that in a for loop. The problem is, I need to save that output inside a variable.`
import random
r=random.randint(0, 9)
cards={'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1}
print(cards)
cards2={}
for i in range(52):
global res
res = key, val = random.choice(list(cards.items()))
print("Your deck contains " + str(res))
cards2.update(i) # All output should go in here
I tried using cards2.update, but it didn't work.
I also tried using cards2.(keys).
I just need to create 52 random samples and store them as dictionary value pairs.
First remove the double assignment (res = key, val). And I don't see any point in using a global variable here. Just do _dict[key] = value as shown below, and it will work fine. Also remember that you can’t get all 52 random cards, because if the key exists then the value will be replaced.
import random
r = random.randint(0, 9)
cards = {'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1}
print(cards)
cards2 = {}
for i in range(52):
key, val = random.choice(list(cards.items()))
cards2[key] = val
print(cards2)

Python create nested dict in for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to created a nested dictionary but I have a problem inside the for loop, at least is what I'm thinking.
I do several requests based on args passed but when I try to add values to the nested dict created before it just adds the last arg passed.
I'll show the code and the output.
def api_metrics():
my_list = []
my_dict_1 = {}
number = len(my_metrics)
metricz = range(number)
for indice in metricz:
my_dict_1[indice] = {}
for metric in my_metrics:
urlnotoken = ""
urlnotoken = urlnotoken.replace(" ","%20")
preurl = urlnotoken + "&dateToken="+expirationDate
msg = preurl + apikey
token = calcMd5(msg)
finalurl = "http://"+host+preurl+"&token="+token
data_get = requests.get(finalurl, headers=app_headers)
json_data = json.loads(data_get.text)
metrics_path = json_data['data'][0]['metrics'][0]
metric_name = metrics_path['label']
metric_value = metrics_path['values'][0]['data'][0][1]
metric_unit = metrics_path['magnitudes']['y']
my_list.append(metric_name)
my_list.append(metric_value)
my_list.append(metric_unit)
number = len(my_metrics)
metricz = range(number)
my_values = metric
for entry in my_dict_1.keys():
my_dict_1[entry] = metric
return(my_dict_1)
And the output
{0: 'avgRenditionSwitchTime', 1: 'avgRenditionSwitchTime', 2: 'avgRenditionSwitchTime', 3: 'avgRenditionSwitchTime', 4: 'avgRenditionSwitchTime'}"
This should output the different args passed. I have moved the code inside and outside the loop, I've read lots of posts but I need further help!
Cheers.
In here:
for entry in my_dict_1.keys():
my_dict_1[entry] = metric
You are assigning the value of metric to all your dict (my_dict_1) items. Reason why 'it just adds the last arg passed'.
Without cleaning up your code, here's the patch to fix your issue:
for i, metric in enumerate(my_metrics):
...
my_dict_1[i] = metric

Linking elements of a list as a tree [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a python list that looks like this for example :
[Product(parent=tube,child=spokes), Product(parent=bicycle, child=wheel), Product(parent=wheel,child=tube)]
Where Product is a python class with two members parent and child.
The Products could appear in any order in the list.
What would be the most efficient one liner to achieve the following :
Given an input spokes for example , return the `root of the tree` , bicycle in this case.
What have i tried so far : inefficient for loops that does not give the right results when the Product does not appear in the same order each time.
You do not write how strong assumption you can apply to data (if it is always proper tree). So my code check some conditions to not stick in infinity loop.
def find_root(pr_list, child):
if len(pr_list) == 0:
return None
child_translate_dict = {x.child: x for x in pr_list}
potential_root = child
count = 0
while count < len(pr_list):
if potential_root not in child_translate_dict:
return potential_root
else:
potential_root = child_translate_dict[potential_root].parent
count += 1
return None
and shorter version
def find_root(pr_list, child):
child_translate_dict = {x.child: x for x in pr_list}
while child in child_translate_dict:
child = child_translate_dict[potential_root].parent
return child
Here is a pseudo code for your problem :
def recursiveRootFinder(child,theList):
for(i in theList):
if (i.child==child):
child=recursiveRootFinder(i.parent,theList)
return child
You can use lambda definition to implement it in one line like that :
lambda child,theList: recursiveRootFinder(i.parent,theList) for i in list if i.child==child if [1 for i in list if i.child==child]!=[] else child

Implementing treeset data structure store and read in VBA / Python/ Shell [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a text file like this
LEVEL=3
LEVEL1=CLASS7
LEVEL2=ROLLNO1
LEVEL3=MALE
JOHN,12
LEVEL2=ROLLNO2
LEVEL3=FEMALE
JULIA,11
We need to read this file and need output like
CLASS7|ROLLNO1|MALE|JOHN|12
CLASS7|ROLLNO2|FEMALE|JULIA|11
1st LELVEL=3 means maximum LEVEL present in the file.
Here LEVEL 1 is common, but in actual data sometimes LEVEL 1 and 3
can be common when maximum LEVEL is say 7.Basically there is no clear
pre-defined pattern.
I have solved it in VBA using normal array structure but when file becomes
very big and maximum LEVEL becomes more( like more than 10)
it becomes slow.
Then I tried to read more things and came to know using
treeset data structure and iterator kind of things it works fast.
But this things possible in Java.
How we can do it in VBA ?
If possible in shell or python that is also ok.
here is a little python approache, but very specific on you string formating, with "text.txt" containing your text:
f = open( "text.txt", 'r' )
text = f.readlines()
f.close()
d = { }
for line in text :
pair = line.split( '=' )
if len( pair ) == 2 : # save Levels as pairs in dict
d[pair[0].strip()] = pair[1].strip()
else : line without level means time for output
out = [] # gather the values in here
try :
for i in range( 1, int( d['LEVEL'] ) + 1 ) : # number of levels (1-based)
out.append( d['LEVEL' + str( i )] ) # add every level
except KeyError :
pass
out += line.split( ',' ) # add current line
out_as_string = '|'.join( out ) # convert to string with "|"
print( out_as_string )
outputs:
CLASS7|ROLLNO1|MALE|JOHN|12
CLASS7|ROLLNO2|FEMALE|JULIA|11

Python letter frequency mapping [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a Python script that reads in a encrypted text file and decrypts it in various ways. The last 2 options I am trying to add are to map out the most frequent letters of the file and the most frequent letters in the English language.
Here are my previous functions that display frequency:
def functOne:
Crypt = input("what file would you like to select? ")
filehandle = open(Crypt, "r")
data = filehandle.read().upper()
char_counter = collections.Counter(data)
for char, count in char_counter.most_common():
if char in string.ascii_uppercase:
print(char, count)
def FunctTwo:
print "Relative letter Freq of letters in English Language A-Z; ENGLISH = (0.0749, 0.0129, 0.0354, 0.0362, 0.1400, 0.0218, 0.0174, 0.0422, 0.0665, 0.0027, 0.0047, 0.0357, 0.0339, 0.0674, 0.0737, 0.0243, 0.0026, 0.0614, 0.0695, 0.0985, 0.0300, 0.0116, 0.0169, 0.0028, 0.0164, 0.0004)"
Here's the description of what I need to do for the next two:
Function 3:
Map the most frequent letter in text to the most frequent in the English language in descending order.
[letter in cryptogram] -> [letter in english language]
Function 4:
Allow user to manually edit frequency maps
How would I go about doing this? I'm kinda lost on the mapping part, at least combing the two frequencies and allow editing.
First, you have to turn your code into actual valid Python code. For example, your functions have to be defined with a list of arguments.
Then, you have to do is return values rather than just printing them.
Also, you don't want a string representation of a tuple of frequencies, but an actual tuple of them that you can use.
And finally, you're going to have to put the two collections into some kind of format that can be compared. ENGLISH is just a sequence of 26 frequencies; the value computed by functOne is a sequence of up to 26 (letter, count) pairs in descending order of frequency. But really, we don't need the counts or the frequencies at all; we just need the letters in descending order of frequency.
In fact, if you look at it, functTwo is completely unnecessary—it's effectively computing a constant, so you might as well just do that at module level.
While we're at it, I'd reorganize functOne so it takes the input as an argument. And close the file instead of leaking it. And give the functions meaningful names.
def count_letters(data):
data = data.upper()
char_counter = collections.Counter(data)
return [char for char, count in char_counter.most_common()]
english_freqs = (0.0749, 0.0129, 0.0354, 0.0362, 0.1400, 0.0218, 0.0174,
0.0422, 0.0665, 0.0027, 0.0047, 0.0357, 0.0339, 0.0674,
0.0737, 0.0243, 0.0026, 0.0614, 0.0695, 0.0985, 0.0300,
0.0116, 0.0169, 0.0028, 0.0164, 0.0004)
pairs = zip(english_freqs, string.ascii_uppercase)
english_letters = [char for count, char in sorted(pairs, reversed=True)]
def decrypt(data):
input_letters = count_letters(data)
return {input_letter: english_letter
for input_datum, english_datum in zip(input_letters, english_letters)}
crypt = input("what file would you like to select? ")
with open(crypt, "r") as f:
data = f.read()
mapping = decrypt(data)
For the editing feature… you'll have to design what you want the interface to be, before you can implement it. But presumably you're going to edit the english_freqs object (which means you may want to use a list instead of a tuple) and rebuild english_letters from it (which means you may want that in a function after all).

Categories

Resources