How to remove n minimum numbers in a list - python

I was searching for an answer for this question but couldn't find it. I am posting a answer. Hope it helps someone in the future. Program is tested and works.
n = count of numbers to remove from the list

numbers_list = input().split()
n = int(input())
for i in range(len(numbers_list)): # converts it from string to integers
numbers_list[i] = int(numbers_list[i])
for i in range(n):
min_element = min(numbers_list)
numbers_list.remove(min_element)
for i in range(len(numbers_list)): # converts it again from integers to string
numbers_list[i] = str(numbers_list[i])
print(", ".join(numbers_list))

Related

Why doesn't my if...in statement work in python?

this program takes 3 lists of numbers, and compares A and B to the list n. if a term from A is in n, the happiness increases. if a term from B is in n, the happiness decreases. However, when I am doing these calculations, the if ... in statement to check if a term from A/B is in n doesn't work - I have done print(happy) after each one to check, and I get no result
A = []
B = []
n = []
happy = 0
lengthn, lengthAB = input("").split()
for i in lengthn:
numbers = input("")
newNumbers = numbers.split()
n.append(newNumbers)
for i in lengthAB:
numbers = input("")
ANumbers = numbers.split()
A.append(ANumbers)
for i in lengthAB:
numbers = input("")
BNumbers = numbers.split()
B.append(BNumbers)
long = int(lengthAB)
for i in range(long):
j = int(i)
if A[j - 1] in n:
happy = happy + 1
print(happy)
if B[j - 1] in n:
happy = happy - 1
print(happy)
i = i + 1
print(happy)
Thank you so much for the help!!
You appended a list to n, not each element of that list. You can write
n.extend(newNumbers)
instead.
You could just write n = newNumbers.split(), but as pointed out in a comment, you probably have an indentation error:
for i in lengthn:
numbers = input("")
newNumbers = numbers.split()
n.extend(newNumbers)
Or, you don't need split at all:
for i in lengthn:
number = int(input(""))
n.append(number)
At some point, you probably mean to convert the string inputs to integers; may as well do that immediately after reading the string. (I'm declaring various techniques for handling conversion errors beyond the scope of this answer.)
Contrary to what you seem to expect the variables: lengthn, lengthAB are strings
The for-loop
for i in lengthn:
numbers = input("")
iterates over the characters in the string lengthn. If lengthn='12' it will ask to provide input twice.
If lengthAB is '13' for example you will get 2 numbers in your list BNumbers but later on you try to test 13 values because int('13') is 13.
for i in lengthn:
numbers = input("")
so the numbers you are getting are the form of string it's will iterate on string rather then a number.
You should look for beeter python book. Based on desription I think this should look like this:
def happiness(A, B, n):
return sum(x in n for x in A) - sum(x in n for x in B)
def get_data(prompt=""):
return [int(x) for x in input(prompt).split()]
print(happiness(get_data(), get_data(), get_data()))
https://ideone.com/Q2MZCo

Convert x digit number into two digit number

I am currently having x number in a list, and I am trying to convert inconsistent data that may be in 1 digit, 5 digit or 2 digit.
How can I convert all into 2 digit number?
Example:
def List_Convert_2_Digit(z):
for i in range(len(z)):
while(z[i]<100 or z[i]>10):
if(z[i]<100):
z[i]=z[i]/10
else:
z[i]=z[i]*10
return z
list_a = [5.2,1600,520,3600,13,55,4000]
result_list= List_Convert_2_Digit(list_a)
Result should yields: [52,16,52,36,13,55,40]
But the above code does not work and it's running forever.
I've tried mod, but it is not what I am looking for.
It looks like you just want to take the first two characters from each, and if there is a separator (dot in your case) ignore it.
In that case you can do this:
two_digit_list = [int(str(x).replace('.', '')[:2]) for x in List]
If other non numeric characters than a dot are going to appear your would have to deal with those as well of course :)
What this does is just converts the numbers to a string, removes dots and then grabs the first two characters and converts it back to an int.
EDIT: Since I saw you replied to someone above that single digit numbers should have 0 added to the end you can do this instead to cover that case:
two_digit_list = [int(str(x).replace('.', '')[:2]) if len(str(x).replace('.', '')) > 1 else int(f"{x}0") for x in List]
At that point it's a bit too long to be a pretty list comprehension so you could always just break it up into a for loop if it's unclear, might be a good exercise if nothing else :)
This is a simple solve to this.
yield_list = []
number_list = [5.2,1600,520,3600,13,55,4000]
for number in number_list:
string = str(number)
string =string.replace('.', '')
yield_list.append(string[:2])
yield_list
There is an error in your logic; your < and > are flipped. This code works:
def List_Convert_2_Digit(z):
for i in range(len(z)):
while(z[i]>100 or z[i]<10):
if(z[i]>100):
z[i]=z[i]/10
else:
z[i]=z[i]*10
return z
Solution that increases/decreases the numbers magnitude until we can get the left two digits:
def two_digit_list(lst):
rv = []
for item in lst:
if item < 10:
item *= 10
while item > 99:
item //= 10
rv.append(int(item))
return rv

Removing duplicates and sorting list python

Given a list, I need to print the numbers in sorted order and remove any duplicates. I am using python 3.7.2
My code:
def sorted_elements(numbers):
return sorted(set(numbers))
testcase = int(input())
while testcase > 0:
numbers = input().split()
l = sorted_elements(numbers)
for x in l:
print (x, end = ' ')
print ()
testcase -= 1
However, whenever my input consists of a 2 digit number, the logic fails.
Eg. for input of 2 1 43 2 5, I get an output of 1 2 43 5.
This work perfectly for single digit numbers. Can someone help me out with this?
You only need a slight modification. You are comparing strings instead of numbers, so try this instead:
def sorted_elements(numbers):
return sorted(set(numbers))
testcase = int(input())
while testcase > 0:
numbers = map(int, input().split())
l = sorted_elements(numbers)
for x in l:
print (x, end = ' ')
print ()
testcase -= 1
If you want, you can also do:
numbers = (int(x) for x in input().split())
You can simplify this in various aspects. Sort by numeric value using an appropriate key function, use a for loop if you know the number of iterations beforehand, utilize appropriate string utils like str.join, etc.
testcases = int(input())
for _ in range(testcases):
print(' '.join(sorted(set(input().split()), key=int)))
You are going correct way with set(numbers) to remove duplicates. The problem comes from sorted with your numbers being list of strs not ints.
Try this:
x_numbers = input().split()
numbers = [int(x) for x in x_numbers]
Try it now:
testcase = int(input())
n=list(str(testcase))
results = map(int, n)
numbers= sorted(set(results))
print(numbers)
code here:https://repl.it/repls/SeriousRosybrownApplicationprogrammer
We can keep it simple like this. This is a reference
input=raw_input() #took input as string
inputlist=input.split() #split the string to list
lsintegers = map(int, list(set(inputlist))) #remove duplicates converted each element to integer
lsintegers.sort() #sorted
print(lsintegers)`

Python Error. Trying to convert number into list and pull out first digit

So this:
for n in range (500):
lst = [int(i) for i in str(n)]
first_n = int(n[0])
list = lst
print list
print first_n
Is giving me the TypeError: 'int' object has no attribute 'getitem'.
But if I change the 3rd line from n into i then this:
for n in range (500):
lst = [int(i) for i in str(n)]
first_n = int(i[0])
list = lst
print list
print first_n
Gives me the list and the last number on that list. I need the first number not the last.
It gives me the first if instead I replace n in range (500): with n = raw input()
n = raw_input()
lst = [int(i) for i in str(n)]
first_n = int(n[0])
list = lst
print list
print first_n
But this is single number and need to have run thousands of numbers. (As you can see I change the i on the 3rd line back into n)
Please can you help?
Your issue lies with the raw_input. In python 2, it returns a string, not an integer. What you need is input(), which just returns an integer:
n = input()
lst = [int(i) for i in str(n)]
first_n = int(lst[0]) #also, need lst here, not n, as it is now an integer
list = lst
print list
print first_n
Probably an easier solution here is to instead convert it to a string:
>>> str(123)[0] # Convert to string and take 1st character
'1'
If you need it as a number, you can int it back. This feels inefficient, but you're trying to solve a problem strongly related to the written representation of a number, so strings feel like the appropriate solution. You can however use solutions related to taking the place value. If you are looking for the number of hundreds in the above, for example, you could % 100. This requires a little more work to make general, though.

How to strip white spaces in Python without using a string method?

I am fairly new to programming and have been learning some of the material through HackerRank. However, there is this one objective or challenge that I am currently stuck on. I've tried several things but still cannot figure out what exactly I am doing wrong.
Objective: Read N and output the numbers between 0 and N without any white spaces or using a string method.
N = int(input())
listofnum = []
for i in range(1, N +1):
listofnum.append(i)
print (*(listofnum))
Output :
1 2 3
N = int(input())
answer = ''
for i in range(1, N + 1):
answer += str(i)
print(answer)
This is the closest I can think of to 'not using any string methods', although technically it is using str.__new__/__init__/__add__ in the background or some equivalent. I certainly think it fits the requirements of the question better than using ''.join.
Without using any string method, just using integer division and list to reverse the digits, print them using sys.stdout.write:
import sys
N = int(input())
for i in range(1,N+1):
l=[]
while(i):
l.append(i%10)
i //= 10
for c in reversed(l):
sys.stdout.write(chr(c+48))
Or as tdelaney suggested, an even more hard-code method:
import os,sys,struct
N = int(input())
for i in range(1,N+1):
l=[]
while(i):
l.append(i%10)
i //= 10
for c in reversed(l):
os.write(sys.stdout.fileno(), struct.pack('b', c+48))
All of this is great fun, but the best way, though, would be with a one-liner with a generator comprehension to do that, using str.join() and str construction:
"".join(str(x) for x in range(1,N+1))
Each number is converted into string, and the join operator just concatenates all the digits with empty separator.
You can print numbers inside the loop. Just use end keyword in print:
print(i, end="")
Try ''.join([str(i) for i in range(N)])
One way to accomplish this is to append the numbers to a blank string.
out = ''
for i in range(N):
out += str(i)
print(out)
You can make use of print()'s sep argument to "bind" each number together from a list comprehension:
>>> print(*[el for el in range(0, int(input())+1)], sep="")
10
012345678910
>>>
You have to do a simple math to do this. What they expect to do is multiply each of your list elements by powers of ten and add them up on each other. As an example let's say you have an array;
a = [2,3,5]
and you need to output;
235
Then you multiply each of loop elements starting from right to left by 10^0, 10^1 and 10^2. You this code after you make the string list.
a = map(int,a)
for i in range(len(a)):
sum += (10**i)*a[-i]
print sum
You are done!

Categories