so I have this string dictionary of tuples:
data = '604452601061112210'
NewDict = {'60': ('PUSH1', 1), '61': ('PUSH2', 2), '52' : ('MSTORE', 0 ), '12' : ('ADD', 0)}
im trying to scan the string for the dictionary keys, to add to add the dict key to the list, along with the following bytes within the string, for example, it should print out in this order:
[PUSH1 44, MSTORE, PUSH1 10, PUSH2 1122, ADD]
however, my output is:
['PUSH1 44', 'MSTORE ', 'PUSH1 10', 'PUSH2 2210']
this is my code:
i = 0
L = []
while i < len(data):
op = data[i:i+2]
for item in NewDict:
if op in item:
i += NewDict[item][1] * 2
pep = NewDict[item][0] + ' ' + data[i:i+NewDict[item][1] * 2]
L.append(pep)
else:
i += 2
print(L)
any help would be appreciated, thanks
The problem is that you're incrementing i by NewDict[item][1] * 2 before you extract the parameter after the operator. You should do this after extracting.
You also don't need the for item in NewDict: loop, just access the element of NewDict directly.
while i < len(data):
op = data[i:i+2]
if op in NewDict:
opname, oplen = NewDict[op]
param = data[i+2:i+2+oplen*2]
L.append(opname + " " + param)
i += 2 + oplen*2
else:
i += 2
Even after fixing this you don't get ADD in the result because the last op in data is 10, not 12.
i = 0
L = []
while i < len(data):
op = data[i:i+2]
for item in NewDict:
if op in item:
i += NewDict[item][1] * 2
pep = NewDict[item][0] + ' ' + data[i:i+NewDict[item][1] * 2]
L.append(pep)
else:
i += 2
print(','.join(L))
','.join(L) removes the quotes around it. Hope this is what you meant? you can't really add a tuple to a list because those are different things. A tuple is, easy said, an unchangeable list.
Related
Given the following list:
list = [2,10,10,10,4,5]
How can I write a function that returns the output:
output = 210AA:45
I was working with this code so far, but don't know what else to add so that once a number between 10 and 15 is repeated, return the repeated number in its hexadecimal form as in the output
def int_to_string(data):
string = ""
for i in data:
hexadecimal = hex(i)
string += hexadecimal[2:]
string[0] = 15
return string
Use a list [] instead of a string ""
strings are immutable and don't support index lookup and assignment.
append the hex val and then edit the first index as you see fit to get your result
and retun a joined list with
''.join(#ur_lst)
A dictionary describing the mapping between decimal and hex could add readability.
Remark: don't shadow the name of build-functions, in this case list. See doc for a complete list.
lst = [2,10,10,10,4,5,13,15,0] # <- new testing list
# dictionary for conversion
num2hex = {i: str(i) for i in range(10)}
num2hex.update(zip(range(10, 16), "ABCDEF"))
# conversion list -> str
res = ''
consecutve_hex, is_last_hex = 0, False
for d in lst:
if 10 <= d <= 15:
consecutive_hex += 1
is_last_hex = False
if consecutive_hex > 1:
res += num2hex[d]
else:
res += str(d)
else:
if not is_last_hex:
if res:
res += ':'
consecutive_hex = 0
is_last_hex = True
res += str(d)
print(res)
#210AA:4513F:0
Example:
list = [abcc, typpaw, gfssdwww]
expected result = atgbyfcpscpsadwwww
Any ideas?
This is what i made so far:
def lazy_scribe(sources: list):
result: str = ''
i = 0
while i < len(max(sources, key=len)):
for source in sources:
for char in source:
if i <= len(source):
result = result + source[int(i)]
else:
continue
i += 1 / (len(sources))
break
return result
sources = ["python", "java", "golang"]
print(lazy_scribe(sources))
print(len(sources))
result: "pjgyaoyvlhaaononngn". I dont know why there is "y" instead of t (7 char in result string)
If I understand the problem correctly, this should work.
list = ["abcc", "typpaw", "gfssdwww"]
max_len = len(max(list, key=len))
res = ""
char_iterator = 0
while char_iterator < max_len:
for word in list:
if char_iterator < len(word):
res += word[char_iterator]
char_iterator += 1
print(res)
Another possible solution is as follows:
l = ['abcc', 'typpaw', 'gfssdwww']
max_len = len(max(l, key=len))
padded_l = list(zip(*[e + " " * (max_len - len(e)) for e in l]))
''.join([''.join(e) for e in padded_l]).replace(' ', '')
find the longest string in the list
then pad all the strings in the list with blank space
use zip on the result list
join the elements and replace the blank space to get the desired result
I am trying to loop over through multiple lists and check whether the list has multiple occurrences. If so I want to rename he lists.
I have tried looping over using two for loops but this code works perfectly for single list and not multi list.
new_word = [['abc'],['out'],['pqr'],['abc']]
for i in range(len(new_word)-1):
word_counter = 1
for j in range(i+1, len(new_word)):
if new_word[i] == new_word[j]:
word_counter = word_counter + 1
new_word[j] = new_word[j] + "_" + str(word_counter)
if word_counter > 1:
new_word[i] = new_word[i] + "_1"
Expected :
[['abc_1'],['out'],['pqr'],['abc_2']]
Actual:
[['abc'],['out'],['pqr'],['abc']]
This is a bit more verbose than the accepted answer, but will scan all
items in the original a list just once. It does not matter the least thing for small lists, (<10000 items) and no critical response time (i.e. , you don't have to feed this result to a HTTP response several times each second, for example).
from copy import deepcopy
def suffix_repeats(lst):
result = deepcopy(lst)
mapping = {}
for i, item in enumerate(lst):
mapping.setdefault(item[0], []).append(i)
for key, positions in mapping.items():
if len(positions) > 1:
for j, pos in enumerate(positions, 1):
result[pos][0] += f"_{j}"
return result
new_word = [['abc'],['out'],['pqr'],['abc']]
print(suffix_repeats(new_word))
new_word = [["abc"], ["out"], ["pqr"], ["abc"]]
for i in range(len(new_word) - 1):
word_counter = 1
for j in range(i + 1, len(new_word)):
if new_word[i] == new_word[j]:
word_counter = word_counter + 1
new_word[j] = [new_word[j][0] + "_" + str(word_counter)]
if word_counter > 1:
new_word[i] = [new_word[i][0] + "_1"]
Try this:
new_word = [['abc'],['out'],['pqr'],['abc']]
res=[[el[0]] if new_word.count(el)<2 else [el[0]+"_"+str(new_word[:k].count(el)+1)] for k, el in enumerate(new_word)]
print(res)
And output:
[['abc_1'], ['out'], ['pqr'], ['abc_2']]
[Program finished]
Is there a way to convert the string "12345678aaaa12345678bbbbbbbb" to "12345678-aaaa-1234-5678-bbbbbbbb" in python?
I am not sure on how to do it, since I need to insert "-" after elements of variable lengths say after 8th element then 4th element and so on.
This function inserts a char at a postion for a string:
def insert(char,position,string):
return string[:position] + char + string[position:]
Python strings cannot be mutated. What we can do is create another string with the hyphen inserted in between, as per your wish.
Consider the string s = "12345678aaaa12345678bbbbbbbb"
Giving s[:8] + '-' + s[8:] will give you 12345678-aaaa12345678bbbbbbbb
You can give the hyphen as you wish by adjusting the : values.
For more methods to add the hyphen, refer to this question thread for answer as to how to insert hypForhen.
Add string in a certain position in Python
You can follow this process :
def insert_(str, idx):
strlist = list(str)
strlist.insert(idx, '-')
return ''.join(strlist)
str = '12345678aaaa12345678bbbbbbbb'
indexes = [8, 4, 4, 4]
resStr = ""
idx = 0
for val in indexes:
idx += val
resStr = insert_(str,idx)
str = resStr
idx += 1
print(str)
output :
12345678-aaaa-1234-5678-bbbbbbbb
This doesn't exactly create the string you want but posting it anyway.
It finds all the indexes where digit becomes alpha and vice versa.
Then it inserts "-" at these indexes.
a = "12345678aaaa12345678bbbbbbbb"
lst = list(a)
index = []
for ind,i in enumerate(list(a)[:-1]):
if (i.isdigit() and lst[ind+1].isalpha()) or (i.isalpha() and lst[ind+1].isdigit()):
index.append(ind)
for i in index[::-1]:
lst.insert(i+1,"-")
''.join(lst)
'12345678-aaaa-12345678-bbbbbbbb'
Simplest solution:
str = '12345678aaaa12345678bbbbbbbb'
indexes = [8, 4, 4, 4]
i = -1
for index in indexes:
i = i + index + 1
str = str[:i] + '-' + str[i:]
print str
Prints: 12345678-aaaa-1234-5678-bbbbbbbb
You are free to change indexes array to achieve what you want.
If your want do this in one time , you can like this.
str = "12345678aaaa12345678bbbbbbbb"
def insert(char,positions,string):
result = ""
for post in range(0, len(positions)):
print(positions[post])
if post == 0:
result += string[:positions[post]] + char
elif post == (len(positions) -1 ):
result += string[positions[post-1]:positions[post]] + char + string[positions[post]:]
else:
result += string[positions[post-1]:positions[post]] + char
print(result)
return result
insert("-", [8, 12, 16, 20], str)
Here is my question
count += 1
num = 0
num = num + 1
obs = obs_%d%(count)
mag = mag_%d%(count)
while num < 4:
obsforsim = obs + mag
mylist.append(obsforsim)
for index in mylist:
print index
The above code gives the following results
obs1 = mag1
obs2 = mag2
obs3 = mag3
and so on.
obsforrbd = parentV = {0},format(index)
cmds.dynExpression(nPartilce1,s = obsforrbd,c = 1)
However when i run the code above it only gives me
parentV = obs3 = mag3
not the whole list,it only gives me the last element of the list why is that..??
Thanks.
I'm having difficulty interpreting your question, so I'm just going to base this on the question title.
Let's say you have a list of items (they could be anything, numbers, strings, characters, etc)
myList = [1,2,3,4,"abcd"]
If you do something like:
for i in myList:
print(i)
you will get:
1
2
3
4
"abcd"
If you want to convert this to a string:
myString = ' '.join(myList)
should have:
print(myString)
>"1 2 3 4 abcd"
Now for some explanation:
' ' is a string in python, and strings have certain methods associated with them (functions that can be applied to strings). In this instance, we're calling the .join() method. This method takes a list as an argument, and extracts each element of the list, converts it to a string representation and 'joins' it based on ' ' as a separator. If you wanted a comma separated list representation, just replace ' ' with ','.
I think your indentations wrong ... it should be
while num < 4:
obsforsim = obs + mag
mylist.append(obsforsim)
for index in mylist:
but Im not sure if thats your problem or not
the reason it did not work before is
while num < 4:
obsforsim = obs + mag
#does all loops before here
mylist.append(obsforsim) #appends only last
The usual pythonic way to spit out a list of numbered items would be either the range function:
results = []
for item in range(1, 4):
results.append("obs%i = mag_%i" % (item, item))
> ['obs1 = mag_1', 'obs2 = mag_2', 'ob3= mag_3']
and so on (note in this example you have to pass in the item variable twice to get it to register twice.
If that's to be formatted into something like an expression you could use
'\n'.join(results)
as in the other example to create a single string with the obs = mag pairs on their own lines.
Finally, you can do all that in one line with a list comprehension.
'\n'.join([ "obs%i = mag_%i" % (item, item) for item in range (1, 4)])
As other people have pointed out, while loops are dangerous - its easier to use range