How to print only one message for different results - python

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

Related

Write a Python program that reads a positive integer n and finds the average of all odd numbers between 1 and n

This is the question:
Write a Python program that reads a positive integer n and finds the
average of all odd numbers between 1 and n. Your program should not
accept a negative value for n.
And here is my code, which curiously doesn't work:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
while b <= k:
if b % 2 == 1:
sum1 = sum1+b
b += 1
avg = sum/k
print(avg)
Example: input: 8 and output: 2.5, while it should be 4. Any tips?
if we use while True, the program will run until it receives a positive number. and when we get a positive number, then we execute the instructions and turn off the loop using a break
1 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = [i for i in range(1, n + 1) if i % 2 == 1]
print(sum(numbers) / len(numbers))
break
2 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = []
for i in range(1, n+1):
if i % 2 == 1:
numbers.append(i)
break
print(sum(numbers)/len(numbers))
3 version with counter
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
summ = 0
c = 0
for i in range(1, n+1):
if i % 2 == 1:
summ += i
c += 1
print(summ/c)
break
You have used sum (builtin function name) instead of sum1 (your variable name) in the 2nd last line. Additionally, you need to count the total number of odd numbers and divide using that number instead of the input.
Okay I reviewed the question and here is the answer:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
c = 0
while b <= k:
if b % 2 == 1: #determines if odd
sum1 = sum1+b
c += 1 #variable which counts the odd elements
b += 1 #counter
avg = sum1/c
print(avg)
sum = int(input("Enter a positive integer: "))
Oddtotal = 0
for number in range(1, sum+1):
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number

Divide an element in a list with every other element in the list

I would like to take a list of numbers and a value (v) from user and see whether an element divided by another element in the list is equal to v:
e.g.
user input:[ 9, 5, 8, 1 ], v = 10, result: false
user input:[ 2, 4, 5, 7 ], v = 2, result: 2 and 4
user input: [ 3, 5, 15, 20 ] v = 4, result: 5 and 20
below is what I have now:
listnum = input("Enter a list of numbers: ")
list1 = []
v = int(input("Enter the value of v: "))
listnum = listnum.split()
for num in listnum:
list1.append(num)
for a in range(len(list1)):
for b in range(len(list1)):
if int(list1[a])/int(list1[b]) == v:
print(list1[b], list1[a])
else:
print('False')
but my output is like:
Enter a list of numbers: 2 4 5 7
Enter the value of v: 2
2 4
False
how could I adjust the code? Thanks!
Here goes:
from itertools import combinations
listnum = input("Enter a list of numbers: ")
list1 = []
v = int(input("Enter the value of v: "))
listnum = map(int, listnum.split())
combs = combinations(listnum, 2)
divisors = [(n1, n2) for n1, n2 in combs if n1/n2 == v or n2/n1 == v]
if len(divisors) == 0:
print(False)
else:
print(divisors)
Enter a list of numbers: 3 5 15 20
Enter the value of v: 4
[(5, 20)]
A bit optimized version:
listnum = input("Enter a list of numbers: ")
list1 = []
v = int(input("Enter the value of v: "))
listnum = sorted(list(map(int, listnum.split())), reverse=True)
if(v<2): print("False")
else:
for i in range(len(listnum)):
if(listnum[i]%v==0):
for j in range(i+1, len(listnum)):
if(listnum[i] == v*listnum[j]):
list1.append((listnum[i], listnum[j]))
if(len(list1)==0): print("False")
else: print(list1)
Few notes - what I do here:
(1) to make it easier - sort the input array in a descending order. Thanks to this you won't have to run over the whole list twice, but just run over the reminder in the second step (which is still O(n^2), yet it's 2x less operations).
(2) you only need to execute the lookup through reminder, if v is a divisor of the bigger number - otherwise you won't find the smaller one anyways.
In total - depending on the input sample - you should see some major performance improvements with this code.
You have an indentation problem, your else condition isn't working as you're expecting.
If what you want to do is print False when no result are found, then you can do something like:
exists = False
for a in range(len(list1)):
for b in range(len(list1)):
if int(list1[a])/int(list1[b]) == v:
print(list1[b], list1[a])
exists = True
if not exists:
print('False')
Try this :
listnum = input("Enter a list of numbers: ")
list1 = []
v = int(input("Enter the value of v: "))
listnum = listnum.split()
for num in listnum:
list1.append(int(num))
found=False
for a in list1:
for b in list1:
if a/b == v:
print(b,a)
found=True
break
if found:
break
else:
print('False')
Note :
You can just loop through list1 without explicitly using the index.
You will need a break statement inside the for loop. The associated else part will be executed only if the for loop is not terminated by any break statement.
Please notice that even if there are multiple pairs which can result in producing v after division, the above snippet will only print the first pair.
You can use a flag to decide whether an element divided by another element in the list is equal to v, like this way
listnum = input("Enter a list of numbers: ")
v = int(input("Enter the value of v: "))
listnum = listnum.split()
isDevided=False
for a in range(len(listnum)):
for b in range(len(listnum)):
if int(listnum[a])/int(listnum[b]) == v:
print(listnum[b], listnum[a])
isDevided=True
if isDevided==False:
print ("False")
Another thing i want to mention that is you are using list1 as an extra variable and an extra for loop which may decrease the performance, Above code is little bit more optimized, memory and computation wise.
Try this
a=input("Enter list of numbers Like 2 4 5 1: ")
v= float(input("Enter the value of v: "))
a= a.split()
b = [int(a[i]) for i in range(len(a))]
b = sorted(b)
final_list = []
for i in b:
if i not in final_list:
final_list.append(i)
count = 0
for i in range(len(final_list)):
for j in final_list[i+1:]:
if int(j) / int(final_list[i]) == v:
print(final_list[i], " and ", j)
count += 1
if count == 0:
print(False)
...
You can do this in a much more compact way using list comprehensions. By computing a list of resulting products (number * v) you can use a set to only go throuh the list twice instead of going through it for every single number in it. This will give you an O(n) complexity instead of O(n^2).
numbers = input("Enter a list of numbers: ")
numbers = list(map(int,numbers.split(",")))
value = int(input("Enter the value of v: "))
products = { divisor*value for divisor in numbers }
matches = [ number for number in numbers if number in products ]
print( ", ".join(f"{prod}/{prod//value}" for prod in matches) or "False")
sample runs:
Enter a list of numbers: 9,5,8,1
Enter the value of v: 10
False
Enter a list of numbers: 2,4,5,7
Enter the value of v: 2
4/2
Enter a list of numbers: 3,5,15,20
Enter the value of v: 4
20/5
Enter a list of numbers: 5,10,15,30,45
Enter the value of v: 3
15/5, 30/10, 45/15
note that some special cases would need to be adressed (zeroes or repetitions in the list or v == 1) but since your original code didn't bother with those I assumed they are not part of the problem statement
Here's an even more condensed version:
nums = map(int,input("Enter a list of numbers: ").split(","))
v = int(input("Enter the value of v: "))
print(*([f"{n}/{n//v}" for s in [set(nums)] for n in s if n//v in s] or "False"))

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

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

Covert while loop to for loop

I'm trying to find the average of a list by using a for loop. I've done it with a while loop.
Is it possible to convert this into a for loop?
List_1 =[]
while (True):
val_1 = float( input("Enter a number: "))
List_1.append (val_1)
if len(List_1)>=5:
List_sum = sum(List_1)
List_avg = (List_sum / len(List_1))
print("AVG:",List_avg)
break
This is what I've come up with:
val_1 = int(input("Enter a number: " ))
List_1 = []
List_1.append (val_1)
List_sum = 0
List_len = 0
List_avg = 0
for i in range (List_1):
List_sum = sum(numbers)
List_len = len(numbers)
if len(numbers) >=5:
List_avg = List_sum / List_len
print (List_avg)
L = []
for _ in range(5):
L.append(float( input("Enter a number: ")))
print("The length is", len(L))
print("The total is", sum(L))
print("The average is", sum(L)/len(L))
Instead of checking for the end of the list (a length of 5 in your example) within the loop, loop over a range of that length (a list isn't an appropriate argument for the range function), and print the result afterward. You don't need to use a list, either.
list_len = 5
result = 0
for i in range(list_len):
result += float(input('Enter a number: '))
print(result/list_len)

Categories

Resources