Python: Using def in a factorial program - factorial

So i am trying to make a program that finds the factorial using def.
changing this:
print ("Please enter a number greater than or equal to 0: ")
x = int(input())
f = 1
for n in range(2, x + 1):
f = f * n
print(x,' factorial is ',f)
to
something that uses def.
maybe
def intro()
blah blah
def main()
blah
main()

Not entirely sure what you are asking. As I understand your question, you want to refactor your script so that the calculation of the factorial is a function. If so, just try this:
def factorial(x): # define factorial as a function
f = 1
for n in range(2, x + 1):
f = f * n
return f
def main(): # define another function for user input
x = int(input("Please enter a number greater than or equal to 0: "))
f = factorial(x) # call your factorial function
print(x,'factorial is',f)
if __name__ == "__main__": # not executed when imported in another script
main() # call your main function
This will define a factorial function and a main function. The if block at the bottom will execute the main function, but only if the script is interpreted directly:
~> python3 test.py
Please enter a number greater than or equal to 0: 4
4 factorial is 24
Alternatively, you can import your script into another script or an interactive session. This way it will not execute the main function, but you can call both functions as you like.
~> python3
>>> import test
>>> test.factorial(4)
24

def factorial(n): # Define a function and passing a parameter
fact = 1 # Declare a variable fact and set the initial value=1
for i in range(1,n+1,1): # Using loop for iteration
fact = fact*i
print(fact) # Print the value of fact(You can also use "return")
factorial(n) // Calling the function and passing the parameter
You can pass any number to n for getting factorial

Related

Trying to make a reimann sum program. new to python and struggling

I am new to python and have been assigned to create a function to find the Reimann sum for the equation, 3x^3 + 2x^2, where the equation asks for the upper and lower bounds and the delta value and uses the equation A=[f (a)+f (b)+...+f ( y )]∗delta to find the area under the curve.
# A function that is in charge of prompting the user for any input they
# give. It receives an argument representing the required data, prompts
# the user for that data, and then returns it to the calling statement.
def limits ():
a = int(input("What is the value of \"a\":"))
b = int(input("What is the value of \"b\":"))
return a, b
# A function that is in charge of printing out the introductory
# statement(s) for the program.
def introduction():
print("This progrram will calculate the integral of the function f(x) = 3x^3 - 2x^2 between user defined limits: a and b")
# A function that prints out the statement about the accuracy of delta.
def accuracy():
print("The accuracy of this calculation depends on the value of delta that you use.")
# A function to evaluate the given mathematical formula at a given
# point. It takes a numerical argument that represents x, and returns
# the result of f(x).
def f(x):
y = float((3*(x**3))-(2(x**2)))
return y
# A function that calculates an approximation of the integral of f(x)
# using the riemann sum. It takes three arguments that represent the
# lower limit, the upper limit, and the delta value. It then returns the
# integral approximation as a result to the calling statement.
def reimann(p, q, r):
AOTC = delta*((f(a)+delta)(f(b)-delta))
return AOTC
########################### MAIN ##################################
# In the space below, use the functions defined above to solve the
# problem.
###################################################################
# Print the introductory statements of the program
intro = introduction()
# Prompt the user for both the lower and upper limits
a , b = limits()
# Print the statements about delta
accuracy = accuracy()
# Promt the user for the delta value
delta = float(input("What is the value of \"delta\":"))
# Calculate the integral approximation
Area = reimann(a, b, delta)
# Print out the result.
print(Area)
Whenever I try to run this I get an error that says:
Exception has occurred: TypeError
'int' object is not callable
File "C:\Users\rayro\OneDrive\Documents\Fall22\CSC 130\03 Riemann Sum.py", line 27, in f
y = float((3*(x**3))-(2(x**2)))
File "C:\Users\rayro\OneDrive\Documents\Fall22\CSC 130\03 Riemann Sum.py", line 34, in reimann
AOTC = delta*((f(a)+delta)(f(b)-delta))
File "C:\Users\rayro\OneDrive\Documents\Fall22\CSC 130\03 Riemann Sum.py", line 51, in <module>
Area = reimann(a, b, delta)
enter code here

Making a collatz program and end it after 500 runs

This is my script. How do i add so the loop ends if it has to run 500 times or more?
x=0
while x<=500:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
n = input("Give me a number: ")
while n != 1:
n = collatz(int(n))
x=x+1
else:
print('Loop ended)
break
This is the collatz equation but it is not always sure that it ends up on 1. So I need to rewrite my program so that the loop ends if the number series will be longer than 500 numbers.

R: how to let .C call update output variable?

I am trying to write a C code to use in R, but found that the .C function call won't update output variable. The real C code is complicated, but here is a simple example to show the behavior:
void doubleMe(const int *input, int *output) {
output[0] = input[0] * 2;
}
Save above C function into file doubleMe.c. Under Linux, compile it to create doubleMe.so file:
R CMD SHLIB doubleMe.c
In R, if I do following:
dyn.load("doubleMe.so") # load it
input = 2
output = 0
.C("doubleMe", as.integer(input), as.integer(output)) # expect output=4
[[1]]
[1] 2
[[2]]
[1] 4
The screen output indicates the input is doubled, but the output in R is still 0:
output
[1] 0
If I do fowllwing
output = .C("doubleMe", as.integer(input), as.integer(output))[[2]]
the output is 4. This should work for the example.
But my real input and output are matrix, and I have to reshape the output to correct dimension. Is there a way to let .C call update output directly?
With the .Call() interface using SEXP data types where P stands for pointer, this is automagic:
R> Rcpp::cppFunction("void doubleMe(NumericVector x) { x = 2*x; } ")
R> x <- 1 # set to one
R> doubleMe(x) # call function we just wrote
R> x # check ...
[1] 2 # and it has doubled as a side-effect
R>
I use Rcpp here as it allows me to do this on one line, you could do the same in a few lines of C code if you wanted to.

Couldn't convert C program to Ruby

This code in C language works perfectly, I will explain what it does:
Given a positive integer "n" and a sequence of "n" integers, the sum will determine a sequence of positive integers.
Examples of inputs:
4 9 -1 4 -2
expected output: 13 / input: 3 3 0 -2 output: 3/
#include <stdio.h>
int main(){
int cont=0,n,num,sum;
scanf("%i",&n);
while(n>cont){
cont++;
scanf("%i",&num);
if(num>0){
sum=num+sum;
}
}
printf("%i",sum);
}
and this was my attempt to convert it to Ruby
cont=0
n=gets.to_i
while n>cont do
cont=cont+1
num=gets.to_i
if num>0
sum=num+sum
end
puts"#{sum}"
and this is what im getting:
ruby test.rb
test.rb:10: syntax error, unexpected end-of-input, expecting keyword_end
puts"#{sum}"
^
. Can anyone help?
Thank you, so this is the right code that works
cont=0
sum=0
n=gets.to_i
while n>cont do
cont=cont+1
num=gets.to_i
sum=num+sum if num>0
end
puts"#{sum}"
You were not far off. The syntax of the if-statement needs a then and an end. Also, sum needs to be zero at the start.
cont=0
sum=0 # sum needs an initial value
n=gets.to_i
while n>cont do
cont=cont+1
num=gets.to_i
sum=num+sum
# num = num+sum if num >0
# #or
# if num >0 then
# sum=num+sum
# end
# #But both "if's" serve no purpose
end
puts"#{sum}"
Another way of writing this is:
sum = 0
gets.to_i.times{sum += gets.to_i} # no bookkeeping with cont
puts sum # more simple then puts"#{sum}"

Using random library to guess number (Python)

#This program generates random number
#user enters guess
#progam tells user higher, lower or correct based on user input.
import random
def main():
# Get a random number.
number = random.randint(1, 101)
user_guess = int(input("Pick a number between 1 and 100: "))
userguess = guess(user_guess, number)
print(userguess)
def guess(num1, num2):
if num1 > num2:
return("Lower")
elif num1 < num2:
return("Higher")
else:
return("Correct")
main()
I can get the program to generate a random number, then display higher or lower, but not as again. It is supposed to ask again until it hits the random and then displays 'correct'
You need a loop to keep prompting until the correct answer is guessed, while(True) keeps going until a break; is reached. Try something like this.
def guess(num):
while(True):
user_guess = int(input("Pick a number between 1 and 100: "))
if user_guess > num:
print("Lower\n")
elif user_guess < num:
print("Higher\n")
else:
print("Correct")
break;
This will repeatedly ask user for numbers untill they are correct replace your main method with the following
def main():
# Get a random number.
number = random.randint(1, 101)
guess(number)
Edit: replaced true with True

Resources