Python - how to get numbers to always print in ascending order - python

I am trying to write something that always prints numbers in ascending order.
I have something like this below, but it will always print the numbers in the order of which I have the variables. I know I am missing something here to make it so they will print in ascending order even if I toss in more numbers so they are always sorted. I am just not sure what to add in.
# This function compares two numbers and returns them
# in increasing order.
def order_numbers(number1, number2):
if number2 > number1:
return number1, number2
else:
return number2, number1
smaller, bigger = order_numbers(100, 99)
print(smaller, bigger)
I know I can write something like this print(sorted([smaller, bigger])) but I don't want it to print like this [99,100]
edit1: the same goes for print(order_numbers(smaller, bigger))

def order_numbers(*args):
numbers = list(args)
numbers.sort()
return numbers
# the * here unpacks the list, so you don't the the square brackets of list output.
print(*order_numbers(100,21,32,12))
# 12 21 32 100
OR
print(*sorted(number_list))

Related

Python descending number

I need to create a program that will take a integer, (e.g. 4586), and return the number with the digits in descending order (e.g. 8654).
num = 4586
num1 = num #num1 is a string
descendingNumber = []
for i in num1:
for j in i:
if i < j:
descendingNumber.append(i)
else:
descendingNumber.insert(1,i)
What am I doing wrong?
That insertion process doesn't look quite right. You can accomplish this in one line using built-ins.
First, we get the individual digits by using str(), and then sort them using sorted(). This gives us a list of digits, so we then use ''.join() to turn it back into a string. Finally, we cast the result back into an integer to get our desired output.:
int(''.join(sorted(str(num), reverse=True)))
This outputs:
8654

Trying to compare return values to list

randomgenerator() is a function that yields 6 random integers, the user is prompted to also enter 6 values which are added to lucky[].
I want to compare each yield value to the lucky[] list for a match, but the if condition is not being met.
for x in randomgenerator():
print(f"\n{x} is a winning number.")
if x in lucky:
print(f"There is a match with number {x}")
match.append(x)
def randomgenerator():
for i in range(5):
yield random.randint(1,2)
yield random.randint(1,2)
You said randomgenerator returns a tuple containing ints.
randomgenerator() is a function that yields 6 random values
I guess by "values" you meant integers, since it's very strange to generate random strings.
Then lucky is filled with input() returned values, which are strings.
if str(x) in lucky: # This should work, since it will convert the int x to a string
a similar solution would be:
lucky = list(map(int, lucky)) # all the elements are converted to integers

Sorting a list with negative numbers as strings produces unexpected result [duplicate]

This question already has answers here:
How to sort a list of strings numerically?
(14 answers)
Closed 2 years ago.
I made a program to calculate the second largest number from a list. Input is a string that is sliced into a list. Here's the code
score1 = input()
score = score1.split()
score.sort()
maximum = max(score)
count = score.count(maximum)
for i in range(0,count):
score.pop()
print(max(score))
And it is working fine for positive numbers but if the list contains a negative number my program fails to produce the correct answer.
For Input -7 -7 -7 -7 -6
Output is -6 instead of -7
Any way to improve it?
Since the input is a string, when you call sort and max they're working lexicographically, not numerically. You need to convert to integers first:
score = [int(item) for item in score1.split()]
The reason your code does not work for negative numbers (btw it also does not work for numbers with more than 1 digits as well) is that you are not sorting numbers, you are sorting strings. input()'s return value is always a string since no implicit conversion takes place. Therefore, in order to get the result you want you have to cast them to some number form first.
score = [int(x) for x in input().split()]
score.sort()
after that you can do whatever you want with it.
Note that wrapping the list-comprehension in a try-except block would also be a good idea to avoid bad input.
score1 = input()
score = score1.split()
#converting the list of strings into list of integers
score = [int(i) for i in score]
#removing duplicates
score = list(set(score))
#sorting the list
score.sort()
#printing the second largest number
print(score[-2])
You can get your expected answer by doing this :
score = input().split()
li = []
for value in score:
x = int(value) # converting to int
li.append(x) # appending to empty list
final = set(li) # removing duplicates values
print(max(final)) # getting the maximum value
Hope that it will help you ..
Try this maybe:
score1 = input()
score = score1.split()
score = sorted(set(map(int, score)))
second_max=score[-2]

Simple Python Assistance

two fixes:, main should sort the returned list, and the for loop should print all numbers on one line.
This is the question I am answering, Thought I got it all but the two errors I have explained above need help:
In main, generate a random integer that is greater than 5 and less than 13. print this number on its own line.
Call the makelist function with the random integer as sole argument.
Make an empty list inside the makelist function.
Use a loop to append to the list a number of elements equal to the random integer argument. All new list elements must be random integers ranging from 1 to 100, inclusive. Duplicates are okay.
Return the list to main.
Back in main, catch the returned list and sort it.
Finally, use a for loop to display the sorted list elements, all on one line, separated by single spaces.
List size will be 7
Here is the sorted list:
8 28 35 41 51 62 72
ANOTHER SAMPLE OUTPUT
List size will be 10
Here is the sorted list:
3 3 9 20 36 43 48 50 81 93
Any help with my code is very much appreciated. Im a beginner and have tried tutorials.
Here is my code
import random
def main():
random_int = random.randint(6, 12)
print (random_int)
elements = makelist(random_int)
for n in sorted(elements):
print (n,)
def makelist(random_int):
number_list = []
for count in range(random_int):
number_list.append(random.randint(1, 101))
return number_list
main()
print (n,) if you want to print your items like your samples output, Your comma placement is where the problem lies. You see, parenthesis in python are used both for enclosing mathematical / logical expressions and for tuples. What happens if you want a 1-item tuple? (n) is the same as n. To solve that, python understands (n,)as a tuple.
So to print your items like you want, use:
for n in sorted(elements):
print (n),
print() # This last one is only to go down a line
# for any further prints
Edit: also, if you want a random_intbetween 1 and 100, use random.randint(1, 100), not 101
I would sort the list in the makelist function. In addition to this, you should remove the comma from print (n,). Otherwise your code pretty much solves the problem. Just be more specific with your question next time.
Edit: Calling each print() on each element on the list will print each element on a newline (Vertically). Since you needed to get rid of the commas, ' '.join(map(str, sorted(elements)) will convert the list to a string, with each element separated by an empty space.
import random
def main():
random_int = random.randint(6, 12)
print ("The list size will be %d" %random_int)
elements = makelist(random_int)
print("This sorted list is %s" %' '.join(map(str, sorted(elements))) )
def makelist(random_int):
number_list = []
for count in range(random_int):
number_list.append(random.randint(1, 100))
return number_list
Do it like this
import random
def main():
random_int = random.randint(6, 12)
print ('List size will be %d' % random_int)
elements = makelist(random_int)
print('Here is the sorted list:')
print( ' '.join(map(str, sorted(elements))) )
def makelist(random_int):
number_list = []
for count in range(random_int):
number_list.append(random.randint(1, 100))
return number_list
main()
The line of interest is
print( ' '.join(map(str, sorted(elements))) )
Which does a few things.
sorted(elements)
Return a sorted copy of the list.
map(str, sorted(elements))
Map (convert) the integer elements to strings. This just calls str on each element in the list. Its needed because join requires an iterable of strings.
' '.join(map(str, sorted(elements)))
This funny looking syntax will create one long string out of all the values. It will use ' ' (space character) as the value between each element and will join all the elements which have been sorted and converted to strings into one long string which can be printed.

Return a list after append() and reverse()

I'm new at python (2.7.3) and I'm trying to write a program that converts a given decimal number into a binary one.
To that end, I wrote a function that takes the decimal number and an empty list, divides the number by 2 appends the rest to the list and repeats the function with the remaining quotient until the quotient is 0.
def convert_to_bin(dec_num,list):
quo = dec_num/2 # val is the quotient when dividing by 2
rest = dec_num%2 # rest is the rest when dividing by 2
list.append(rest)
if (quo==0):
list.reverse()
print list
return list
else:
convert_to_bin(quo,list)
bin_list = [] # initialize list for binary entries
dec_num = 83 # decimal number that is to be converted into binary
bin_list = convert_to_bin(dec_num,bin_list)
print bin_list
The function works all right so far, I just can't find a way to actually return the list after calling the function - instead I always get "None" as a return statement.
What am I doing wrong? Any help would be greatly appreciated.
You forgot to return the result of the recursive call:
else:
return convert_to_bin(quo,list)
A recursive call returns to the caller, not the top-level frame. So a convert_to_bin() function calling convert_to_bin() again was ignoring the return value from the nested call, instead then returning None as the end of function is reached.

Categories

Resources