Thu*_*ira 2 python iterator generator
给定一个任意输入字符串,我想找到该字符串中所有数字的总和.这显然要求我在迭代它时知道字符串中的NEXT元素......并决定它是否为整数.如果前一个元素也是一个整数,则这两个元素形成一个新的整数,所有其他字符都被忽略,依此类推.
例如输入字符串
ab123r.t5689yhu8
Run Code Online (Sandbox Code Playgroud)
应该导致总和123 + 5689 + 8 = 5820.
这一切都是在不使用正则表达式的情况下完成的.
我已经在python中实现了一个迭代器,我认为其(next())方法返回下一个元素,但是传递输入字符串
acdre2345ty
Run Code Online (Sandbox Code Playgroud)
我得到以下输出
a
c
d
r
e
2
4
t
y
Run Code Online (Sandbox Code Playgroud)
有些数字3和5缺失了......为什么会这样?我需要next()为我工作,以便能够筛选输入字符串并正确地进行计算
更好的是,我应该如何实现下一个方法,以便在给定的迭代期间直接生成元素?
这是我的代码
class Inputiterator(object):
'''
a simple iterator to yield all elements from a given
string successively from a given input string
'''
def __init__(self, data):
self.data = data
self.index = 0
def __iter__(self):
return self
def next(self):
"""
check whether we've reached the end of the input
string, if not continue returning the current value
"""
if self.index == len(self.data)-1:
raise StopIteration
self.index = self.index + 1
return self.data[self.index]
# Create a method to get the input from the user
# simply return a string
def get_input_as_string():
input=raw_input("Please enter an arbitrary string of numbers")
return input
def sort_by_type():
maininput= Inputiterator(get_input_as_string())
list=[]
s=""
for char in maininput:
if str(char).isalpha():
print ""+ str(char)
elif str(char).isdigit() and str(maininput.next()).isdigit():
print ""+ str(char)
sort_by_type()
Run Code Online (Sandbox Code Playgroud)
Python字符串已经可以迭代,不需要创建自己的迭代器.
因此,无需迭代器即可实现您想要的任务:
s = "acdre2345ty2390"
total = 0
num = 0
for c in s:
if c.isdigit():
num = num * 10 + int(c)
else:
total += num
num = 0
total += num
Run Code Online (Sandbox Code Playgroud)
结果如下:
>>> print total
4735
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
276 次 |
| 最近记录: |