I’m studying Python and I don’t understand how to use iterators.
I need to write code. In C it’ll be like this:
list_node *cp = list_of_chars;
char dp = '>'; int flag = 0;
while (cp != NULL)
{ if( isdigit(cp->val) )
{ printf("%c",cp->val);
if( cp->val == '0' )
{ cp->prev->next = cp->next; cp->next->prev = cp->prev; }
else cp->val--;
}
else if( (cp->val == '>') || (cp->val == '<') )
{ dp = cp->val; flag = 1; }
if( dp == '>' ) cp = cp->next;
else if( dp == '<' ) cp = cp->prev;
else return ERR;
if( flag && ( (cp->val == '>') || (cp->val == '<') ))
{ cp->prev->prev->next = cp;
cp->prev = cp->prev->prev;
}
}
Can you help me translate this code to python? I started to write, but have some errors and I not sure, that I understand documentation.
ip = {'cp' : iter(program), 'dp' : '>'}
flag = 0
while ip['cp'] != []:
if ('0' <= ip['cp']) & (ip['cp'] <= '9'):
print ip['cp']
if ip['cp'] == '0': ip['cp'] = []
else: ip['cp'] -= 1
elif (ip['cp'] == '>') | (ip['cp'] == '<'):
ip['dp'] = ip.['cp']
flag = 1
else: raise NameError('incorrect cp-value')
if ip['dp'] == '>': ip['cp'].next()
elif ip['dp'] == '<': ip['cp'].prev()
else: raise NameError('incorrect dp-value')
if flag & ( (ip['cp'] == '>') | (ip['cp'] == '<') ):
ip['cp'].prev()
ip['cp'] = []
The question is how can I get the value of the iterator without the function next().
Examples of python-expert code with advanced uses of iterators would also be nice to see.
Okay here are lots of problems in you python code.
Well start with the simple
Could be written to simply
It will do while
ip['cp']isn’t a falsly value.[], None, ''are a falsly value for example.Instead of:
write
Even if in some case, writing inline code can work. Think about readability. Inline code is almost never a good start to make code readable and easy to debug. It will also make 90% of your syntax error easy to fix.
Here’s where the fun starts…
and
In python ‘0’ is the string
0. In python you’re working with string when you have a string object. You’re working with numbers when you have numbers… In other words the code you’re trying to write in python can’t be purely translated to python. The last char in a python string is not ‘\0’. It’s the last char in the string. In other words, you can really test for the last char like in C.Now lets talk about iterators
That said, disregarding all other problems in your code, here is how to work with iterators.
iter()is a builtin function that returns an iterator. In most case you don’t have to call it yourself. There are constructions that will do that for you.for example, you can write :
Is the same as:
That said, iterators are used to iter over something. What you are really looking for isn’t an iterator. Because iterator are one way thing. You can go to the end and you can’t go back. There is no previous. Your
Ccode implement a linked-list that can be used with an iterable but in your code, you’re changing the position of some nodes.If you want to write python code, don’t write C code in python