Finding the additive and multiplicative roots of a number using python - python-3.x

http://www.cs.uni.edu/~diesburg/courses/cs1510_sp15/homework/PA04/index.htm
So I have this assignment. I have been trying to work out the code to find the additive and multiplicative roots of a user given input. I am new to python and know how to work the problem out, but without the tools (coding know how) have been just running in circles for quite a while now. So if anyone could be so kind as to help me figure out the coding. I have tried slicing the list, but keep getting an error if I try to make the string an int and if I leave it as an string it just doesn't seem to run. I know there is probably a way using modulous as well, but have yet to quite master it.
Thank you for any help any of you are able to leave me.
Edit
Here is the code I have so far.
import sys
userStr = input("What number should I use for my \
calculations? ")
userInt = int (userStr)
original = userStr #Save Copy of original value
originalTwo = userStr #Save second Copy of original value
addCount = 0
mulCount = 0
#Stop the program if the integer is less than or equal to 0
while userInt <= 0:
print ("Thanks for playing along!")
sys.exit()
#Use a while loop to repeat the process of splitting an integer into single digits and then adding the individual digits.
print = ("Addition")
while userInt > 9:
userInt = sum(map(int, userStr))
print("New Value: ",userStr)
addCount = addCount + 1
#Use a while loop to repeat the process of splitting an integer into single digits and then multiplying the individual digits.
print = ("Multiplication")
while original > 9:
original = (map (int, original))
print("New Value: ",original)
mulCount = mulCount + 1
#Print the outputs to the screen for the user.
print("For the Integer: ",userInt)
print(" Additive Persistence= ",addCount,", Additive Root= ", userInt)
print(" Multiplicative Persistence= ",mulCount,",
Multiplicative Root= ", original)

Related

I am getting a "Time Limit Exceeded " error in the following code. How to fix that error

The following code is my view of checking whether the sum of a number and it's reverse is a palindrome or not.If the sum is a palindrome then sum will be displayed.Otherwise the process will be repeated until we get a palindrome. When it is set to execute, I am getting a time limit exceeded error.Where do I need to correct the code?
def pal(n1):
temp=n1
rev=0
while(temp>0):
rev=(rev*10)+(temp%10)
temp=temp/10
sum1=n1+rev
temp=sum1
rev=0
while(temp>0):
rev=(rev*10)+(temp%10)
temp=temp/10
if(rev==sum1):
print(sum1)
else:
pal(sum1)
n=int(input())
pal(n)
I expect the output of a number 453 to be 6666.
i.e.
453+354=807 (not a palindrome. So repeat the process)
807+708=1515
1515+5151=6666 (it is a palindrome)
Your problem is that you are checking for while temp > 0: but inside that loop you are using float division: temp=temp/10. So the condition will always hold. For example:
>>> 8/10
0.8
>>> 0.8/10
0.08
What you want is to change your divisions to int division:
>>> 8//10
0
Still you might consider working with strings which is much easier in that case:
def pal(n):
rev_n = str(n)[::-1]
sum_str = str(n + int(rev_n))
while sum_str != sum_str[::-1]:
# print(sum_str)
sum_rev = sum_str[::-1]
sum_str = str(int(sum_str) + int(sum_rev))
print(sum_str)
And with the commented print this gives:
>>> pal(453)
807
1515
6666
Here is one way of doing this using string manipulation, which goes a lot easier than trying to do this with numbers. It is also a more direct translation of what you describe afterwards. (I do not really see the link between your code and your description...)
def is_palindrome(text):
# : approach1, faster for large inputs
# mid_length = len(text) // 2
# offset = 0 if len(text) % 2 else 1
# return text[:mid_length] == text[:-mid_length - offset:-1]
# : approach2, faster for small inputs
return text == text[::-1]
def palindrome_sum(num):
while not is_palindrome(num):
num = str(int(num) + int(num[::-1]))
return num
num = input() # 453
palindrome = palindrome_sum(num)
print(palindrome)
# 6666

Python Collatz Infinite Loop

Apologies if similar questions have been asked but I wasn't able to find anything to fix my issue. I've written a simple piece of code for the Collatz Sequence in Python which seems to work fine for even numbers but gets stuck in an infinite loop when an odd number is enter.
I've not been able to figure out why this is or a way of breaking out of this loop so any help would be greatly appreciate.
print ('Enter a positive integer')
number = (int(input()))
def collatz(number):
while number !=1:
if number % 2 == 0:
number = number/2
print (number)
collatz(number)
elif number % 2 == 1:
number = 3*number+1
print (number)
collatz(number)
collatz(number)
Your function lacks any return statements, so by default it returns None. You might possibly wish to define the function so it returns how many steps away from 1 the input number is. You might even choose to cache such results.
You seem to want to make a recursive call, yet you also use a while loop. Pick one or the other.
When recursing, you don't have to reassign a variable, you could choose to put the expression into the call, like this:
if number % 2 == 0:
collatz(number / 2)
elif ...
This brings us the crux of the matter. In the course of recursing, you have created many stack frames, each having its own private variable named number and containing distinct values. You are confusing yourself by changing number in the current stack frame, and copying it to the next level frame when you make a recursive call. In the even case this works out for your termination clause, but not in the odd case. You would have been better off with just a while loop and no recursion at all.
You may find that http://pythontutor.com/ helps you understand what is happening.
A power-of-two input will terminate, but you'll see it takes pretty long to pop those extra frames from the stack.
I have simplified the code required to find how many steps it takes for a number to get to zero following the Collatz Conjecture Theory.
def collatz():
steps = 0
sample = int(input('Enter number: '))
y = sample
while sample != 1:
if sample % 2 == 0:
sample = sample // 2
steps += 1
else:
sample = (sample*3)+1
steps += 1
print('\n')
print('Took '+ str(steps)+' steps to get '+ str(y)+' down to 1.')
collatz()
Hope this helps!
Hereafter is my code snippet and it worked perfectly
#!/usr/bin/python
def collatz(i):
if i % 2 == 0:
n = i // 2
print n
if n != 1:
collatz(n)
elif i % 2 == 1:
n = 3 * i + 1
print n
if n != 1:
collatz(n)
try:
i = int(raw_input("Enter number:\n"))
collatz(i)
except ValueError:
print "Error: You Must enter integer"
Here is my interpretation of the assignment, this handles negative numbers and repeated non-integer inputs use cases as well. Without nesting your code in a while True loop, the code will fail on repeated non-integer use-cases.
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)
# Program starts here.
while True:
try:
# Ask for input
n = input('Please enter a number: ')
# If number is negative or 0, asks for positive and starts over.
if int(n) < 1:
print('Please enter a positive INTEGER!')
continue
#If number is applicable, goes through collatz function.
while n != 1:
n = collatz(int(n))
# If input is a non-integer, asks for a valid integer and starts over.
except ValueError:
print('Please enter a valid INTEGER!')
# General catch all for any other error.
else:
continue

How to convert an improper fraction to a mixed number, using python

I have to write a program that converts an improper fraction to a mixed number. Prompt the user for the numerator and the denominator, then calculate and display the equivalent mixed number. numerator is 23 and denominator is 6.
This is what I have so far...
num = int(input('Type numerator'))
dem = int(input('Type denominator'))
I'm not exactly sure what the next step is...I know the answer is supposed to be The mixed number is 3 and 5/6.
Assuming that your inputs are always integer values, you can use the divide and mod operators to do this.
The following should work:
a = num // dem
b = num % dem
print 'The mixed number is {} and {}/{}'.format(a, b, dem)
Good question. Here's one solution using Fraction function. Fraction is nice because it reduces fractions. You use floor divide (//) to strip out the whole number and then feed the remaining fraction to Fraction:
From fractions import Fraction
num = int(input('Type numerator'))
dem = int(input('Type denominator'))
Print str(num // dem) + ' and ' + str(Fraction(num%dem,dem)) if num//dem != 0 else str(Fraction(num%dem,dem))
[Python 3.5] (https://docs.python.org/2/library/fractions.html#fractions.Fraction) Extended reading on Fraction. Because you feed it num and dem rather than a pure decimal, it is pretty fail-safe.
This also gets rid of response of '0 and ...' which was bothering me.
Without using fractions module, we have to find the greatest common divider (borrowing gcd function from fractions) reduce our initial fraction and then use brilliant solution from #Jenner Felton
def gcdm(num,dem):
while dem:
num, dem = dem, num%dem
return num
gcd = gcdm(num,dem)
num, dem = num/gcd, dem/gcd
Print "%d and %d/%d" % ((num//dem), (num%dem),dem) if num//dem !=0 else "%d/%d" % (num%dem,dem)
As the other answers point out, you can use the integer division and modulo operators to get the numbers you want.
Another aspect to coding this problem that will make things easier is creating a while loop along with a try, except block for the entry of the improper fraction so that you do not get exceptions.
It would look like this:
while True:
try:
num = int(input('Type numerator'))
break
except:
continue
Split this off into a separate function to make things a bit nicer:
def get_data(message, f = lambda data: data):
'''Prompts the user for data entry.
Function f is applied to data; any exception encountered
results in user being prompted again.
Entry is simply returned if no function is supplied.'''
message = str(message)
while True:
try:
num = f(input(message))
break
except:
continue
return num
num = get_data('Type numerator', int)
den = get_data('Type denominator', int)
Here's my one-liner for obtaining the mixed number:
'%s%s%s' % ('%s ' % (num//den) if num//den != 0 else '', '%s/' % (num%den) if num%den != 0 else '', '%s' % den if num%den != 0 else '')

using a looop to add user input to the set and dict in order discovered

So I'm trying to write a small program that does a few things. First is:
Write a while loop that repeatedly creates a list of words from a line of input from the user. So I did this:
s = input("Please enter a sentence: ")
while True:
pos = 0
for c in s:
if c == " ":
print(s[:pos])
s = s [pos+1:]
break
pos += 1
else:
print(s)
break
I need to add the user inputted words to the set and dict and then display their value in the order in which the program discovered them. I believe I need another loop but I'm not sure. I'm pretty lost at this point and the above is as far as I can seem to come on this program. Any help is appreciated as I am (obviously)new at python.

Binary search code not working

Good afternoon everyone,
I'm trying to sort out names which are already sorted in alphabetical order. I can't figure out why my program isn't working. Any tips or pointers would be nice. Thanks.
def main():
names = ['Ava Fiscer', 'Bob White', 'Chris Rich', 'Danielle Porter', 'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle', 'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']
input('Please enter the name to be searched: ', )
binarySearch
main()
def binarySearch(names):
first = 0
last = len(names) - 1
position = -1
found = False
while not found and first <= last:
middle = (first + last) / 2
if names[middle] == value:
found = True
position = middle
elif arr[middle] > value:
last = middle -1
else:
first = middle + 1
return position
What does it mean that the program isn't working? Is it a syntax error or is the problem in the wrong results?
With the code you pasted, there are several indentation problems, but besides that, lines:
input('Please enter the name to be searched: ', )
binarySearch
are also syntactically incorrect, the comma is redundant and only the function name appearing just like that is plain wrong. If you are interested in the correctness of your algorithm, it seems alright, but the boundaries can always be tricky. My code below is working and syntactically correct, if you find it helpful. (names are numbers, but that is irrelevant in this case)
names = [1,2,4,5,6,8,9]
def bs(n):
start = 0
end = len(names)
while end - start > 0:
m = (start+end)/2
if names[m] == n:
return m
elif n < names[m]:
end = m
else:
start = m + 1
return -1
print (bs(1))
print (bs(6))
print (bs(9))
print (bs(3))
print (bs(10))
print (bs(-8))
Another thing I would like to point out is that this kind of binary search is already in the python standard library, the bisect module. However, if you are writing your own for practice or for any other reason that is just fine.
if you are using python 3.* then you are going to want to change
m = (start+end)/2
to
m = (start+end)//2
When you do /2 it outputs a float in 3.*

Resources