repeat = "y"
while repeat == "y":
#First get the two integers from the user
a = int(input("Enter the first integer: "))
b = int(input("Enter the second integer: "))
#Start the answer with 0
answer = 0
print("A", "B")
print("---")
print(a, b)
#run loop until b is not zero
while b != 0:
#loop while 'b' is odd number
if (b % 2 != 0):
answer = answer + a
print(a*2, b//2)
a = a*2 #double every 'a' integers
b = b//2 #halve the 'b' integers
#loop while 'b' is even number
elif (b % 2 == 0):
print(a*2, b//2)
a = a*2 #double every 'a' integers
b = b//2 #halve the 'b' integers
print("The product is {}.".format(answer))
repeat = input("Would you like to repeat? (y/n)")
print("Goodbye!")
I am writing a program that uses Ancient Egyptian method to multiply. My program works for positive numbers but not negative. How do I fix it so that if both inputted values of user are negative. My result should give the product of any two positive, negative or one negative and positive number. My current program gives the product for any two positive values, or negative a value and positive b value. However, when user enters a negative b value, it produces infinite outputs.
The issue is with the floor division b//2, when b is negative the result will be the lower integer, so -0.5 will be rounded to -1. To avoid it cast to an int a regular division b = int(b / 2).
After removing duplicate code the while loop looks like that
while b != 0:
if b % 2 != 0:
answer = answer + a
print(a * 2, int(b / 2))
a = a * 2
b = int(b / 2)
Edit
To get the correct sign you can check the expected sign after getting the numbers and multiple by 1 or -1 at the end. Since you only check a for the answer you need to work on a positive a
....
answer = 0
sign = 1 if a * b > 0 else -1
a = abs(a)
while b != 0:
....
print("The product is {}.".format(answer * sign))
Welcome to Stack Overflow!!
This is what the program returned when I used -2 on the second integer (b).
A B
---
1 -2
2 -1
4 -1
8 -1
16 -1
If you notice, B stays on -1, while A starts increasing *2 and it does indifinitely because the while loop doesn't break.
Let's look at the code
while b != 0:
#loop while 'b' is odd number
if (b % 2 != 0):
answer = answer + a
print(a*2, b//2)
a = a*2 #double every 'a' integers
b = b//2 #halve the 'b' integers
#loop while 'b' is even number
elif (b % 2 == 0):
print(a*2, b//2)
a = a*2 #double every 'a' integers
b = b//2 #halve the 'b' integers
So on the if section, you do a=a*2 and b=b//2 since b%2!=0 (-1%2 is -1). However, for the while to break, you need to get b=0, and you get that by doing b=b//2. The problem, as Guy said before, is that when you get b=-1 (as you saw on my example), doing -1//2 will give you -1, instead of the supposed 0 that you'll get if you do 1//2. Since you won't get b=0, the program never stops multiplying.
The solution is simple, as guy mentioned, use b=int(b/2)
EDIT for the negative numbers
The reason it gives you the wrong sign when you are using multiplication is this instruction
while b != 0:
#loop while 'b' is odd number
if (b % 2 != 0):
answer = answer + a #<--------------- THE INSTRUCTION
a = a*2 #double every 'a' integers
# b = b//2 #halve the 'b' integers
b = int(b/2)
print(a, b)
answer = answer + a #<--------------- THE INSTRUCTION
since you get your answer by just adding up A, you will have these two wrong scenarios
----> a positive and b negative ->gives you positive (the sign of A) when it should be negative
----> a negative and b negative -> gives you negative (the sign of A) when it should be positive
I tried to find on google how you handled negative numbers with the egyptian method but i didn't find anything, so I guess you can handle that issue with whichever method you prefer.
An alternative to Guy method is multiplying the sign (1 or -1) to the result depending of b, not the multiplication
#------------------Your code-------------------------
#Start the answer with 0
answer = 0
print("A", "B")
print("---")
print(a, b)
#run loop until b is not zero
#------------------The fix proposed-------------------------
#Start the answer with 0
answer = 0
sign = 1 if b > 0 else -1 #---------> the fix
print("A", "B")
print("---")
print(a, b)
#run loop until b is not zero
and at the end, you multiply the sign with the general answer
#------------------Your code-------------------------
elif (b % 2 == 0):
print(a*2, b//2)
a = a*2 #double every 'a' integers
b = b//2 #halve the 'b' integers
print("The product is {}.".format(answer))
repeat = input("Would you like to repeat? (y/n)")
print("Goodbye!")
#------------------The fix proposed-------------------------
elif (b % 2 == 0):
a = a*2 #double every 'a' integers
b = int(b/2) #---->the previous fix to your first problem
print(a,b)
# b = b//2 #halve the 'b' integers
answer=answer*sign #---->The another fix: the multiplication i mentioned
print("The product is {}.".format(answer))
repeat = input("Would you like to repeat? (y/n)")
print("Goodbye!")
With that, you should have the signs working properly
btw, the reason I changed the print insruction that you used to just print (a,b) at the end of the operation of the if sentence is to avoid redundant operations on the program.
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
Consider:
Enter image description here
Input: 20
17
999997
Output: 2^2 * 5
17
757 * 1321
My code:
a = int(input())
# Find the factors first
for i in range(2, a+1):
s = 0
b = a
d = 0
# See if it is a prime number
if a%i == 0:
for x in range(1, i+1):
if a%x == 0:
d = d + x
if (d-1)/i == 1:
d = 0
print(i)
else:
s = 0
b = a
d = 0
continue
d = 0
# I will see how many prime numbers
while(b>0):
if (b/i)%1 == 0:
s = s + 1
b = b/i
else:
b = 0
if b == 1:
b = 0
print(s)
I will find the factors first, and then see if it is a prime number. If so, I will see how many prime numbers it is
if i input 12, it outputs 2 2
Enter link description here
I believe you need the output of the following.
import math
a = int(input())
while (a % 2 == 0):
print(2)
a = int(a/2)
while (a % 3 == 0):
print(3)
a = int(a/3)
for i in range(5, math.ceil(math.sqrt(a)), 6):
while (a % i == 0):
print(i)
a = int(a / i)
while (a % (i + 2) == 0):
print(i + 2)
a = int(a / (i + 2))
if (a > 3):
print(a)
This will give you the prime factors for a given number. As I can understand, it is what you are looking for.
a = int(input("Enter a number:"))
for i in range(2, a + 1):
if a % i != 0:
continue
# SETTING THE DEFAULT VALUES AT THE BEGINNING OF EVERY ITERATION OF THE LOOP
s = 0
b = a
d = 0
for x in range(1, i + 1):
if b % x == 0:
d = d + x
if (d - 1) / i == 1:
d = 0
print(i)
else:
# s = 0 # NO LONGER NEEDED, AS WE RESET THEM AT THE BEGINNING OF THE LOOP
# b = a
# d = 0
continue
while b > 0:
if (b / i) % 1 == 0:
s = s + 1
b = b / i
else:
b = 0
if b == 1:
b = 0
print(s)
a /= i**s # THIS LINE IS IMPORTANT
You were close. You forgot to set the default values at the beginning of every iteration of the loop, so they sometimes didn't have the right values ; and you should set a to a different value by dividing it by the factor you found (i**s, so i to the power of s).
As has been mentioned, your code also follows an odd coding style. I suggest you stop putting newlines between each statement, and start separating operators with spaces (example: range(3+5) is bad, range(3 + 5) is more readable)
You are using too many loops here and that's why you are getting too much confused. Here is the code which serve the same purpose (if I understand your problem correctly)
a = int(input("Enter a number: "))
i = 2
factors = []
while i <= a:
if (a%i) == 0:
factors.append(i)
a = a/i
else:
i = i + 1
print(factors)
here I am returning a list, if you want you can change the type accordingly.
Here are the inputs/outputs:
Enter a number: 17
[17]
Enter a number: 100
[2, 2, 5, 5]
Enter a number: 12
[2, 2, 3]
I am trying to make a python program that will find keith numbers. If you don't what keith numbers are, here is a link explaining them:
Keith Numbers - Wolfram MathWorld
My code is
from decimal import Decimal
from time import sleep
activator1 = 1
while (activator1 == 1):
try:
limit = int(raw_input("How many digits do you want me to stop at?"))
activator1 = 0
except ValueError:
print "You did not enter an integer"
limitlist = []
activator2 = 1
while (activator2 <= limit):
limitlist.append(activator2)
activator2 += 1
print limitlist
add1 = 0
add = 0
count = 9
while 1:
sleep (0.1)
numbers = list(str(count))
for i in limitlist:
if (i > 0) & (add < count):
add = sum(Decimal(i) for i in numbers)
lastnumber = int(numbers[-1])
add1 = lastnumber+int(add)
numbers.reverse()
numbers.pop()
numbers.append(add1)
print add1
print add
print count
print numbers
if (add1 == count):
print"________________________________"
print add1
print count
elif (i > 0) & (add > count):
count += 1
break
It doesn't output any errors but it just outputs
18
9
9
[18]
Could someone please tell me why it doesn't just repeatedly find Keith numbers within the number of integers range?
You have it in front of you:
add1 = 18
add = 9
count = 9
numbers = [18]
You're in an infinite loop with no output. You get this for once. After this, i runs through the values 1, 2, and 3. Each time through the for loop, all three if conditions are False. Nothing changes, you drop out of the for loop, and go back to the top of the while. Here, you set numbers back to ['9'], and loop forever.
I suggest that you learn two skills:
Basic debugging: learn to single-step through a debugger, looking at variable values. Alternately, learn to trace your logic on paper and stick in meaningful print statements. (My version of this is at the bottom of this answer.)
Incremental programming: Write a few lines of code and get them working. After you have them working (test with various input values and results printed), continue to write a few more. In this case, you wrote a large block of code, and then could not see the error in roughly 50 lines. If you code incrementally, you'll often be able to isolate the problem to your most recent 3-5 lines.
while True:
# sleep (0.1)
numbers = list(str(count))
print "Top of while; numbers=", numbers
for i in limitlist:
print "Top of for; i =", i, "\tadd =", add, "\tcount =", count, "\tadll =", add1
if (i > 0) & (add < count):
add = sum(Decimal(i) for i in numbers)
lastnumber = int(numbers[-1])
add1 = lastnumber+int(add)
numbers.reverse()
numbers.pop()
numbers.append(add1)
print "add1\t", add1
print "add\t", add
print "count\t", count
print "numbers", numbers
if (add1 == count):
print"________________________________"
print add1
print count
elif (i > 0) & (add > count):
count += 1
print "increment count:", count
break
Prune has already given you good advices! Let's put a little example of what he meant though, let's say you got an algorithm which determine whether n is a keith number or not and also a test loop to print some keith numbers:
def keith_number(n):
c = str(n)
a = list(map(int, c))
b = sum(a)
while b < n:
a = a[1:] + [b]
b = sum(a)
return (b == n) & (len(c) > 1)
N = 5
for i in range(N):
a, b = 10**i, 10**(i + 1)
print("[{0},{1}]".format(a, b))
print([i for i in filter(keith_number, range(a, b))])
print('-' * 80)
such snippet gives you this:
[1,10]
[]
--------------------------------------------------------------------------------
[10,100]
[14, 19, 28, 47, 61, 75]
--------------------------------------------------------------------------------
[100,1000]
[197, 742]
--------------------------------------------------------------------------------
[1000,10000]
[1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909]
--------------------------------------------------------------------------------
[10000,100000]
[31331, 34285, 34348, 55604, 62662, 86935, 93993]
--------------------------------------------------------------------------------
Wow, that's awesome... but wait, let's say you don't understand the keith_number function and you want to explore a little bit the algorithm in order to understand its guts. What about if we add some useful debug lines?
def keith_number(n):
c = str(n)
a = list(map(int, c))
b = sum(a)
print("{0} = {1}".format("+".join(map(str, a)), b))
while b < n:
a = a[1:] + [b]
b = sum(a)
print("{0} = {1}".format("+".join(map(str, a)), b))
return (b == n) & (len(c) > 1)
keith_number(14)
print '-' * 80
keith_number(15)
that way you'll be able to trace the important steps and the algorithm will make sense in your head:
1+4 = 5
4+5 = 9
5+9 = 14
--------------------------------------------------------------------------------
1+5 = 6
5+6 = 11
6+11 = 17
Conclusion: I'd advice you learn how to debug your own code instead asking strangers about it ;-)
I hope this solves your problem , and also I'm actually new here , so basically I solved it with the use of lists I hope u can understand :)
def kieth(n):
n1 = n[::-1]
f = [0]
[f.insert(0, int(x)) for x in n1]
for x in range(1, int(n)):
if f[-2] == int(n):
break
else:
f.insert(-1, sum(f[-abs(len(n1)) - 1:-1]))
return True if int(n) in f else False
n = input(" enter a number ")
print("is a kieth number " if kieth(str(n)) else "not a keith")
I have only just started to learn python as my first language and whilst i worked out the code for fizzbuzz, i cannot for the life of me get it to do the items below. I also want it to print horizontally instead of vertically. Any help would be great (heads spinning).
Create a function which does this.
For example
fizzbuzz(20)
would print
1,2,fizz,4,buzz,fizz,7,8,fizz,buzz,11,fizz,13,14,fizzbuzz,16,17,fizz,19,buzz
def fizzbuzz(n):
for x in range (101):
if x%3==0 and x%5==0:
print("fizz buzz")
elif x%3==0:
print('fizz')
elif x%5==0:
print('buzz')
else:
print (x)
def main():
print(fizzbuzz(20))
Shorter yet:
for n in range(100):
print("Fizz"*(not n % 3) + "Buzz"*(not n % 5) or n)
Yes, but why?
To understand this, let's look at the parts separately.
"Fizz"*(not n % 3)
In Python, we can "multiply" strings, so "a"*3 would result in "aaa". You can also multiply a string with a boolean: "a" * True is "a", whereas "a" * False is an empty string, "". That's what's happening to our "Fizz" here. When n % 3 == 0 (ie. n is 3, 6, 9, ...), then not n % 3 will be the same as not 0, which is True. Conversely, when n is 1, 2, 4, 5, 7, ... then n % 3 will be either 1 or 2, and not n % 3 will be false. In Other words, whenever n is divisible by 3, the term "Fizz"*(not n % 3) will multiply the string "Fizz" by True, and when it's not, it will multiply by False, resulting in an empty string.
The same logic applies to the next part, "Buzz"*(not n % 5). It'll give us an empty string when n is not divisible by 5, and the string "Buzz" when it is.
Now we're adding those two things together:
"Fizz"*(not n % 3) + "Buzz"*(not n % 5)
When n is neither divisible by 3 nor 5, this will be adding two empty strings together (ie. "" + ""), which will of course give us another empty string. In that case, the whole print statement reads print("" or n). Since an empty string is False-y, it will print our number n. If n is divisible by 3 (but not 5), this would be print("Fizz" or n), and since "Fizz" is Truthy, it will just print that and omit the number.
Bonus points
Or, if you really want to impress your interviewer,
for n in range(100):
print("FizzBuzz"[n%-3&4:12&8-(n%-5&4)] or n)
Collect the items into a list. Then print the list at the end of function. You can join the items together with a comma in between using ', '.join(...).
def fizzbuzz(n):
result = []
for x in range(1, n+1):
if x % 3 == 0 and x % 5 == 0:
result.append("fizz buzz")
elif x % 3 == 0:
result.append('fizz')
elif x % 5 == 0:
result.append('buzz')
else:
result.append(str(x))
return result
def main():
print(', '.join(fizzbuzz(20)))
main()
It's good to also know that print(..., end=', ') would print "horizontally" with a comma and space at the end, and this would almost solve your problem except that the very last item would also have a comma and space at the end, which is not what you desire.
It's usually a good idea to (1) separate printing from computing, (2) make functions reusable. You often want to compute more frequently than print. In the future you may wish to pass the computation on to some other function before you print. So functions that immediate print are not as useful. So I recommend taking the print statements out of fizzbuzz.
You could return the string ', '.join(result), but how useful would that be? The list result might be (in the future) more useful for further processing, so I chose to return result. The printing I left for the main function.
def fizzbuzz(numbers, fizz, buzz):
x = ['Fizzbuzz' if x % fizz == 0 and x % buzz == 0 else 'Fizz' if x % fizz == 0 else 'Buzz' if x % buzz == 0 else x for x in numbers]
return x
Slightly more elegant
def fizzbuzz(n):
for x in range(1,n+1):
if not x % 15:
yield 'fizz buzz'
elif not x % 3:
yield 'fizz'
elif not x % 5:
yield 'buzz'
else:
yield x
if __name__ == "__main__":
print ','.join(fizzbuzz(20))
I'm a novice coder so some of the answers I did not understand or it did not seems to directly apply to my problem. This answer incorporates Fizz_Buzz as a variable and the range of x is determined by the user. I looked at the above solutions and came up with this:
def Fizz_Buzz(x):
for x in range (0,x):
if x % 3 == 0 and x % 5 == 0:
print('FizzBuzz')
elif x % 3 == 0:
print('Fizz')
elif x % 5 == 0:
print ('Buzz')
else:
print (x)
You can add end=', ' to print in order to print on the same line, with whatever character you want separating the values.
class FizzBuzz:
#staticmethod
def fizz_buzz(n):
if n % 15 == 0:
return 'FizzBuzz'
elif n % 3 == 0:
return 'Fizz'
elif n % 5 == 0:
return 'Buzz'
else:
return str(n)
def __str__(self, rng):
[print(self.fizz_buzz(n), end=', ') for n in range(1, rng + 1)]
But it leaves , at the end. Instead:
def __str__(self, rng):
print(', '.join(self.fizz_buzz(n) for n in range(1, rng + 1)))
one more :) just for fun :)
get_index = lambda i: bool(i%3)+2*bool(i%5) if i !=0 else 3
afb = lambda x: ('fizzbuzz','buzz', 'fizz', str(x))[get_index(x)]
fizzbuzz = lambda inpt: print(','.join([ afb(i) for i in inpt ]))
fizzbuzz(range(101))
'0,1,2,fizz,4,buzz,fizz,7,8,fizz,buzz,11,fizz,13,14,fizzbuzz,16,17,fizz,19,buzz,fizz,22,23,fizz,buzz,26,fizz,28,29,fizzbuzz,31,32,fizz,34,buzz,fizz,37,38,fizz,buzz,41,fizz,43,44,fizzbuzz,46,47,fizz,49,buzz,fizz,52,53,fizz,buzz,56,fizz,58,59,fizzbuzz,61,62,fizz,64,buzz,fizz,67,68,fizz,buzz,71,fizz,73,74,fizzbuzz,76,77,fizz,79,buzz,fizz,82,83,fizz,buzz,86,fizz,88,89,fizzbuzz,91,92,fizz,94,buzz,fizz,97,98,fizz,buzz'
i made a fizzbuzz that works for any number and words, so you can do fizzbuzzfuzz if you wanted. i made it in 6 lines (7 if you count the line that runs through the fizzfuzz)
def f(n:int,m:list,w:list):
s=''
for x in m:
if n%x==0: s+=w[m.index(x)]
if s=='': s=n
return s
for i in range(1, 100 +1): print(f(i,[3,5],['Fizz','Buzz']))
def fizzbuzz(num):
if x % 3 == 0 and x % 5 == 0:
return "Fizz Buzz"
elif x % 3 == 0:
return "Fizz"
elif x % 5 == 0:
return "Buzz"
else:
return x
MAXNUM = 100
for x in range (MAXNUM):
print fizzbuzz(x)
I've found the following works well (Python 3):
def fizzbuzz():
for i in range(1,101):
print("Fizz"*(i%3==0)+"Buzz"*(i%5==0) or i)
print (fizzbuzz())
Here's a fun one (obviously not the best for readability, but still kinda fun to think about list comprehensions):
def fizzBuzz():
print(", ".join(["FizzBuzz" if x%15==0 else "Fizz" if x%3 == 0 else "Buzz" if x%5==0 else str(x) for x in range(1,101)]))
Don't forget, 3 and 5 are coprime! So you can check x % 15 instead of (x % 3 and x % 5) for "FizzBuzz".
Yet another one with list comprehension and Python3
def is_mod_zero(num, *div):
return not [d for d in div if num % d is not 0]
def fizz_buzz(num):
if is_mod_zero(num, 3, 5):
return 'FizzBuzz'
if is_mod_zero(num, 3):
return 'Fizz'
if is_mod_zero(num, 5):
return 'Buzz'
return num
if __name__ == "__main__":
for i in range(100):
print(fizz_buzz(i))
def fizzBuzz(n):
for x in range(1, n + 1):
if x % 3 == 0 and x % 5 == 0:
print("fizzbuzz")
elif x % 3 == 0:
print("fizz")
elif x % 5 == 0:
print("buzz")
else:
print(x)
print(fizzBuzz(50))