import random
wordlist = {'Candy', 'Monkey'}
level = 0
while level == 0:
number = random.randint(1, 2)
if number == 1:
print 'Candy'
secword = 'Candy'
level = 2
elif number == 2:
print 'Monkey'
secword = 'Monkey'
level = 2
for i in secword:
print i
I have a couple of questions about the code I just randomly wrote (I'm a beginner)
1) How do I assign a word in a list to a variable?
ex. assign the word 'Candy' into a variable because I always get the error (List is not callable)
2) How do I assign the variable i (in the for loop) to a separate variable for each letter?
Thanks! Tell me if it's not specific enough.
It should be pointed out that wordlist is not actually a list, but a set. The difference is that a set does not allow duplicate values, whereas a list does. A list is created using hard-brackets: [], and a set is created using curly-brackets: {}.
This is important because you can't index a set. In other words, you can't get an element using wordlist[0]. It will give you a 'set does not support indexing' error. So, before you try to get an element out of wordlist, make sure you actually declare it as a list:
wordlist = ['Candy', 'Monkey']
I'm not sure what you're asking in your second question. Can you elaborate?
You are getting List is not callable because you are probably using small brackets (). If you use small brackets, and do wordlist(0), you actually make interpreter feel like wordlist is a method and 0 is it's argument.
s = worldlist[0] # to assign "Candy" to s.
Related
I am currently writing a small bit of logic for my HTML page. My aim is to create variables (lists) within an iteration (using the iteration to create the names of said lists as the amount of them will be unknown to the program). I am currently creating the lists like this:
maps={}
currentMap = elements[0].process
counter=0
for i in elements:
if(counter==0):
maps["mapsEle{0}".format(counter)]=[]
counter+=1
if(i.process!=currentMap):
currentMap = i.process
maps["mapEle{0}".format(counter)]=[]
counter+=1
else:
print("No change found, keeping heading the same.")
However as you can probably tell, this does not create a list but a string. I try to print the variables (e.g. mapsEle0) and it returns the variable name (e.g. print(mapsEle0) returns "mapsEle0") this too me is suprising as I would have thought if the dictionary is saving it as a string it would print "[]".
So I am looking for a way to create lists within the dictionary in that iteration I am using there, basically want to just reformat my declaration. Cheers in advance everyone :)
Edit:
As requested here is the code where I attempt to append. Please note I want to append 'i' into the lists and no the dictionary.
for i in maps:
for x in elements:
if(x.process!=currentMap):
currentMap=x.process
elif(x.process==currentMap):
#i.append(x)
The syntax of your print statement is wrong, if you want to access the contents of the dictionary, you need to use different notation.
Instead of print('mapsEle0') you need to do print(maps['mapsEle0']).
Update:
Unfortunately your description of what you want and your code are a bit conflicting, so if you can, please try to explain some more what this code is supposed to do.
for i in maps.iterkeys():
for x in elements:
if(x.process!=currentMap):
currentMap=x.process
elif(x.process==currentMap):
maps[i].append(x)
This will iterate over all keys of maps ('mapsEle0'...'mapsEleN') and add x to the contained list if the elif condition is fulfilled.
You're printing the string by doing print('mapsEle0').
To print the dict, you must print(maps) - 'll print the whole dictionary, OR, to print a specific key/element print(maps['mapsEle0'])
To elaborate it further here's a interpreter session:
>>> maps = {}
>>> counter = 0
>>> maps["mapsEle{0}".format(counter)]=[]
>>> maps
{'mapsEle0': []}
>>>
>>> print(maps)
{'mapsEle0': []}
>>>
>>> print(maps['mapsEle0'])
[]
>>>
For the append part:
>>> maps['mapsEle1'].append('hello')
>>> print(maps['mapsEle1'])
['hello']
Edit 2: Your statement is still not clear
As requested here is the code where I attempt to append. Please note I
want to append 'i' into the lists and no the dictionary.
I think sobek has got it right - you want to append x to the mapsEle0, mapsEle1 lists, which are keys in maps dictionary.
for i in maps.iterkeys():
for x in elements:
if(x.process!=currentMap):
currentMap=x.process
elif(x.process==currentMap):
maps[i].append(x)
Okay so I've annotated almost everything in my code, but I'm struggling slightly with annotating my for loop, I've got all of it except these two lines I just don't know how to explain with it making sense to anyone but me. Would be great if I could get some tips on this!
y = {} #
Positions = [] #
for i, word in enumerate (Sentence): #This starts a for look to go through every word within the variable 'Sentence' which is a list.
if not word in y: #This continues the code below if the word isn't found within the variable 'y'.
y[word] = (i+1) #This gives the word that wasn't found within the variable 'y' the next unused number plus 1 so that it doesn't confuse those unfamiliar with computer science starting at 0.
Positions = Positions + [y[word]] #This sets the variable 'Positions' to the variables 'Positions' and '[d[word]]'.
If you're going to comment a variable, then the comment should explain that the variable contains (or to be precise, since the purpose of the code is to populate these variables, our goal for what the variable will contain) and/or what it's expected to be used for. Since we don't see this data used for anything, I'll stick to the former:
y = {} # dictionary mapping words to the (1-based) index of their first occurrence in the sentence
Positions = [] # list containing, for each position in the sentence, the (1-based) index of the first occurrence of the word at that position.
In one you are declaring a dictionary:
y = {} #
in another a list:
Positions = [] #
Dictionaries store objects with keys. Lists are stacks of elements (position wise).
I'm currently learning python so I apologize in advance for the messiness of my code. My function is meant to take in a single string and add the string numbers together. i.e. A string argument of 123 will become 1 + 2 + 3 and return 6.
My issue is when I iterate through my list - python keeps indicating that the variable has been referenced before any value has been assigned. However when I print out the values being calculated they are correct. Even more confusing is that when I return them - they are incorrect. I can't seem to work out where I'm going wrong. Could anyone tell me what the issue may be?
Thank you!
listy = []
global total
#Convert number to a list then cycle through the list manually via elements and add them all up
def digit_sum(x):
number= []
number.append(x)
print number
for i in range(len(number)):
result = str(number[i])
print result
#Now it has been converted to a string so we should be able to
#read each number separately now and re-convert them to integers
for i in result:
listy.append(i)
print listy
#listy is printing [5,3,4]
for i in listy:
total += int(i)
return total
print digit_sum(x)
I'm not really sure what's going on in your code there, especially with the messed up indentation, but your problem is easily sovled:
sum(map(int, str(534)))
It makes the number a string, then converts each digit to an int with map, then just sums it all.
If your concern is only about summing a string of numbers, then list comprehension itself would do or as #Maltysen suggested you could use map
sum([int(x) for x in "534"])
pretty simple:
You can use a map or a list comprehension. They are pretty much equivalent. Other people gave an answer using map but I decided to use a list comprehension.
s = "1234567"
sum([int(character) for character in s])
I believe I have worked out what was wrong with my code. As I am still new to Python, I made some very novice mistakes such as not realizing declaring a variable outside the local function would result in the solution not being what I had expected.
Due to my returns being placed incorrectly as well as my listy [] variable being instantiated outside my function, instead of reading each number once, it would read it three times.
This has now been corrected in the code below.
#Convert number to a list then cycle through the list manually via elements and add them all up
def digit_sum(x):
total = 0
number= []
number.append(x)
print number
for i in range(len(number)):
result = str(number[i])
print result
#Now it has been converted to a string so we should be able to
#read each number separately now and re-convert them to integers
for i in result:
listy = []
listy.append(i)
# print listy
#listy is printing [5,3,4]
for i in listy:
print i
total+= int(i)
print total
break
return total
print digit_sum(111)
I am python/programming newbie. Using python 2.7
I have been trying to figure out how to 'subtract' the elements in 1 list from the elements in another list. However I put 'subtract' in quotes because I am not working with integers, and could not think of another way to explain.
First up, here is my code:
plural_string = "cell phones|sheep|oxen" # result of user input with raw_input()
plural_endings_string = "s,,en" # result of user input with raw_input() - always comma separated.
plural_list = plural_string.split('|')
plural_endings_list = plural_endings_string.split(',')
# This is pseudo code since '-' does not work with non-integers in a string
# but it expresses what I am trying to achieve
new_list = [a - b for a, b in zip(plural_list, plural_endings_list)]
So, what I actually want the new list to look like is this:
>>> new_list
>>> ['cell phone', 'sheep', 'ox']
I basically want to de-pluralize the words(elements) in the plural_list variable using the plural-endings(elements) in the plural_endings_list variable.
A key things to note is: The number of elements (and therefore word choices) in the lists will vary based on user input (me). So, in a different situation, the lists I am working with could look like this:
plural_list = ['children', 'brothers', 'fish', 'penguins']
plural_endings_list = ['ren', 's', '', 's']
I have tried to figure out how to do this using the strings - and not lists - using the '.replace' function, but I come up against a brick wall, given that I don't know what the user input will be in each run of the script. I could not find a '1 fits all' solution. Unsuccessfully tried regex too, and had the same problem of not knowing what the user input will be. It is beyond my newbie brain right now.
Hopefully, I have explained myself clearly! If not I am trying to do the opposite of this other question in SO - How do i add two lists' elements into one list?
But, instead of concatenation, I need 'subtraction'
Cheers
Darren
EDIT1: In response to #brad comment. I actually feed in the plural endings to the plural_endings_list via user input (this is part of a larger script). So if a list contains the element "children's", then I would choose "'s" as the ending for the plural_endings_list. It is always case specific.
EDIT2: In response to #Graeme Stuart comment. Graeme - the input will always vary in length. There could be 2 elements in each list, or there could be 10 elements in each list, or anything in between.
I think this does what you need. Its a bit clunky though. Will your input always be the same length?
def depluralise(plurals, plural_endings):
new_list = []
for plural, plural_ending in zip(plurals, plural_endings):
if plural.endswith(plural_ending):
if plural_ending == '':
new_list.append(plural)
else:
new_list.append(plural[:-len(plural_ending)])
return new_list
plural_string = "cell phones|sheep|oxen"
plurals = plural_string.split('|')
plural_endings_string = "s,,en"
plural_endings = plural_endings_string.split(',')
print depluralise(plurals, plural_endings)
plurals = ['children', 'brothers', 'fish', 'penguins']
plural_endings = ['ren', 's', '', 's']
print depluralise(plurals, plural_endings)
>>> p = 'children'
>>> e = 'ren'
>>> if p.endswith(e):
... print p[:-len(e)]
...
child
This may not be the answer you want, but to get the best de-pluralization, you'd want a dictionary of nouns and their plurals.
Search for the plural, and replace it with the singular.
I'd think you'd pull less hair out doing it this way than trying to handle all of the exceptions you'd run into:
women
geese
phenomena
data
dice
...
for example, if i have a list like:
one = [1,2,3]
what function or method can i use to split each element into their own separate list like:
one = [1]
RANDOM_DYNAMIC_NAME = [2]
RANDOM_DYNAMIC_NAME_AGAIN = [3]
and at any given time, the unsplit list called one may have more than 1 element, its dynamic, and this algorithm is needed for a hangman game i am coding as self-given homework.
the algorithm is needed to complete this example purpose:
pick a word: mississippi
guess a letter: s
['_','_','s','s','_','s','s','_','_','_','_']
Here is my code:
http://pastebin.com/gcCZv67D
Looking at your code, if the part you're trying to solve is the comments in lines 24-26, you definitely don't need dynamically-created variables for that at all, and in fact I can't even imagine how they could help you.
You've got this:
enum = [i for i,x in enumerate(letterlist) if x == word]
The names of your variables are very confusing—something called word is the guessed letter, while you've got a different variable letterguess that's something else, and then a variable called letter that's the whole word… But I think I get what you're aiming for.
enum is a list of all of the indices of word within letterlist. For example, if letterlist is 'letter' and word is t, it will be [2, 3].
Then you do this:
bracketstrip = (str(w) for w in enum)
So now bracketstrip is ['2', '3']. I'm not sure why you want that.
z = int(''.join(bracketstrip))
And ''.join(bracketstrip) is '23', so z is 23.
letterguess[z] = word
And now you get an IndexError, because you're trying to set letterguess[23] instead of setting letterguess[2] and letterguess[3].
Here's what I think you want to replace that with:
enum = [i for i,x in enumerate(letterlist) if x == word]
for i in enum:
letterguess[i] = word
A few hints about some other parts of your code:
You've got a few places where you do things like this:
letterlist = []
for eachcharacter in letter:
letterlist.append(eachcharacter)
This is the same as letterlist = list(letter). But really, you don't need that list at all. The only thing you do with that is for i, x in enumerate(letterlist), and you could have done the exact same thing with letter in the first place. You're generally making things much harder for yourself than you have to. Make sure you actually understand why you've written each line of code.
"Because I couldn't get it to work any other way" isn't a reason—what were you trying to get to work? Why did you think you needed a list of letters? Nobody can keep all of those decisions in their head at once. The more skill you have, the more of your code will be so obvious to you that it doesn't need comments, but you'll never get to the point where you don't need any. When you're just starting out, every time you figure out how to do something, add a comment reminding yourself what you were trying to do, and why it works. You can always remove comments later; you can never get back comments that you didn't write.
for question one ,just list comprehension is good . it will return each element as a separate list
[ [x,] for x in one ]
As for a literal answer to your question, here's how you do it, though I can't immagine why you would want to to this. Generally, dynamic variable names are poor design. You probably just want a single list, or list of lists.
import random
for x in one:
name = 'x' + str(random.getrandbits(10))
globals()[name] = [x]