Maintaining a Variables Value through Recursion - python

def even_divide_count(num1, num2):
y = 0
number = num1 // num2
if number % 2 == 1 or number == 0:
return 0
else:
even_divide_count(number, num2)
y += 1
return y
I apologize because this is the first question I'm asking on stack overflow so apologizes for the formatting. I'm attempting to maintain the value for the variable y through recursion however the maximum value I get when y is returned is 1 as it doesn't end up adding all the y values through levels of incursion. Any help is greatly appreciated!
*updated because I forgot a line
def even_divide_count(num1, num2):
y = 0
number = num1 // num2
if number % 2 == 1 or number == 0:
return 0
else:
1 + even_divide_count(number, num2)
y += 1
return y
*found my answer, it's posted above

Related

Why does if loop is not working on this python program?

while adding two numbers, I want to check how many times carry is occurring –
for eg:
Input
Num 1: 451
Num 2: 349
Output
2
Explanation:
Adding ‘num 1’ and ‘num 2’ right-to-left results in 2 carries since ( 1+9) is 10. 1 is carried and (5+4=1) is 10, again 1 is carried. Hence 2 is returned.
def NumberOfCarries(num1, num2):
count = 0
l = str(num1)
i = 0
if i <= len(l):
n = num1 % 10
n2 = num2 % 10
sum = n + n2
print(f" num is {num1} and {num2} n1 is {n} and n2 is {n2} and sum is {sum}")
if sum > 9:
count += 1
num1 = num1 // 10
num2 = num2 // 10
i += 1
else:
num1 = num1 // 10
num2 = num2 // 10
i += 1
return count
num1 = int(input("> "))
num2 = int(input("> "))
print(NumberOfCarries(num1, num2))
Here loop is not working, only one time the sum is generating. I want to generate for each number in numb1. I tired with while, if and for. Please help me.I am new to this
I think you tried to do this:
def number_of_carries(num1, num2):
amplitude_num1 = len(str(num1))
amplitude_num2 = len(str(num2))
count = 0
i = 0
carry_over = 0
while i < amplitude_num1 or i < amplitude_num2:
n = num1 % 10
n2 = num2 % 10
sum_of_digits = n + n2 + carry_over
print(f" num is {num1} and {num2}, n1 is {n} and n2 is {n2}, carry digit from previous addition is {carry_over}, sum is {sum_of_digits}")
if sum_of_digits > 9:
count += 1
carry_over = 1
else:
carry_over = 0
num1 //= 10
num2 //= 10
i += 1
return count
num1 = int(input("> "))
num2 = int(input("> "))
print(number_of_carries(num1, num2))
But if you want to have a solution that would accept more that 2 numbers this could be modified to:
def number_of_carries(numbers):
amplitude = max(len(str(x)) for x in numbers)
count = 0
i = 0
carry_over = 0
for i in range(amplitude):
current_numbers = tuple(x % 10 for x in numbers)
sum_of_digits = sum(current_numbers) + carry_over
print(
f" numbers are {' '.join(str(x) for x in numbers)}, "
f"current_numbers are {' '.join(str(x) for x in current_numbers)}, "
f"carry digit from previous addition is {carry_over}, sum is {sum_of_digits}"
)
if sum_of_digits > 9:
count += 1
carry_over = sum_of_digits // 10
numbers = tuple(x // 10 for x in numbers)
return count
input_numbers = (198, 2583, 35)
print(number_of_carries(input_numbers))

How to perform digitsum for a negative integer input until a single digit is obtained?

My code:
def add_digits():
num=int(input("Enter "))
return (num - 1) % 9 + 1 if num > 0 else 0
print(add_digits())
How to make this work for negative input? Please do help. Thanks in advance for your time and help.
First, you should have your add_digits function take in the value as a parameter rather than getting it from the user; that'll make it easier to build on it:
def add_digits(num: int) -> int:
return (num - 1) % 9 + 1 if num > 0 else 0
print(add_digits(int(input("Enter "))))
Now you have a much simpler problem to solve: how do we make sure that when this function gets passed a negative number, it returns the negative of the result of the corresponding positive number? That's very easy to express as a simple recursive call at the beginning:
def add_digits(num: int) -> int:
if num < 0:
return -add_digits(-num)
return (num - 1) % 9 + 1 if num > 0 else 0
assert add_digits(123456) == 3 # ok
assert add_digits(-123456) == -3 # ok
Why not just use the absolute value of num?
def add_digits(num):
if num == 0:
return 0
elif num > 0:
return (num - 1) % 9 + 1
else:
return -( (abs(num) - 1) % 9 + 1 )
num = int(input("Enter "))
print(add_digits(num))

Generate Random Math in Python 3

This program will ask the user a series of questions about two numbers. These two numbers will be generated randomly between 1 and 10 and it will ask the user 10 times. At the end of these 10 questions the program will display how many the user got correct out of those questions.
Each question should randomly decide between asking for the product, sum, or difference. Separate the question asking into a function, as well as the validating user input.
I tried using with three product, sum or difference in random to generate. I tried to use z = random.randint(1, 4) is to select from 1 is product, 2 is sum, or 3 is difference and then I used with if variable z is 1, then do product math or if var z is 3, then it should be difference like this x / y, but I couldn't figure it finish it up. I have the expected result when I first run with product but it works so I just need to add with sum and difference included.
EXPECTED OUTPUT with product (Some are incorrect for testing with scores):
> python3 rand3.py
What is 3 x 4
Enter a number: 12
What is 3 x 7
Enter a number: 27
What is 6 x 3
Enter a number: 18
What is 7 x 10
Enter a number: 70
What is 9 x 10
Enter a number: 90
What is 9 x 7
Enter a number: 72
What is 5 x 9
Enter a number: 54
What is 6 x 8
Enter a number:
Incorrect Input!
Enter a number: 48
What is 1 x 5
Enter a number: 5
What is 10 x 3
Enter a number: 30
You got 7 correct out of 10
My Work for Product Only (Success):
import random
def askNum():
while(1):
try:
userInput = int(input("Enter a number: "))
break
except ValueError:
print("Incorrect Input!")
return userInput
def askQuestion():
x = random.randint(1, 100)
y = random.randint(1, 100)
print("What is " + str(x) + " x " +str(y))
u = askNum()
if (u == x * y):
return 1
else:
return 0
amount = 10
correct = 0
for i in range(amount):
correct += askQuestion()
print("You got %d correct out of %d" % (correct, amount))
My Currently Work: (I am working to add sum and difference like the expected output
UPDATED: After the expected output works well with product so I am trying to add new random int for z with 1-3 which means I am using with 1 is for product, 2 is for sum and 3 is difference by using if-statement by given random select. I am struggle at this is where I stopped and figure it out how to do math random because I am new to Python over a month now.
import random
def askNum():
while(1):
try:
userInput = int(input("Enter a number: "))
break
except ValueError:
print("Incorrect Input!")
return userInput
def askQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
z = random.randint(1, 4)
print("What is " + str(x) + " "+ str(z)+ " " +str(y))
u = askNum()
if (z == 1):
x * y #product
return 1
else if (z == 2):
x + y #sum
return 1
else if (z == 3):
x / y #difference
return 1
else
return 0
amount = 10
correct = 0
for i in range(amount):
correct += askQuestion()
print("You got %d correct out of %d" % (correct, amount))
OUTPUT:
md35#isu:/u1/work/python/mathquiz> python3 mathquiz.py
File "mathquiz.py", line 27
if (z == 1):
^
IndentationError: unexpected indent
md35#isu:/u1/work/python/mathquiz>
With this currently output, I double checked with corrected Python formatting and everything are sensitive, and still the same as running output. Any help would be more appreciated with explanation. (I hope my English is okay to understand since i'm deaf) I have started this since on Saturday, than expected on time to meet.
Your problem is that python 3 does not allow mixing spaces and tabs for indentation. Use an editor that displays the whitespace used (and fix manually) or one that replaces tabs into spaces. It is suggested to use 4 spaces for indentation - read PEP-0008 for more styling tips.
You can make your program less cryptic if you use '+','-','*','/' instead of 1,2,3,4 to map your operation: ops = random.choice("+-*/") gives you one of your operators as string. You feed it into a calc(a,ops,b) function and return the correct result from it.
You can also shorten your askNum and provide the text to print.
These could look like so:
def askNum(text):
"""Retunrs an integer from input using 'text'. Loops until valid input given."""
while True:
try:
return int(input(text))
except ValueError:
print("Incorrect Input!")
def calc(a,ops,b):
"""Returns integer operation result from using : 'a','ops','b'"""
if ops == "+": return a+b
elif ops == "-": return a-b
elif ops == "*": return a*b
elif ops == "/": return a//b # integer division
else: raise ValueError("Unsupported math operation")
Last but not least you need to fix the division part - you allow only integer inputs so you can also only give division problems that are solveable using an integer answer.
Program:
import random
total = 10
correct = 0
nums = range(1,11)
for _ in range(total):
ops = random.choice("+-*/")
a,b = random.choices(nums,k=2)
# you only allow integer input - your division therefore is
# limited to results that are integers - make sure that this
# is the case here by rerolling a,b until they match
while ops == "/" and (a%b != 0 or a<=b):
a,b = random.choices(nums,k=2)
# make sure not to go below 0 for -
while ops == "-" and a<b:
a,b = random.choices(nums,k=2)
# as a formatted text
result = askNum("What is {} {} {} = ".format(a,ops,b))
# calculate correct result
corr = calc(a,ops,b)
if result == corr:
correct += 1
print("Correct")
else:
print("Wrong. Correct solution is: {} {} {} = {}".format(a,ops,b,corr))
print("You have {} out of {} correct.".format(correct,total))
Output:
What is 8 / 1 = 3
Wrong. Correct solution is: 8 / 1 = 8
What is 5 - 3 = 3
Wrong. Correct solution is: 5 - 3 = 2
What is 4 - 2 = 3
Wrong. Correct solution is: 4 - 2 = 2
What is 3 * 1 = 3
Correct
What is 8 - 5 = 3
Correct
What is 4 / 1 = 3
Wrong. Correct solution is: 4 / 1 = 4
What is 8 * 7 = 3
Wrong. Correct solution is: 8 * 7 = 56
What is 9 + 3 = 3
Wrong. Correct solution is: 9 + 3 = 12
What is 8 - 1 = 3
Wrong. Correct solution is: 8 - 1 = 7
What is 10 / 5 = 3
Wrong. Correct solution is: 10 / 5 = 2
You have 2 out of 10 correct.
def askQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
z = random.randint(1, 4)
print("What is " + str(x) + " "+ str(z)+ " " +str(y))
u = askNum()
if (z == 1):
x * y #product
return 1
elif (z == 2):
x + y #sum
return 1
elif (z == 3):
x / y #difference
return 1
else:
return 0
Write your block like this your u = askNum() and next if loop should be on same vertical line.
To Generate n number of random number you can use
random.sample(range(from, to),how_many_numbers)
User this as reference for more info on random
import random
low=0
high=4
n=2 #no of random numbers
rand = random.sample(range(low, high), n)
#List of Operators
arithmetic_operators = ["+", "-", "/", "*"];
operator = random.randint(0, 3)
x = rand[0];
y = rand[1];
result=0;
# print(x, operator, y)
if (operator == 0):
result = x + y# sum
elif(operator == 1):
result = x - y# difference
elif(operator == 2):
result= x / y#division
else :
result=x * y# product
print("What is {} {} {}? = ".format(x,arithmetic_operators[operator],y))
The following stores a random number(int)
operator = random.randint(0, 3)
to compare it with the list for operators.
Example: operator = 2
elif(operator == 2):
result= x / y#division
than this code will executed and because operator=2, 3rd element from list(/) will be selected
Output:
What is 3 / 2?

finding emrips with python, what am i doing wrong?

An Emirp is a prime number whose reversal is also a prime. For
example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps.
Write a program that prints out the first N emirps, five on each line.
Calculate the first N emirp (prime, spelled backwards) numbers, where
N is a positive number that the user provides as input.
Implementation Details
You are required to make use of 2 functions (which you must write).
isPrime(value) # Returns true if value is a prime number. reverse
(value) # Returns the reverse of the value (i.e. if value is 35,
returns 53). You should use these functions in conjunction with logic
in your main part of the program, to perform the computation of N
emirps and print them out according to the screenshot below.
The general outline for your program would be as follows:
Step 1: Ask user for positive number (input validation) Step 2:
Initialize a variable Test to 2 Step 3: While # emirps found is less
than the input:
Call isPrime with Test, and call it again with reverse(Test).
If both are prime, print and increment number of emirps found. Test++ Hint - to reverse the number, turn it into a string and then
reverse the string. Then turn it back into an int!
MY CODE:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
count = 0
while(test < value):
if( value % test == 0):
count+=count
test+=test
if(count == 0):
return 1
else:
return 0
def reverse(value):
reverse = 0
while(value > 0):
reverse = reverse * 10 + (value % 10)
value = value / 10
return reverse
n = float(input("Please enter a positive number: "))
while(count < n):
i+=i;
if(isPrime(i)):
if(isPrime(reverse(i))):
print("i" + "\n")
count+=count
if((count % (5)) == 0 ):
print("\n")
where are the mistakes?
UPDATED CODE BUT STILL NOT RUNNING:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
def reverse(value):
return int(str(value)[::-1])
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
There are a lot of issues with your code. I altered the function isPrime. There is among other no need for count here and if you want to increment test by 1 every loop use test +=1:
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
return 1
There is an easy way to reverse digits by making value a string in reversed order and to convert this into an integer:
def reverse(value):
return int(str(value)[::-1])
You among other have to assign the input to i. n in your code is a constant 5. You have to increment i by one in any condition and increment the count by one if i is an emirp only:
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
def emrip_no(num):
i=0
j=0
for i in range(1,num+1):
a=0
for j in range(1,i+1):
if(i%j==0):
a+=1
if(a==2):
print("Number is a prime number")
k=0
l=0
rv=0
while(num!=0):
r=num%10
rv=(rv*10)+r
num=num//10
print("It's reverse is: ",rv)
for k in range(1,rv+1):
b=0
for l in range(1,k+1):
if(k%l==0):
b+=1
if(b==2):
print("It's reverse is also a prime number")
else:
print("It's reverse is not a prime number")
n=int(input("Enter a number: "))
emrip_no(n)

working with negative numbers in python

I am a student in a concepts of programming class. The lab is run by a TA and today in lab he gave us a real simple little program to build. It was one where it would multiply by addition. Anyway, he had us use absolute to avoid breaking the prog with negatives. I whipped it up real quick and then argued with him for 10 minutes that it was bad math. It was, 4 * -5 does not equal 20, it equals -20. He said that he really dosen't care about that and that it would be too hard to make the prog handle the negatives anyway. So my question is how do I go about this.
here is the prog I turned in:
#get user input of numbers as variables
numa, numb = input("please give 2 numbers to multiply seperated with a comma:")
#standing variables
total = 0
count = 0
#output the total
while (count< abs(numb)):
total = total + numa
count = count + 1
#testing statements
if (numa, numb <= 0):
print abs(total)
else:
print total
I want to do it without absolutes, but every time I input negative numbers I get a big fat goosegg. I know there is some simple way to do it, I just can't find it.
Perhaps you would accomplish this with something to the effect of
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
a = int(split_text[0])
b = int(split_text[1])
# The last three lines could be written: a, b = map(int, text.split(','))
# but you may find the code I used a bit easier to understand for now.
if b > 0:
num_times = b
else:
num_times = -b
total = 0
# While loops with counters basically should not be used, so I replaced the loop
# with a for loop. Using a while loop at all is rare.
for i in xrange(num_times):
total += a
# We do this a times, giving us total == a * abs(b)
if b < 0:
# If b is negative, adjust the total to reflect this.
total = -total
print total
or maybe
a * b
Too hard? Your TA is... well, the phrase would probably get me banned. Anyways, check to see if numb is negative. If it is then multiply numa by -1 and do numb = abs(numb). Then do the loop.
The abs() in the while condition is needed, since, well, it controls the number of iterations (how would you define a negative number of iterations?). You can correct it by inverting the sign of the result if numb is negative.
So this is the modified version of your code. Note I replaced the while loop with a cleaner for loop.
#get user input of numbers as variables
numa, numb = input("please give 2 numbers to multiply seperated with a comma:")
#standing variables
total = 0
#output the total
for count in range(abs(numb)):
total += numa
if numb < 0:
total = -total
print total
Try this on your TA:
# Simulate multiplying two N-bit two's-complement numbers
# into a 2N-bit accumulator
# Use shift-add so that it's O(base_2_log(N)) not O(N)
for numa, numb in ((3, 5), (-3, 5), (3, -5), (-3, -5), (-127, -127)):
print numa, numb,
accum = 0
negate = False
if numa < 0:
negate = True
numa = -numa
while numa:
if numa & 1:
accum += numb
numa >>= 1
numb <<= 1
if negate:
accum = -accum
print accum
output:
3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129
How about something like that? (Uses no abs() nor mulitiplication)
Notes:
the abs() function is only used for the optimization trick. This snippet can either be removed or recoded.
the logic is less efficient since we're testing the sign of a and b with each iteration (price to pay to avoid both abs() and multiplication operator)
def multiply_by_addition(a, b):
""" School exercise: multiplies integers a and b, by successive additions.
"""
if abs(a) > abs(b):
a, b = b, a # optimize by reducing number of iterations
total = 0
while a != 0:
if a > 0:
a -= 1
total += b
else:
a += 1
total -= b
return total
multiply_by_addition(2,3)
6
multiply_by_addition(4,3)
12
multiply_by_addition(-4,3)
-12
multiply_by_addition(4,-3)
-12
multiply_by_addition(-4,-3)
12
Thanks everyone, you all helped me learn a lot. This is what I came up with using some of your suggestions
#this is apparently a better way of getting multiple inputs at the same time than the
#way I was doing it
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
numa = int(split_text[0])
numb = int(split_text[1])
#standing variables
total = 0
if numb > 0:
repeat = numb
else:
repeat = -numb
#for loops work better than while loops and are cheaper
#output the total
for count in range(repeat):
total += numa
#check to make sure the output is accurate
if numb < 0:
total = -total
print total
Thanks for all the help everyone.
Try doing this:
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
ans = num1*num2
if num1 > 0 or num2 > 0:
print(ans)
elif num1 > 0 and num2 < 0 or num1 < 0 and num1 > 0:
print("-"+ans)
elif num1 < 0 and num2 < 0:
print("Your product is "+ans)
else:
print("Invalid entry")
import time
print ('Two Digit Multiplication Calculator')
print ('===================================')
print ()
print ('Give me two numbers.')
x = int ( input (':'))
y = int ( input (':'))
z = 0
print ()
while x > 0:
print (':',z)
x = x - 1
z = y + z
time.sleep (.2)
if x == 0:
print ('Final answer: ',z)
while x < 0:
print (':',-(z))
x = x + 1
z = y + z
time.sleep (.2)
if x == 0:
print ('Final answer: ',-(z))
print ()

Categories

Resources