I'm making a project where I need to generate a random number (which is later modified). Currently I have this piece of code:
x=input("x = ")
num1_child = randint(0,100)
num1.extend(str(num1_child))
num2 = randint(0,100)
if int(num1[n]) - num2 >= x:
print(str(int(num1) - num2))
print("yes \n")
num_yes += 1
Yes()
elif int(num1) - num2 <= -x:
print(str(num2 - int(num1)))
print("yes \n")
num_yes += 1
Yes()
else:
print(str(int(num1[n]) - num2) + " // " + str(num2 - int(num1)))
print("no \n")
num_no += 1
No()
I want to generate a number between 1 and 100, but it only generates a number netween 50 and 100.
just randint(0, 100) will not work in this usecase, it ahs to be set up using the num1_child etc.
Its quite simple to generate random number-
Simplest way to make a float number between a range:
import random
def makerandom(min,max):
num = random.random()
num = num * (max - min) + min
return num
print(makerandom(0,100))
Get a random integer instead:
import random
print(random.randint(0,100))
There is no random number set that follows a "specific set of rules". A series of numbers can either be (pseudo) random or it can fullfill other specifications. You cannot combine both as per any "rule" you will reduce the entropy.
Related
I know how to do this with a while loop and know how to use a for-loop in other languages like Java and C++. I want to use a for-loop in place of where I have written the while loop asking for the user input.
# You are required to use for-loop to solve this and round your answer to 2 decimal places. Write
# a program that takes n ∈ N (i.e., any positive integer including zero) from the user and use the
# input value to compute the sum of the following series:
n = -1
while n < 0:
n = int(input("Enter a value to compute: "))
# keep asking for user input until a whole number (0, 1, 2, 3, etc...) has been entered
k = 0
sum = 0
# To hold the sum of the fraction to be displayed
lastTerm = 0
# This variable represents the last term to be added to the fraction sum before the while loop below terminates
if n == 0:
sum = 0
elif n == 1:
sum = 1
else:
while lastTerm != 1 / n:
lastTerm = (n - k) / (k + 1)
sum = sum + (n - k) / (k + 1)
k += 1
print("{:.2f}".format(sum))
# Print the sum to two decimal places
One option is to catch the exception which is thrown when you cannot convert the input to an int, i.e.
while(True):
try:
# read input and try and covert to integer
n = int(input("Enter a value to compute: "))
# if we get here we got an int but it may be negative
if n < 0:
raise ValueError
# if we get here we have a non-negative integer so exit loop
break
# catch any error thrown by int()
except ValueError:
print("Entered value was not a postive whole number")
Alternative, slightly cleaner but I'm not 100% sure isdigit() will cover all cases
while(true):
n = input("Enter a value to compute: ")
if value.isdigit():
break
else:
print("Entered value was not a postive whole number")
How about this? It uses the for loop and sums all the values in the list.
x=[1,2,3,4] #== test list to keep the for loop going
sum_list=[]
for i in x:
j=float(input("Enter a number: "))
if not j.is_integer() or j<0:
sum_list.append(j)
x.append(1) #=== Add element in list to keep the cyclone going
else:
break
sums=sum(sum_list)
print("The Sum of all the numbers is: ",round(sums,2))
Use this to check for whole numbers -
if num < 0:
# Not a whole number
elif num >= 0:
# A whole number
for a for loop:
import itertools
for _ in itertools.repeat([]): # An infinite for loop
num = input('Enter number : ')
if num < 0:
# Not a whole number
pass # This will ask again
elif num >= 0:
# A whole number
break # break from for loop to continue the program
Easier Way -
mylist = [1]
for i in mylist : # infinite loop
num = int(input('Enter number : '))
if num < 0:
mylist.append(1)
pass # This will ask again
elif num >= 0:
# A whole number
break
what is wrong with this code(newbie)
def find_sum (n):
sum_num = (n * (n + 1)) / 2
n=int(input ("Enter a number: "))
return sum_num
print("The sum of first"+sum_num)
If you really need a recursive function, then it'll be something like this:
def recursive_sum(n):
if n == 1:
return 1
else:
return n + recursive_sum(n - 1)
print(recursive_sum(10)) # -> 55
But are you actually sure it has to be recursive?
Problems
You are not using a recursive function
You are not calling your function ( you need to return the value of it then print it)
You are using 'n' as a input to your function call but then trying to overwrite it
Solution
Don't use recursion, it would be a bad use to recursively gather inputs from a user, also move the input call to outside of the function
def find_sum (n):
sum_num = (n * (n + 1)) / 2
return sum_num
n=int(input ("Enter a number: "))
result = str(find_sum(n))
print("The sum of first " + result)
Learn more about function calls here
python takes code one step at a time so you cant define n after you used it you have to define it before using n and if you want to get the return value you will use the difined function as shown below:
n=int(input ("Enter a number: "))
def find_sum (n):
sum_num = (n * (n + 1)) / 2
return sum_num
print("The sum of first" ,find_sum(n))
You never acctually call your function
Try something like this:
def find_sum ():
n=int(input ("Enter a number: "))
sum_num = (n * (n + 1)) / 2
return sum_num
sum = find_sum()
print("The sum of first"+sum)
this way the return value of find_sum will be saved to sum
You are not taking input properly also you are not calling function also you have not used any concept of recursion.
Solution with recursion is below:
def find_sum (n):
if n==0:
return 0
else:
return (n+sum(n-1))
n=int(input("Enter a number: "))
print("The sum of first"+find_sum(n))
If it solved your problem mark this as your answer
I'm trying to use a timer to see how fast each function is. My codes work but after running it many times I get slightly different results and wonder if I'm implementing function correctly. I am only going to the 10th Fibonacci number which is 55 for testing. Each time I run the "A" option the clockTime() function returns a slightly larger number than before. Any thoughts would be appreciated.
import math
import time
#create a time variable
start_time = time.time()
#create the golden Ratio formula
golden_ratio = (1 + math.sqrt(5)) / 2
#the runtime function
def clockTime():
print("\nrun time: " + str(time.time()-start_time))
#the golden ration function
def fibGen(num):
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print('{i:3}: {v:3}'.format(i=number, v=round(val)))
#the find element < Max number function
def elemFib(num):
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
if val < num:
print('Fib({}): {}'.format(number, round(val)))
#Pythonic way
def pythonic():
a, b = 0,1
while a < 57:
print(a, sep=" ", end="\n")
a, b = b, a+b
#display the Main Menu
def dispMenu():
print('---------------------Fibonacci Series ------------------\n')
print('(A) Print Fibonacci numbers to the nth term')
print('(B) Print Fibonacci numbers until element is less than Max number')
print('(C) pythonic print')
print('(Q) Quit the program\n')
def main():
# set boolean control variable for loop
loop = True
#Create while loop for menu
while loop:
#Display the menu
dispMenu()
#Get user's input
choice = (input('Please make a selection: '))
#Perform the selected action
if choice.upper() == 'A':
num = int(input("How many Fibonacci numbers should I print? "))
fibGen(num)
clockTime()
elif choice.upper() == 'B':
num = int(input("the element should be less than? "))
elemFib(num)
clockTime()
elif choice.upper() =='C':
pythonic()
clockTime()
elif choice.upper() == 'Q':
print('\nExiting program, Thank you and Goodbye')
loop = False
else:
print('\nInvalid selection, try again\n')
main()
The problem is you initialized start_time at the start of the program rather than right before you ran the function to be timed. You were adding in the times of previous runs as well as the time the user took to read the instructions and make a decision, etc. Here's a rework of your code that should do what you want:
import math
import time
# create the golden Ratio formula
golden_ratio = (1 + math.sqrt(5)) / 2
# the runtime function
def clockTime(start_time):
print("\nrun time:", time.time() - start_time)
# the golden ration function
def fibGen(num):
for number in range(num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print('{i:3}: {v:3}'.format(i=number, v=round(val)))
# the find element < Max number function
def elemFib(num):
for number in range(num + 1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
if val < num:
print('Fib({}): {}'.format(number, round(val)))
# Pythonic way
def pythonic():
a, b = 0, 1
while a < 57:
print(a, sep=" ", end="\n")
a, b = b, a + b
# display the Main Menu
def dispMenu():
print('---------------------Fibonacci Series ------------------\n')
print('(A) Print Fibonacci numbers to the nth term')
print('(B) Print Fibonacci numbers until element is less than Max number')
print('(C) pythonic print')
print('(Q) Quit the program\n')
def main():
# set boolean control variable for loop
loop = True
# Create while loop for menu
while loop:
# Display the menu
dispMenu()
# Get user's input
choice = input('Please make a selection: ').upper()
# Perform the selected action
if choice == 'A':
num = int(input("How many Fibonacci numbers should I print? "))
start_time = time.time()
fibGen(num)
clockTime(start_time)
elif choice == 'B':
num = int(input("the element should be less than? "))
start_time = time.time()
elemFib(num)
clockTime(start_time)
elif choice == 'C':
start_time = time.time()
pythonic()
clockTime(start_time)
elif choice == 'Q':
print('\nExiting program, Thank you and Goodbye')
loop = False
else:
print('\nInvalid selection, try again\n')
main()
the function i am working on is supposed to tell a user whether a number they have given is a perfect number or not (i.e. is equal to half the sum of its factors). if a user gives the number 8, the output should look like this:
8 is not a perfect number
but i can't figure out what to put in the return statement to make the int, which changes depending on the user input, print out with the string. the code so far looks like this:
#the code is within another larger function which is the reason for the elif
elif(message == 2):
num1 = int(input("""Please enter a positive integer :"""))
while(num1 <= 0):
print("Number not acceptable")
num1 = int(input("""Please enter a positive integer :"""))
thisNum = isPerfect(num1)
if(thisNum == True):
return num1, is a perfect number
elif(thisNum == False):
return num1 is not a perfect number
def isPerfect(num1):
sumOfDivisors = 0
i = 0
listOfDivisors = getFactors(num1)
for i in range(0, len(listOfDivisors) - 1):
sumOfDivisors = sumOfDivisors + listOfDivisors[i]
i += 1
if(sumOfDivisors / 2 == num1):
return True
else:
return False
if i were to do return(num1, "is not a perfect number") it would come out like
(8, 'is not a perfect number')
return "%d is not a perfect number" % number
You can do this with string formating using %s. Anyway there is some other ways as describes String Formating Operators
convert the integer to a string and concatenate the rest of your statement:
return str(num1) + ' is not a perfect number'
You can use the .format() mini language, and at the same time, simplify your code:
elif(message == 2):
num1 = int(input("""Please enter a positive integer :"""))
while(num1 <= 0):
print("Number not acceptable")
num1 = int(input("""Please enter a positive integer :"""))
if isPerfect(num1):
return '{} is a perfect number'.format(num1)
else:
return '{} is not a perfect number'.format(num1)
Also in your other method, simply return the result of the comparison:
def isPerfect(num1):
sumOfDivisors = 0
listOfDivisors = getFactors(num1)
for i listOfDivisors:
sumOfDivisors += i
#if(sumOfDivisors / 2 == num1):
# return True
#else:
# return False
return sumOfDivisors / 2 == num1
Also, I would suggest having a read of PEP-8, which is the style guide for Python.
I'm currently learning maths through Khan Academy and I'm creating a program in Python's IDLE to give me randomized questions so that I can practice maths. So far I've just done addition and subtraction and would like to check that I'm covering all possible sum scenarios under 7 digits (9999999). This is the basic addition script:
def one_digit_addition():
counter = 0
target = 5
while counter < target:
random_digit_one = random.randint(0, 9)
random_digit_two = random.randint(0, 9)
print "What is %s + %s?" % (random_digit_one, random_digit_two)
answer = random_digit_one + random_digit_two
userAnswer = int(raw_input("Answer: "))
if userAnswer == answer:
counter = counter + 1
print "\n*CORRECT*, your score is %s. Next question...\n" % counter
elif userAnswer != answer:
counter = counter - 5
print "\n*INCORRECT*! Your score is %s. Next question...\n" % counter
if counter == 5:
print "**CONGRATULATIONS, you've passed one digit addition. Now loading two digit addition...**\n"
two_digit_addition()
After this one_digit_addition function I have functions of the copied code above going right up to seven digit addition. The only difference is is that I've added an extra 9 to both the random integer variables each time. Here's the subtraction script:
def one_digit_subtraction():
counter = 0
target = 5
while counter < target:
random_digit_one = random.randint(0,9)
random_digit_two = random.randint(0,9)
if random_digit_one > random_digit_two:
print "What is %s - %s?" % (random_digit_one, random_digit_two)
answer = random_digit_one - random_digit_two
else:
print "What is %s - %s?" % (random_digit_two, random_digit_one)
answer = random_digit_two - random_digit_one
userAnswer = int(raw_input("Answer: "))
if userAnswer == answer:
counter = counter + 1
print "\n*CORRECT*, your score is %s. Next question...\n" % counter
elif userAnswer != answer:
counter = counter - 5
print "\n*INCORRECT*! Your score is %s. Next question...\n" % counter
if counter == 5:
print "**CONGRATULATIONS, you've passed one digit subtraction. Now loading two digit subtraction...**\n"
two_digit_subtraction()
It's the same for this script. I've copied the code and added a 9 integer to the number variables. My main concern is that I'm missing out certain sums with this current formula. I basically would like there to be a chance of there being every possible sum combination <= 999999999. I hope this question was worded better than my last one.
Try to parametrise your function in order to avoid the repetitions.
For instance with this:
import random
import operator
ops = {'+' : operator.add, '-': operator.sub, '*': operator.mul}
def quiz (operator, digits):
start = 10 ** (digits - 1) if digits > 1 else 0
a = random.randint (start, 10 ** digits - 1)
b = random.randint (start, 10 ** digits - 1)
if operator == '-' and a < b: a, b = b, a
r = input ('What is {} {} {}? '.format (a, operator, b) )
try: return int (r) == ops [operator] (a, b)
except ValueError: return False
You can ask for a 2-digit addition with quiz('+', 2) for a three digit subtraction with quiz('-', 3) or for a 1-digit multiplication with quiz('*', 1). In each case the function returns True iff the user answered correctly.
For python2 replace input with raw_input.