Compare numbers in form: 12,3K , 1,84M in python - python

In need to compare numbers which look like: 12,3K , 1,84M, etc
eg:
a = 12,3K
b = 1,84M
if b > a :
print b

You need to use replace for it:
a = ("12,3K", "1,84M")
numbers = {"K": 1000, "M": 1000000}
result = []
for value in a:
if value:
i = value[-1]
value = float(value[:-1].replace(',', '.')) * numbers[i]
result.append(int(value))
print max(result)
You can add more numbers to dictionary and you will get more results.

I would recommend a function to convert a and b into the corresponding number like so (also I'd make a and b strings:
def convert(num):
return num.replace(',','').replace('K','000').replace('M','000000')
a = '12,3K'
b = '1,84M'
if convert(b) > convert(a) :
print b

If your values are strings, then the re module would make it easy to replace commas with '' and K or M with 3 or 6 zeroes. Then wrap in int() and compare. Where / how are you getting the values you're comparing?

Related

how do I compare a string of integers with an integer?

I have written the code below:
d = 4
int_list = [1,2,3,4,5]
string_digits = [str(int) for int in int_list]
str_of_ints = ''.join(string_digits)
this produces -> str_of_ints = 1491625 (and this is a string)
for i in str_of_ints:
if i == 'd':
print("hello")
the issue I have is with the line i == 'd' ; this is returning false- why is this? And how can I compare the string 1491625 with say an integer 5, in particular how can I check if any of the digits of 1491625 is equal to 5?
I have tried doing:
for i in str_of_ints:
if i == d:
print("hello")
this of course doesn't work because then we would be comparing a string with an integer?
Your problem is comparing an integer d to a string as you iterate over str_of_ints. Your data types must match. 4 is not the same as '4'. This can be solved by converting your searched value to a str using the str() method:
d = 4
int_list = [1,2,3,4,5]
string_digits = [str(int) for int in int_list]
str_of_ints = ''.join(string_digits)
# this produces -> str_of_ints = 1491625 (and this is a string)
if str(d) in str_of_ints:
print('hello')
This will work:
d = 4
int_list = [1,2,3,4,5]
str_list = [str(i) for i in int_list]
str_string = "".join(str_list)
if str(d) in str_string:
print("hello")

Remove adjacent duplicates given a condition

I'm trying to write a function that will take a string, and given an integer, will remove all the adjacent duplicates larger than the integer and output the remaining string. I have this function right now that removes all the duplicates in a string, and I'm not sure how to put the integer constraint into it:
def remove_duplicates(string):
s = set()
list = []
for i in string:
if i not in s:
s.add(i)
list.append(i)
return ''.join(list)
string = "abbbccaaadddd"
print(remove_duplicates(string))
This outputs
abc
What I would want is a function like
def remove_duplicates(string, int):
.....
Where if for the same string I input int=2, I want to remove my n characters without removing all the characters. Output should be
abbccaadd
I'm also concerned about run time and complexity for very large strings, so if my initial approach is bad, please suggest a different approach. Any help is appreciated!
Not sure I understand your question correctly. I think that, given m repetitions of a character, you want to remove up to k*n duplicates such that k*n < m.
You could try this, using groupby:
>>> from itertools import groupby
>>> string = "abbbccaaadddd"
>>> n = 2
>>> ''.join(c for k, g in groupby(string) for c in k * (len(list(g)) % n or n))
'abccadd'
Here, k * (len(list(g)) % n or n) means len(g) % n repetitions, or n if that number is 0.
Oh, you changed it... now my original answer with my "interpretation" of your output actually works. You can use groupby together with islice to get at most n characters from each group of duplicates.
>>> from itertools import groupby, islice
>>> string = "abbbccaaadddd"
>>> n = 2
>>> ''.join(c for _, g in groupby(string) for c in islice(g, n))
'abbccaadd'
Create group of letters, but compute the length of the groups, maxed out by your parameter.
Then rebuild the groups and join:
import itertools
def remove_duplicates(string,maxnb):
groups = ((k,min(len(list(v)),maxnb)) for k,v in itertools.groupby(string))
return "".join(itertools.chain.from_iterable(v*k for k,v in groups))
string = "abbbccaaadddd"
print(remove_duplicates(string,2))
this prints:
abbccaadd
can be a one-liner as well (cover your eyes!)
return "".join(itertools.chain.from_iterable(v*k for k,v in ((k,min(len(list(v)),maxnb)) for k,v in itertools.groupby(string))))
not sure about the min(len(list(v)),maxnb) repeat value which can be adapted to suit your needs with a modulo (like len(list(v)) % maxnb), etc...
You should avoid using int as a variable name as it is a python keyword.
Here is a vanilla function that does the job:
def deduplicate(string: str, treshold: int) -> str:
res = ""
last = ""
count = 0
for c in string:
if c != last:
count = 0
res += c
last = c
else:
if count < treshold:
res += c
count += 1
return res

Concatenate List in Python

I have 3 list's which are having one value i want to concatenate the list, so i used + operator to concatenate but the output is not what i expected. I need to use the list because in some cases i can get more results instead of one.
Lists:
A = ["F"]
B = ["SZLY"]
C = ["RQTS"]
D = ["19230711"]
Output:
['F']['SZLY']['RQTS']['19230711']
Expected Output:
FSZLYRQTS19230711
Update:
I used below code to concatenate. I used str() because i want to cast the topmost list element to string.
hrk = str(A)+str(B)+str(C)+str(D)
How can i get the expected output.
str on a list prints a representation of the list (for debug purposes). It's bad to process that as string further in your code.
most pythonic way: use join in a list comprehension for first & only item of your lists
A = ["F"]
B = ["SZLY"]
C = ["RQTS"]
D = ["19230711"]
print(["".join(x[0] for x in (A,B,C,D))])
results in:
FSZLYRQTS19230711
Try like this,
In [32]: A[0]+B[0]+C[0]+D[0]
Out[32]: 'FSZLYRQTS19230711'
Try:
A[0] + B[0] + C[0] + D[0]
You are trying to access first element of list so you have to access them by index.
What you are currently doing will create a single list with all the elements. Like:
A = ['2414214']
B = ['fefgg']
C = A + B
print C
# Will print
['2414214', 'fefgg']

Add "0" to number in strings if they have two digits only

Lets say, I have this array:
s = ["data_s01", "data_s99", "data_s133"]
I want to add "0" after "s" if there are only two digits. so the result is:
["data_s001", "data_s099", "data_s133"]
I have this now:
for v in s:
data = v.split('_s')
if "0" in data:
out_s = data[0] + "0" + data[1]
print(out_s)
But nothing is printed?
>>> ["data_s{:0>3}".format(x[6:]) for x in s]
['data_s001', 'data_s099', 'data_s133']
x=["data_s01", "data_s99", "data_s133"]
print ["".join(["data_s",k.split("_s")[1].zfill(3)]) for k in x]
Try this.
The print function should not be inside the if, since only original strings with no 0 would get printed. Then again, I don't know why you care if there is a 0 in there or not.

Create a Python list filled with the same string over and over and a number that increases based on a variable.

I'm trying to create a list that is populated by a reoccurring string and a number that marks which one in a row it is. The number that marks how many strings there will be is gotten from an int variable.
So something like this:
b = 5
a = range(2, b + 1)
c = []
c.append('Adi_' + str(a))
I was hoping this would create a list like this:
c = ['Adi_2', 'Adi_3', 'Adi_4', 'Adi_5']
Instead I get a list like this
c = ['Adi_[2, 3, 4, 5]']
So when I try to print it in new rows
for x in c:
print"Welcome {0}".format(x)
The result of this is:
Welcome Adi_[2, 3, 4, 5]
The result I want is:
Welcome Adi_2
Welcome Adi_3
Welcome Adi_4
Welcome Adi_5
If anybody has Ideas I would appreciate it.
You almost got it:
for i in a:
c.append('Adi_' + str(i))
Your initial line was transforming the whole list a as a string.
Note that you could get rid of the loop with a list comprehension and some string formatting:
c = ['Adi_%s' % s for s in a]
or
c = ['Adi_{0}'.format(s) for s in a] #Python >= 2.6
Or as a list comprehension:
b = 5
a = range(2, b + 1)
c = ["Adi_" + str(i) for i in a]
Using list comprehensions:
b = 5
a = range(2, b + 1)
c = ['Adi_'+str(i) for i in a]
for x in c:
print"Welcome {0}".format(x)
Or all on one line:
>>> for s in ['Welcome Adi_%d' % i for i in range(2,6)]:
... print s
...
Welcome Adi_2
Welcome Adi_3
Welcome Adi_4
Welcome Adi_5

Categories

Resources