I am trying to create a calculator program - python

I am writing a code that removes '√' symbol from a string and get's the index of it, By using the 'enumerate' function in python, I have already made an functioning calculator but I am improving it.
Code:
cal = input(">>> ")
for i, c in enumerate(cal):
if c == '√':
cal = cal[0:i]+cal[i+1:]
print(cal)
Input:
>>> 123√456√789√123
Output:
123456√89√13
I am not getting the right output when I remove a character from the string the enumerate function messes up the index , So I can't figure it out.
[My first time using stackover flow Don't judge]

As per the comments. You have made the classic error of editing a list whilst looping thru it. The edits will change the list, so the positions will be incorrect.
a good solution is this:
cal = '123√456√789√123'
cal = cal.replace('√','')
cal
Which returns this:
'123456789123'

Related

Why can't I change items in a Python list using a step?

So I am still in the beginning stages of learning Python--and coding as a whole for that matter.
My question is why can I not change items in a Python list using a step, like this:
def myfunc2(string):
new = list(string)
new[0::2] = new[0::2].upper()
new[1::2] = new[1::2].lower()
return '' .join(new)
myfunc2('HelloWorld')
I want to make every other letter upper and lower case, starting at index 0.
I had already seen a solution posted by another user, and although this other solution worked I had trouble understanding the code. So, in my curiosity I tried to work out the logic myself and came up with the above code.
Why is this not working?
new[0::2] returns a list, which does not have an upper method . Same goes for new[1::2] and lower.
You can achieve your goal with map:
def myfunc2(string):
new = list(string)
new[0::2] = map(str.upper, new[0::2])
new[1::2] = map(str.lower, new[1::2])
return '' .join(new)
print(myfunc2('HelloWorld'))
# HeLlOwOrLd

Cannot understand how this Python code works

I found this question on HackerRank and I am unable to understand the code(solution) that is displayed in the discussions page.
The question is:
Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer at position .
print: Print the list.
remove e: Delete the first occurrence of integer .
append e: Insert integer at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Even though I have solved the problem using if-else, I do not understand how this code works:
n = input()
slist = []
for _ in range(n):
s = input().split()
cmd = s[0]
args = s[1:]
if cmd !="print":
cmd += "("+ ",".join(args) +")"
eval("slist."+cmd)
else:
print slist
Well, the code takes advantage of Python's eval function. Many languages have this feature: eval, short for "evaluate", takes a piece of text and executes it as if it were part of the program instead of just a piece of data fed to the program. This line:
s = input().split()
reads a line of input from the user and splits it into words based on whitespace, so if you type "insert 1 2", s is set to the list ["insert","1","2"]. That is then transformed by the following lines into "insert(1,2)", which is then appended to "slist." and passed to eval, resulting in the method call slist.insert(1,2) being executed. So basically, this code is taking advantage of the fact that Python already has methods to perform the required functions, that even happen to have the same names used in the problem. All it has to do is take the name and arguments from an input line and transform them into Python syntax. (The print option is special-cased since there is no method slist.print(); for that case it uses the global command: print slist.)
In real-world code, you should almost never use eval; it is a very dangerous feature, since it allows users of your application to potentially cause it to run any code they want. It's certainly one of the easier features for hackers to use to break into things.
It's dirty code that's abusing eval.
Basically, when you enter, for example, "remove 1", it creates some code that looks like sList.remove(1), then gives the created code to eval. This has Python interpret it.
This is probably the worst way you could solve this outside of coding competitions though. The use of eval is entirely unnecessary here.
Actually I Find some error in the code, but I came to an understanding of how this code runs. here is it:
input :
3
1 2 3
cmd = 1 + ( 2 + 3)
then eval(cmd) i.e., eval("1 + (2 + 3)") which gives an output 6
another input:
4
4 5 6 2
cmd = 4 + ( 5 + 6 + 2)
eval(cmd)
if __name__ == '__main__':
N = int(raw_input())
lst=[]
for _ in range(N):
cmd, *line = input().split()
ele= list(map(str,line))
if cmd in dir(lst):
exec('lst.'+cmd+'('+','.join(ele)+')')
elif cmd == 'print':
print(lst)
else:
print('wrong command', cmd)

Python .find() to return the end of found string

So I want to pick some data out of a text file, which looks like this:
##After some other stuff which could change
EASY:[5,500]
MEDIUM:[10,100]
HARD:[20,1000]
EXPERT:[30,2000]
EXTREME:[50,5000]
I'm writing a function which uses the difficulty ('EASY' 'HARD' e.t.c) to return the following list. My current code looks like this:
def setAI(difficulty): #difficulty='EASY' or 'HARD' or...e.t.c)
configFile=open('AISettings.txt')
config=configFile.read()
print(config[(config.find(difficulty)):(config.find(']',(config.find(difficulty))))]) #So it will return the chunk between the difficulty, and the next closed-square-bracket after that
This produces the following output:
>>> HARD:[20,1000
I tried fixing it like this:
print(config[(config.find(difficulty)+2):(config.find(']',(config.find(difficulty)+2))+1)])
which returns:
>>>RD:[20,1000]
The issue I'm trying to adress is that I want it to start after the colon, I am aware that I could use the length of the difficulty string to solve this, but is there a simpler way of returning the end of the string when using the .find() command?
P.S: I couldn't find any duplicates for this, but it is a slightly odd question, so sorry if it's already on here somewhere; Thanks in advance
EDIT: Thanks for the replies, I think you basically all solved the problem, but the chosen answer was becasue I like the iteration line-by-line idea, Cheers guys :)
Well if the file look like this, why not just iterate line by line and do something like:
def setAI(difficulty): #difficulty='EASY' or 'HARD' or...e.t.c)
configFile=open('AISettings.txt')
config=configFile.readlines()
for line in config:
if line.startswith(difficulty.upper()):
print(line[len(difficulty) + 1:])
Find returns the location. But ranges assume that their end number should not be included. Just add one to the end.
config = """
##After some other stuff which could change
EASY:[5,500]
MEDIUM:[10,100]
HARD:[20,1000]
EXPERT:[30,2000]
EXTREME:[50,5000]
"""
difficulty = 'HARD'
begin = config.find(difficulty)
end = config.find(']', begin)
print(config[begin:end+1])
The function find will always give you the position of the first letter of the string. Also consider that the notation string[start:end] will give you the substring including the character at start but excluding the character at end. Therefore you could use something like the following:
def setAI(difficulty):
configFile = open('AISettings.txt')
config = configFile.read()
start = config.find(difficulty) + len(difficulty) + 1
end = config.find(']', start) + 1
print(config[start:end])

Python issue with replace statement?

I've been write this practice program for while now, the whole purpose of the code is to get user input and generate passwords, everything almost works, but the replace statements are driving me nuts. Maybe one of you smart programmers can help me, because I'm kinda new to this whole field of programming. The issue is that replace statement only seems to work with the first char in Strng, but not the others one. The other funcs blower the last run first and then the middle one runs.
def Manip(Strng):
#Strng = 'jayjay'
print (Strng.replace('j','h',1))
#Displays: 'hayjay'
print (Strng.replace('j','h',4))
#Displays: 'hayhay'
return
def Add_nums(Strng):
Size=len(str(Strng))
Total_per = str(Strng).count('%')
# Get The % Spots Position, So they only get replaced with numbers during permutation
currnt_Pos = 0
per = [] # % position per for percent
rGen = ''
for i in str(Strng):
if i == str('%'):
per.append(currnt_Pos)
currnt_Pos+=1
for num,pos in zip(str(self.ints),per):
rGen = Strng.replace(str(Strng[pos]),str(num),4);
return rGen
for pos in AlphaB: # DataBase Of The Positions Of Alphabets
for letter in self.alphas: #letters in The User Inputs
GenPass=(self.forms.replace(self.forms[pos],letter,int(pos)))
# Not Fully Formatted yet; you got something like Cat%%%, so you can use another function to change % to nums
# And use the permutations function to generate other passwrds and then
# continue to the rest of this for loop which will generate something like cat222 or cat333
Add_nums(GenPass) # The Function That will add numbers to the Cat%%%
print (rGen);exit()

Python, loop that gets a value then tests that value again

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

Categories