Ok im new to Alexa skill development but its going well, my skill is coming on well however, id like to add some more content in the form of a card. The data id like to populate the card with is in the form of a list. So I thought id try passing the list directly (didnt think it would work but worth a shot). There is nothing in the docs that explains passing lists to the card system. Can anyone explain how to achieve this?
The intent function looks like this:
#ask.intent('TopTenCounties')
def top_ten():
top_countries = get_top_ten_countries()
stats = []
for item in top_countries[1]:
stat = str(item[0]) + ' ' + str(item[1])
stats.append(stat)
msg = "The top ten countries are, {}".format(top_countries[0])
return statement(msg).standard_card(title='Top Ten Usage Stats:',
text=stats,
large_image_url='url.com/img.png')
Alexa's cards only take text, no other rich format is currently supported (https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/providing-home-cards-for-the-amazon-alexa-app). What's happening here is that the list is being converted to string automatically. You probably want to make your own little function to do it yourself so you have more fine control on how it's done.
def lst2str(lst, last='and'):
if len(lst)==1:
return lst[0]
else:
return ', '.join(lst[0:-1]) + ' ' + last + ' ' + lst[-1]
Related
I'm making an infinite text-based survival game for my computer science/cyber security class in school. I'm working in Python and have an inventory[] list, which I use .append(item) to add items and materials to the inventory list. Then I also use seperate variables to actually give the strings meaning, but that is unrelated. Each item is written in the format "item, (item amount)" in the inventory list. I need to know if I can use .index() to search for only the "item, " section of the element in the list, so that I can edit only the (item amount) section of the element, and if there isn't I need to know if there is an alternative. Preferably without undoing the method I'm using with the inventory being a list, since much of the game is built around that method.
materials = ["log", "stone", "sticks", "string", "junk", "rocks", "cloth", "herbs"]
inventory = []
def material_gathering():
global health, hunger, log_amount, stone_amount, stick_amount, string_amount, junk_amount, rock_amount, cloth_amount, herb_amount
material_type = random.choice(materials)
material_amount = random.randint(2, 10)
health = health - material_amount
hunger = hunger + material_amount
if material_type == "log":
log_amount = log_amount + material_amount
print("You gathered " + str(material_amount) + " logs.")
if "log, " in inventory:
log_position = inventory.index("log, ")
inventory[log_position] = ("log, " + str(log_amount))
else:
inventory.append("log, " + str(log_amount))
Thank you Green Cloak Guy for your comment, using a dictionary worked really well, I converted the list inventory to a dictionary, then replaced all of the inventory.append with inventory["item"] = item_amount, that way it removes the need for all of the item searching and indexing, ETC.
I was able to come up with these two parts, but I'm having trouble linking them.
Part 1 - This accepts a filter which is listed as 'project = status = blocked'. This will list all issue codes that match the filter and separate them line by line. Is it necessary to convert the results into a list? I'm also wondering if it converts the entire result into one massive string or if each line is a string.
issues_in_project = jira.search_issues(
'project = status = Blocked'
)
issueList = list(issues_in_project)
search_results = '\n'.join(map(str, issueList))
print(search_results)
Part 2 - Right now, the jira.issue will only accept an issue code one at a time. I would like to use the list generated from Part 1 to keep running the code below for each and every issue code in the result. I'm having trouble linking these two parts.
issue = jira.issue(##Issue Code goes here##)
print(issue.fields.project.name)
print(issue.fields.summary + " - " + issue.fields.status.statusCategory.name)
print("Description: " + issue.fields.description)
print("Reporter: " + issue.fields.reporter.displayName)
print("Created on: " + issue.fields.created)
Part 1
'project = status = Blocked' is not a valid JQL. So first of all, you will not get a valid result from calling jira.search_issues('project = status = Blocked').
The result of jira.search_issues() is basically a list of jira.resources.Issue objects and not a list of string or lines of string. To be correct, I should say the result of jira.search_issues() is of type jira.client.ResultList, which is a subclass of python's list.
Part 2
You already have all the required data in issues_in_project if your JQL is correct. Therefore, you can loop through the list and use the relevant information of each JIRA issue. For your information, jira.issue() returns exactly one jira.resources.Issue object (if the issue key exists).
Example
... # initialize jira
issues_in_project = jira.search_issues('status = Blocked')
for issue in issues_in_project:
print(issue.key)
print(issue.fields.summary)
I am new to python and want to write a simple text adventure game. The player enters a tavern and interacts with the guests. The game takes place in a fantasy setting, where there are multiple races. I want to randomly generate each guest and then interact with them in the tavern. Here is my simplified code:
import random
class guest:
def __init__(self,race,name,fav_food):
self.race = race
self.name = name
self.fav_food = fav_food
guest1 = guest('human','Tom','chicken')
print('The first guest you meet is a '+guest1.race+ ' named '+guest1.name+ '. He really likes '+guest.fav_food+ '.')
So far so good. But here i get stuck: I want the set of data for guest1 to be randomly selected from other guests that i create beforehand.
guest1 = guest('human','Tom','chicken')
guest1 = guest('dwarf','Bjorn','potatoes')
guest1 = guest('orc','Orok','pork')
guest1 = guest('elf',,'Eli','Salad')
How do i do that? Sure, i could name them guest2,guest3 etc., but then it wouldn´t be random anymore.
When i run the code, i want to randomly encounter Tom,Bjorn,Orok or Eli
I would really appreciate any help on this matter.
Sorry for my bad english :)
You can put all of your guests into an array and use random.choice to set random guest to a variable called random_guest.
guests = [guest('human', 'Tom', 'chicken'),
guest('dwarf', 'Bjorn', 'potatoes'),
guest('orc', 'Orok', 'pork'),
guest('elf', 'Eli', 'Salad')]
random_guest = random.choice(guests)
print('The first guest you meet is a '+ random_guest.race + ' named '+ random_guest.name + '. He really likes '+ random_guest.fav_food + '.')
It's perfectly fine to use random.choice to select one character from a list of characters but sometimes random.choice is not what you want.
I mean, no problem if your game is conversational: you meet George, move on to Rita and next it's George again...
But, if your game implies that you KILL George (or George kills you... Game Over) then you KILL Rita, well it would be strange (unless your game is titled Zombie34 — the Tavern Massacre) if George comes back to harass you.
If your use case is the second one, I'd suggest using a combination of random.shuffle
characters = [...]
random.shuffle(characters)
and the .pop method of a list
# whenever you need a new character
try:
a_character = characters.pop()
except IndexError:
# if you are here, you have exausted your list of characters,
# you could consider generating a new list and possibly starting a new level
I'm making a program to collect information from the user, and to add it to a text file.
It's a program that will be used to get said information from a number of applicants.
For linearity in the results I collect, I want to randomly ask the questions.
What i'm asking is a way to pull a question from the list, ask for input, store the input in the text file, and then ask another question pulled from the list at random.
Here is my code so far:
def ques():
global quesnum
for i in questions:
num = int(random.randint(0,len(questions)-1))
j = int(numbers.count(str(num)))
while j >= 1:
num = int(random.randint(0,len(questions)-1))
##DEBUG ONLY##
print('true')
break
else:
num = str(num)
numbers.append(num)
##DEBUG ONLY##
print('false')
num = int(num)
answer = input(str(quesnum) + '. ' + questions[num] + ': ')
answers.write(str(quesnum) + '. ' + questions[num] + ': ')
answers.write(answer + '\n')
quesnum = int(quesnum + 1)
Errors:
Once the number has been used it is added to the list.
If a number has already been used, ideal situation is to generate a new number and use that instead.
I can't see any errors in my code, and as far as I can see it should work fine.
Can anyone point out a fix or suggest a better way of doing this? I have already found answers suggesting to use random.sample() but I have tried this already and can't get that working either.
Thanks in advance.
You can solve this by using random.shuffle:
import random
questions = ['Q1: ...', 'Q2: ...', 'Q3: ...']
random.shuffle(questions)
for q in questions:
answer = raw_input(q + ': ')
with open("answers.txt", "a") as myfile:
myfile.write("{}: {}\n\n".format(q, answer))
This will shuffle your questions, ask them in random order and save them to a text file. If you want to save more detailed information for each question, this will also work with a list of dicts. E.g.
questions = [
{'nr.': 1, 'text': 'Do you like horses?'},
{'nr.': 2, 'text': 'Where were you born?'}
]
I've been learning Python for a couple of months, and wanted to understand a cleaner and more efficient way of writing this function. It's just a basic thing I use to look up bus times near me, then display the contents of mtodisplay on an LCD, but I'm not sure about the mtodisplay=mtodisplay+... line. There must be a better, smarter, more Pythonic way of concatenating a string, without resorting to lists (I want to output this string direct to LCD. Saves me time. Maybe that's my problem ... I'm taking shortcuts).
Similarly, my method of using countit and thebuslen seems a bit ridiculous! I'd really welcome some advice or pointers in making this better. Just wanna learn!
Thanks
json_string = requests.get(busurl)
the_data = json_string.json()
mtodisplay='220 buses:\n'
countit=0
for entry in the_data['departures']:
for thebuses in the_data['departures'][entry]:
if thebuses['line'] == '220':
thebuslen=len(the_data['departures'][entry])
print 'buslen',thebuslen
countit += 1
mtodisplay=mtodisplay+thebuses['expected_departure_time']
if countit != thebuslen:
mtodisplay=mtodisplay+','
return mtodisplay
Concatenating strings like this
mtodisplay = mtodisplay + thebuses['expected_departure_time']
Used to be very inefficient, but for a long time now, Python does reuse the string being catentated to (as long as there are no other references to it), so it's linear performance instead of the older quadratic performance which should definitely be avoided.
In this case it looks like you already have a list of items that you want to put commas between, so
','.join(some_list)
is probably more appropriate (and automatically means you don't get an extra comma at the end).
So next problem is to construct the list(could also be a generator etc.). #bgporter shows how to make the list, so I'll show the generator version
def mtodisplay(busurl):
json_string = requests.get(busurl)
the_data = json_string.json()
for entry in the_data['departures']:
for thebuses in the_data['departures'][entry]:
if thebuses['line'] == '220':
thebuslen=len(the_data['departures'][entry])
print 'buslen',thebuslen
yield thebuses['expected_departure_time']
# This is where you would normally just call the function
result = '220 buses:\n' + ','.join(mtodisplay(busurl))
I'm not sure what you mean by 'resorting to lists', but something like this:
json_string = requests.get(busurl)
the_data = json_string.json()
mtodisplay= []
for entry in the_data['departures']:
for thebuses in the_data['departures'][entry]:
if thebuses['line'] == '220':
thebuslen=len(the_data['departures'][entry])
print 'buslen',thebuslen
mtodisplay.append(thebuses['expected_departure_time'])
return '220 buses:\n' + ", ".join(mtodisplay)