I have a string such as
'(((a+b)+a)+c)' which I'd like to break into two parts, the result would be ('((a+b)+a)','c').
If I were to run it again on the first element of the result it would give me ('(a+b)', 'a')
and if I ran it again on '(a+b)' it would return ('a', 'b').
I was thinking I could do this via a regular expression but I couldn't figure this out and went down the path of having many if statements checking for opening and closing brackets but it gets a bit messy
Here is an example that works on examples such as yours:
def breakit(s):
count = 0
for i, c in enumerate(s):
if count == 1 and c in '+-':
return s[1:i].strip(), s[i+1:-1].strip()
if c == '(': count +=1
if c == ')': count -= 1
return s
breakit(s)
>> ('((a+b)+a)', 'c')
breakit(_[0])
('(a+b)', 'a')
breakit(_[0])
('a', 'b')
voila:
#!/usr/bin/python3.5
def f(s):
p=s.rsplit('+',1)
return [p[0][1:],p[1][:-1]]
s='(((a+b)+a)+c)'
for i in range(3):
k=f(s)
s=k[0]
print(k)
output:
['((a+b)+a)', 'c']
['(a+b)', 'a']
['a', 'b']
I thought I'd post my answer as well, not quite as elegant as the chosen solution but it works
def break_into_2(s):
if len(s) == 1:
# limiting case
return s
# s[0] can either be a digit or '('
if s[0].isdigit():
# digit could be 10,100,1000,...
idx = 0
while s[idx].isdigit():
idx += 1
a = s[:idx]
b = s[idx+1:]
return a, b
# otherwise, s[0] = '('
idx = 1
counter = 1
# counter tracks opening and closing parenthesis
# when counter = 0, the left side expression has
# been found, return the idx at which this happens
while counter:
if s[idx] == '(':
counter+=1
elif s[idx] == ')':
counter -=1
idx +=1
if s[:idx] == s:
# this case occurs when brackets enclosing entire expression, s
# runs the function again with the same expression from idxs 1:-1
return break_into_2(s[1:-1])
return s[:idx], s[idx+1:]
Related
This is my code. I have looked at many similar codes and have mine set up exactly how I should. I do not receive an error!
The problem is the output I receive is [11]. When the user inputs [1,2,3,4,5,6,7,8,9,11]. Why is it only pulling one odd number??
totlist = []
max_int = 10
oddlist = []
while len(totlist) < max_int:
nums = int(input('Enter a number: '))
totlist.append(nums)
def find_odds(totlist, oddlist):
if len(totlist) == 0:
return
v = totlist.pop()
if v % 2 == 1:
oddlist.append(v)
find_odds(totlist,oddlist)
print(oddlist)
You have forgoot the loop boucle inside the function
def find_odds(totlist, oddlist):
for item in range(len(totlist)) : # here
if len(totlist) == 0:
return
v = totlist.pop()
if v % 2 == 1:
oddlist.append(v)
I'm trying to make a simple 2 player game on python 2.7 .
The program will determine the result of a rock, paper, scissors game, given Player 1 and Player 2’s choices. The program will print out the result, score by each player and the total number of game played.
My question is:
The code doesn't work when "Rock" is the input.It works when "rock" is the input. Same goes to paper and scissors. How can I make it work?
1.The code doesn't work when "Rock" is the input.It works when "rock" is the input. Same goes to paper and scissors. How can I make it work?
From:
player_1 = str(input(">>Player 1? "))
player_2 = str(input(">>Player 2? "))
Add:
player_1 = str(input(">>Player 1? ")).lower()
player_2 = str(input(">>Player 2? ")).lower()
2.Both player must input their choices before the program can be terminated. That means when player 1's input "-1", the program doesn't terminate immediately. It will proceed to ask player 2 for input before it get terminated. How can I make the program terminate itself immediately when player 1's input is "-1"?
From:
player_1 = str(input(">>Player 1? "))
player_2 = str(input(">>Player 2? "))
Add:
player_1 = str(input(">>Player 1? "))
if (player_1=='-1'):
print 'End of game'
break
player_2 = str(input(">>Player 2? "))
3.My code is very long, any suggestions or tips on shortening it without sacrificing any of the function?
use function definitions. Sample:
if (player_1=='-1' or player_2=='-1'):
print 'End of game'
break
elif dif in [-1, 2]:
print ('Player 1 wins.')
score1 = score1 + 1
showScore()
elif dif in [1, -2]:
print('Player 2 wins.')
score2 = score2 + 1
showScore()
else:
print('Tie')
showScore()
continue
def showScore():
print '==================='
print 'Score:'
print 'Player 1: ' + `score1`
print 'Player 2: ' + `score2`
print 'Total game played: ' + `times`
print ''
Here's a good read
For starters, I converted your program to Python 3. It's better in every way. For one thing, it has a normal definition for input.
In general, if you have N of something, where N is greater than 1, it's better to use an array. If you see repetition, move the data into an array and call a function. When N is 2, you won't necessarily shorten the code (my version is longer than yours) but you'll avoid treating the players differently because they both pass through the same logic.
Put the main logic in a function, too, and reserve the "main" code for dealing with startup & command-line stuff.
When you see a string of elifs, that's also a use data instead indicator. In my victor function, I iterate over tuples of winning combinations. You might consider how to use a dict instead.
import sys, os
def print_results( msg, times, scores ):
print( (msg) )
print( '===================' )
print( 'Score:' )
print( 'Player 1: %d' % scores[0] )
print( 'Player 2: %d' % scores[1] )
print( 'Total game played: %d' % times )
print( '' )
def victor( inputs ):
results = ( ('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock') );
for (a, b) in results:
if a == inputs[0] and b == inputs[1]:
return 1
if b == inputs[0] and a == inputs[1]:
return 2
return 0
def play(times, scores):
inputs = ['', '']
for (i, choice) in enumerate(inputs):
prompt = '>>Player %d? ' % (i + 1)
choice = input(prompt).lower()
if choice == '-1':
return False
inputs[i] = choice
result = victor(inputs)
if result == 0:
print_results('Tie', times, scores)
else:
scores[result - 1] += 1
print_results('Player %d wins' % result, times, scores)
times += 1
return True
print('''Welcome to play Rock, Paper, Scissors game. Enter -1 to end''')
scores = [0, 0]
times = 0
while play(times, scores):
pass
if scores[0] == scores[1]:
player = 'Tie'
else:
if scores[0] > scores[1]:
i = 1
else:
i = 2
player = 'Player %d' % i
print( '*******************' )
print( 'Winner: %s' % player )
print( '*******************' )
Could you please help me with writing a function, which receives a character char (ie., a string of length one ), and an integer rotation. My function should return a new string of length one, the resulting of rotating char by rotation number of places to the right. My output for this code should be like this:
print(alphabet_position(a, 13)) = Output = n
print(alphabet_position(A, 14)) = Output = (capital) O
print(alphabet_position(6, 13)) = Output = 6
My function looks like this
def alphabet_position(letter, number):
for char in letter:
return ord(char)+ number
print(alphabet_position("g", 2))
print(alphabet_position("Z", 2))
The output is 105
The output is 92
You forgot to do the checks you have mentioned and also, you need to use the chr(returnedValue) to convert the returned integer to a character. Check out the below code for the function:
def alphabet_position(letter, number):
if len(letter) != 1:
return -1 #Invalid input
elif letter.isalpha() == False:
return letter #If its not an alphabet
else:
ans = ord(letter) + number
# the below if-statement makes sure the value does not overflow.
if ans > ord('z') and letter.islower():
ans = ans - ord('z') + ord('a')
elif ans > ord('Z') and letter.isupper():
ans = ans - ord('Z') + ord('A')
return chr(ans)
I'm very new to python and I've been working on a basic calculator within python for the last few hours (rhetorical I know, given what python has built in, but it's part of my learning process), I've run into an error I can't seem to fix, generally I'm able to get my scripts on their feet and running with the assistance of a couple of Google searches but this one has me stumped. I'm getting a syntax error where I have an else, and while at first I was pretty sure it was a structure issue, rewriting the script didn't fix anything, vague I know, so here's the script (I've marked the spot with a comment) :
def Calculator():
tempnums = [] #stores nums only
tempfuncs = [] #stores funcs only
tmpfuncs = {} #stores funcs only
times = lambda multiply: tempnums[0]*tempnums[1]
div = lambda divide: tempnums[0]%tempnums[1]
plus = lambda add: tempnums[0]+tempnums[1]
minus = lambda subtract:tempnums[0]-tempnums[1]
done = 0
varnum = 0
xtimes = 0
divtimes = 0
plustimes = 0
mintimes = 0
while done == 0: #USER INPUT PROCESS
varnum = varnum + 1
tempint = input() #nums
exec("num%d = tempint" % (varnum))
function = raw_input() #functions
if function != "=":
if function == 'x':
if x not in tmpfuncs:
xtimes = xtimes + 1
tmpfuncs[x] = times
else:
xtimes = xtimes + 1
exec("tmpfuncs[x%d] = times" % (xtimes)
else: #ERROR COMES HERE
if function == '//':
if dv not in tmpfuncs:
divtimes = divtimes + 1
tmpfuncs[dv] = div
else:
divtimes = divtimes + 1
exec("tmpfuncs[dv%d] = div" % (divtimes)
if function == '+':
if pls not in tmpfuncs:
plustimes = plustimes + 1
tmpfuncs[pls] = plus
else:
plustimes = plustimes + 1
exec("tmpfuncs[pls%d] = plus" % (plustimes)
if function == '-':
if mn not in tmpfuncs:
mintimes = mintimes + 1
tmpfuncs[mn] = minus
else:
mintimes = mintimes + 1
exec("tmpfuncs[mn%d] = minus" % (mintimes)
else: #user has selected to calculate input
done = 1
for i in range(1, varnum + 1):
exec("tempnums.append(num%d)" % (i)) #adding nums to a list with dynamic var names
print tmpfuncs
#next we'll make it so that tempnums[0] is the changing result as we use tempnums 0 and 1 to calculate the answer, deleting one as we go until there is only zero
Calculator()
Calculator()
I'm hoping this is legible as I'm posting from mobile (as a matter of fact I'm writing this from mobile as well).
The line above the else is missing a closing parens:
exec("tmpfuncs[x%d] = times" % (xtimes)
should be
exec("tmpfuncs[x%d] = times" % (xtimes))
The same error occurs in many other of your exec lines. Also, I suggest you consider restructuring your code so you do not need to use exec at all.
I was stuck solving a sudoku puzzle with python.I am solving it using the method of backtracking error.My Code is implementing this method correctly upto some number of elements.But after some element it is not moving to the next empty cell to implement this,but it is staing at that particular cell.I think my function to check whether a value is valid at a position is working correctly.I was not able to figure out the mistake I was doing. Can someone help me regarding this.
code:
from numpy import *
def isValid(matrix,row,col):
element = matrix[row][col]
#print element
#print where(matrix[row,:] == element)
if len(where(matrix[row,:] == element)[0]) == 1 and len(where(matrix[:,col] == element)[0]) == 1:
#print 'entered'
row_type = row%3;col_type =col%3
row_index = row-row_type;col_index = col-col_type
if len(where(matrix[row_index:row_index+3,col_index:col_index+3])[0] == 1):
return 1
else:
return 0
else :
return 0
sudoku = loadtxt('1')
sudoku = array(sudoku,dtype = int)
blankRow,blankCol = where(sudoku == 0)
i=0
while i< len(blankRow):
print 'i:',i
#print 'entered'
while sudoku[blankRow[i],blankCol[i]] < 9:
#print 'entered',sudoku[blankRow[i],blankCol[i]]
sudoku[blankRow[i],blankCol[i]] += 1
#j = sudoku[blankRow[i],blankCol[i]]
valid = isValid(sudoku,blankRow[i],blankCol[i])
if valid == 1:
break
if sudoku[blankRow[i],blankCol[i]] == 9 and valid != 1:
print 'entered' #invalid,i:',i,'j',j,'row:',blankRow[i],'col:',blankCol[i]
sudoku[blankRow[i],blankCol[i]] = 0
i-= 1
i+=1
Your backtracking never works, because you unconditionally add 1 to i at the end of the outer loop. I think you want to put that increment in an else block, attached to the if just above it:
if sudoku[blankRow[i],blankCol[i]] == 9 and valid != 1:
print 'entered' #invalid,i:',i,'j',j,'row:',blankRow[i],'col:',blankCol[i]
sudoku[blankRow[i],blankCol[i]] = 0
i-= 1
else: # add this!
i+=1 # indent this!
Note that you might need to add some additional checking to make your code behave properly if it is given an unsolvable puzzle. In that situation, i will become negative, as it backtracks past the first position. This won't actually lead to an immediate error, as you can index a list or array with a negative value, but it will eventually raise an exception after trying (and failing) to solve the puzzle again several times.