Ascending and descending order in Python 3 - python

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()

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))

How to print only one message for different results

I have this code and I'm trying to print only one message with all the results, but instead is printing each message with the result which is getting awful.
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
if a < b:
for i in range(a, b + 1):
print('The Numbers in Ascending Order Are: ', i)
else:
for i in range(a, b - 1, -1):
print('The Numbers in Descending Order Are: ', i)
Don't print each item in a loop then.
Write instead.
Code
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
if a < b:
print(f'The Numbers in Ascending Order Are: {list(range(a, b+1))}')
else:
print(f'The Numbers in Descending Order Are: {list(range(a, b-1, -1))}')
Output
Another approach with for loop
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
if a < b:
temp = []
for i in range(a, b + 1):
temp.append(i)
print('The Numbers in Ascending Order Are: ', temp)
else:
temp = []
for i in range(a, b - 1, -1):
temp.append(i)
print('The Numbers in Descending Order Are: ', temp)
Output
First of all, print the order message before each for loop. Secondly, you can use range in the following way:
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
if a < b:
print('The Numbers in Ascending Order Are: ')
for i in range(a,b + 1): # adding 1 to include b
print(i)
else:
print('The Numbers in Descending Order Are:')
for i in range(a , b - 1, -1): # reducing 1 to include b
print(i)
Input:
First Integer: 1
Second Integer: 5
Output:
1
2
3
4
5
Input:
First Integer: 5
Second Integer: 1
Output:
5
4
3
2
1
To avoid repeating the message, take it out of the for loop, like this:
a = int(input("First Integer:"))
b = int(input("Second Integer:"))
if (a < b):
print("The numbers in ascending order are:")
for number in range(a, b + 1):
print(number)
else:
print("The numbers in descending order are:")
for number in range(a, b - 1, -1):
print(number)
Sample outputs:
First Integer:5
Second Integer:2
The numbers in descending order are:
5
4
3
2
First Integer:2
Second Integer:4
The numbers in ascending order are:
2
3
4
You can sort them:
a = int(input("First Integer"))
b = int(input("Second Integer"))
c = [a,b]
if a < b:
sorted(c)
else:
sorted(c,reverse=True)
You need to correct your second loop and each message should be issued with the result of the loop instead of per item.
a = int(input('First Integer: '))
b = int(input('Second Integer: '))
asc = ", ".join([str(i) for i in range(a, b + 1)])
desc = ", ".join([str(i) for i in range(b, a - 1, -1)])
if a < b:
print(f'The Numbers in Ascending Order Are: {asc}')
print(f'The Numbers in Descending Order Are: {desc}')

Sum of digits untill reach single digit

I set an algorithm which sum a number's digits but I couldn't make it till single digit. It only work for one step.
For example:
a=2, b=8
a^b=256 = 6+5+2 = 13
But I want to reach single digit, like:
a^b=256 = 6+5+2 = 13 = 3+1 = 4
Below you can see my codes.
a = int(input("Enter a value"))
b = int("Enter second value")
number = pow(a, b)
sum= 0
while float(number) / 10 >= .1:
m = number % 10
sum += m
number = number // 10
if float(number) / 10 > .1:
print(m, end=" + ")
else:
print(m, "=", sum)
Here you go:
n = 256
while n > 9:
n = sum(int(i) for i in str(n))
print(n)
So whats going on? str(n) converts n to a string, strings in python can be iterated over so we can access digit by digit. We do this in a generator, converting each digit back to a integer, int(i) for i in str(n), we use sum to sum the elements in the generator. We repeat this process until n is a single digit.
Added a solution that gives the calculation explicitly:
def sum_dig(n):
_sum = sum(int(i) for i in str(n))
explained = "+".join(list(str(n)))
return _sum, explained
n = 256
s = ""
while n > 10:
n, e = sum_dig(n)
s+= f'{e}='
s += str(n)
print(s)
yields:
2+5+6=1+3=4
you can try this.
a = int(input("Enter a value"))
b = int(input("Enter second value"))
number = pow(a, b)
result = str(a)+'^'+str(b) + ' = ' + str(number)
while number > 9:
digit_sum = sum(map(int, str(number)))
result += ' = ' + '+'.join(str(number)) + ' = ' + str(digit_sum)
number = digit_sum
print ( result )
for a=2, b=8 result:
2^8 = 256 = 2+5+6 = 13 = 1+3 = 4
This produces the output in the format OP asked for:
a = int(input("Enter a value: "))
b = int(input("Enter second value: "))
n = pow(a, b)
while n >= 10:
nums = [i for i in str(n)]
op = "+".join(nums)
n = eval(op)
print("{}={}".format(op, n))
Logic:
Store the input in an array of individual numbers as strings.
Create the summation string using "+".join(nums) - for the output print.
Calculate the sum using eval(op) which works on strings (a built-in function) - store in n.
Print the summation string and what it equals.
Output:
Enter a value: 2
Enter second value: 8
2+5+6=13
1+3=4
Enter a value: 2
Enter second value: 6
6+4=10
1+0=1
Enter a value: 2
Enter second value: 50
1+1+2+5+8+9+9+9+0+6+8+4+2+6+2+4=76
7+6=13
1+3=4
sol = 0
if (a^b)%9==0:
sol = 9
else:
sol = (a^b)%9

Variable is overwritten in if statement

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)

Categories

Resources