Variable is overwritten in if statement - python

Write a program to read 3 integers from the user, and calculate the sum of the integers. However, if one of the values is the same as another of the values, it should not count towards the sum.
Enter a: 3
Enter b: 3
Enter c: 3
The sum is 3
The correct answer should be 0, however I realise by my first if statement a has been reassigned to 0 and since by that point a!=c for 0!=3, I am stuck on this testcase
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
if a == b:
a = 0
b = 0
elif a == c:
a = 0
c = 0
elif b == c:
b = 0
c = 0
print("The sum is", a + b + c)

you could use collections.Counter and only count the values that appear once:
count = Counter((a, b, c))
s = sum(value for value, quantity in count.items() if quantity == 1)
print(f"The sum is {s}")
the problem with your implementation is that if a == b the other two elifs will never be executed. you need change the elifs to ifs.
then you would test a == c again (after having set a to 0). for that approach to work you would have to use temporary variables instead:
tmp_a, tmp_b, tmp_c = a, b, c
if a == b:
tmp_a, tmp_b = 0, 0
if a == c:
tmp_a, tmp_c = 0, 0
if b == c:
tmp_b, tmp_c = 0, 0
print(f"The sum is {tmp_a + tmp_b + tmp_c}")

The problem is that you reassign 0 to values that could be duplicate of other values. You first need to do the comparison between all values at the same time, and then do single comparison.
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
s = 0
if a == b and a == c:
s = 0
elif a == b:
s = c
elif a == c:
s = b
elif b == c:
s = a
else:
s = a + b + c
print("The sum is ", s)

Related

Arranging Integers using Conditional statements

I was wondering if someone would be able to help me regarding my coding problem. I'm still a beginner and I may have missed something here.
Basically, the instruction says that I need to arrange 3 integers in ascending order.
e.g Input : 5 2 4 ------> Output : 2 4 5
I need to utilize the conditional statements for this. Here is what I've done so far.
a, b, c = input().split()
a = int (a)
b = int (b)
c = int (c)
if a < b and a < c:
smallest = a
elif b < a and b < c:
smallest = b
else:
smallest = c
if a > b and a < c:
middle = a
elif a < b and a > c:
middle = a
elif b > a and b < c:
middle = b
elif b < a and b > c:
middle = b
else:
middle = c
if a > b and a > c:
largest = a
elif b > a and b > c:
largest = b
else:
largest = c
print(smallest, middle, largest)
This is on CodeChum btw, I'm stuck in this because I can't figure out why it doesn't accept the code I did. Basically there are 5 tests that the code needs in order to submit the whole activity. I managed to do test 1-4 but for some reason it fails on test 5.
The problem is that your code does not react well if two numbers are identical. You should replace your strict inequalities with non-strict ones.
a = 3
b = 3
c = 1
if a > b and a < c:
middle = a
elif a < b and a > c:
middle = a
elif b > a and b < c:
middle = b
elif b < a and b > c:
middle = b
else:
middle = c
print(middle) # 1 when it should be 3
As a == b, none of the 4 conditions can be True, and therefore the middle number will always be c.
In order to support the case where a == b, we can add another condition:
elif a == b:
middle = a
else:
middle = c
we can simplify this code by replacing the strict inequalities with non-strict ones (⩽ , <= in Python):
if b <= a < c:
middle = a
elif b >= a > c:
middle = a
elif a < b < c:
middle = b
elif a > b > c:
middle = b
else:
middle = c
We simply said that if a == b, the middle is always a. I also simplified the structure for better readability.
Why don't you simply use sorted function?
This one results in the exact thing you are looking for.
smallest, middle, largest = sorted(map(int, input().split()))
print(smallest, middle, largest)
Note that you don't need the map to int function for this. But you if don't do that, the smallest, middle, largest variables will remain str objects.
As the input is guaranteed to contain exactly 3 numbers (separated by whitespace) you can just do this:
if (inval := input()):
if len(nums := inval.split()) == 3:
try:
lo, mid, hi = sorted(map(int, nums))
print(lo, mid, hi)
except ValueError:
pass

how to sort multiple arguments without using the sort function in python?

my goal is to sort three numbers into a, b, and c, with a being the largest, b being the middle, and c being the smallest. To do this, I'm required to write a function. However, I've tried multiple ways and haven't found a way to allow it to work.
num1 = int(input("input an integer: "))
num2 = int(input("input another integer: "))
num3 = int(input("input another integer: "))
def simple_sort(a,b,c):
if a > b and a > c:
return a
if b < a and b > c:
return b
if c < a and c < b:
return c
a,b,c=simple_sort(num1,num2,num3)
print(a,b,c)
#for it to be correct, when i do print(a,b,c), it should print num1, num2 and num3
#in ascending order
You're only returning one value (a, b, or c) where you need to return a tuple or list.
def simple_sort(a,b,c):
if a < b:
a,b = b,a
# above guarantees that a > b
if c > a:
return (c,a,b)
elif c > b:
return (a,c,b)
else:
return (a,b,c)
values = list(map(int,input("Input three integers separated by spaces: ").split()))
print(simple_sort(*values))

Ascending and descending order in Python 3

Just starting to learn Python and this is my problem:
I am taking input a and b and if a < b then then output is a to b in ascending order. If a > b then the output is in descending order. When I put in a < b it works but it gives me nothing when a >b. This is the code:
a = int(input('input a number for a: '))
b = int(input('input a number for b: '))
numbers = list(range(a, b + 1))
if a < b:
print(numbers)
else:
numbers.sort(reverse=True)
print(numbers)
This is the output when a > b:
input a number for a: 10
input a number for b: 1
[]
Process finished with exit code 0
When a is 10 and b is 2 your code is doing:
>>> numbers = list(range(10, 2))
>>> numbers
[]
Maybe you want to do:
numbers = list(range(min(a, b), max(a, b) + 1))
Okay so what you want to do is this....
a = int(input('input a number for a: '))
b = int(input('input a number for b: '))
list = []
if a > b:
while a > b:
list.append(a)
a -= 1
How about
a = int(input('input a number for a: '))
b = int(input('input a number for b: '))
print(list(range(a, b + (b >= a) - (a > b), 1 - 2 * (a > b))))
You can change numbers to the following:
numbers = list(range(a, b + 1)) if a < b else list(range(b, a + 1))
and your code will work just fine. You can also shorten your code by doing it like this:
a = int(input('input a number for a: '))
b = int(input('input a number for b: '))
numbers = list(range(a, b+1)) if a < b else list(range(b, a+1))
print numbers if a < b else sorted(numbers, reverse=True)
Because the last value range() prints is the biggest value for start + step * i that is less than end. If end is less than start and the step is positive, there is no number which satisfies that condition:
10 + i * 1 will never be smaller than 1 (where i is a positive integer)
Instead, do this before you range:
if a > b:
a, b = b, a
which will ensure a is always the smaller number moving forward, by swapping their values if that is not the case.
If you want to preserve the ascending/descending order:
if a > b:
a, b = b, a
rev = True
Then, after building the list
if rev:
numbers.reverse()

What do I need to add, to ask my Python 3 program to check if the input is in ascending or descending order?

I need to make my program to check whether the input is in ascending order on in descending order. It works already, however not correctly, I believe I need to add something more? I am very new to programming.
Here is my code :
b = 0
last = int(input())
finished= False
while not finished:
new = int(input())
if new == -1:
finished = True
elif last == -1:
finished = True
elif new > last :
b = 1
elif new <= last:
b = 2
last = new
if b == 1:
print ('yes')
elif b == 2:
print ('no')
You should consider the values of b:
b = 0
last = int(input())
while True:
new = int(input())
if (new == -1) or (last == -1):
break
elif new > last :
if b == 2: # this has been descending until now
b = 0 # neither ascending nor descending
break
b = 1
elif new < last:
if b == 1: # this has been ascending until now
b = 0
break
b = 2
else: # when two adjacent values are equal, this order is neither ascending, nor descending
b = 0
break
last = new
if not b:
print("Neither ascending, nor descending")
elif b == 1:
print ('ascending')
elif b == 2:
print ('descending')
else:
print("This is odd, we shouldn't have got here...")
This will continue asking the user for inputs until it receives a -1 as input. If there's a single input that makes the list in descending order, it will print 'no' at the end of the loop (when the user inputs -1).
b = 0
last = int(input('Last: '))
while True:
new = int(input('New: '))
if new == -1 or last == -1:
break
elif new <= last:
b = 2
last = new
if b == 2:
print ('no')
else:
print ('yes')

How to break out of a while loop in Python 3.3

m = int(input("First number (0 to stop): "))
n = int(input("Second number: "))
def gcd(a, b):
while b != 0:
c = a % b
a = b
b = c
if b == 0:
break
return a
print ("The greatest common divisor of", n,"and", m, "is", abs(gcd(m,n)))
How do I break out of this while loop, when m is equal to 0.
You probably want an outer loop, judging from your input hint of (0 to stop):
def gcd(a, b):
while b != 0:
c = a % b
a, b = b, c # tuple assignment FTW!
if b == 0:
break
return a
while True:
m = int(input("First number (0 to stop): "))
if m == 0:
break
n = int(input("Second number: "))
print("The greatest common divisor of {0} and {1} is {2}".format(n, m, abs(gcd(m, n))))

Categories

Resources