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

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

Related

How to convert numeric string from a sublist in Python

I'm a freshie. I would like to convert a numeric string into int from a sublist in Python. But not getting accurate results. 😔
countitem = 0
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
for list in list_samp:
countitem =+1
for element in list:
convert_element = int(list_samp[countitem][0])
list_samp[countitem][1] = convert_element
You can do it like this:
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
me = [[int(u) if u.isdecimal() else u for u in v] for v in list_samp]
print(me)
The correct way to do it:
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
list_int = [[int(i) if i.isdecimal() else i for i in l] for l in list_samp]
print(list_int)
Let's go through the process step-by-step
countitem = 0
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
#Let's traverse through the list
for list in list_samp: #gives each list
for i in range(len(list)): # get index of each element in sub list
if list[i].isnumeric(): # Check if all characters in the string is a number
list[i] = int(list[i]) # store the converted integer in the index i

Function that recieves an integer and returns a tuple with all of its' digits in order in Python

def function(n):
res = 0
if not isinstance(n, int):
raise ValueError('argument is not an integer')
else:
while n > 0: #inverting the integer's digits
dig = n % 10
res = 10*res + dig
n = n//10
dig2 = res % 10
res2 = (dig2,)
res = res // 10
while res > 0:
dig2 = res % 10
res2 = (res2,) + (dig2,)
res = res // 10
return res2
Input: 123
Output: (1, 2, 3)
With the current program that I have my output is (((1,), 2), 3).Im having trouble with creating a tuple and adding it to another tuple and also with the logic part of analyzing each digit. I'm new to python, if you could try to explain it to me wihtout the use of lists I'd also be very grateful.
I can't comment on efficiency/performance, but take a look at the following code:
num = 123456789
lis = [int(char) for char in str(num)]
tup = tuple(lis)
print(tup)
Output:
(1, 2, 3, 4, 5, 6, 7, 8, 9)
Here we are using list comprehensions (which are loved by Python programmers). First, num is converted to string, then each char of this string is converted to an int, building a list of integers. The list can then be converted to a tuple.
I know you said "if you could try to explain it to me wihtout the use of lists...", but understand that lists (and list comprehensions) are an important part/tool of Python, you should not avoid them.
Again, the list comprehension above can be "read" as such:
Convert to int each char in the string (where this string is the number converted to a string).

Taking a 8 bit number and split them into two 4 bit numbers

I have an integer integer = 10101001. I wanted to split that number into an array of 2 four bit numbers array = [1010,1001]. How do I do this? Are there any python methods?
This is a way to do it:
num = 10101001
str_num = str(num)
split_num = [int(str_num[0:4]), int(str_num[4:])]
print(split_num)
Output:
[1010, 1001]
You need to pass by the string version of you int
i = 10101001
str_i = str(i)
res = str_i[:len(str_i) // 2], str_i[len(str_i) // 2:]
print(res) # ('1010', '1001')
If that is indeed the general case, you can use a simple method.
def func(x):
x = str(x) # this takes x and turns it into a string
sub1 = int(x[:4]) # this takes the first 4 digits and turns it into an integer
sub2 = int(x[4:]) # this takes the last 4 digits and turns it into an integer
return [sub1, sub2]
Note that I used the fact that strins are subscriptable. You can fetch characters in a string just like a list.

Convert numbers in mixed data type objects in python to int/float while keeping rest as is

I have a list as below:
input_a= [['a','12','','23.5'],[12.3,'b2','-23.4',-32],[-25.4,'c']]
I want to convert the numbers in this to numbers to get an output like this
output_a = [['a',12,'',23.5],[12.3,'b2',-23.4,-32],[-25.4,'c']]
I wrote the following code to get this to work:
def str_to_num(str_object=None):
if not isinstance(str_object,str):
return str_object
try:
x = int(str_object)
except ValueError:
try:
x = float(str_object)
except ValueError:
x =str_object
return x
def getNumbers(num_object=None,return_container=None):
a = return_container
if isinstance(num_object,list):
b = []
for list_element in num_object:
if isinstance(list_element,list):
x = getNumbers(list_element,a)
if isinstance(list_element,str):
y = str_to_num(list_element)
b += [y]
if isinstance(list_element,int):
y = list_element
b += [y]
if isinstance(list_element,float):
y = list_element
b += [y]
a += [b]
return return_container
return_container = []
output_a = getNumbers(input_a,return_container)[:-1]
This works (for this situation). But I have two problems:
1. It does not work so well if there is another level of nesting of list. I want to make it such that it can handle any level of nesting.
so if
input_b= [['a','12','','23.5',['15']],[12.3,'b2','-23.4',-32],[-25.4,'c']]
This gives
output_b= [[-15],['a',12,'',23.5],[12.3,'b2',-23.4,-32],[-25.4,'c']]
which is wrong as the [-15] should be nested within the first sub-list.
The code is very verbose!! I am sure there must be a much simpler way to handle this.
You follow the tradition of "Ask forgiveness not permission" - explain and simply try to convert.
input_b= [['a','12','','23.5',['15']],[12.3,'b2','-23.4',-32],[-25.4,'c']]
def parseEm(l):
"""Parses a list of mixed strings, strings of floats, strings of ints, ints and floats.
Returns int where possible, float where possible else string as list elements."""
def tryParse(elem):
def asInt(e):
"""Tries to convert to int, else returns None"""
try:
return int(e)
except:
return None
def asFloat(e):
"""Tries to convert to float, else returns None"""
try:
return float(e)
except:
return None
# if elem itself is a list, use list comp to get down it's elements
if isinstance(elem,list):
return [tryParse(q) for q in elem]
# try to convert to int, else to float or return original value
if isinstance(elem,str):
a,b = asInt(elem),asFloat(elem)
if a is not None:
return a
elif b is not None:
return b
return elem
# this does not work, as interger 0 is considered false:
# return asInt(elem) or asFloat(elem) or elem
# apply tryParse to all elements of the input list
return [tryParse(k) for k in l]
print(parseEm(input_b))
Output:
[['a', 12, '', 23.5, [15]], [12, 'b2', -23.4, -32], [-25, 'c']]
Be careful though, some things can be converted to floats that you might (not) want to - f.e. ["NaN"] is a valid list with 1 float in it.

Compare numbers in form: 12,3K , 1,84M in 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?

Categories

Resources