Python - PseudoCode for functions and operands - python

I am quite new to the PseudoCode concept... I would like to get an idea of how functions and operands like modulus, floor division and the likes would be written in PseudoCode. Writing the PseudoCode for this code might actually help me understand better...
user_response=input("Input a number: ")
our_input=float(user_response)
def string (our_input):
if (our_input % 15) == 0 :
return ("fizzbuzz")
elif (our_input % 3) == 0 :
return ("fizz")
elif (our_input % 5) == 0 :
return ("buzz")
else :
return ("null")
print(string(our_input))

Your code really isn't that hard to understand assuming the knowledge of % as the modulus operation. Floor division can really just be written as a regular division. Floor the result, if really necessary.
If you don't know how to express them, then explicitly write modulus(x, y) or floor(z).
Pseudocode is meant to be readable, not complicated.
Pseudocode could even be just words, and not "code". The pseudo part of it comes from the logical expression of operations

The basic idea of PseudoCode is either to
a) Make complicated code understandable, or
b) Express an idea that you are going to code/haven't yet figured out how to code.
For example, if I am going to make a tool that needs to read information in from a database, parse it into fields, get just the info that the user requests, then format the information and print it to the screen, my first draft of the code would be simple PseudoCode as so:
# Header information
# Get user input
# Connect to Database
# Read in values from database
# Gather useful information
# Format information
# Print information
This gives me a basic structure for my program, that way I don't get lost as I'm making it. Also, if someone else is working with me, we can divvy up the work (He works on the code to connect to the database, and I work on the code to get the user input.)
As the program progresses, I would be replacing PseudoCode with real, working code.
# Header information
user_input_row = int(input("Which row (1-10)? "))
user_input_column = input("Which column (A, B, C)? "))
dbase = dbconn("My_Database")
row_of_interest = dbase.getrow(user_input_row)
# Gather useful information
# Format information
# Print information
At any point I might realize there are other things to do in the code, and if I don't want to stop what I'm working on, I add them in to remind myself to come back and code them later.
# Header information #Don't forget to import the database dbconn class
user_input_row = int(input("Which row (1-10)? "))
#Protect against non-integer inputs so that the program doesn't fail
user_input_column = input("Which column (A, B, C)? "))
#Make sure the user gives a valid column before connecting to the database
dbase = dbconn("My_Database")
#Verify that we have a connection to the database and that the database is populated
row_of_interest = dbase.getrow(user_input_row)
# Separate the row by columns -- use .split()
# >> User only wants user_input_column
# Gather useful information
# Format information
# >> Make the table look like this:
# C C1 C2 < User's choice
# _________|________|_______
# Title | Field | Group
# Print information
After you're done coding, the old PseudoCode can even serve to be good comments to your program so that another person will know right away what the different parts of your program are doing.
PseudoCode also works really well when asking a question when you don't know how to code something but you know what you want, for example if you had a question about how to make a certain kind of loop in your program:
my_list = [0,1,2,3,4,5]
for i in range(len(my_list)) but just when i is even:
print (my_list[i]) #How do I get it to print out when i is even?
The PseudoCode helps the reader know what you're trying to do and they can help you easier.
In your case, useful PseudoCode for things like explaining your way through code might look like:
user_response=input("Input a number: ") # Get a number from user as a string
our_input=float(user_response) # Change that string into a float
def string (our_input):
if (our_input % 15) == 0 : # If our input is divisible by 15
return ("fizzbuzz")
elif (our_input % 3) == 0 : # If our input is divisible by 3 but not 15
return ("fizz")
elif (our_input % 5) == 0 : # If our input is divisible by 5 but not 15
return ("buzz")
else : # If our input is not divisible by 3, 5 or 15
return ("null")
print(string(our_input)) # Print out response

THANKS GUYS FOR ALL OF YOUR INPUT, FROM ALL I READ, I CAME UP WITH THIS, IF THERE ARE ANY AREAS U THINK NEEDS TO BE ADJUSTED PLEASE LET ME KNOW.
THANKS AGAIN
THE FUNCTION USING PYTHON
user_response=input("Input a number: ")
our_input=float(user_response)
def string (our_input):
if (our_input % 15) == 0 :
return ("fizzbuzz")
elif (our_input % 3) == 0 :
return ("fizz")
elif (our_input % 5) == 0 :
return ("buzz")
print(string(our_input))
<<------------------------------->>
IT'S PSEUDOCODE
Request an input from the user
Ensure that the input is a number
If the input is divisible by 15
send "fizzbuzz" to the main
program
But if the input is divisible by 3 and not 15
send "fizz" to the main program
But if the input is divisible by 5 and not 15 or 3
send "buzz" to the main program
Display the result.

Related

50% Probability of multiple elements on Python

I'm trying to create a "football" game on python and if the user wants to pass the ball, my code is supposed to have a 50% probability of having an incomplete pass or a completion yielding between 3 and 15 yards
I know that to print the yardage, the code would look something like
import random
input("Enter r to run and p to pass")
p = print(random.randint(3,15))
but I'm not sure how to make "Incomplete" show up as a 50% probabilty
You can use the code below. As you have defined a statement to pick a random number between 3-15, you can create another statement to pick 0 or 1 (not %50 guaranteed). Also in your code, you are assigning return value of the print function to a parameter. This is definitely wrong! Print function returns nothing so assigning it to another variable is meaningless.
x = random.randint(0,1)
if x == 1:
random.randint(3,15)
else:
# incomplete pass
You could use something like this.
import random
inp = input("Enter r to run and p to pass")
if(inp == "p"):
print(random.choice([random.randint(3,15),0]))
elif(inp == "r"):
print("ran successfully")
This: random.choice([random.randint(3,15),0]) is the important bit. random.choice takes multiple values (in this case 2) in a list, and picks one randomly (2 values => 50% probability).
I also fixed the input output thing. To get input from the user you assign the value of input to a variable like this: example = input("Your input here: "). If you ran that line of code, and answered with potato for instance, you'd be able to print example and get potato (or whatever the user answered) back.
If you'd like to really flesh your game out, I'd suggest looking into template strings. Those let you do wonderful things like this:
import random
inp = input("Enter r to run and p to pass")
if(inp == "p"):
print(random.choice([f"Successfully passed the ball {random.randint(3,15)} yards","You tripped, the ball wasn't passed."]))
elif(inp == "r"):
print("Ran successfully.")

How to print take something out of a list and store it elsewhere

I am making a music key theory test.
In order to achieve something else that I won't explain right now here (maybe I will later though if this doesn't work), I need to take the root chord out of the list, store it somewhere else, and call back upon it for the user input when they are asked what key the chords come from.
I don't know how to do this, but I am pretty sure it is possible. I would love it if someone could help me. After I have this problem sorted out I will be much further.
Before, I was trying to find someway to have the actual variable represent the variable, while representing what the variable contains. So then after printing the randomized chords from the variable, the user can input the key from which the chords come from, which I have as the variable. But I don't think that will work.
import random
print('Key Theory Werkout')
Dmajor = {'D','E-','F⌗-','G','A','B-','C⌗dim'}
Gmajor = {'G','A-','B-','C','D','E-','F⌗dim'}
Cmajor = {'C','D-','E-','F','G','A-','Bdim'}
Fmajor = {'F','G-','A-','Bb','C','D-','Edim'}
Bbmajor = {'Bb','C-','D-','Eb','F','G-','Adim'}
Ebmajor = {'Eb','F-','G-','Ab','Bb','C-','Ddim'}
Abmajor = {'Ab','Bb-','C-','Db','Eb','F-','Gdim'}
Dbmajor = {'Db','Eb-','F-','Gb','Ab','Bb-','Cdim'}
Cxmajor = {'C⌗','D⌗-','E⌗-','F⌗','G⌗','A⌗-','B⌗dim'}
Gbmajor = {'Gb','Ab-','Bb-','Cb','Db','Eb-','Fdim'}
Fxmajor = {'F⌗','G⌗-','A⌗-','B','C⌗','D⌗-','E⌗dim'}
Bmajor = {'B','C⌗-','D⌗','E','F⌗','G⌗','A⌗dim'}
Cbmajor = {'Cb','Db-','Eb-','Fb','Gb','Ab-','B-dim'}
Emajor = {'E','F⌗-','G⌗-','A','B','C⌗-','D⌗dim'}
Amajor = {'A','B-','C⌗-','D','E','F⌗-','G⌗dim'}
questions = [Dmajor, Gmajor, Cmajor, Fmajor, Bbmajor, Ebmajor,
Abmajor, Dbmajor, Cxmajor, Gbmajor, Fxmajor, Bmajor, Cbmajor,
Emajor, Amajor]
print('Difficulty:Easy, Hard')
begin = input("Choose Difficulty:")
if begin == 'easy':
while begin == "easy":
q = random.choice(questions)
qq = random.sample(list(q), 7)
print(qq)
answer = input('Please Provide the key:')
if answer == q
'''HERE IS THE PROBLEM. Lets say the code outputs F, A-, Bb, C, D-
for Dmajor. How can I have the user type in Dmajor and have it
print correct, or incorrect? I am thinking I will have to put .
entire blocks for each question, and then have the easy choose
random out of all of those questions and that will be how I have to
do it. But maybe there is an easier way.
'''
print("correct")
I would like it to tell the user if they are correct or wrong, while keeping the randomness of questions, and chords it spits out exactly the way it is.
What do I need to do?
Maybe you can try using a dictionary to represent your questions, like this:
questions = {
'Dmajor': {'D','E-','F⌗-','G','A','B-','C⌗dim'},
'Gmajor': {'G','A-','B-','C','D','E-','F⌗dim'},
'Cmajor': {'C','D-','E-','F','G','A-','Bdim'},
'Fmajor': {'F','G-','A-','Bb','C','D-','Edim'},
'Bbmajor': {'Bb','C-','D-','Eb','F','G-','Adim'},
'Ebmajor': {'Eb','F-','G-','Ab','Bb','C-','Ddim'},
'Abmajor': {'Ab','Bb-','C-','Db','Eb','F-','Gdim'},
'Dbmajor': {'Db','Eb-','F-','Gb','Ab','Bb-','Cdim'},
'Cxmajor': {'C⌗','D⌗-','E⌗-','F⌗','G⌗','A⌗-','B⌗dim'},
'Gbmajor': {'Gb','Ab-','Bb-','Cb','Db','Eb-','Fdim'},
'Fxmajor': {'F⌗','G⌗-','A⌗-','B','C⌗','D⌗-','E⌗dim'},
'Bmajor': {'B','C⌗-','D⌗','E','F⌗','G⌗','A⌗dim'},
'Cbmajor': {'Cb','Db-','Eb-','Fb','Gb','Ab-','B-dim'},
'Emajor': {'E','F⌗-','G⌗-','A','B','C⌗-','D⌗dim'},
'Amajor': {'A','B-','C⌗-','D','E','F⌗-','G⌗dim'},
}
Then, you select a random question like this:
key = random.choice(list(questions))
set = questions[key]
sample = random.sample(set, 7)
Now, you only have to check if answer is equal to key.

Reducing multiple if statements to a table

I am translating a kids choose your own adventure book into a python program eg, 'If you choose x go to page y or if you choose a go to page b'
While this program works, by the end of the book there will be over 100 if statements is there any way to create a table that that compares a user input to a list of pages. An example I saw while researching displayed a similar table to this:
#this would hold the potential user inputs
[0,0,0,0,0,0]
[0,0,0,0,0,0]
[0,0,0,0,0,0]
However i am unsure how to implement it
#imports the pages of the book from another python file
from Content import *
clrscrn = (chr(27) + "[2J")
def page0():
print "\n %s" % page1
page0()
#User input loop
while True:
inp = raw_input(">>> ").lower()
#clears the screen then prints the variable (page)
if inp == '3':
print clrscrn
print '%s' % page3
if inp == '10':
print clrscrn
print '%s' % page10
if inp == '5':
print clrscrn
print '%s' % page5
if inp == '14':
print clrscrn
print '%s' % page14
#quits python
elif inp == 'quit':
raise SystemExit
The only difference in each if statement is which page variable you access. Since you want to get at page14 if the user enters "14" you can use the dictionary returned by globals() to access the page variables in a dynamic way.
So, instead of hundreds of if statement, you really don't need any at all. You can use the following lines instead.
print clrscrn
print globals()['page' + inp]
Define in your head what the inputs and outputs will be.
To me, it seems likely that you will have multiple questions, on different pages. So one input would be the "current page number." That would identify the question.
The other input, of course, would be the user's response. In a binary (yes/no) system, there would always be exactly two possible responses from the user (yes, or no). In a non-binary system, there might be more possible responses.
I'd suggest that you assume non-binary, and further, even if only one question is possibly non-binary, go with that. It helps keep things consistent.
Let's assume, then, that you've got a non-binary system with 100 questions. Each question appears at the end of a "page." (Maybe it's at the end of a "chapter" or "paragraph" or something. Feel free to replace words.) When the user answers, they are directed to go to a different "page."
So your mapping is going to be "current page + user input -> new page".
The easiest way to implement this in python is with a list of dictionaries. The list index can be the current page. That will identify the question, and the possible responses. The responses (keys in the dictionary) can be text strings. The results (values from the dictionary) will be integers, indicating the new page number. Thus:
Pages = [ # List of questions, one per page. Use {} for page with no Q
{}, # 0
{}, # 1
{
"yes": 12,
"no": 16,
}, # 2
]
If you want to be a little more efficient, you can store the questions in the same list, using a key like " q " which cannot be input by the user (because you will run .strip() on the user input, naturally)!
{
" q ": "Do you like pizza?",
"yes": 12,
"no": 16,
}
If you're feeling really energetic, you can make the dictionaries into a class, with attributes, store the various pages as JSON, etc.

Trouble with functions in python 2.7.3

I am new to learning python, and I only have limited programing experience, so I am sorry for asking such a basic question. I am doing an online python tutorial and wanted to take the program a bit further than the lesson requested to test out how far I could take it. The problem is that I have been hitting a roadblock. After reading a bunch of posts on here I have moved things around, changed variable names, used more functions, less functions, if else statements, and toyed around/ troubleshot, but have received all sorts of errors. I am going to paste where I currently am at below and would really appreciate if someone out there could help me finish up the program.
Here is what I would like for the program to do:
I would like the user to be prompted to enter a number.
I would like to make sure that the user entered a number, and if they don't I would like the program to give them an error and restart.
I would like that once the number is received the program squares that number and then prints the answer.
(again thanks much for all the help)
HERE IS WHERE I AM AT:
n1 = raw_input('Please enter your desired number:')
def n2():
n2 = n1.isnumeric()
return n2
def square(n2):
squared = n2**2
print "%d squared is %d." % (n2, squared)
return squared
square(n2)
n2 = raw_input("number pls\n")
while not n2.isdigit():
print("why did you do this\n")
n2 = raw_input("number pls\n")
print int(n2)**2
Problems from your code:
You need a control structure which repeatedly tries to do something until the right thing happens. This should make you think "while loop."
isnumeric isn't a method. but you had the right idea.
Naming all of your variables and functions n2 is not a good way to easily see what's going on..
If you want to add a construct for floats, you should write a function which takes a string in and returns true or false based on if it looks like a float! This is a good example for using functions to decompose the problem you're working with- you know you need to do something like
while not (n2.isdigit or isFloat(n2)):
There are some good suggestions here and elsewhere about how to do that :)
You could check if you could convert into float if so print the square else print the error .To repeat this process while you get a number you could use while loop
def number_validator( numb ):
try:
float( numb )
return True
except Exception:
print "GIven input is not a valid number"
return False
def square( n2 ):
n2=float( n2 )
squared = n2**2
print "%s squared is %s." % ( n2 , squared )
return squared
n2 = raw_input( 'Please enter your desired number:' )
while not number_validator( n2 ):
n2 = raw_input( 'Please enter your desired number:' )
square( n2 )
Output:
Please enter your desired number:wq
GIven input is not a valid number
Please enter your desired number:we
GIven input is not a valid number
Please enter your desired number:21.0
21.0 squared is 441.0.

Serial Key Generation and Validation

I'm toying around with writing creating a serial code generator/validator, but I can't seem to get how to do a proper check.
Here's my generator code:
# Serial generator
# Create sequences from which random.choice can choose
Sequence_A = 'ABCDEF'
Sequence_B = 'UVWQYZ'
Sequence_C = 'NOPQRS'
Sequence_D = 'MARTIN'
import random
# Generate a series of random numbers and Letters to later concatenate into a pass code
First = str(random.randint(1,5))
Second = str(random.choice(Sequence_A))
Third = str(random.randint(6,9))
Fourth = str(random.choice(Sequence_B))
Fifth = str(random.randint(0,2))
Sixth = str(random.choice(Sequence_C))
Seventh = str(random.randint(7,8))
Eighth = str(random.choice(Sequence_D))
Ninth = str(random.randint(3,5))
serial = First+Second+Third+Fourth+Fifth+Sixth+Seventh+Eighth+Ninth
print serial
I'd like to make a universal check so that my validation code will accept any key generated by this.
My intuition was to create checks like this:
serial_check = raw_input("Please enter your serial code: ")
# create a control object for while loop
control = True
# Break up user input into list that can be analyzed individually
serial_list = list(serial_check)
while control:
if serial_list[0] == range(1,5):
pass
elif serial_list[0] != range(1,5):
control = False
if serial_list[1] == random.choice('ABCDEF'):
pass
elif serial_list[1] != random.choice('ABCDEF'):
control = False
# and so on until the final, where, if valid, I would print that the key is valid.
if control == False:
print "Invalid Serial Code"
I'm well aware that the second type of check won't work at all, but it's a place holder because I've got no idea how to check that.
But I thought the method for checking numbers would work, but it doesn't either.
The expression `range(1, 5)' creates a list of numbers from 1 to 4. So in your first test, you're asking whether the first character in your serial number is equal to that list:
"1" == [1, 2, 3, 4]
Probably not...
What you probably want to know is whether a digit is in the range (i.e. from 1 to 5, I assume, not 1 to 4).
Your other hurdle is that the first character of the serial is a string, not an integer, so you would want to take the int() of the first character. But that will raise an exception if it's not a digit. So you must first test to make sure it's a digit:
if serial_list[0].isdigit() and int(serial_list[0]) in range(1, 6):
Don't worry, if it's not a digit, Python won't even try to evaluate the part after and. This is called short-circuiting.
However, I would not recommend doing it this way. Instead, simply check to make sure it is at least "1" and no more than "5", like this:
if "1" <= serial_list <= "5":
You can do the same thing with each of your tests, varying only what you're checking.
Also, you don't need to convert the serial number to a list. serial_check is a string and accessing strings by index is perfectly acceptable.
And finally, there's this pattern going on in your code:
if thing == other:
pass
elif thing != other:
(do something)
First, because the conditions you are testing are logical opposites, you don't need elif thing != other -- you can just say else, which means "whatever wasn't matched by any if condition."
if thing == other:
pass
else:
(do something)
But if you're just going to pass when the condition is met, why not just test the opposite condition to begin with? You clearly know how to write it 'cause you were putting it in the elif. Put it right in the if instead!
if thing != other:
(do something)
Yes, each of your if statements can easily be cut in half. In the example I gave you for checking the character range, probably the easiest way to do it is using not:
if not ("1" <= serial_list <= "5"):
Regarding your python, I'm guessing that when your wrote this:
if serial_list[0] == range(1,5):
You probably meant this:
if 1 <= serial_list[0] <= 5:
And when you wrote this:
if serial_list[1] == random.choice('ABCDEF'):
You probably meant this:
if serial_list[1] in 'ABCDEF':
There are various other problems with your code, but I'm sure you'll improve it as you learn python.
At a higher level, you seem to be trying to build something like a software activation code generator/validator. You should know that just generating a string of pseudo-random characters and later checking that each is in range is an extremely weak form of validation. If you want to prevent forgeries, I would suggest learning about HMAC (if you're validating on a secure server) or public key cryptography (if you're validating on a user's computer) and incorporating that into your design. There are libraries available for python that can handle either approach.

Categories

Resources