Converting a list of tuples into a string - python

I'm new to run-length coding and need help. I've been given a run-length string of a series of integer followed by characters that include letters/characters.
For example, I have a string:
1-4c8k2)
And I need to convert it into:
-cccckkkkkkkk))
What I've done is convert the run-length string into a list of tuples:
[('1','-'),('4','c'),('8','k'),('2','c')]
And tried creating a function which would convert it into a string however I get a TypeError: can't multiply sequence by non-int of type 'str'.
def decode(lst):
q = ''
for count, character in lst:
q += count * character
return q
I'm trying to think of a way to improve space complexity instead of creating a new list of tuples and more so, trying to resolve this TypeError.

I suspect that what has happened is you forgot to convert the counts into ints:
>>> 3 * 'a'
'aaa'
>>> '3' * 'a'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
>>> int('3') * 'a'
'aaa'

You try through this way :
lst = [('1','-'),('4','c'),('8','k'),('2','c')]
def decode(lst):
q = ''
for count, character in lst:
q += int(count) * character
return q
print(decode(lst))
Output :
-cccckkkkkkkkcc
Check this code here

Related

getting space separated input in python

I am trying to get space separated inputs. while the first method works completely fine, the second method throws an error saying:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
what is wrong with the second method?
Method 1:
x = [int(j) for j in input().split()]
Method 2:
x = [j for j in int(input().split())]
Because you are using split() to a string which will return a list, then you are passing this list to int() that's why you are getting error. for changing datatype of list you need to use map() as below or first approach of your's.
Try Below code
x = [j for j in map(int,input().split())]

I need to convert all the elements in my list to int in python when i used map it doesn't work

I am reading numbers from a file and storing it in a list numbers and want to convert all the elements in the list to be converted to int
num=[int(i) for i in numbers]
error msg:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
I also tried using map
num = list(map(int, numbers))
print("The integer list \n",num)
error msg:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
class int(x, base=10)
Return an integer object constructed from a number or string x, or
return 0 if no arguments are given. If x is a number, it can be a
plain integer, a long integer, or a floating point number.
It does not seem that all the elements in your list are valid.So maybe some of elements are like a1 or they aren't string, you should check out your list.
Try to run this and you will find why it didn't work:
from datetime import datetime
s=['1',datetime.now(),'a1'] # your list
def convert_to_int(s):
if isinstance(s,str):
try:
return int(s)
except:
print s, type(s)
return None
else:
print s,type(s)
return None
print list(map(convert_to_int,s))
Hope this helps.

Python list types

This is quite a weird/silly question so if anyone as a better title name, please request an edit.
I've created a function that returns the product of numbers in a list.
When testing this function, I tried lists that that included intergers and reals(floats), such as items = [1,2.0,3,4.0]
Function:
items = [1.0, 2, 3.0, 10, "a"]
def mult1(items):
total = 1
for i in items:
total = total * i
return total
print mult1(items)
This function above works with items being [1.0, 2, 3.0, 10] and the output of that particular list being 60.0.
I've studied Standard ML where you can only generally have a list of a particular type (I'm sure there's code out there that somehow makes my statement irrelevant), so intrigued to find out what would happen if I entered a string as a list item, I did, and got an error (I expected to get an error because you can't multiply a string with a number).
However, the error I received has confused me:
TypeError: can't multiply sequence by non-int of type 'float'
This error has confused me. I understand that a string cannot be multiplied, but does this also suggest that all of the items in the list are considered a float despite some looking like integers?
I thought that the error should suggest it cannot compute a type that is not a float or not an integer, but to me (probably wrong) it seems like it's suggesting that it can't multiply the list by a a type that is not an integer that is also not of type float?
To me this sounds like each element has two types, integer and float.
You're getting this error because you are (perhaps unintentionally) multiplying a sequence (list, str, tuple) by a float.
>>> a = [1, 2]
>>> a * 2
[1, 2, 1, 2]
>>> a * 2.0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
>>>
This error occurs because you can actually multiply some non-number types by ints, but not by floats. So if your product function looks something like:
def product(l):
prod = l[0]
for x in l[1:]:
prod *= x
return prod
and your list looks like this : l = ['this string',3,2.0]
then your iterations will show the following:
>>> def product(l):
prod = l[0]
for x in l[1:]:
prod *= x
print(prod)
return prod
>>> l = ['this string',3,2.0]
>>> product(l)
this stringthis stringthis string
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
product(l)
File "<pyshell#67>", line 4, in product
prod *= x
TypeError: can't multiply sequence by non-int of type 'float'
note that the first iteration is allowed because str*int is a valid expression (so is list*int and tup*int etc) and so prod is still valid but is a STRING, not an int or float. then when you DO try to do a str*float expression, the TypeError will occur.
You can multiply a string but only by an int, you see the error as you are trying to multiply a string by a float:
In [7]: "foo" * 2
Out[7]: 'foofoo'
In [8]: "foo" * 2.0
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-3128e6ce951c> in <module>()
----> 1 "foo" * 2.
TypeError: can't multiply sequence by non-int of type 'float'
In your particular case you are trying to multiply a from your list by a float:
[1.0, 2, 3.0, 10, "a"]
^
error
Total starts out an int but when you multiply an int by a float you get a float so total = total * 1.0 -> 1.0:
In [9]: 1 * 1.0
Out[9]: 1.0

Using str.replace to replace letters in a string at different placeholders of the string

I have a problem that I am working on. The goal of the problem is to take the string placeholder i. If i is an even placeholder, replace the letter at i with the letter at i -1. If the i place holder is odd, then replace the letter i with the letter at i +1.
Here is my code so far:
def easyCrypto (s):
for i in range (0,len(s)-1):
if i % 2 == 0:
str(s).replace(i,((i-1)))
if i % 2 != 0:
str(s).replace(i,((i+2)))
print (s)
My error:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
easyCrypto('abc')
File "C:/Python/cjakobhomework7.py", line 4, in easyCrypto
str(s).replace(i,((i-1)))
TypeError: Can't convert 'int' object to str implicitly
update!!
New code based on answers:
def easyCrypto (s):
for i in range (0,len(s)-1):
if i % 2 == 0:
s = str(s).replace(s(i),(s(i-1)))
else:
s = s.replace(s(i), s(i + 1))
print (s)
However I still have the following errors:
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
easyCrypto('abc')
File "C:/Python/cjakobhomework7.py", line 4, in easyCrypto
s = str(s).replace(s(i),(s(i-1)))
TypeError: 'str' object is not callable
Any ideas? thank you
Use s[i] instead of s(i), and likewise for the other indexes.
There are two things here:
str.replace does not automatically stringify its arguments. You need to manually convert them into strings. Remember that: "Explicit is better than implicit."
str.replace does not work in-place because strings are immutable in Python. You need to reassign s to the new string object returned by str.replace.
Your code should be:
s = s.replace(str(i), str(i-1))
Also, you can replace if i % 2 != 0: with else: since the condition of the second if-statement can only be true if the first is false:
if i % 2 == 0:
s = s.replace(str(i), str(i-1))
else:
s = s.replace(str(i), str(i+1))
Regarding your edited question, you are trying to call the string s as a function by placing parenthesis after it. You need to use square brackets to index the string:
>>> 'abcde'[0]
'a'
>>> 'abcde'[3]
'd'
>>>
In your case it would be:
s = s.replace(s[i], s[i-1])
As a general rule of thumb, parenthesis (...) are for calling functions while square brackets [...] are for indexing sequences/containers.

Python encoding key, minus one character if too long

Here is my code so far:
def code_block(text, key):
itext = int(text)
rkey = int(key)
res= itext + rkey
def last():
return res[-1:]
if res>=11111111:
last()
return res
Here is the task I've been set:
Now we need a function to take a block of code and a key as input, where both are assumed to be 8 digits long, and encrypts each digit of the number with the corresponding digit of the key:
>>> code_block('12341234','12121212')
'24462446'
>>> code_block('66554433','44556677')
'00000000'
Where am I going wrong? Could you point me in the right direction and indicate me how I was wrong?
You are going about this the wrong way. Treat this character by character:
def code_block(text, key):
res = [str(int(c) + int(k))[-1:] for c, k in zip(text, key)]
return ''.join(res)
which gives me:
>>> code_block('12341234','12121212')
'24462446'
>>> code_block('66554433','44556677')
'00000000'
The code sums each and every character separately, turning it back into a string and only using the last character of the result; 9 + 9 is 18, but the result would be '8'.
Your code would sum the whole numbers, but that would result in:
>>> 66554433 + 44556677
111111110
which is not the correct result. Neither did you ever turn your sum back into a string again, so your code, attempting to treat the sum result as a string by slicing it, gave an exception:
>>> code_block('12341234', '12121212')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in code_block
File "<stdin>", line 6, in last
TypeError: 'int' object has no attribute '__getitem__'

Categories