I have created an if statement in Python, it is a password strength checker. I think it might be the numbers, but I have no clue.
When I type in; aabbcc3
it is meant to be MEDIUM, but it comes up with WEAK. Same as RTH14hl as it comes up with MEDIUM but it's meant to be STRONG.
if u >=6 or l >=6 or n >=6:
print("weak")
elif u > 1 and n > 1:
print("medium")
elif l > 3 and n >= 1:
print("medium")
elif u > 1 and l> 1:
print("medium")
elif u > 3 and l > 2 and nums > 2:
print("strong")
The problem is that the order in which the statements are set up is producing an effect that you do not want. For example:
elif u > 1 and l> 1:
print("medium")
elif u > 3 and l > 2 and nums > 2:
print("strong")
The last line here will never be executed. Because anything that makes the last conditional true will make the previous conditional be true.
For example if u is 4 and l is 4 then:
elif u > 1 and l> 1:
becomes:
elif 4 > 1 and 4 > 1:
which will evaluate to True and print "medium"
You can solve this issue by rearranging the order of the statements like so:
elif u > 3 and l > 2 and nums > 2:
print("strong")
elif u > 1 and l> 1:
print("medium")
Essentially you want the hardest things to match be at the top then let non matches fall down to easier to match cases, not the other way around.
Also from the comment made I think it's highly likely that you probably want to generate the u l and n values differently to how you currently are doing it. Python has a nice feature called generator expressions that along with some library function will make your code much more maintainable.
Instead of:
u = p.count("A") + p.count("B") + p.count("C"), ...
l = p.count("a") + p.count("b") + p.count("c"), ...
n = p.count("1") + p.count("2") + p.count("3"), ...
you can do:
u = sum((char.isalpha() for char in p))
l = sum((char.islower() for char in p))
n = sum((char.isdigit() for char in p))
Related
I was wondering if someone would be able to help me regarding my coding problem. I'm still a beginner and I may have missed something here.
Basically, the instruction says that I need to arrange 3 integers in ascending order.
e.g Input : 5 2 4 ------> Output : 2 4 5
I need to utilize the conditional statements for this. Here is what I've done so far.
a, b, c = input().split()
a = int (a)
b = int (b)
c = int (c)
if a < b and a < c:
smallest = a
elif b < a and b < c:
smallest = b
else:
smallest = c
if a > b and a < c:
middle = a
elif a < b and a > c:
middle = a
elif b > a and b < c:
middle = b
elif b < a and b > c:
middle = b
else:
middle = c
if a > b and a > c:
largest = a
elif b > a and b > c:
largest = b
else:
largest = c
print(smallest, middle, largest)
This is on CodeChum btw, I'm stuck in this because I can't figure out why it doesn't accept the code I did. Basically there are 5 tests that the code needs in order to submit the whole activity. I managed to do test 1-4 but for some reason it fails on test 5.
The problem is that your code does not react well if two numbers are identical. You should replace your strict inequalities with non-strict ones.
a = 3
b = 3
c = 1
if a > b and a < c:
middle = a
elif a < b and a > c:
middle = a
elif b > a and b < c:
middle = b
elif b < a and b > c:
middle = b
else:
middle = c
print(middle) # 1 when it should be 3
As a == b, none of the 4 conditions can be True, and therefore the middle number will always be c.
In order to support the case where a == b, we can add another condition:
elif a == b:
middle = a
else:
middle = c
we can simplify this code by replacing the strict inequalities with non-strict ones (⩽ , <= in Python):
if b <= a < c:
middle = a
elif b >= a > c:
middle = a
elif a < b < c:
middle = b
elif a > b > c:
middle = b
else:
middle = c
We simply said that if a == b, the middle is always a. I also simplified the structure for better readability.
Why don't you simply use sorted function?
This one results in the exact thing you are looking for.
smallest, middle, largest = sorted(map(int, input().split()))
print(smallest, middle, largest)
Note that you don't need the map to int function for this. But you if don't do that, the smallest, middle, largest variables will remain str objects.
As the input is guaranteed to contain exactly 3 numbers (separated by whitespace) you can just do this:
if (inval := input()):
if len(nums := inval.split()) == 3:
try:
lo, mid, hi = sorted(map(int, nums))
print(lo, mid, hi)
except ValueError:
pass
So basically I want python to first wait and let me input stuff and then do whatever it has to for every pair of inputs.
t = int(input())
E = 0
for i in range(0, t):
M, N = [int(M) for M in input(" ").split()]
if E in range(0, t):
if M > 0 and N > 0:
print("X")
if M > 0 and N == 0:
print("Y")
if M == 0 and N > 0:
print("Z")
i += 1
The terminal looks somewhat like this,
13 100
X
2 0
Y
I want the 2 0 to be before X but at the same time I want the code to calculate for 13 100 and output X but just after I input the 2nd pair of X, Y.
I also want to know how to remove the spaces before the '2 0' and the 'Y'.
Thanks.
Firstly, the reason you have spaces before 2 0 is because in the line:
M, N = [int(M) for M in input(" ").split()]
your input function has a space within the quotes, so you must remove it and just have an empty string:
M, N = [int(M) for M in input("").split()]
Next, the reason your code is asking for input then generating an output and so on is because the logical operators are within the for loop you have. To fix this you should have your loop to first gather the inputs then, have another loop to perform the logical operators on those inputs as so:
t = 2
E = 0
numList = []
for i in range(0, t):
M, N = [int(M) for M in input("").split()]
numList.append([M, N])
for val in numList:
if E in range(0, t):
if val[0] > 0 and val[1] > 0:
print("X")
if val[0] > 0 and val[1] == 0:
print("Y")
if val[0] == 0 and val[1] > 0:
print("Z")
To simplify things I set t = 2 since we are only talking about 2 pairs of numbers. Furthermore, I created a list to hold each pair of inputs (numList), in which the first for loop appends the values to it as an list. The next for loop looks at each item in numList and since numList is a list of lists I changed M and N to val[0] and val[1] which refer to the first number you inputed (M) and the second one you inputed (N).
Finally,
for i in range(0, t):
should look like:
for i in range(t):
Since the range function automatically just counts from 0 to t and "i += 1" at the end of the loop is also unnecessary and redundant.
My final output:
[1]: https://i.stack.imgur.com/1Bo9U.png
Put all the inputs in a 2-dimensional list before the loop that processes them.
t = int(input())
E = 0
all_inputs = [[int(M) for M in input(" ").split()] for _ in range(t)]
for M, N in all_inputs:
if E in range(0, t):
if M > 0 and N > 0:
print("X")
if M > 0 and N == 0:
print("Y")
if M == 0 and N > 0:
print("Z")
i += 1
The space before the 2 0 is the prompt " " in your input(" ") call. If you don't want that, use input() with no prompt.
I don't see any reason for the space before Y.
Hope this help. Its a little cleaned up:
iterations = int(input("How many times? "))
values = []
for i in range(iterations):
values.append([int(M) for M in input(f"{i+1}. Enter two numbers: ").split()])
for M, N in values:
print(M, N, end=' -> ')
if M > 0 and N > 0:
print("X")
if M > 0 and N == 0:
print("Y")
if M == 0 and N > 0:
print("Z")
Hi I have looked up a few recursive multiplication of 2 numbers in python, but none of them take into account the possibility of negative numbers or if they do they don't explain the entire steps.
I have coded the following the program but I am getting an error, can someone please let me know what is wrong with it?
def mult(a,b):
if a==0 | b==0:
return 0
elif a==1:
return b
elif a > 0 & b >0:
return b + mult(a-1,b)
elif a < 0 & b > 0:
return - b + mult(a+1,b))
elif a > 0 & b < 0:
return - b + mult(a-1, b))
else:
return -b + mult(a+1, b)
print(mult(-4,5))
| and & are bitwise operators, not logical operators, and their (relatively) high precedence means that a > 0 & b >0 is parsed as a > (0 & b) > 0, which is not what you want. Use or and and instead.
You have some python syntax errors and some sign problems. This works for mult(-4,5) and mult(5,-4).
def mult(a,b):
if a == 0 or b == 0:
return 0
elif a == 1:
return b
elif b == 1:
return a
elif a >0 and b > 0:
return b + mult(a-1,b)
elif a < 0 and b > 0:
return -b+mult(a+1,b)
elif a > 0 and b < 0:
return b+mult(a-1,b)
else:
return b + mult(a+1,b)
In your elif statement, you're using a bitwise "and" operator rather than the logical and operator. Everywhere that you have "&" replace it with "and"
Trying to solve the following problem:
Given a binary D containing only digits 0's and 1's, I have to determine if all the digits could be made the same, by flipping only one digit.
The input is the number of Ds to test, and then the Ds, one per line. for instance:
3
11111001111010
110
100000000000000
The output is "Yes" or "No", namely in this instance, the run will look like:
$ python3 first.py
3
11111001111010
NO
110
YES
100000000000000
YES
However, the automatic evaluator of this problem judges the following code wrong:
T = int(input())
for i in range(T):
line = input()
ones = zeros = 0
for c in line:
if int(c) == 1:
ones += 1
elif int(c) == 0:
zeros += 1
else:
raise ValueError
if ones > 1 and zeros > 1:
print("NO")
break
if ones == 1:
print("YES")
elif zeros == 1:
print("YES")
Can you suggest why?
Your program doesn't output anything in case that all the digits are the same. You can fix the problem by changing the last part in following way:
if ones == 1:
print("YES")
elif zeros == 1:
print("YES")
elif ones == 0 or zeros == 0:
print("NO") # assuming that one bit must be changed
Note that you could just use str.count to count zeros (or ones) and then check if count is 1 or len(line) - 1:
T = int(input())
for i in range(T):
line = input()
zeros = line.count('0')
print('YES' if zeros == 1 or zeros == len(line) - 1 else 'NO')
The solution is rather embarrassing: I outputted the answer as all uppercase, where the expected output is Title case. The following code is accepted:
T = int(input())
for i in range(T):
line = input()
ones = zeros = 0
for c in line:
if int(c) == 1:
ones += 1
elif int(c) == 0:
zeros += 1
else:
raise ValueError
if ones > 1 and zeros > 1:
print("No")
break
if ones == 1:
print("Yes")
elif zeros == 1:
print("Yes")
elif ones == 0 or zeros == 0:
print("No")
I failed an interview earlier this morning on this question, and haven't been able to figure out why. Can anyone help me out?
An expression consisting of operands and binary operators can be written in Reverse Polish Notation (RPN) by writing both the operands followed by the operator. For example, 3 + (4 * 5) can be written as "3 4 5 * +".
You are given a string consisting of x's and *'s. x represents an operand and * represents a binary operator. It is easy to see that not all such strings represent valid RPN expressions. For example, the "x*x" is not a valid RPN expression, while "xx*" and "xxx**" are valid expressions. What is the minimum number of insert, delete and replace operations needed to convert the given string into a valid RPN expression?
5
x
xx*
xxx**
*xx
xx*xx**
OUTPUT
0
0
0
2
0
Code so far:
import fileinput
def solution (rpn):
xs = 0
numReplaces = 0
numDeletes = 0
numInserts = 0
for i in xrange(len(rpn)):
if rpn[i] == 'x':
xs += 1
elif rpn[i] == '*':
if xs > 1:
xs -= 1
elif xs == 1:
if numDeletes > 0:
numReplaces += 1
numDeletes -= 1
else:
if i == len(rpn)-1:
numInserts += 1
else:
numDeletes += 1
else:
if numDeletes > 1:
numDeletes -= 2
numReplaces += 2
else:
numDeletes += 1
while xs > 1:
if xs > 2:
numReplaces += 1
xs -= 2
if xs == 2:
numInserts += 1
xs -= 1
return numReplaces + numDeletes + numInserts
first = True
for line in fileinput.input():
if first:
numCases = int(line)
first = False
else:
print solution(line)
I think the way to start is that RPM evaluation can be performed easily by maintaining a stack of operands. For a valid input string, when you hit an operator, you pop the last two values off the stack, apply the operator and push the result back on to the stack.
Therefore, we need to find the value added by each of the "fixes":
Insert
Operand: you hit an operator, and there is only one item on the stack
Operator: You finish the string and there are multiple items left on the stack
Delete
Operand: you are at the end of the string. Adding operators will have the same result
Operator: there is only one item on the stack, adding an operand will have the same result. If the stack is empty, delete the operator
Replace
Operator -> operand: There is only one operand on the stack
Operand -> operator: Here be dragons. I believe that this will be useful only when you're out of operators, meaning the stack size is > 1; unfortunately, we don't know if these are direct operands or the result of operations, so we'll just add n-1 operators to condense the stack into a result.
I'm not 100% sure on these, but it sounds like any error condition can be handled by any of these, at equal cost, so:
def count_errors(input_):
def tokenize(input_):
''' for our purposes, each character is a token '''
for char in input_:
yield char
def is_operator(val):
return val == '*'
def is_operand(val):
return val == 'x'
stack = []
error = 0
for token in tokenize(input_):
if is_operand(token):
stack.append(token)
elif is_operator(token):
if len(stack) >= 2:
stack.pop()
stack.pop()
stack.append('x')
elif len(stack) == 1:
stack.pop()
stack.append('x')
errors += 1
else:
errors += 1
if len(stack):
return errors + len(stack) - 1
else:
return errors + 1