Is there any way I can include all integers? - python

Can someone please show me how to include all integers instead just "1234567890". So in that case the program will check if token is in as much integers as possible.
for token in tokenList:
if token in "1234567890"
need it to be all integers instead of "1234567890"
Update: more in depth.
Instead of "for token in tokenList:
if token in "1234567890"
How can I say, "for token in token list:
if token is in integers.
def infixToPostfix(infixexpr):
prec = {}
prec["**"] = 3
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
prec[")"] = 1
opStack = Stack()
postfixList = []
tokenList = infixexpr.split()
for token in tokenList:
if token in "1234567890":
postfixList.append(token)
elif token == '(':
opStack.push(token)
elif token == ')':
topToken = opStack.pop()
while topToken != '(':
postfixList.append(topToken)
topToken = opStack.pop()
else:
while (not opStack.isEmpty()) and \
(prec[opStack.peek()] >= prec[token]):
postfixList.append(opStack.pop())
opStack.push(token)
while not opStack.isEmpty():
postfixList.append(opStack.pop())
return " ".join(postfixList)

Already solved : How to check if a variable is an integer or a string?
try:
value = int(value)
except ValueError:
pass # it was a string, not an int. (or anything alse)

Related

How to avoid backspace/delete/null when print cipher text?

I am testing a substitution cipher. I'm using the 256 standard ASCII. Here's my code:
def Encrypt(psw, key):
res = ""
for i in psw:
new_letter = chr((ord(i)+key)%255)
if new_letter == '\n':
new_letter = '。'
res += new_letter
return res
def Decrypt(psw, key):
res = ""
for i in psw:
if i == '。':
i = '\n'
old_letter = chr((ord(i)-key)%255)
res += old_letter
return res
if __name__ == "__main__":
try:
while True:
i = input("1 for encryption, 2 for decryption")
s = "";k = 0
if i == '1':
s = input("Input Plaintext:")
k = (int)(input("Input Key:"))
print("Ciphertext is:"+Encrypt(s, k))
elif i == '2':
s = input("Input Ciphertext:")
k = (int)(input("Input Key:"))
print("Plaintext is:"+Decrypt(s, k))
else:
break
except:
print("Error")
When I test some keys, such as 6012, the ciphertext is ãøôøø³ø³ûº³ú
I used this result to restore the plaintext, but failed, and it became Peasee me wh's wrong
I think this is due to special operators such as Delete, Backspace, and Null in the encryption process. It caused me to be unable to recover. Is there any way to solve this problem?
Most of the time, you should not print binary data (ciphertext) in a human-text channel (stdout) because it will interpret the non-printable data instead of displaying it.
If what you want is just to be able to copy-paste, you should escape the non-printable bits. One simple way to do it is to use urllib.parse.quote and unquote :
import urllib.parse
[...]
print("Ciphertext is: "+urllib.parse.quote(Encrypt(s, k)))
[...]
s = urllib.parse.unquote(input("Input Ciphertext:"))
Example :
1 for encryption, 2 for decryption
1
Input Plaintext:hello
Input Key:6012
Ciphertext is:%C3%BB%C3%B8%00%00%03
1 for encryption, 2 for decryption
2
Input Ciphertext:%C3%BB%C3%B8%00%00%03
Input Key:6012
Plaintext is:hello

Need help fixing a ValueError of and 'i' index

So I'm making this code that uses strings to cipher a given phrase with a given key (I can't use the preset functions in python to do it). I believe I've got the idea of how to do it but I;m experiencing this error that I can't figure out how to fix. My code is the following.
def inputForChipher():
input1 = False
input2 = False
while input1 == False:
string = input('Enter the message: ')
input1 = verifyString(string)
while input2 == False:
key = input('Enter the key you want to use: ')
input2 = verifyString(key)
print(cipherWithKey(string, key))
def cipherWithKey(string, key):
string = string.lower()
key = key.lower()
letters = 'abcdefghijklmnopqrstuvwxyz'
count = 0
newCode = ''
for i in string:
if i == '':
count = 0
newCode += i
else:
if count > (len(key)-1):
count = 0
value1 = letters.index(i) + 1
value2 = letters.index(key[count]) + 1
num = value1 + value2
if num > 26:
num -= 26
newCode += letters[num-1]
count += 1
return newCode
And I'm getting the following error:
File "C:\Users\xxxxx\Desktop\funciones.py", line 29, in cipherWithKey
value1 = letters.index(i) + 1
ValueError: substring not found
I know what causes this error, but I'm not sure of why I'm getting it in this case.
well its clear , in your input 'tarea de' you are passing space in your input ( string varible) which is not in letters variable and it fails in that line.
you can add the possible characters to your letters variable like :
letters = 'abcdefghijklmnopqrstuvwxyz '
alternatively you can use string module to provide the full list of whitespaces
import string as st
letters = st.ascii_lowercase + st.whitespace

my pop( ) function does not delete the top element of a list, but rather a random one

I have created the following pop function:
def pop(arr):
if not isempty(arr):
topelement = arr[len(arr)-1]
arr.remove(topelement)
return topelement
And it worked correctly until I used it in order to reverse order of a stack of numbers and operators:
"3 6 2 + * 14 3 4 + + /"
into
"/ + + 4 3 14 * + 2 6 3".
In first iteration of while loop shown below it pushed "/" operator to the auxiliary stack and deleted it from the top of entry, which is OK - but in the second iteration it deleted "+" sign from the middle of the entry instead of the plus sign with the highest index.
def evaluation(eq):
entryunsplit = errpostfix(eq)
entry = entryunsplit.split()
lengthofentry = len(entry)
stack = []
while len(stack) != lengthofentry:
push(stack,pop(entry))
Could someone please explain me why didn't it delete the last element and how can I avoid that error?
I am putting the whole code below in case some other element turns out to be significant.
stack1 = []
max_size = 30
def push(arr,a):
if len(arr) < max_size:
arr.append(a)
def isempty(arr):
if len(arr) == 0:
return True
else:
return False
def top(arr):
if not isempty(arr):
return arr[len(arr)-1]
def pop(arr):
if not isempty(arr):
topelement = arr[len(arr)-1]
arr.remove(topelement)
return topelement
def errpostfix(eq):
entry = eq.split()
opstack = []
exit = []
priorities = { "+": 1, "-": 1, "*": 0, "/": 0 }
for token in entry:
if token == "(":
push(opstack,token)
elif token == "*" or token == "/" or token == "+" or token == "-":
if top(opstack) == "*" or top(opstack) == "/" or top(opstack) == "+" or top(opstack) == "-":
while not isempty(opstack) and priorities[top(opstack)] >= priorities[token]:
push(exit,pop(opstack))
isempty(opstack)
push(opstack,token)
elif token == ")":
while top(opstack) != "(":
push(exit,pop(opstack))
pop(opstack)
else:
push(exit,token)
while not isempty(opstack):
push(exit, pop(opstack))
output = " ".join(exit)
return output
def isop(ch):
if ch == "+" or ch == "-" or ch == "*" or ch == "/":
return True
else:
return False
def evaluation(eq):
entryunsplit = "3 6 2 + * 14 3 4 + + /"
entry = entryunsplit.split()
lengthofentry = len(entry)
stack = []
while len(stack) != lengthofentry:
push(stack,pop(entry))
The remove() operation on a list will delete the first occurrence of an item in that list, is not "random" (check the docs). If there are several repeated elements, the first one encountered will be the one that gets deleted. To delete the last element, simply use the built-in pop() method:
def pop(arr):
if not isempty(arr):
topelement = arr[-1]
arr.pop()
return topelement

Accept an string if the pattern has the same count value Python

I'm trying to make a program that prints if a string is accepted or not under the condition that the number of times a pattern appears in the sequence has the same count value; for example: 'aaabbbccc' would be accepted but not 'aabccc'. I have some ideas of how to implement it, but I'm stuck. Any advice would be helpful, thanks a lot
# B = {a^n b^n c^n | n ≥ 0}
string = 'aaabbbccc'
count_a = 0
count_b = 0
count_c = 0
for i in string:
if i == 'a':
count_a += 1
elif i == 'b':
count_b += 1
elif i == 'c':
count_c += 1
else:
pass
if count_a == count_b and count_b == count_c:
print('String accepted')
else:
print('Not accepted')
You're looking to accept the language B = {a^n b^n c^n | n ≥ 0}. A concise method of checking this is:
def accept_b(s):
n = len(s) - len(s.lstrip('a'))
return len(s) == 3*n and s[n:2*n] == 'b'*n and s[2*n:] == 'c'*n
from collections import Counter
test_str = "aabbccc"
counter = Counter(test_str)
print(len(set(counter.values())) == 1)
so the Counter counts the amount of times each char is repeated and then we check
how many different values are inside the dictionary. if they are all the same then the length is 1.
Just count each unique characters in the string and if character count is not equal then return "Not accepted" else "String Accepted"
def character_counter(string):
set_string = set(string)
current_count = 0
for char in set_string:
if current_count == 0:
current_count = string.count(char)
else:
count_char = string.count(char)
if count_char!=current_count:
return 'Not accepted'
return 'String accepted'

How to check if token is a float?

So I need to modify the following code so that the methods PostfixEval() and infixToPostfix() can take floats, as well as integers with more than one digit. I've tried isinstance(token,float) == True. Maybe I'm not using it correctly.
def infixToPostfix(infixexpr):
prec = {}
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
opStack = Stack()
postfixList = []
tokenList = infixexpr.split()
for token in tokenList:
if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or isinstance(token,int) == True :
postfixList.append(token)
elif token == '(':
opStack.push(token)
elif token == ')':
topToken = opStack.pop()
while topToken != '(':
postfixList.append(topToken)
topToken = opStack.pop()
else:
while (not opStack.isEmpty()) and \
(prec[opStack.peek()] >= prec[token]):
postfixList.append(opStack.pop())
opStack.push(token)
while not opStack.isEmpty():
postfixList.append(opStack.pop())
return " ".join(postfixList)
and
def postfixEval(postfixExpr): # also fix this to do floats
operandStack = Stack()
tokenList = postfixExpr.split()
for token in tokenList:
if isinstance(token,int) == True:
operandStack.push(int(token))
else:
operand2 = operandStack.pop()
operand1 = operandStack.pop()
result = doMath(token,operand1,operand2)
operandStack.push(result)
return operandStack.pop()
tokenList = infixexpr.split() creates a list of strings of which none could be a float. You could make a function to cast to float returning True if you could cast to float.
def is_float(s):
try:
float(s)
return True
except ValueError:
return False
Then:
lett_set = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
if token in lett_set or isfloat(token)
You can also return the float and use it in your other function:
def is_float(s):
try:
return float(s)
except ValueError:
return None
for token in tokenList:
test = is_float(token)
if test is not None: # catch potential 0
operandStack.push(test)
You can use the second version in both functions. You mention float in your title so I presume you can have floats which would fail trying to cast to int.
On a side note isinstance(token,int) == True etc.. can simpy be written isinstance(token,int), that will be True or False so any if isinstance(token,int) will be evaluated correctly

Categories