determinating if the input is even or odd numbers - python

Hello I am trying to write a program in python that asks the user to input a set of numbers of 1's and 0's and I want the program to tell me if I have and even number of zeros or an odd number of zeros or no zero's at all. Thanks for your help!!
forstate = "start"
curstate = "start"
trans = "none"
value = 0
print "Former state....:", forstate
print "Transition....:", trans
print "Current state....", curstate
while curstate != "You hav and even number of zeros":
trans = raw_input("Input a 1 or a 0: ")
if trans == "0" and value <2:
value = value + 1
forstate = curstate
elif trans == "1" and value < 2:
value = value + 0
forstate = curstate
curstate = str(value) + " zeros"
if value >= 2:
curstate = "You have and even number of zeros"
print "former state ...:", forstate
print "Transition .....:", trans
print "Current state....", curstate

Looks like you're trying to do a finite state machine?
try:
inp = raw_input
except NameError:
inp = input
def getInt(msg):
while True:
try:
return int(inp(msg))
except ValueError:
pass
START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']
state = START
while True:
num = getInt('Enter a number (-1 to exit)')
if num==-1:
break
elif num==0:
state = state_next[state]
print 'I have seen {0}.'.format(state_str[state])
Edit:
try:
inp = raw_input
except NameError:
inp = input
START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']
def reduce_fn(state, ch):
return state_next[state] if ch=='0' else state
state = reduce(reduce_fn, inp('Enter at own risk: '), START)
print "I have seen " + state_str[state]

It sounds like homework, or worse an interview questions, but this will get you started.
def homework(s):
counter = 0
if '0' in s:
for i in s:
if i == '0':
counter = counter + 1
return counter
don't forget this part over here
def odd_or_even_or_none(num):
if num == 0:
return 'This string contains no zeros'
if num % 2 == 0
return 'This string contains an even amount of zeros'
else:
return 'This string contains an odd amount of zeros'
if you call homework and give it a string of numbers it will give you back the number of 0
homework('101110101')
now that you know how many 0s you need to call odd_or_even_or_none with that number
odd_or_even_or_none(23)
so the solution looks like this
txt = input('Feed me numbers: ')
counter = str( homework(txt) )
print odd_or_even_or_none(counter)

try:
inp = raw_input
except NameError:
inp = input
zeros = sum(ch=='0' for ch in inp('Can I take your order? '))
if not zeros:
print "none"
elif zeros%2:
print "odd"
else:
print "even"

The simple solution to your problem is just to count the zeros, then print a suitable message. num_zeros = input_stream.count('0')
If you're going to build a finite state machine to learn how to write one, then you'll learn more writing a generic FSM and using it to solve your particular problem. Here's my attempt - note that all the logic for counting the zeros is encoded in the states and their transitions.
class FSMState(object):
def __init__(self, description):
self.transition = {}
self.description = description
def set_transitions(self, on_zero, on_one):
self.transition['0'] = on_zero
self.transition['1'] = on_one
def run_machine(state, input_stream):
"""Put the input_stream through the FSM given."""
for x in input_stream:
state = state.transition[x]
return state
# Create the states of the machine.
NO_ZEROS = FSMState('No zeros')
EVEN_ZEROS = FSMState('An even number of zeros')
ODD_ZEROS = FSMState('An odd number of zeros')
# Set up transitions for each state
NO_ZEROS.set_transitions(ODD_ZEROS, NO_ZEROS)
EVEN_ZEROS.set_transitions(ODD_ZEROS, EVEN_ZEROS)
ODD_ZEROS.set_transitions(EVEN_ZEROS, ODD_ZEROS)
result = run_machine(NO_ZEROS, '01011001010')
print result.description

Related

Python how to check if input is a letter or character

How can I check if input is a letter or character in Python?
Input should be amount of numbers user wants to check.
Then program should check if input given by user belongs to tribonacci sequence (0,1,2 are given in task) and in case user enter something different than integer, program should continue to run.
n = int(input("How many numbers do you want to check:"))
x = 0
def tribonnaci(n):
sequence = (0, 1, 2, 3)
a, b, c, d = sequence
while n > d:
d = a + b + c
a = b
b = c
c = d
return d
while x < n:
num = input("Number to check:")
if num == "":
print("FAIL. Give number:")
elif int(num) <= -1:
print(num+"\tFAIL. Number is minus")
elif int(num) == 0:
print(num+"\tYES")
elif int(num) == 1:
print(num+"\tYES")
elif int(num) == 2:
print(num+"\tYES")
else:
if tribonnaci(int(num)) == int(num):
print(num+"\tYES")
else:
print(num+"\tNO")
x = x + 1
You can use num.isnumeric() function that will return You "True" if input is number and "False" if input is not number.
>>> x = raw_input()
12345
>>> x.isdigit()
True
You can also use try/catch:
try:
val = int(num)
except ValueError:
print("Not an int!")
For your use, using the .isdigit() method is what you want.
For a given string, such as an input, you can call string.isdigit() which will return True if the string is only made up of numbers and False if the string is made up of anything else or is empty.
To validate, you can use an if statement to check if the input is a number or not.
n = input("Enter a number")
if n.isdigit():
# rest of program
else:
# ask for input again
I suggest doing this validation when the user is inputting the numbers to be checked as well. As an empty string "" causes .isdigit() to return False, you won't need a separate validation case for it.
If you would like to know more about string methods, you can check out https://www.quackit.com/python/reference/python_3_string_methods.cfm which provides information on each method and gives examples of each.
This question keeps coming up in one form or another. Here's a broader response.
## Code to check if user input is letter, integer, float or string.
#Prompting user for input.
userInput = input("Please enter a number, character or string: ")
while not userInput:
userInput = input("Input cannot be empty. Please enter a number, character or string: ")
#Creating function to check user's input
inputType = '' #See: https://stackoverflow.com/questions/53584768/python-change-how-do-i-make-local-variable-global
def inputType():
global inputType
def typeCheck():
global inputType
try:
float(userInput) #First check for numeric. If this trips, program will move to except.
if float(userInput).is_integer() == True: #Checking if integer
inputType = 'an integer'
else:
inputType = 'a float' #Note: n.0 is considered an integer, not float
except:
if len(userInput) == 1: #Strictly speaking, this is not really required.
if userInput.isalpha() == True:
inputType = 'a letter'
else:
inputType = 'a special character'
else:
inputLength = len(userInput)
if userInput.isalpha() == True:
inputType = 'a character string of length ' + str(inputLength)
elif userInput.isalnum() == True:
inputType = 'an alphanumeric string of length ' + str(inputLength)
else:
inputType = 'a string of length ' + str(inputLength) + ' with at least one special character'
#Calling function
typeCheck()
print(f"Your input, '{userInput}', is {inputType}.")
If using int, as I am, then I just check if it is > 0; so 0 will fail as well. Here I check if it is > -1 because it is in an if statement and I do not want 0 to fail.
try:
if not int(data[find]) > -1:
raise(ValueError('This is not-a-number'))
except:
return
just a reminder.
You can check the type of the input in a manner like this:
num = eval(input("Number to check:"))
if isinstance(num, int):
if num < 0:
print(num+"\tFAIL. Number is minus")
elif tribonnaci(num) == num: # it would be clean if this function also checks for the initial correct answers.
print(num + '\tYES')
else:
print(num + '\NO')
else:
print('FAIL, give number')
and if not an int was given it is wrong so you can state that the input is wrong. You could do the same for your initial n = int(input("How many numbers do you want to check:")) call, this will fail if it cannot evaluate to an int successfully and crash your program.

Go back to specific number in a for-loop

I have the following code:
def five_numbers():
my_list = []
for i in range(1, 6):
user_nr = check_if_number_is_1_to_25(input("Number " + str(i) + ": "))
my_list.append(user_nr)
return my_list
def check_if_number_is_1_to_25(number):
if number.isalpha():
print("Enter a number between 1 and 25.")
# Here I want to go back to five_numbers() and the number x (for example number 4)
Now I want to check if the input contains any letters. If it has, I want to print a message and then I want to go back to the number that the user was on earlier. I've tried to return five_numbers() but then the user will start from the beginning.
I appreciate all the help.
Add a keyword arg for num and default it to None:
def five_numbers(num=None):
my_list = []
if num is None:
for i in range(1, 6):
user_nr = check_if_number_is_1_to_25(input("Number " + str(i) + ": "))
my_list.append(user_nr)
else:
# do other stuff with num (4) here...
return my_list
def check_if_number_is_1_to_25(number):
if number.isalpha():
print("Enter a number between 1 and 25.")
five_numbers(4)
You can use a while loop to keep asking the user for a valid input until the user enters one. You should also make the check function raise an exception instead so the caller can catch the exception and retry the input:
def five_numbers():
my_list = []
for i in range(1, 6):
while True:
user_nr = input("Number " + str(i) + ": ")
try:
check_if_number_is_1_to_25(user_nr)
break
except ValueError as e:
print(str(e))
my_list.append(user_nr)
return my_list
def check_if_number_is_1_to_25(number):
if number.isalpha():
raise ValueError('Enter a number between 1 and 25.')
Don't use a for loop, use a while loop with the list length as its condition. Make the check function return a boolean and use it to decide whether to append to the list.
def five_numbers():
my_list = []
while len(my_list) < 5:
user_nr = input("Number {}: ".format(len(my_list)+1))
if check_if_number_is_1_to_25(user_nr):
my_list.append(user_nr)
else:
print("Enter a number between 1 and 25.")
return my_list
def check_if_number_is_1_to_25(number):
return number.isdigit() and (1 <= float(number) <= 25)

Validated Value still causing TypeError?

keep running into this error, but I'm confused because in theory I've already validated the variable as an integer before sending it through my function as a parameter. Any ideas? Thank you!
The function is question is: "calculate_distance(n):" and it doesn't like that I'm using the "<>" operators with those values.
print("Welcome Astronaut to Apollo 11 - the mission to land on The Moon.")
print("Lets determine the length of your journey so far - It should take about 3 days to reach Lunar orbit.")
# Function Boolean valid_integer(String input_string)
# Declare Boolean is_valid
#
# is_valid = is input_string a valid integer?
# Return is_valid
# End Function
def valid_integer(input_string):
try:
val = int(input_string)
is_valid = True
except ValueError:
is_valid = False
return is_valid
# Function Integer get_number()
# Declare String input_string
# Declare Boolean is_valid
#
# Display "Enter a number: "
# Input input_string
# Set is_valid = valid_integer(input_string)
# While Not is_valid
# Display "Please enter a whole number: "
# Input input_string
# is_valid = valid_integer(input_string)
# End While
# input_integer = int(input_string)
# Return input_integer
# End Function
def get_number():
input_string = input("Enter your hours of spaceflight: ")
is_valid = valid_integer(input_string)
while not is_valid:
input_string = input("Please enter a whole number: ")
is_valid = valid_integer(input_string)
input_integer = int(input_string)
return input_string
def output_distance(counter, distance, percent):
print("Since hour", counter, "you have traveled", distance, "miles,", percent, "of the way there")
def calculate_distance(n):
counter = 0
distance = 0
percent = 0
if(n < 1):
print("You're still on the launchpad")
return
if(n > 72):
print("You made it! The Eagle has landed")
return
while counter < n:
counter = counter + 1
distance = counter * 3333
percent = ((counter * 3333) / 240000) * 100
output_distance(counter, distance, percent)
# Module main()
# Set n = get_number()
# Call calculate(n)
# End Module
def main():
n = get_number()
calculate_distance(n)
main()
Even though you're validating the number as an integer within the valid_integer() function, you could pass the number as an integer to the calculate_distance() function.
calculate_distance(int(n))
Or at any other point along the way, for that matter. Return it in the get_number() function, for instance:
return(int(input_string))
use int(input) for input number

Trying to Make a Quiz

So I am trying to run a program on python3 that asks basic addition questions using random numbers. I have got the program running however, I wanted to know if there was a way I could count the occurrences of "Correct" and "Wrong" so I can give the person taking the quiz some feedback on how they did.
import random
num_ques=int(input('Enter Number of Questions:'))
while(num_ques < 1):
num_ques=int(input('Enter Positive Number of Questions:'))
for i in range(0, (num_ques)):
a=random.randint(1,100)
b=random.randint(1,100)
answer=int(input(str(a) + '+' + str(b) + '='))
sum=a+b
if (answer==sum):
print ('Correct')
else:
print ('Wrong.')
You could use a dict to store counts for each type, increment them when you come across each type, and then access it after to print the counts out.
Something like this:
import random
stats = {'correct': 0, 'wrong': 0}
num_ques=int(input('Enter Number of Questions:'))
while(num_ques < 1):
num_ques=int(input('Enter Positive Number of Questions:'))
for i in range(0, (num_ques)):
a=random.randint(1,100)
b=random.randint(1,100)
answer=int(input(str(a) + '+' + str(b) + '='))
sum=a+b
if (answer==sum):
print ('Correct')
stats['correct'] += 1
else:
print ('Wrong.')
stats['wrong'] += 1
print "results: {0} correct, {1} wrong".format(stats['correct'], stats['wrong'])
import operator
import random
def ask_float(prompt):
while True:
try: return float(input(prompt))
except: print("Invalid Input please enter a number")
def ask_question(*args):
a = random.randint(1,100)
b = random.randint(1,100)
op = random.choice("+-/*")
answ = {"+":operator.add,"-":operator.sub,"*":operator.mul,"/":operator.div}[op](a,b)
return abs(answ - ask_float("%s %s %s = ?"%(a,op,b)))<0.01
num_questions = 5
answers_correct = sum(map(ask_question,range(num_questions)))
print("You got %d/%d Correct!"%(answers_correct,num_questions))

Python and Functions

I'll admit it, I am very new to python and need some help. I am trying to convert a very simple calculator from c++ to python. Here is the code so far:
x = 0
y = 0
sign = '+'
def getnum(prompt, number):
number = input(prompt)
def getsign(prompt, sign):
sign = raw_input(prompt)
print sign
def calc(string, number1, number2, sign):
print string
print " "
if sign == '+' or 'plus':
a = x + y
elif sign == 'x' or '*' or 'times':
a = x * y
elif sign == '/' or 'divided by':
a = x / y
elif sign == '-' or 'minus':
a = x - y
print string, a
getnum("Enter first number: ", x)
getnum("Enter second number: ", y)
getsign("Enter sign: ", sign)
calc("The answer is: ", x, y, sign)
print x
print y
print sign
The problem with the functions. At the end, I get this:
The answer is: 0
0
0
+
I can't seem to get the two numbers at the end to change.
I give you few suggestions at the places where you have to change your code, these will certainly make your program work given you know how functions work in python (in genral any language)
def getnum(prompt, number):
number = input(prompt)
The variable 'number' is local to that function. So every time you call the function "getnum" you assign a value to the number but what else do you do with that.
**Hint 1: A mechanism where as soon as you get the number, try throwin this number to a variable which can use it. Try using return.
**Hint 2: When you use input, by default the value entered will be converted into a string. So think of a method where the value will be changed from string to int. "casting"?
def getsign(prompt, sign):
sign = raw_input(prompt)
print sign
print sign
Directly prints the sign to the console, just think of a situation where your program can use the sign. I will give the same hint.
**Hint: Try using return.
Python does not have "call by name". C does. Python does not.
A function evaluation like this:
getnum("Enter first number: ", x)
Will never assign a new value to x in Python. In C, a new value can be assigned. In Python a new value cannot be assigned this way.
[A value can be mutated, but that's not relevant to this question.]
There are a number of issues.
Let's look at them in the interactive Python interpreter, which is an invaluable tool when you're experimenting with Python.
Firstly, getnum() doesn't do what you think it does...
>>> def getnum(prompt, number):
... number = input(prompt)
...
>>> x = 0
>>> getnum("Enter first number: ", x)
Enter first number: 6
>>> print x
0
Here you should return the value and capture it in a variable.
>>> def getnum(prompt):
... return input(prompt)
...
>>> x = 0
>>> x = getnum("Enter first number: ")
Enter first number: 6
>>> print x
6
getsign() has a similar issue.
Moving onto calc(). Here or isn't doing what you expect:
>>> sign = '*'
>>> if sign == '+' or 'plus':
... print 'plus'
...
plus
This needs to look more like:
>>> sign = '*'
>>> if sign == '+' or sign == 'plus':
... print 'plus'
... else:
... print 'not plus'
...
not plus
Or better still:
>>> if sign in ('+', 'plus'):
... print 'plus'
... else:
... print 'not plus'
...
not plus
>>> sign = '+'
>>> if sign in ('+', 'plus'):
... print 'plus'
... else:
... print 'not plus'
...
plus
The other conditions in this function have the same issue.
I'm inclined to treat this like a "homework" problem and tell you what you're doing wrong rather than show you the exact solution. When you take your inputs using input(prompt), you are getting a string. If you want to treat it as a number, you need to tell Python that explicitly.
I asume this is for the school, so this maybe can help you.
#!/usr/bin/env python
import re
#put the logic in an object like enviroment
class CalculatorProto(object):
def __init__(self, numberone, numbertwo):
"""
initialize the data
"""
self.firsn = numberone
self.twon = numbertwo
def Verifynumber(self):
"""
verify is you pass abs numbers
"""
numbers = re.compile("^[0-9]+$")
if numbers.search(self.firsn) and numbers.search(self.twon):
self.firsn = int(self.firsn)
self.twon = int(self.twon)
return True
else:
return False
def sum(self):
"""
manage sum
"""
rsum = self.firsn + self.twon
return rsum
def rest(self):
"""
manage rest
"""
if self.firsn > self.twon:
rrest = self.firsn - self.twon
return rrest
else:
rrest = self.twon - self.firsn
return rrest
def div(self):
"""
manage div
"""
if int(self.firsn) > int(self.twon):
if self.twon != 0:
rdiv = self.firsn / self.twon
return rdiv
return "Is not good idea div a number by 0"
else:
if self.firsn != 0:
rdiv = self.twon / self.firsn
return rdiv
return "Is not good idea div a number by 0"
def mul(self):
rmul = self.firsn * self.twon
return rmul
if __name__ == "__main__":
#here you cant write you small interface
print "Enter two numbers, and a operation please"
o = raw_input("One: ")
t = raw_input("Two: ")
operation = raw_input("Operation: ")
while operation not in ("sum", "div", "rest", "mul"):
print "WTF?? Enter a valid operation"
print "sum\ndiv\nrest\nor mul"
operation = raw_input("Operation: ")
cal = CalculatorProto(o, t)
if cal.Verifynumber():
exec("print cal.%s()" % operation)
else:
print "Please insert absolute numbers"
You cant modify this, for a more complex manage.

Categories

Resources