Getting wrong answer for "Geek and New job" problem gfg - python

#code
testcases=int(input())
while testcases!=0:
s=input()
lower,upper,numeric=0,0,0
for i in s:
if ord(i)>=49 and ord(i)<=57:
numeric+=1
elif ord(i)>=65 and ord(i)<=90:
upper+=1
elif ord(i)>=97 and ord(i)<=122:
lower+=1
if(upper>=1 and lower>=1 and numeric>=1):
print("YES")
else:
print("NO")
testcases-=1
The Question is : Given a string i have to Say if the String is a Valid Paswword or not.
For a String to be a valid password following needs to be fullfilled:
1.Atleast one uppercase letter
2.Atleast one lower case letter
3.Atleast one numeric.
if its a valid pasword print "YES" orelse print "NO"
I am not able to figure out why i am getting "wrong answer" on submission in GFG. When i run against custom test cases i get the desired result , but on submission it shows "wrong answer". Can someone please help, what wrong with my code?
I would be able to figure out but the ide of gfg does not tell the reason behind wrong number it just says wrong answer..how will i be able to figure out then?
Constraints:
1<=T<=10^4
1<=|S|<=4*10^5
Sum of S over all tc's does not exceed 4*10^5

You are not checking for zero. To avoid this kind of error use the chars, so it is clearer what the code is doing.
The cause of the error is the antipattern "magic numbers". Programmers should avoid writing numbers directly in the code, because is harder for humans to understand the code, and is prone to error, like this one.
testcases = int(input())
while testcases != 0:
s = input()
lower, upper, numeric = 0, 0, 0
for i in s:
if ord(i) >= ord("0") and ord(i) <= ord("9"):
numeric += 1
elif ord(i) >= ord("A") and ord(i) <= ord("Z"):
upper += 1
elif ord(i) >= ord("a") and ord(i) <= ord("z"):
lower += 1
if upper >= 1 and lower >= 1 and numeric >= 1:
print("YES")
else:
print("NO")
testcases -= 1

Edit:
I misread the testcases part and see that you want to test multiple... still leaving this code here for anyone that finds it useful:
You can do a while True loop and then break the loop when the desired result occurs. This will stop your double input() so you don't have to enter the password twice (as you do in your code). Also, if you use isnumeric(), isupper(), and islower() it looks cleaner:
while True:
s=input()
lower,upper,numeric=0,0,0
for i in s:
if i.isnumeric():
numeric+=1
elif i.isupper():
upper+=1
elif i.islower():
lower+=1
if(upper>=1 and lower>=1 and numeric>=1):
print("YES")
break
else:
print("NO")

Related

Python: random number game with input validation

I'm writing a program that is a guessing game where the user has one chance to guess a number between 1 and 20.
There are two problems with the code:
Number one is still the input validation. The firstGuess variable is actually in main().
firstGuess = userguess()
def userGuess():
while True:
try:
guess = int(input('Enter a number between 1 and 20: '))
if 1 <= guess >= 20:
return guess
except ValueError:
print (guess, 'is not a valid guess!')
break
What I'm trying to do is put the input validation in a loop (while True:) until the user gives good input (in this case a positive number between 1 and 20). If the user were to enter 'd', or '-5', the program should continue looping until good input is given. However, this is not the case. By adjusting the code, I have been able to ask for the input again once bad input is entered, but if bad input is given a third time I get "another exception occured while handling this exception."
*Removed other problem, #Henry Woody was correct in that I wasn't using the conditionals correctly.
The issues are with the conditionals.
The first is the line:
if 1 <= guess >= 20:
in userGuess, which is checking for a number greater than or equal to 20, which is not what you want. You can fix this issue by changing the condition to:
if 1 <= guess <= 20:
Next, the conditional:
if guess1 == randomOne or randomTwo or randomThree:
checks whether guess1 == randomOne or if randomTwo is truthy or if randomThree is truthy. It does not check if guess1 == randomOne or guess1 == randomTwo or guess1 == randomThree as intended. You can fix this by changing the condition to:
if guess1 in [randomOne, randomTwo, randomThree]:
to check if guess1 is equal to either of the three random variables.
Edit:
There is also an issue in the try/except block. If the user enters a non-digit character in the input, a ValueError will be raised before guess is defined. But then guess is referenced in the except block, but guess isn't defined at that point.
You can fix this by getting the user input and then, separately, trying to convert the input to an int.
Here's an example:
while True:
guess = input('Enter a number between 1 and 20: ')
try:
guess = int(guess)
if 1 <= guess <= 20:
return guess
except ValueError:
print (guess, 'is not a valid guess!')
break

Creating a game where the computer guesses a value through inputs of <,> or =

I am trying to create a game where i think of a number in my head. And then the computer guesses the number through me telling it if its guess is too low or high.
This is what I've come up with but i am pretty lost tbh.
maxguess = 100
minguess = 1
count = 0
print("Think of a number between {} and {}".format(minguess,maxguess))
def midpoint(maxguess, minguess) :
z = ((maxguess + minguess)/2)
def guessing(x) :
print("Is you number greater (>) , equal (=) ,or less (<) than" ,z,)
print("please answer <,=, or >! >")
x = input()
if x == (">") :
minpoint = z
count += 1
continue
elif x == ("<") :
maxpoint = z
count += 1
continue
elif x == ("=") :
print ("I have guessed it!")
count += 1
break
print("I needed {} steps!".format(count))
Purposely not a complete solution, but some hints for you:
I'd recommend avoiding the global variables like count, maxguess, and minguess. Instead, make a function that holds all these variables.
Change your midpoint function to return z instead, then call it inside your guessing function.
Your continue and break functions would need to be inside a for or while loop. Since you aren't sure how many iterations you need to guess the number, I think a while loop would make sense here
Your functions are never run. On a style point, bring all your 'main' statements down to the bottom so they're together. After the prompt to think of a number, you need to call the guessing() function. When you call it, you should pass the minguess and maxguess values to it.
I can see what you're trying to do with the if...elif statements, but they need to be in a while True: block. So should the three statements preceding them so the script repeatedly asks for new advice from you.
Either bring the content of the midpoint() function into guessing() or make it return the value of z.
You also offer the user a choice of '>1' but don't handle it - and you don't need it as far as I can tell.
You never use minpoint or maxpoint - and you dont need them. Call the midpoint function instead and pass it the appropriate values, e.g., if '>', z = midpoint(z, maxguess).
Also, you're going to spend forever trying to get it to guess as you are using floats. Make sure everything is an integer.
Finally, you should add some code to manage input that isn't expected, i.e., not '<', '>' or '='.
Good luck!
minguess=1
maxguess=100
z=50
count=0
print("Think of a number between 1 and 100")
condition = True
while condition:
z=((maxguess + minguess)//2)
print("Is your number greater (>) , equal (=) ,or less (<) than" ,z,)
print("Please answer <,=, or >! >")
x = input()
if x == (">"):
minguess=z
count += 1
elif x == ("<") :
maxguess=z
count += 1
elif x == ("=") :
print ("I have guessed it!")
count += 1
condition=False

For loops concatenated – beginner python exercise

Hi everyone I’m writing because I’m stuck with an exercise in which I should only use for loops and if/else statements. I found a way but practically I’m iterating the same block of code four times and I’m really looking for a way to automate it.
I know that probably this is not the best way to solve the exercise but now I’m not looking for the most efficient way (I already found on the solutions of the exercise), I’m asking you how can I use for to iterate the block of code
The exercise tells me to create a program that takes an IP address from the keyboard and validates that it can be interpreted as a valid IP address.
An IP address consists of 4 numbers, separated from each other with a full stop. Each number can have no more than 3 digits. (Examples: 127.0.0.1)
Important
This challenge is intended to practise for loops, and if/else statements, so although it would probably be written for real using regular expressions we don't want you to use them here even if you know what they are.
This is what I made:
# ipAddress = input("please enter an ipAddress: ")
ipAddress = "192.168.7.7" #test ip address
# check if number of dots is 3
numberOfDot = 0
for char in ipAddress:
if char == '.':
numberOfDot += 1
totNumbOfDot = numberOfDot # output of this section is totNumberOfDot, to be checked at the end
if totNumbOfDot != 3:
print("You inserted a wrong ip address")
# first number check # THIS IS THE BLOCK OF CODE I WANT TO
number1 = '' # ITERATE WITH FOR IF POSSIBLE
for char in ipAddress:
if char in "0123456789":
number1 += char
if char == '.':
break
if 1 <= len(number1) <= 3:
print("First number: OK")
else:
print("First number: Fail")
digitN1 = len(number1) + 1
print(number1)
# second number check
numberMinus2 = ipAddress[digitN1:]
number2 = ''
for char in numberMinus2:
if char in "0123456789":
number2 += char
if char == '.':
break
if 1 <= len(number2) <= 3:
print("Second number: OK")
else:
print("Second number: Fail")
digitN2 = len(number2) + digitN1 +1
print(number2)
# third number check
numberMinus3 = ipAddress[digitN2:]
number3 = ''
for char in numberMinus3:
if char in "0123456789":
number3 += char
if char == '.':
break
if 1 <= len(number3) <= 3:
print("Third number: OK")
else:
print("Third number: Fail")
digitN3 = len(number3) + digitN2 + 1
print(number3)
# fourth number check
numberMinus4 = ipAddress[digitN3:]
number4 = ''
for char in numberMinus4:
if char in "0123456789":
number4 += char
if char == '.':
break
if 0 < len(number4) <= 3:
print("Fourth number: OK")
else:
print("Fourth number: Fail")
digitN4 = len(number4) + digitN3 + 1
print(number4)
I would also say, split() is the way to go. Your question was if there was a way to use your logic and still not have to repeat code 4 times. To achieve that you could do something like this:
numberOfDot=0
number=""
for char in ip+'.':
if char=='.':
numberOfDot+=1
if len(number) in [1,2,3]:
print("number %d OK"%numberOfDot)
else:
print("number %d not OK"%numberOfDot)
print(number)
number=""
elif char in '1234567890':
number+=char
else:
print("character not valid")
if numberOfDot!=4:
print("you inserted a wrong ip")
As i said, i would also recommend using split() - this is just to try and provide an answer closer to your question. Also please note that this code (same as yours) will mark ip adresses containing letters, not only numbers, as OK.
Well, you have to ask yourself the right question: "can I do better?". Please always do that. Yes, in fact, you can. The code that deals with numbers validation between dots is essentially the same. So you should split the string on dots and use for loop to validate each group:
for str in ipAddress.split("."):
your validation here
how about that? split the string at the dots . and check if between the dots there are numbers in the valid range (that would also accept '255.255.255.255')
def valid(ipaddress):
# we need 3 dots; otherwise this is no ipaddress.
if not ipaddress.count('.') == 3:
return False
# check what is before, between and after the dots
for byte in ipaddress.split('.'):
# if byte can not be interpreted as an integer -> no good!
try:
i = int(byte)
except ValueError:
return False
# now check if byte is in the valid range
if i < 0:
return False
if i > 255:
return False
return True
print(valid(ipaddress='192.168.7.7')) # -> True
print(valid(ipaddress='.168.7.7')) # -> False
print(valid(ipaddress='721.168.7.7')) # -> False

My program is not printing out the message I want

I have written a prime number program and I'm having a trouble with printing out the message "Neither prime nor a composite" as below. I think my code is fine as it is. I'd highly appreciate any comment on this issue. Thank you, in advance
def prime_number():
a = input("Please enter a number:")
x = True
s = 0
for i in range(2, a):
while x:
if a%i == 0:
x = False
elif s:
print s,"Neither a prime nor a composite"
else:
x = True
if x:
print a,"is a prime number."
elif s:
print s,"Neither a prime nor a composite"
else:
print a,"is not a prime number."
prime_number()
Your variable s will stay equall to 0 which is equall to False forever, so there is no way that Your code is going to print "Neither a prime nor a composite"
Just like Chantwaffle said, you'll never get s equal to anything else than 0, because there's no code changing it to anything else. Also, if a <= 2 you'll never enter this for loop, and elif s is always False, since s is defined as 0 at the beginning. Rewrite that code thinking of what you want to achieve and what should be done to get it. Repair logic of this code.

If and elif in Python for good programming practices

Hello there I'm currently trying to get a good grasp of the if, elif, else structure in Python. I'm trying some weird combinations in python having a test program to know the output in this if, if, elif, elif, else code. However I'm getting weird results such as this
input = raw_input('Please enter the required digit: ')
intput = int(input)
if intput == 0:
print 'if1'
if intput == 1:
print 'if2'
elif intput == 0:
print 'elif1'
elif intput == 1:
print 'elif2'
else:
print 'else'
if I in put 1 it will print "if2", I thought that it will also print "elif2" and other shenanigans when I try to change the "intput == n" code. So my question is do I have to stick to the if,elif, elif, .... n * elifs, else method which seems to me working alright than working with the wacky if,if.... n * ifs, elif, elif, ...n* elifs, else.
Thanks
The elif tree is designed such that at anywhere along if one of the statement turns out to be True, the rest of the elifs will not be evaluated.
Here's a tutorial that might help you understand if else better.
this may be more clear to understand:
if input == 0:
print "if1"
switch(input):
case 1:
print "if2"
break
case 0:
print "elif1"
break
case 1:
print "elif2"
break
default:
print "else"
break
of course, the code does not work.

Categories