对python的简单迭代

时间:2018-04-08 17:39:37

标签: python python-2.7 loops methods

我的目标是编写一个类并仅使用__iter__next方法来查找数字的除数。这是我写的:

class Divisors(object):
    def __init__(self, integer):
        self.integer = integer
    def __iter__(self):
        self.divisor = 1
        return self
    def next(self):
        div = 0
        if self.divisor >= self.integer:
            raise StopIteration
        else:
            if self.integer % self.divisor == 0:
                div = self.divisor
            self.divisor += 1
        return div

当我查看时:

for i in Divisors(6):
    print i

我得到了

1
2
3
0
0

而不是1 2 3 6

但我不确定是否应该使用print而不是上面使用的 div 。关于我在这里做错了什么的提示?

2 个答案:

答案 0 :(得分:1)

在这种情况下进行调试时,您应该逐行进行操作。您编写的代码不会只打印数字的除数。

如果仔细查看方法- (IBAction)albumView:(id)sender { UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; [imagePicker.view setFrame:self.view.frame]; [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; [imagePicker setDelegate:self]; [ipc presentViewController:imagePicker animated:YES completion:nil]; } - (IBAction)cancel_IPC:(id)sender { [self imagePickerControllerDidCancel:ipc]; } -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{ [picker dismissViewControllerAnimated:YES completion:nil]; if(picker.sourceType == UIImagePickerControllerSourceTypeCamera){ LeafsnapTabBarController * tabBarController = (LeafsnapTabBarController*)self.tabBarController; [self.tabBarController setSelectedIndex:tabBarController.previousTabIndex]; } } -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage* origImage = [info objectForKey:UIImagePickerControllerOriginalImage]; /*do whatever you need to do with the img*/ [picker dismissViewControllerAnimated:YES completion:nil]; /*dismiss the original UIImagePickerController in background */ if(picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary){ [ipc dismissViewControllerAnimated:YES completion:nil]; } [mLocationManager stopUpdatingLocation]; } ,它首先将next初始化为0.然后,如果除数大于或等于整数,则停止循环。否则,如果整数可被除数整除,则修改div然后返回div(修改后的或原始的0)。

遵循上述逻辑,只要整数不能被除数整除,代码就会返回0。循环执行5次后停止(整数= 6)。因此输出div。在前三次迭代中,除数成功地将整数除(divisor = 1,2,3),而在接下来的两次中它没有(divisor = 4和5)。当除数变得等于整数(在这种情况下为6)时,循环停止而不返回任何内容。

这是python2的工作代码,它产生所需的输出

1 2 3 0 0

产生的输出是:

class Divisors(object):
def __init__(self,integer):
    self.integer = integer

def __iter__(self):
    self.divisor = 0
    return self

def next(self):
    div = 0

    self.divisor += 1
    while self.integer >= self.divisor and self.integer % self.divisor != 0:
        self.divisor += 1

    if self.divisor > self.integer:
        raise StopIteration

    div = self.divisor
    return div


for i in Divisors(6):
    print i

答案 1 :(得分:0)

您的-方法中需要while循环。我们可以添加它,然后简化您的逻辑:

next()