convert integer to string then back to integer - python-3.x

I'm doing this python exercise where the goal is for a user to key in an integer and the function should be able to re-arrange (descending) I decided to convert the integer first to a string so I can iterate from that and the result is stored in a list. But when i try to convert it back to integer it doesn't get converted.
as shown in my code below, i tried printing the type of my variables so that I would see if its getting converted.
def conversion(nums):
int_to_str = str(nums)
list_int = []
ans = []
for x in int_to_str:
list_int.append(x)
list_int.sort(reverse=True)
ans = list_int
print (type(ans))
print(ans)
ans = ''.join(list_int)
print(type(ans))
print(ans)
str_to_int = [int(x) for x in list_int] # LIST COMPREHENSION to convert
# string back to integer type
print(type(str_to_int))
print(str_to_int)
final = ''.join(str_to_int)
print(type(final))
print(final)
enter code here
<class 'list'>
['9', '5', '4', '2', '1', '0']
<class 'str'>
954210
<class 'list'>
[9, 5, 4, 2, 1, 0]
TypeError: sequence item 0: expected str instance, int found

if I understood your question, you are receiving an input (assuming string representation of some int) and you want to convert that input to a list of integers then reverse sort and return. if that is the case:
def reverse_numeric_input(x):
try:
if type(x) != str:
x=str(x)
lst=[int(i) for i in x]
lst.sort(reverse=True)
return "".join([str(i) for i in lst])
except Exception as e:
print("%s error coverting ur input caused by: %s" % (e.__class__.__name__, str(e)))
the problem in the code you posted lies in this line final = ''.join(str_to_int) when you call join, the joined items must be cast to str() first. hope that helps.

Related

How to convert an integer into a roman numeral?

I'm having trouble to make an integer into roman numeral for having an ouptut of integer with square brackets (I'm pretty sure it's a list, but what I want is to have an integer) and I couldn't find solution why I'm having 'None' on 'rom' value.
I'm using python3.
roman.py
#!/usr/bin/env python3
import sys
def numToRom(number):
rom = ["", "I", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
if number in range(0, 9):
result = rom[number]
return result
num = sys.argv[1:]
rom = numToRom(num)
print(num, " is ", rom)
$ ./roman.py 2
Old output:
['2'] is None
Desired output:
2 is II
Your problem stems from the fact that you're passing a list with a character inside to your function. And that function expects an integer (if number in range(0, 9)), so you need to convert it to the right integer.
import sys
def numToRom(number):
if type(number) is list: # If you know your number might be a list with only one str(value)
number = int(number[0])
rom = ["", "I", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
if number in range(0, 9):
result = rom[number]
return result
That will work specifically for your use case, if number is of the form ['{some digit}]. If you want to get fancier, you could use recursion to return a list with the roman number of each number in a list, like so:
def numToRom(number):
if type(number) is list:
rom = []
for value in number:
rom.append(numToRom(int(value)))
return rom
else:
rom = ["", "I", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
if number in range(0, 9):
result = rom[number]
return result
>>> num = ['2', '3', '5']
>>> numToRom(num)
['2', '3', '5'] is ['III', 'IV', 'VI']
Note that this function works even if the values inside the input list are not characters, but normal integers.
>>> num = [2, 3, 5]
>>> rom = numToRom(num)
[2, 3, 5] is ['III', 'IV', 'VI']
pip install roman
import roman
print(roman.toRoman(int(input())))

creating a new object based on the type of the given object in python

I have a function that gets a sequence as a parameter and based on the type of that sequence, it creates a new object of that type.
def myFunc(seq):
new_object = # don't know how to instantiate it based on seq type.
For example, if 'seq' is a list, 'new_object' will be an empty list.
Or if 'seq' is a string, 'new_object' will be an empty string and so on.
How can I do that??
This works:
def make_empty(obj):
return type(obj)()
>>> make_empty([1, 2, 3])
[]
>>> make_empty('abc')
''
Works also for numbers not only sequences:
>>> make_empty(2)
0
or dictionaries:
>>> make_empty({'a': 100})
{}
Use type to get the type of the object and use () to create new, empty instance of it.
A version that allows to specified the allowed types:
def make_empty(obj, allowed_types=None):
if allowed_types is None:
return type(obj)()
for typ in allowed_types:
if isinstance(obj, typ):
return type(obj)()
raise TypeError(f'Type {type(obj)} not allowed')
Now.
It still works non-sequences:
>>> make_empty(3)
0
But the allowed types can be specified:
>>> make_empty(3, allowed_types=(str, list, tuple))
...
TypeError: Type <class 'int'> not allowed
The sequences work if allowed:
>>> make_empty('abc', allowed_types=(str, list, tuple))
''
>>> make_empty([1, 2, 3], allowed_types=(str, list, tuple))
[]
>>> make_empty((1, 2, 3), allowed_types=(str, list, tuple))
()
A dictionary does not if not allowsd:
>>> make_empty({'a': 100}, allowed_types=(str, list, tuple))
...
TypeError: Type <class 'dict'> not allowed
since your object is a sequence you can use a slice to get a new object of the same type but empty:
def make_empty(obj):
return obj[:0]
make_empty(['a', 'b', 'c'])
output:
[]
You could access its __class__() attribute.
def empty(obj):
return obj.__class__()
print(empty(2)) # -> 0
print(empty([1,2,3])) # -> []

Python taking input as list of integers

I am trying to take input as list of integers. Here is my attempted code
input_binary = int(list(input("enter a binary number: "))) # taking a user input as integers
Here is the error it is throwing
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
Have any idea?
You can't convert a list into an integer (at least, not with int()), which is what you're trying to do. Instead, try doing things in the other order.
Say you want a list of 5 integers:
binary = []
for _ in range(5): # do the following 5 times
inp = int(input("enter a binary number: ")) # take user input as string, convert to int
binary.append(inp) # put that int into our list
If you want to have input "123456" and output [1,2,3,4,5,6]
input_string = [int(num) for num in input("enter a binary number: ")]
print(input_string)
Result:
enter a binary number: 123456
[1, 2, 3, 4, 5, 6]

How to test if an input has only specific characters

Im trying to make a script that tests id there are characters in the input that are not A, T, C, G and if there are than the input is false.
I dont have any clue how to start. I would love if someone could help.
Thanks!
The following function can check a string to find out if it only contains the characters A, T, C, and G.
def check_string(code):
return all(character in {'A', 'T', 'C', 'G'} for character in code)
Expressed using sets:
The list function takes a string and returns a list of its characters. The set function takes a list and returns a set (with duplicates discarded).
>>> def check_string(code):
... return set(list('ACTG')).issuperset(set(list(code)))
...
>>> check_string('IT')
False
>>> check_string('ACTG')
True
>>> check_string('')
True
>>> check_string('ACT')
True
output = True
nucl_dict = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
n = input("Insert DNA seqence: ").upper()
for c in n:
if(c in ("A", "T", "C", "G")):
output = False
if(output == False):
print('Issue detected please try again')
print(n)
print(''.join(nucl_dict.get(nucl, nucl) for nucl in n))
else:
print("All good")

How to change values in a dictionary from a string to an integer and back again?

I have a dictionary like this:
d = {(1,1):'.',(2,2):'b', (3,3):'1',(4,4):'2',(5,5):'3'}
and i want to be able to iterate over the items in the dictionary, check if a key's value is a number (it is currently a string type but I need to check if said string is actually a numeral not a dot or letter) and add to that value,
as in value += 1.
I need to return the dictionary with it's key's values back in string form.
What's the best way to change the values from a string type to an integer (in order to add +1) and back into a string so that the returned dictionary will look like this?:
d = {(1,1):'.',(2,2):'b', (3,3):'2',(4,4):'3',(5,5):'4'}
>>> d = {(1,1):'.',(2,2):'b', (3,3):'1',(4,4):'2',(5,5):'3'}
>>> {k:(str(int(v)+1) if v.isdigit() else v) for k, v in d.items()}
{(2, 2): 'b', (1, 1): '.', (4, 4): '3', (5, 5): '4', (3, 3): '2'}
>>>
You could use dictionary comprehensions for this where in you can check if the value comprises of digits then return +1 value else return as it is.

Resources