Question about changing the argument in range function through iterations - python

I'm a newbie so I'm really sorry if this is too basic of a question, but I just couldn't solve it on my own. Perhaps it's not considered complex enough ( at all ) which would explain why I couldn't find an adequate answer online.
I've made a tic-tac-toe program following the Automate the Boring Stuff with Python textbook, but modified it a tiny bit so it doesn't allow players to enter 'X'/'O' in already filled slots. Here's what it looks like :
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
def printBoard(board):
print(board['top-L']+'|'+board['top-M']+'|'+board['top-R'])
print('-+-+-')
print(board['mid-L']+'|'+board['mid-M']+'|'+board['mid-R'])
print('-+-+-')
print(board['low-L']+'|'+board['low-M']+'|'+board['low-R'])
turn='X'
_range=9
for i in range(_range):
printBoard(theBoard)
print('''It is the '''+turn+''' player's turn.''')
move=input()
if theBoard[move]==' ':
theBoard[move]=turn
else:
print('The slot is already filled !')
_range+=1
if turn=='X':
turn ='O'
else:
turn='X'
printBoard(theBoard)
However, it doesn't seem like the _range variable is being increased by one at all through iterations where I intentionally enter 'X'\'O' in the slots where such symbols are already existent.
Is there something that I'm missing her ? Is there any way I could make this work as I planned it ?
Thank you in advance.

It could be easier to sanitize the input immediately via a while loop instead of increasing the range.
move = input(f"It is the {turn} player's turn.")
while theBoard[move]!=' ':
move=input('The slot is already filled')
Your attempt did not work because you changed _range after it being used and it is not used after you changed it.

Related

Unable To Remove Whitespace On String Using Python

I'm trying to get rid of the whitespace on this list however I am unable to. Anyone know where I am going wrong with my code?
love_maybe_lines = ['Always ', ' in the middle of our bloodiest battles ', 'you lay down your arms', ' like flowering mines ', ' to conquer me home. ']
love_maybe_lines_joined = '\n'.join(love_maybe_lines)
love_maybe_lines_stripped = love_maybe_lines_joined.strip()
print(love_maybe_lines_stripped)
Terminal:
Always
in the middle of our bloodiest battles
you lay down your arms
like flowering mines
to conquer me home.
love_maybe_lines = ['Always ', ' in the middle of our bloodiest battles ', 'you lay down your arms', ' like flowering mines ', ' to conquer me home. ']
love_maybe_lines = [item.strip() for item in love_maybe_lines]
That may help.

Selecting specific results from print out in Python - 2.7

I am looking to take the three most recent (based on time) lists from the printed code below. These are not actual files but text parsed and stored in dictionaries:
list4 = sorted(data1.values(), key = itemgetter(4))
for complete in list4:
if complete[1] == 'Completed':
print complete
returns:
['aaa664847', ' Completed', ' location' , ' mode', ' 2014-xx-ddT20:00:00.000']
['aaa665487', ' Completed', ' location' , ' mode', ' 2014-xx-ddT19:00:00.000']
['aaa661965', ' Completed', ' location' , ' mode', ' 2014-xx-ddT18:00:00.000']
['aaa669696', ' Completed', ' location' , ' mode', ' 2014-xx-ddT17:00:00.000']
['aaa665376', ' Completed', ' location' , ' mode', ' 2014-xx-ddT16:00:00.000']
I have tried to append these results to another list got this:
[['aaa664847', ' Completed', ' location' , ' mode', ' 2014-xx-ddT20:00:00.000']]
[['aaa665487', ' Completed', ' location' , ' mode', ' 2014-xx-ddT19:00:00.000']]
I would like one list which i then could use [-3:] to print out the three most recent.
storage = [['aaa664847', ' Completed', ' location' , ' mode', ' 2014-xx-ddT20:00:00.000'],['aaa665487', ' Completed', ' location' , ' mode', ' 2014-xx-ddT19:00:00.000']]
So,
import itertools
storage = list(itertools.islice((c for c in list4 if c[1]=='Completed'), 3))
maybe...?
Added: an explanation might help. The (c for c in list4 if c[1]=='Completed') part is a generator expression ("genexp") -- it walks list4 from the start and only yields, one at a time, items (sub-lists here) satisfying the condition.
The () around it are needed, because itertools.islice takes another argument (a genexp must always be surrounded by parentheses, though when it's the only argument to a callable the parentheses that call the callable are enough and need not be doublled up).
islice is told (via its second argument) to yield only the first up to 3 items of the iterable it receives as the first argument. Once it's done that it stops looping, doing no further work (which would be useless).
We do need a call to list over this all because we require, as a result, a list, not an iterator (which is what islice's result is).
People who are uncomfortable with generators and iterators might choose the following less-elegant, probably less-performant, but simpler approach:
storage = []
for c in list4:
if c[1]=='Completed':
storage.append(c)
if len(c) == 3: break
This is perfectly valid Python, too (and it would have worked just fine as far back as Python 1.5.4 if not earlier). But modern Python usage leans far more towards generators, iterators, and itertools, where applicable...

Conditional statements with multiple if statements (Involves raw_input)

I'm experimenting with raw_input and it works fine except for my 1st if statement and my else statement. Whenever I run the code and answer the 2nd question with a raw_input listed after 'League' in the 1st if statement, it returns both the 1st if's print and the else's print when it should only print the 1st if. Any idea what's wrong?
name = raw_input('What is your name?\n')
game = raw_input('\nWhat MOBA do you play/have played? \n(The answer ' \
'must be case sensitive i.e. LoL for League and DoTA for y\'know the whole darn thing '\
'is too '\
'darn long to say even though I typed a lot more than the name)\n')
if game in ('League' , 'League of Legends' , 'LoL'):
print '\nYou go girl! '
if game in ('DoTA' , 'DoTA 2' , 'DoTA2'):
print '\nThat\'s cool and all but........ Go play League you dang noob. '
else:
print '\nAre you kidding me? You play %s? I\'m severely disappointed in you %s. You ' \
'should at least be playing ' \
'one of these popular games. \nShame, shame, shame. Go install one. ' % (game, name)
you can always use if for the first conditional, elif for any number of other conditionals (if the input is in the second list in your instance) and else if the input is not in any of those lists, your indentation is also a little messed up,nesting if statements inside each other will only run the nested conditional if the first statement is true, I'd also recommend you use the string.lower() method on your users input so you don't have to instruct the user to type case-sensitive input and use variables to store those lists so you can reuse them elsewhere in your code..something like this:
name = raw_input('What is your name?\n')
game = (raw_input('\nWhat MOBA do you play/have played?')).lower()
awesomeGames=['league' , 'league of legends' , 'lol']
coolGames=['dota' , 'dota 2' , 'dota2']
if game in awesomeGames:
print '\nYou go girl! '
elif game in coolGames:
print '\nThat\'s cool and all but........ Go play League you dang noob. '
else:
print '\nAre you kidding me? You play %s? I\'m severely disappointed in you %s. You ' \
'should at least be playing ' \
'one of these popular games. \nShame, shame, shame. Go install one. ' % (game, name)
The indent level is incorrect.
Spend one more space for the second if statement.
or 1 less space and elif instead of the second if.
Replace the second if condition by elif. elif can be used as many times as you want until the condition matches but its better practice to have the last condition as else (which is like default statement when other conditions have failed)

How can i change the variables name according to the function parentiss?

if strengh1 <=0:
death1=True
else:
death1 = False
if strengh2 <=0:
death2=True
else:
death2=False
def output(character):
if death character == False:
print
print('Character', character ,' strengh is now %s' % strengh1)
print('Character ', character ,' skill is now %s' % skill1)
else:
print
print('Character ', character ,' is dead')
output(1)
output(2)
Hi guys I am currently doing a bit of a project. here is part of my very last lines of code. There are two characters and i want to be able to use a function. I am almost fully self taught and i havnt been coding very long at all so there might be basic errors or i might be doing something that just cant work, but how can i change the name of the "death" variable in the function using what is in the function call? So for example output(10 needs to change death to death1? is this possible. Also i need to be able to print this in one solid output as
Character (then the function parameter) is now dead
Your code demonstrates a profound misunderstanding of the way Python names work. Just setting character = 1 and writing death character will not access death1, that simply doesn't make any sense. There is a good primer on how Python deals with names here.
Your specific issue could be solved by passing to output all of the variables it actually needs:
def output(character, strength, skill, death):
if not death:
print
print('Character', character ,' strength is now %s' % strength)
print('Character ', character ,' skill is now %s' % skill)
else:
print
print('Character ', character ,' is dead')
output(1, strength1, skill1, death1)
This is obviously a bit awkward, so the next step would be to encapsulate these parameters as attributes in a Character class; see e.g. the tutorial. Then you can pass a single Character instance to the function.
Very often, the most natural solution is to use a dictionary.
death = dict()
# most probably strength should be a dict too
if strengh1 <=0:
death[1]=True
else:
death[1] = False
# or death[1] = bool(strength1<=0)
if strengh2 <=0:
death[2]=True
else:
death[2]=False
def output(key):
if death[key]== False:
print
print('Character', character ,' strengh is now %s' % strengh1)
print('Character ', character ,' skill is now %s' % skill1)
else:
print
print('Character ', character ,' is dead')
output(1)
output(2)
Depending on what 1 and 2 stand for, you might want to use strings instead -- strength['muscles'], death['poisoning'] perhaps? (Or strength['marketing'] and death['irrelevance'] if this is a startup game.)

Test if sentences contain smaller sentences

So I have 100 million sentences, and for each sentence I'd like to see whether it contains one of 6000 smaller sentences (matching whole words only). So far my code is
smaller_sentences = [...]
for large_sentence in file:
for small_sentence in smaller_sentences:
if ((' ' + small_sentence + ' ') in large_sentence)
or (large_sentence.startswith(small_sentence + ' ')
or (large_sentence.endswith(' ' + small_sentence):
outfile.write(large_sentence)
break
But this code runs prohibitively slowly. Do you know of a faster way to go about doing this?
Without knowing more about the domain (word/sentence length), frequency of read/write/query and specifics around the algorithm.
But, in the first instance you can switch your condition around.
This checks the whole string (slow), then the head (fast), then the tail (fast).
((' ' + small_sentence + ' ') in large_sentence)
or (large_sentence.startswith(small_sentence + ' ')
or (large_sentence.endswith(' ' + small_sentence):
This checks the head then the tail (fast), then the head (fast), then the whole string. Not huge bump in the Big-O sense, but it might add some speed if you know that the strings might be more likely at the start or finish.
(large_sentence.startswith(small_sentence + ' ')
or (large_sentence.endswith(' ' + small_sentence)
or ((' ' + small_sentence + ' ') in large_sentence)

Categories