I need help with working in 2d lists for my computing GCSE NEA(non examined assessment) and what I need to do is show the first letter of each song title on one line(One single song) along with the artists name for example AC/DC 'Back in Black' would be 'B i B' AC/DC
I am generally stuck on how to manipulate the array to show what I need and I've used several websites such as snakify and a few others
this is my program so far:
stageone=[['another one bites the dust','Queen',
'smoke on the water','Deep Purple',
'Stairway to heaven','Led Zeppelin',
'Carry on wayward son','Kansas',
'Don't stop believin','Journey']]
mainmenu=input("Welcome to the game please select an option-s for start the game,ts for top scores,ys for your scores,n for new game")
if mainmenu=='s':
play=input("do you want to continue you last game-c or do you want to start
a new game-n?")
if play=='s':
difficulty=input("What difficulty do you want to play? you can choose
from; easy,medium,difficult and legend")
if difficulty=='easy':
print("The easy mode of this game contains five stages,each with five
questions")
sure=input("Are you sure you want to play this gamemode?")
if sure=='y':
print(stageone)
I need the song to be on its own,not the whole array. And each song needs the first letter of each word not the whole word. I cannot figure out how to code this part of my program and help would greatly be appreciated. The song artist name however needs to be whole not single,first letter like the song title
when you define stageone, make it a list of lists like this:
stageone = [[title, band], [title, band], [title, band]]
then, instead of print(stageone) in the last line do:
for entry in stageone:
shortTitle = ' '.join([word[0] for word in entry[0].split(' ')])
print(shortTitle, entry[1])
Update: To get one hint at a time you'll need some method to select an entry out of stage one (for a game, I imagine this might be a random index). Then you just remove the for loop I gave before and use your selected entry like so
i = #some code to select an entry in stageone
entry = stageone[i]
shortTitle = ' '.join([word[0] for word in entry[0].split(' ')])
print(shortTitle, entry[1])
Note that there are a bunch of ways to make this more compact, but the original question makes me think a more verbose answer is better than a minimal solution. For instance, #calestini commented a one-liner to replace the for loop in my first response,
res = [[' '.join([x[0] for x in i[0].split()]), i[1]] for i in stageone ]
That's a fine solution - res will be a list like [[song hint, band name], [song hint, band name]] and then you print hints however you want. I'm not changing my original answer because I prefer not to use two list comprehensions in one line (I have a hard time reading the code).
Related
I need to calculate the total amount of time each group uses a meeting space. But the data set has double and triple booking, so I think I need to fix the data first. Disclosure: My coding experience consists solely of working through a few Dataquest courses, and this is my first stackoverflow posting, so I apologize for errors and transgressions.
Each line of the data set contains the group ID and a start and end time. It also includes the booking type, ie. reserved, meeting, etc. Generally, the staff reserve a space for the entire period, which would create a single line, and then add multiple lines for each individual function when the details are known. They should segment the original reserved line so it's only holding space in between functions, but instead they double book the space, so I need to add multiple lines for these interim RES holds, based on the actual holds.
Here's what the data basically looks like:
Existing data:
functions = [['Function', 'Group', 'FunctionType', 'StartTime', 'EndTime'],
[01,01,'RES',2019/10/04 07:00,2019/10/06 17:00],
[02,01,'MTG',2019/10/05 09:00,2019/10/05 12:00],
[03,01,'LUN',2019/10/05 12:30,2019/10/05 13:30],
[04,01,'MTG',2019/10/05 14:00,2019/10/05 17:00],
[05,01,'MTG',2019/10/06 09:00,2019/10/06 12:00]]
I've tried to iterate using a for loop:
for index, row in enumerate(functions):
last_row_index = len(functions) - 1
if index == last_row_index:
pass
else:
current_index = index
next_index = index + 1
if row[3] <= functions[next_index][2]:
next
elif row[4] == 'RES' or row[6] < functions[next_index][6]:
copied_current_row = row.copy()
row[3] = functions[next_index][2]
copied_current_row[2] = functions[next_index][3]
functions.append(copied_current_row)
There seems to be a logical problem in here, because that last append line seems to put the program into some kind of loop and I have to manually interrupt it. So I'm sure it's obvious to someone experienced, but I'm pretty new.
The reason I've done the comparison to see if a function is RES is that reserved should be subordinate to actual functions. But sometimes there are overlaps between actual functions, so I'll need to create another comparison to decide which one takes precedence, but this is where I'm starting.
How I (think) I want it to end up:
[['Function', 'Group', 'FunctionType', 'StartTime', 'EndTime'],
[01,01,'RES',2019/10/04 07:00,2019/10/05 09:00],
[02,01,'MTG',2019/10/05 09:00,2019/10/05 12:00],
[01,01,'RES',2019/10/05 12:00,2019/10/05 12:30],
[03,01,'LUN',2019/10/05 12:30,2019/10/05 13:30],
[01,01,'RES',2019/10/05 13:30,2019/10/05 14:00],
[04,01,'MTG',2019/10/05 14:00,2019/10/05 17:00],
[01,01,'RES',2019/10/05 14:00,2019/10/06 09:00],
[05,01,'MTG',2019/10/06 09:00,2019/10/06 12:00],
[01,01,'RES',2019/10/06 12:00,2019/10/06 17:00]]
This way, I could do a simple calculation of elapsed time for each function line and add it up to see how much time they had the space booked for.
What I'm looking for here is just some direction I should pursue, and I'm definitely not expecting anyone to do the work for me. For example, am I on the right path here, or would it be better to use pandas and vectorized functions? If I can get the basic direction right, I think I can muddle through the specifics.
Thank-you very much,
AF
This is my first time asking here. I tried searching for an answer, but wasn't certain how to phrase what I need so I decided to ask.
I am working on a character creator for a tabletop RPG. I want to get the results for the character's previous occupation, which are on a list, then test that value again to get the occupation previous to that.
I already have a way of getting the first occupation, which is then compared with a text database, with entries such as:
Captain ,Explorer,Knight,Sergeant,
Where Captain is the first occupation and the commas mark the beginning and the end of the possible previous occupations. I have managed to get one of those randomly, but I haven't been able to make the loop then take the selected occupation and run it again. For example:
Explorer ,Cartographer,
Here's the simplified version of my code. It gets the first part right, but I'm not sure how to trigger a loop for the next.
import random
def carOld(carrera,nivPoder):
carActual=carrera
u=0
indPoder=int(nivPoder)
carAnterior=[]
commas=[]
entTemp=[]
d=open("listaCarreras.txt","r")
f=(d.readlines())
while indPoder!=0:
indPoder=indPoder-1
for line in f:
if carActual in line:
entTemp=line.split(",")
d.close
del entTemp[0]
del entTemp[-1]
print (entTemp)
carAnterior=random.choice(entTemp)
I think this. I believe based on your description that the current occupation is in the front of the list, and the previous occupations are next in the list.
str_occs = 'Occ1,Occ2,Occ3'
list_occs = str_occs.split(',')
def prev_occ(occupation, list_occs):
prev_occ_index = list_occs.index(occupation) + 1
try:
ret_val = list_occs[prev_occ_index]
except:
ret_val = "No prior occupations."
return ret_val
You can try it out here: https://repl.it/B08A
I'm playing around with Python and any programming language for the first time, so please bear with me. I started an online class two weeks ago, but try to develop a small game at the side to learn faster (and have fun). It's a text adventure, but is shall have random encounters and fights with enemies that have random equipment that the players can then loot.
This is my problem: If I create random objects/weapons for my random encounter, I need to make sure that the object has a unique name. The way the level is designed there could in theory be an infinite number of objects (it can be open ended, with encounters just popping up).
This is my approach so far
class Item_NPCs: #create objects for NPCs
def__init__(self, item_type, item_number):
# e.g. item_type 1 = weapons, item_type2 = potions, etc.
if item_type == 1 and item number == 1:
self.property1 = 5
self.property2 = 4
if item_type == 1 and item_number ==2:
# etc. :)
def prepare_encounter():
inventory_NPC = [] # empty list for stuff the NPC carries around
XXX = Class_Item(item_type, item_number) # I might randomize the arguments.
What is important is that I want "XXX" to be unique and random, so that no object exists more than once and can later be put into the player's inventory.
How to do that?
Joe
Why do you need it to be random ? You could simply use a list, and append every new object to the list, with its index being its unique identifier :
items = []
items.append( Class_Item(item_type, item_number) )
But if you really need random identifier, maybe you can use a dictionary :
items = dict()
items[random_id] = Class_Item(item_type, item_number)
This requires random_id to be hashable (but it should be if it is a number or a string).
I don't know why others haven't thought of this:
yourvariableName = randint(0,1000)
exec("var_%s = 'value'" % yourVariableName)
I just thought of it myself. I hope it helps you.
A downside is you can't just do this:
print(var_yourVariableName)
you can only do this:
exec("print(var_%s)" % yourVariableName)
But you can probably circumvent this one way or another. Leave a comment if you manage to figure it out.
One more downside — if used in certain ways, it could be very insecure (as we are using exec), so make sure to cover any holes!
I have a task that asked me to making two TEXT picture 1 which one of them is only one character 2 to detect on the TEXT picture.
the first task is to detect only one character location and I sorted it out, but the second task is to detect all the characters location in it.
It says that I have to copy, and paste the detectOneChar() and extend it by numbers of alphabetical including "space" meaning 27 times. but I did not understand how to do.
This is my first code:
def driver():
src=makePicture(pickAFile())
tgt=makePicture(pickAFile())
for myOffset in range(0,getWidth(tgt)-getWidth(src)):
detectOneChar(src,tgt,myOffset,0)
explore(tgt)
return tgt
def detectOneChar(src,tgt,xOffset,yOffset):
sWidth=getWidth(src)
sHeight=getHeight(src)
matchPixels=0
perfectMatch=sWidth*sHeight
for sX in range (0,sWidth):
for sY in range (0,sHeight):
tX=sX+xOffset
tY=sY+yOffset
sPx=getPixel(src,sX,sY)
tPx=getPixel(tgt,tX,tY)
if getColor(tPx) == getColor(sPx):
matchPixels=matchPixels+1
if matchPixels == perfectMatch:
print "Found L at position", tX
setColor(tPx,getColor(sPx))
i cant see if your functions works, everything it prints out just the file path, however, it is recommended using an array and create a list of letter inside
First off, this is a homework assignment, but I've been working on it for a week now and haven't made much headway. My goal for this function is to take a list of lists (each list contains data about a football player) and separate the lists based off of the teams which the players belong to. I also want to add up each player's data so that I wind up with one list for each team with all the player's stats combined.
Here's the code I have so far. The problem I'm currently running into is that some teams are printed multiple times with different data each time. Otherwise it appears to be working correctly. Also, we have the limitation imposed on us that we are not allowed to use classes.
def TopRushingTeam2010(team_info_2010): #running into trouble calculating the rusher rating for each team, it also prints out the same team multiple times but with different stats. And just not getting the right numbers and order.
total_yards = 0
total_TD = 0
total_rush = 0
total_fum = 0
#works mostly, but is returning some teams twice, with different stats each time, which
#should not be happening. so... yeah maybe fix that?
for item in team_info_2010:
team = item[0]
total_yards = item[2]
total_TD = item[3]
total_rush = item[1]
total_fum = item[4]
new_team_info_2010.append([team, total_yards, total_TD, total_rush, total_fum])
for other_item in team_info_2010:
if other_item[0] == team:
new_team_info_2010.remove([team, total_yards, total_TD, total_rush, total_fum])
total_yards = total_yards + other_item[2]
total_TD = total_TD + other_item[3]
total_rush = total_rush + other_item[1]
total_fum = total_fum + other_item[4]
new_team_info_2010.append([team, total_yards, total_TD, total_rush, total_fum])
Any help or tips as to which direction I should head, or if I'm even headed in the right direction?
One possible problem is that you are removing from team_info_2010 while you are iterating through the list. Try deleting that line of code. I don't see a clear reason why you would want to delete from team_info_2010 and behavior is often undefined when you modify an object while iterating through it. More specifically, try deleting the following line of code:
team_info_2010.remove(item)