I need to compare 2 numbers,
if they have the same sign (positive or negative), print "same sign".
If they have a different sign, print "different sign"
The catch is, I need to do it without the use of < or > (greater than or less than) and only using addition and subtraction of num1 and num2. You can also use 0 (no other numbers).
Here is what it looks like with the <>s:
num1 = int(input("enter num1: "))
num2 = int(input("enter num2: "))
if num1 < 0 and num2 < 0: print("same sign")
if num1 > 0 and num2 > 0: print("same sign")
if num1 > 0 and num2 < 0: print("different sign")
if num1 < 0 and num2 > 0: print("different sign")
You can check whether two numbers x and y have the same sign by validating the following:
same_sign = abs(x) + abs(y) == abs(x + y)
Well, mb not the prettiest solution, but have a check
#!/usr/bin/env python3
num1 = 10
num2 = 2
if ((num1 & 0x800000) == (num2 & 0x800000)):
print('same sign')
else:
print('different sign')
the trick here, that int type in Python takes 24 bits = 3 bytes. Signed types have 1 in the most significant position. 0x800000 = 1000 0000 0000 0000 0000 0000b. If both nums have this bit - same sign, otherwise - different.
A little late here, but this is what I figured out.
def sameSign(x, y)
if (x*y > 0):
print("same sign")
else:
print("different sign")
Negative times negative and positive time positive both always give positive. Negative time positive gives negative. If you pass in zero, you always get false, so you could add a check.
You can use subtract the number by itself and if the result equal to zero in the two numbers or non equal to zero is the two numbers then it is the same sign, else different sign, here is the code:
num1 = int(input("enter num1: "))
num2 = int(input("enter num2: "))
if num1 + 0 - num1 == 0 and num2 + 0 - num2 == 0: print("same sign") # +
elif num1 + 0 - num1 != 0 and num2 + 0 - num2 != 0: print("same sign") # -
else: print("different sign")
Related
I gotta calculate the sum of digits of the number. It works for positive numbers but not for negative ones. What should i add here?
n = int(input("Input a number: "))
suma = 0
while(n > 0):
if n > 0:
last = n % 10
suma += last
n = n // 10
print("The sum of digits of the number is: ", suma)
Input/Output
Input a number: -56
The sum of digits of the number is: 0
The simple fix is to do n = abs(n) then it will work with your code.
And if you really *lazy* you could simplify the approach to this:
n = abs(n)
sum_digit = sum(int(x) for x in str(n)) # are we cheating? ;-)
When you pass a negative number, the first while loop's condition while(n > 0): will be false, hence the following code will never be executed and sum's value will never be updated and remain 0.
Use abs() function to get absolute value.
n = abs(int(input("Input a number: ")))
suma = 0
while n > 0:
if n > 0:
last = n % 10
suma += last
n = n // 10
print("The sum of digits of the number is: ", suma)
Maybe you could utilize abs and divmod:
def get_int_input(prompt: str) -> int:
while True:
try:
return int(input(prompt))
except ValueError:
print("Error: Enter an integer, try again...")
def get_sum_of_digits(num: int) -> int:
num = abs(num)
total = 0
while num:
num, digit = divmod(num, 10)
total += digit
return total
def main() -> None:
n = get_int_input("Input an integer number: ")
sum_of_digits = get_sum_of_digits(n)
print(f"The sum of digits of the number is: {sum_of_digits}")
if __name__ == "__main__":
main()
Example Usage 1:
Input an integer number: 123456789
The sum of digits of the number is: 45
Example Usage 2:
Input an integer number: -56
The sum of digits of the number is: 11
Example Usage 3:
Input an integer number: asdf
Error: Enter an integer, try again...
Input an integer number: 2.3
Error: Enter an integer, try again...
Input an integer number: -194573840
The sum of digits of the number is: 41
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))
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
This is my python code: Only output that i get in the end is "True"
Why am i not receiving output for others? Please help.
I am using jupyter notebook on visual studio code. Kernel: Python 3.9 64-bit
# RELATIONAL OPERATORS
num1 = 10
num2 = 0
num3 = 10
str1 = "good"
str2 = "life"
# Equals to
num1 == num2
str1 == str2
# Not equal to
num1 != num2
str1 != str2
num1 != num3
# Greater Than
num1 > num2
str1 > str2
# Less Than
num1 < num3
str2 < str1
# Greater than or equal to
num1 >= num2
num2 >= num3
str1 >= str2
#Less then or equal to
num1 <= num2
num2 <= num3
str1 <= str2
You'll have to wrap each of the statements in print()
num1 = 10
num2 = 0
num3 = 10
str1 = "good"
str2 = "life"
print(num1 == num2)
print(str1 == str2)
# so on and so forth
I tried to find the nth term of the Fibonacci series in both Python and Ruby languages, but I could not get the expected output. Can anyone please help me?
My question is that they would give me first and second term with the nth term to find and I've to find my nth term.
My program in Python:
num1=int(raw_input())
num2=int(raw_input())
num=int(raw_input())
for i in range(3,num+1):
sum=num1+num2
num1=num2
num2=sum
print sum
My program in Ruby:
num1=gets.to_i
num2=gets.to_i
num=gets.to_i
for i in 3..num:
sum=num1+num2
num1=num2
num2=sum
print sum
Sample Input
0 1 5
Sample Output
5
In Ruby
alpha = (1 + Math.sqrt(5)) / 2
beta = (1 - Math.sqrt(5)) / 2
((alpha ** n - beta ** n) / Math.sqrt(5)).round
Using Python.
You have two consecutive numbers num1 and num2 of the fibonacci sequence. Let's call the position of num2 i. You want to find the term of the sequence at the position i+n(where n in your case is num). Following your code, this works:
num1 = int(raw_input())
num2 = int(raw_input())
num = int(raw_input())
for i in range(1, num+1):
sum = num1 + num2
num1 = num2
num2 = sum
print sum
Input
0 1 5
Output
8
If you want to simply find the nth term of the sequence you can use this function:
def f(n):
num1, num2 = 0, 1
for _ in range(1, n+1):
num1, num2 = num2, num1+num2
return num2
The Ruby version is close:
num1=gets.to_i
num2=gets.to_i
num=gets.to_i
for i in 3..num # no :
sum=num1+num2
num1=num2
num2=sum
end # explicit end
print sum