首页 \ 问答 \ 生日悖论列表是非类型(Birthday Paradox List is nonetype)

生日悖论列表是非类型(Birthday Paradox List is nonetype)

我正试图用Python解决生日悖论。 我很接近,但最后一块让我感到茫然。 我正在使用随机生成给定范围和要创建的项目数的数字列表。 这样可行。

然后我检查列表(上面生成的)是否有重复。 这样可行。

然后我尝试生成给定(n)列表。 这是我遇到麻烦的地方。 它生成一个列表然后返回“NoneType”不可迭代。 让我感到困惑的是,列表已生成,但Python并未将其视为列表。

这是代码:

def make_bd(n, r):
    """Generates (r) numbers of birthdays in a range (n)."""
    import random
    t = [random.randrange(n) for i in range(r)]
    print (t)


def has_dupe(test):
    """Here I test to see if I can detect a duplicate birthday.
This is based on problem #4."""

    d = []
    count = 0
    for number in test:
        if number in d:
            count = count + 1
        d.append(number)
    if count >= 1:
        return True
    return False

def dupebd(n,r,t):
    count_dupe = 0
    for i in range(n):
        if has_dupe(make_bd(r,t)):
            count_dupe = count_dupe + 1
    print (float(count)/n)       

dupebd(50,365,23)

这是结果:

>>> has_dupe(make_bd(50,6))
[13, 3, 8, 29, 34, 44]
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    has_dupe(make_bd(50,6))
  File "<pyshell#44>", line 7, in has_dupe
    for number in test:
TypeError: 'NoneType' object is not iterable

I'm trying to solve the Birthday Paradox with Python. I'm close but the last piece has me at a loss. I'm using random to generate a list of numbers given a range and number of items to create. That works.

I then check to see if a list (generated above) has duplicates. That works.

I then try to generate a given (n) of lists. Here is where I run into trouble. It generates one list then returns "NoneType" is not iterable. What puzzles me is, the list is generated but Python is not seeing it as a list.

Here's the code:

def make_bd(n, r):
    """Generates (r) numbers of birthdays in a range (n)."""
    import random
    t = [random.randrange(n) for i in range(r)]
    print (t)


def has_dupe(test):
    """Here I test to see if I can detect a duplicate birthday.
This is based on problem #4."""

    d = []
    count = 0
    for number in test:
        if number in d:
            count = count + 1
        d.append(number)
    if count >= 1:
        return True
    return False

def dupebd(n,r,t):
    count_dupe = 0
    for i in range(n):
        if has_dupe(make_bd(r,t)):
            count_dupe = count_dupe + 1
    print (float(count)/n)       

dupebd(50,365,23)

Here's the result:

>>> has_dupe(make_bd(50,6))
[13, 3, 8, 29, 34, 44]
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    has_dupe(make_bd(50,6))
  File "<pyshell#44>", line 7, in has_dupe
    for number in test:
TypeError: 'NoneType' object is not iterable

原文:https://stackoverflow.com/questions/10374256
更新时间:2019-06-23 01:16

最满意答案

在第5行中,您打印t但不返回它,因此make_bd返回None 。 将行更改为

return t

In line 5 you print t but do not return it, so that make_bd returns None. Change the line to

return t
2012-04-29

相关问答

更多

将悖论转换为MDB(Convert Paradox to MDB)

我曾经使用我在此页上找到的Delphi代码成功访问了转换: http://delphi.about.com/od/database/l/aa062601a.htm I once did Paradox to Access conversion successfully using the Delphi code that I found on this page: http://delphi.about.com/od/database/l/aa062601a.htm

'NoneType'对象在Python 3的列表修饰符函数中没有属性'strip'“[closed]('NoneType' object has no attribute 'strip'" on my list modifier function in Python 3 [closed])

我没有得到你的错误,但它可能源于你创建的变量与函数html_list ,也许? 我在python2和python3中测试了这个代码,它似乎工作。 我修改了代码,以便你的函数返回input_list 。 它在输出处调用该函数。 list_1 = ["hey", "hello", "joe"] def html_list(input_list): new_list = ["<ul>"] for item in input_list: new_list.append(

解析表时Python处理NoneType(Python handling NoneType when parsing tables)

itertools.zip_longest接受可选的fillvalue参数。 如果提供,则使用它而不是None : >>> list(itertools.zip_longest([1, 2, 3], [4, 5])) [(1, 4), (2, 5), (3, None)] >>> list(itertools.zip_longest([1, 2, 3], [4, 5], fillvalue='NULL')) [(1, 4), (2, 5), (3, 'NULL')] 您可以提供空行(NULL值

操作必须是可更新的查询 - VB脚本,悖论表(Operation must be an updateable query - VB Script, Paradox Table)

尝试“CREATE TABLE test(id INT,comment VARCHAR(30),primary key(id))” I don't know much about Paradox databases but this has indeed been a learning experience. Even though I have a table file called table.db that's not enough to store more than a single

编译器不断抛出AttributeError:“'NoneType'对象没有属性'append'”[重复](Compiler keeps throwing AttributeError: “'NoneType' object has no attribute 'append'” [duplicate])

更新您的第一个for循环: for number in mather: episode_list.append(number) list.append在list中执行追加操作并返回None 。 另外,在你的第二个for循环中,你需要做: for element in episode_list: total += int(element) # ^ Type-cast the value to `int` type Update your first fo

AttributeError:'NoneType'对象没有属性'findChildren'(美丽的汤)(AttributeError: 'NoneType' object has no attribute 'findChildren' (Beautiful Soup))

soup.find('ul',{'class': "tags"})返回None 。 如果要在列表推导中使用它,则需要在使用它们之前过滤掉None值。 有一个技巧,你可以将值放在列表中,以便过滤它: tags_dict['tags'] = [child.text for tag in [soup.find('ul',{'class': "tags"})] if tag fo

创建元组列表,元组元素作为输入(Create list of tuples , tuple elements taken as Input)

append()函数不返回附加列表,它返回NoneType因为它执行附加到位 ,因此您只需更改行: l=l.append(tuple(i)) 至: l.append(tuple(i)) 这应该工作。 The append() function does not return an appended list, it returns a NoneType because it performs the append in place, so you can simply change the

Python中的逻辑悖论?(Logical paradox in python?)

这是由于运营商的优先。 not none == True意思not (None == True)表示None != True ,这是正确的。 同样, None != False也是如此。 值None与布尔值不同。 你最后的两个表达式表示False != False ,这是假的, False != True ,这是真的。 This is due to operator precedence. not none == True means not (None == True) means None ! ...

相关文章

更多

最新问答

更多
  • 使用javascript为用户延迟加载内容的更好方法是什么?(What is a better way to lazy load content for users with javascript?)
  • 如何修复无法将类型的值...转换为预期的参数类型inout _(How to fix Cannot convert value of type … to expected argument type inout _)
  • 从哪里开始解析JSON?(Where to start with parsing JSON?)
  • Mail.php不适用于.htaccess(Mail.php doesn't work with .htaccess)
  • 使用htaccess设置子域(Setting subdomains using htaccess)
  • mod_pagespeed和java应用服务器(mod_pagespeed and java app servers)
  • Win32:如何崩溃?(Win32: How to crash?)
  • FFmpeg中RGB到YUV转换的错误(Error in RGB to YUV conversion in FFmpeg)
  • 如何在Android中首次打开应用时创建弹出窗口?(How to create pop-up when first open app in Android?)
  • 通过动态传递表名和列名来反转COLUMN DATA(Reversing COLUMN DATA by dynamically passing table name and Column Name)
  • 如何计算C#中ICollection中有多少元素?(How can I count how many elements are in an ICollection in C#)
  • 从pg-promise查询中获得结果(get result out of a pg-promise query)
  • 使用管理器注册一个类,然后调用子类重写方法(Register a class with a manager, then call the sub classes overridden methods)
  • 传递&在查询字符串中(Passing & in query string)
  • 谷歌浏览器打印预览不会第一次加载页面(google chrome print preview does not load the page the first time)
  • FsLexYacc:Tests / MiniProject“在.fsproj中导入错误”(FsLexYacc : Tests/MiniProject “incorrect Import in .fsproj”)
  • 创建一个模型方法,计算用户的帖子并在rspec(Rails)中测试?(Create a model method that counts a user's posts and test in rspec (Rails)?)
  • 记录线程的奇怪行为(Strange behaviour of logging thread)
  • 移动数组中的索引(Moving indices in an array)
  • MVC 5 - > MVC 5.1迁移。(MVC 5 -> MVC 5.1 Migration. Intellisense issues)
  • 使用函数在z3中创建列表(Creating List in z3 using function)
  • 如何进行html随机重定向(How to make a html random redirect)
  • 角度js:使用角度过滤器分割日期,月份和时间(Angular js: spliting date,month and time using angular filter)
  • 将所有模块导入一个文件夹,并按其属性之一使用它们(Import all modules in one folder and use them by one of its attributes)
  • 只需要在git的当前分支上获得合并列表(Just get list of merge happened on my current branch in git)
  • React-Native导入库并在多个组件中可用(React-Native import a library and make available in multiple components)
  • 如何使用jQuery为固定(偏移)位置设置div动画?(How to animate div for a fixed (offset) position using jQuery?)
  • operator ==和vector confusion(operator== and vector confusion)
  • 如何获取所选图像映射alt值?(How to get selected image map alt value?)
  • 在角度,如何使用取消用户事件的美元间隔,如页面更改?(In angular, how to use cancel an $interval on user events, like page change?)