帮我修复一个程序

发布于 2024-10-08 01:22:54 字数 363 浏览 0 评论 0原文

你好,我得到了一个程序,它给出了长度为 n 的随机序列 0 和 1 的输出。但是,我的程序有一个小问题,因为我收到语法错误。我正在使用圣人。我应该解决什么问题?

from random import randint
def randString01(num):
    x = str() 
    count = num 
    while count >0: 
        if randint(0,1) == 0: 
            append.x(0)   
        else: 
            append.x(1) 
        count -= 1
    x=str(x) 
    return x

Hello I have gotten a program that gives an output of a random series of 0s and 1s of length n. However, there is a slight problem in my program because I get syntax error. I am using Sage. What should I fix?

from random import randint
def randString01(num):
    x = str() 
    count = num 
    while count >0: 
        if randint(0,1) == 0: 
            append.x(0)   
        else: 
            append.x(1) 
        count -= 1
    x=str(x) 
    return x

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

微凉徒眸意 2024-10-15 01:22:54

正如其他人指出的那样,您不应该使用“append”

from random import randint
def randString01(num):
    x = str() 
    count = num 
    while count >0: 
        if randint(0,1) == 0: 
            x += "0"   
        else: 
            x += "1" 
        count -= 1
    x=str(x) 
    return x

其次,这不是 Pythonic。您应该查看列表推导式

def randString01(num):
    return ''.join([str(randint(0,1)) for x in range(num)])

示例用法:

>>> randString01(5)
'01101'
>>> randString01(100)
'0110101001101001000110101100101100100100110001011111111101101010010011110000000
101010011001000000000'

为了将其分解为更简单的部分,我将对每个部分进行说明。

str.join

str.join(可迭代)¶
返回一个字符串,它是可迭代对象中字符串的串联。元素之间的分隔符是提供此方法的字符串。

>>> ",".join(["Beans","Eggs","Bacon"])
'Beans,Eggs,Bacon'

我使用此命令和空字符串将所有数值粘贴在一起

range

>>> range(5)
[0, 1, 2, 3, 4]
>>> range(100)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 2
2, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 4
2, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 6
2, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 8
2, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

I使用 range 来确保我的内部循环重复正确的次数

列表理解

>>> [x for x in [1,2,3]]
[1, 2, 3]
>>> [2*x for x in [1,2,3]]
[2, 4, 6]
>>> [str(x) for x in [1,2,3]]
['1', '2', '3']
>>> [str(5) for x in range(5)]
['5', '5', '5', '5', '5']
>>> [str(randint(0,1)) for x in range(5)]
['1', '0', '0', '1', '1']

请注意,我调用 str(randint(0,1)) 以确保列表中的值是字符串元素,而不是整数。如果您尝试调用 str.join(数字列表),您将收到错误:

>>> ''.join[1,2,3]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'builtin_function_or_method' object is unsubscriptable

因此将其捆绑在一起,括号中的部分将创建一个字符串元素列表,要么是 1,要么是 0。 ''.join(list) 将每个数字连接到下一个数字,形成单个字符串。

编辑:

感谢 TokenMacGuy 在评论中指出创建列表是不必要的。将 randString01 定义为就足够了,

def randString01(num):
    return ''.join(str(randint(0,1)) for x in range(num))

这是因为 join 的参数返回的生成器对象是可迭代的,并且 str.join 方法需要工作的只是一个可迭代对象。使用生成器比使用列表更好,因为它允许惰性求值,在这种情况下这不是什么大问题,但如果列表特别大,则可能是大问题。有关生成器的更多信息,请参阅 PEP 289 页面

这是一些相当高级的东西,但请不要被这个例子吓跑了。当您可以使用非常高级的抽象而不是低级的控制结构时,看看代码有多漂亮(一行而不是 ~10 行)。

as others noted, you shouldn't use 'append'

from random import randint
def randString01(num):
    x = str() 
    count = num 
    while count >0: 
        if randint(0,1) == 0: 
            x += "0"   
        else: 
            x += "1" 
        count -= 1
    x=str(x) 
    return x

Second, this is not pythonic at all. You should look into list comprehensions.

def randString01(num):
    return ''.join([str(randint(0,1)) for x in range(num)])

Sample usage:

>>> randString01(5)
'01101'
>>> randString01(100)
'0110101001101001000110101100101100100100110001011111111101101010010011110000000
101010011001000000000'

To break this into simpler pieces, I'll illustrate each piece.

str.join

str.join(iterable)¶
Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method.

>>> ",".join(["Beans","Eggs","Bacon"])
'Beans,Eggs,Bacon'

I use this command with the empty string to paste together all my numerical values

range

>>> range(5)
[0, 1, 2, 3, 4]
>>> range(100)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 2
2, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 4
2, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 6
2, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 8
2, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

I use range to make sure my inner loop repeats the correct number of times

list comprehension

>>> [x for x in [1,2,3]]
[1, 2, 3]
>>> [2*x for x in [1,2,3]]
[2, 4, 6]
>>> [str(x) for x in [1,2,3]]
['1', '2', '3']
>>> [str(5) for x in range(5)]
['5', '5', '5', '5', '5']
>>> [str(randint(0,1)) for x in range(5)]
['1', '0', '0', '1', '1']

Note that I call str(randint(0,1)) to ensure that the values in my list are string elements, rather than integers. If you try to call str.join(a list of numbers), you'll get an error:

>>> ''.join[1,2,3]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'builtin_function_or_method' object is unsubscriptable

So tying it together, the piece in brackets creates a list of string elements, either ones or zeros. The ''.join(list) concatenates each digit to the next, forming a single string.

EDIT:

Thanks to TokenMacGuy in the comments who points out that the list creation is unnecessary. It is sufficient to define randString01 as

def randString01(num):
    return ''.join(str(randint(0,1)) for x in range(num))

This is because the generator object returned by the argument to join is iterable, and all the str.join method needs to work is an iterable object. It is better to use the generator than the list because it allows lazy evaluation, which isn't a big deal in this case, but it could be if the list were exceptionally large. See the PEP 289 page for more on generators.

This is some pretty advanced stuff, but please don't be scared off of python by this example. See how beautiful the code can be (a single line as opposed to ~10), when you can use very high level abstractions rather than low level control structures.

江南月 2024-10-15 01:22:54

您正在尝试在字符串上使用列表的追加方法。

首先,字符串没有 append 方法。

其次,您需要编写 x.append("0").*

最后(因为字符串没有 append 方法),您想要编写的是 x+="0",或x = x+"0"

另外,您不需要最后的 x=str(x) 因为 x 已经是一个字符串。

*在Python中,调用对象的方法,语法为object.methodname(args)

You are trying to use the append method of a list, on a string.

First, strings have no append method.

Second, you would need to write x.append("0").*

And last (since strings have no append method), what you want to write is x+="0", or x = x+"0".

Also, you don't need that final x=str(x) since x is already a string.

*In python, to call the method of an object, the syntax is object.methodname(args),

时间你老了 2024-10-15 01:22:54

我想你想要更多这样的东西:

def randString01(length):
    my_string = ""
    for count in range(length):
        my_string += str(randint(0,1))
    return my_string

I think you want something more like this:

def randString01(length):
    my_string = ""
    for count in range(length):
        my_string += str(randint(0,1))
    return my_string
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文