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]
Related
I should divide the alphabet into lists of letters. I done that, my solution is good but my mentor said to me that I should a little improve this solution.
This is my code:
import string
import random
def generate_list():
list_of_letters=list(string.ascii_lowercase)
number_of_letter = len(list_of_letters)
main_list = []
while number_of_letter > 0:
a = random.randint(4, 7)
number_of_letter -= a
main_list.append(list_of_letters[0:a])
del list_of_letters[0:a]
print(main_list)
generate_list()
My mentor said me that I should take and remove lists of letters in one function, not to manually delete these pieces with lists of all letters manually using the del function So he would like to replace this fragment of code in one line.
main_list.append(list_of_letters[0:a])
del list_of_letters[0:a]
Can someone help me? Thank you in advance :)
You can use the pop() function of lists. It returns one item of the list and removes it from the list.
As it removes from the right side, in your case you have to specifically tell to take the list item at index 0 by calling pop(0).
So replacing your two lines from above with the following snippet should do everything in one step:
main_list.append([list_of_letters.pop(0) for _ in range(min(len(list_of_letters), a))])
Please note, that I stop popping elements from list_of_letters if a is larger then the remaining items in it, hence the min(len(list_of_letters), a).
my_str="ellezagchickenbndodetballigatoraaaolmeznacattleeblrctacfenarcesssadlritfhftrarrssos aoiarefaareppohssarghcerumrheirmmwildfcumeboimltaairfovindalbiglalobehoeasiaxuesabldinbbccrhhrtylrlahsifdlogkrctlaiareogoldfinchefnnddmneepoletnarntadodinosauroxofoeclictnahpelepalgaierhohcaorkcocyatrmoacrflamingoerefafloechateehchdracaribou"
def create_2d_list(N):
output_list=[]
counter=0
for row in range(0,N):
temp=[]
for col in range(0,N):
temp.append(my_str[counter])#you can add a charcter instead of counter
counter=counter+1
output_list.append(temp[:])
return output_list
N=18
x=create_2d_list(N)
for row in range(0,N):
total=0
s="|"
for col in range(0,N):
my_str="{0:2} ".format(x[row][col])
s=s+my_str+"|"
print "-"*(N*4+1)
print s,
print " "
the_valid_words=open("E:/asd/words.txt","r").readlines()
def looking_word_left_to_right(the_list):
for any_words in the_valid_words:
for every in x[0]:
the_first_index=x[0].index(every)
for every in range(the_first_index,(the_first_index)+7):
c=str(every)
the_join=" ".join(c)
if the_join==the_valid_words:
word.upper().replace(every,x[0].upper(every))
return x[0]
print looking_word_left_to_right(x)
every time i run the program, the looking_word_left_to_right doesn't print anything
P.S its similar to small crossword for beginners, Capitalizing the letters that make a word and removing every other letter without changing places, if someone could give like thoughts on how to proceed that would be great. i have certain valid words to look for.
and i'm a newbie so go easy on me :)
appreciate the help.
There seem to be a number of problems.
Why are you operating on x when you also pass it in as the_list" Just use the_list.
You're only looking at the first line of x and never moving beyond that.
It looks like you're putting a space between every character before you compare. If c = "abcdefg" then " ".join(c) will give you "a b c d e f g". If your the_valid_words doesn't have spaces in it, then if the_join==the_valid_words will always evaluate to false.
You're comparing to the_valid_words, which is your entire list. You should probably be comparing to EACH valid word using any_word... which you aren't using anywhere else.
You may also be running into a problem with iterating over x, while you're changing it (it will sometimes invalidate the iterator... but sometimes not). I.e. if you're iterating through x and then you change x before you're done iterating, then Python might not know where the iterator belongs in the new version of x. Since the_list is the same as x anyway, it might be better to do for every in the_list: and then change x to your heart's content.
It looks like you may not quite understand how for loops work in Python. Take a look at those, and that may help some.
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
...
I am working with Google Python class exercises where I am getting this issue -
def front_x(words):
# +++your code here+++
list = []
for i,s in enumerate(words):
print i,s
if s[0] == 'x':
list.append(words.pop(i))
return list
print front_x(['bbb','ccc','axx','xzz','xaa'])
my loop is only iterating from 0 to 3, so print i,s is giving me values till 'xzz'.Please point where I am wrong.
Don't modify something as you're iterating over it. words.pop(i) modifies words, which you're iterating over via enumerate().
I'd suggest looking at list comprehensions for accomplishing your apparent goal.
Yes, you probably shouldn't words.pop(). The word you want is most likely in s - add that to the list instead.
Also, note that naming a list "list", will more or less erase the "list" builtin type from your local scope. It's not a make or break kind of deal, but it's something pylint would warn about.
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.