Sorting of numeric values in python - python-2.7

Here i get the input from the user.
This is my code
num_array=list()
x=int(raw_input('Enter the numbers:'))
for i in range(int(x)):
n=raw_input("")
num_array.append(int(n))
print("\nThe numbers in ascending order are:%d" %(num_array.sort())
And when i want to print the numbers ,it is showing me an error.
I want output to look like this
Enter the number:
5
4
3
2
1
The numbers in ascending order are 1 2 3 4 5

Here is your code
num_array=list()
x=int(raw_input('Enter the numbers:'))
for i in range(int(x)):
n=raw_input("")
num_array.append(int(n))
#print(sorted(num_array))
arr = sorted(num_array)
output = ""
for x in arr:
output = output + str(x) + " "
print(output)

this may be what you want (replaced % print statement with .format() syntax).
num_array.sort() will sort your array but will return None (and that is what your print statement will try to print). sorted on the other hand returns a list.
num_array = []
x = int(raw_input('Enter length of the array: '))
for i in range(int(x)):
n = raw_input("number '{}': ".format(i))
num_array.append(int(n))
print("\nThe numbers in ascending order are: {}".format(sorted(num_array)))
if you do not want the output to look like a python list you could to this:
sorted_str = ' '.join(str(n) for n in sorted(num_array))
print("\nThe numbers in ascending order are: {}".format(sorted_str))

Related

I need to create a loop that prints a graph where each number in the list is shown by a number of characters. Here is an example:

numbers = [1,2,3,4]
results in
1: i
2: ii
3: iii
4: iiii
This is my code so far and I'm not sure where to go.
numbers = [1,2,3,4]
c = 0
for i in numbers:
count += 1
print(len(numbers))
Instead of 'i' you can put any character you like enclosed in single inverted commas.
numbers = [1,2,3,4]
output = []
for number in numbers:
output.append(number*'i')
print(output)

nested list of lists of inegers - doing arithmetic operation

I have a list like below and need to firs add items in each list and then multiply all results 2+4 = 6 , 3+ (-2)=1, 2+3+2=7, -7+1=-6 then 6*1*7*(-6) = -252 I know how to do it by accessing indexes and it works (as below) but I also need to do it in a way that it will work no matter how many sublist there is
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]]
a= nested_lst[0][0] + nested_lst[0][1]
b= nested_lst[1][0] + nested_lst[1][1]
c= nested_lst[2][0] + nested_lst[2][1] + nested_lst[2][2]
d= nested_lst[3][0] + nested_lst[3][1]
def sum_then_product(list):
multip= a*b*c*d
return multip
print sum_then_product(nested_lst)
I have tried with for loop which gives me addition but I don't know how to perform here multiplication. I am new to it. Please, help
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]]
for i in nested_lst:
print sum(i)
Is this what you are looking for?
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]] # your list
output = 1 # this will generate your eventual output
for sublist in nested_lst:
sublst_out = 0
for x in sublist:
sublst_out += x # your addition of the sublist elements
output *= sublst_out # multiply the sublist-addition with the other sublists
print(output)

Find the the total number of 1's in binary form for a group number's in a list in python 3

I want to count total number of '1's in binary format of a number which is in a list.
z = ['0b111000','0b1000011'] # z is a list
d = z.count('1')
print(d)
The output is 0.
Whereas the required output should be in the form of [3,3]
which is number of ones in every element that Z is containing :
Here it is :
z=['0b111000','0b1000011']
finalData = []
for word in z:
finalData.append(word.count('1'))
print(finalData)
The problem with your code was you were trying to use count() method on list type and it is used for string. You first need to get the string from the list and then use count() method on it.
Hope this helps :)
z = ['0b111000','0b1000011']
d = z.count('1')
This attempts to find the number of times the string '1' is in z. This obviously returns 0 since z contains '0b111000' and '0b1000011'.
You should iterate over every string in z and count the numbers of '1' in every string:
z = ['0b111000','0b1000011']
output = [string.count('1') for string in z]
print(output)
# [3, 3]
list.count(x) will count the number of occurrences such that it only counts the element if it is equal to x.
Use list comprehension to loop through each string and then count the number of 1s. Such as:
z = ['0b111000','0b1000011']
d = [x.count("1") for x in z]
print(d)
This will output:
[3, 3]

How to take specific number of input in python

How do I take a specific number of input in python. Say, if I only want to insert 5 elements in a list then how can I do that?
I tried to do it but couldn't figure out how.
In the first line I want to take an integer which will be the size of the list.
Second line will consist 5 elements separated by a space like this:
5
1 2 3 4 5
Thanks in advance.
count = int(raw_input("Number of elements:"))
data = raw_input("Data: ")
result = data.split(sep=" ", maxsplit=count)
if len(result) < count:
print("Too few elements")
You can also wrap int(input("Number of elements:")) in try/except to ensure that first input is actually int.
p.s. here is helpful q/a how to loop until correct input.
Input :-
5
1 2 3 4 5
then, use the below code :
n = int(input()) # Number of elements
List = list ( map ( int, input().split(" ") ) )
Takes the space separated input as list of integers. Number of elements count is not necessary here.
You can get the size of the List by len(List) .
Here list is a keyword for generating a List.
Or you may use an alternative :
n = int(input()) # Number of elements
List = [ int(elem) for elem in input().split(" ") ]
If you want it as List of strings, then use :
List = list( input().split(" ") )
or
s = input() # default input is string by using input() function in python 2.7+
List = list( s.split(" ") )
Or
List = [ elem for elem in input().split(" ") ]
Number of elements count is necessary while using a loop for receiving input in a new line ,then
Let the Input be like :
5
1
2
3
4
5
The modified code will be:-
n = int(input())
List = [ ] #declare an Empty list
for i in range(n):
elem = int(input())
List.append ( elem )
For Earlier version of python , use raw_input ( ) instead of input ( ), which receives default input as String.

Python remove odd numbers and print only even

user = int(raw_input("Type 5 numbers"))
even = []
def purify(odd):
for n in odd:
even.append(n)
if n % 2 > 0:
print n
print purify(user)
Hello I am a beginner and I would like to understand what is wrong with this code.
The User chose 5 numers and I want to print the even numbers only.
Thanks for helping
There are a few problems:
You can't apply int to an overall string, just to one integer at a time.
So if your numbers are space-separated, then you should split them into a list of strings. You can either convert them immediately after input, or wait and do it within your purify function.
Also, your purify function appends every value to the list even without testing it first.
Also, your test is backwards -- you are printing only odd numbers, not even.
Finally, you should return the value of even if you want to print it outside the function, instead of printing them as you loop.
I think this edited version should work.
user_raw = raw_input("Type some space-separated numbers")
user = user_raw.split() # defaults to white space
def purify(odd):
even = []
for n in odd:
if int(n) % 2 == 0:
even.append(n)
return even
print purify(user)
raw_input returns a string and this cannot be converted to type int.
You can use this:
user = raw_input("Input 5 numbers separated by commas: ").split(",")
user = [int(i) for i in user]
def purify(x):
new_lst = []
for i in x:
if i % 2 == 0:
new_lst.append(i)
return new_lst
for search even
filter would be the simplest way to "filter" even numbers:
output = filter(lambda x:~x&1, input)
def purify(list_number):
s=[]
for number in list_number:
if number%2==0:
s+=[number]
return s