将元素循环添加到列表中

huangapple go评论79阅读模式
英文:

looping element into a list

问题

以下是您提供的代码的翻译:

我正在尝试列出数字99除以2的幂248163264的唯一余数这些幂小于99
以下是代码

num = 99
div = 2
lst = []

while div < num:
    r = num % div
    while r != 0 and r not in lst:
        lst.append(r)
    div = div * div
print(lst)

您提到的代码未将99 % 64的余数(35)添加到列表中的问题可能是由于内部循环条件的限制。您可以尝试将内部循环的条件稍微修改,以确保它考虑到99 % 64的情况。以下是一个可能的修复:

num = 99
div = 2
lst = []

while div < num:
    r = num % div
    while r != 0 and r not in lst:
        lst.append(r)
    if div == 2:  # 添加此条件以确保考虑到99 % 64的情况
        lst.append(num % 64)
    div = div * div
print(lst)

这应该产生您期望的输出:[1, 3, 35]。希望这可以帮助您解决问题。如果您有其他问题,请随时提问。

英文:

I am trying to make a list of the unique remainders for the number 99 divided by the powers of 2 (2,4,8,16,32,64) which are lower then that of 99.
here is the code:

num = 99
div = 2
lst = []

while div &lt; num:
    r = num % div
    while r != 0 and r not in lst:
        lst.append(r)
    div = div * div
print(lst)`

The code I use doesn't append the remainder for the 99 % 64 in the list, which is 35.
program output:
[1,3]

intended output:
[1,3,35]

I am a complete beginner in programming, I would appreciate if you can help me find out the correct approach for the problem I have.

答案1

得分: 1

你的方法

添加一个变量来跟踪幂次,并在每次循环中递增它:

num = 99
div = 2
power = 1
lst = []

while div < num:
    r = num % div
    while r != 0 and r not in lst:
        lst.append(r)
    power += 1  # 递增幂次变量
    div = div ** up  # 双星号表示幂运算
    print(div)
print(lst)

另一种方法

你也可以以更具Python风格的方式完成它。

  • 第一行返回一个列表,其中包含小于99的所有2的幂
  • 第二行将每个元素映射到其余数,将其转换为数据类型set(以保留所有唯一元素),最后将其转换为列表。
a = [x for x in [2**p for p in range(1, 11)] if x < 99]
a = list(set(map(lambda x: 99 % x, a)))
print(a)

我不建议像下面这样将所有内容放在一行中,因为这会降低可读性。

a = list(set(map(lambda x: 99 % x, [x for x in [2**p for p in range(1, 11)] if x < 99])))  # 不要这样做
英文:

Your way

Add a variable to keep track of the power and increment it in each loop:

num = 99
div = 2
power = 1
lst = []

while div &lt; num:
    r = num % div
    while r != 0 and r not in lst:
        lst.append(r)
    power += 1 # Increment the power variable
    div = div ** up # Double asterisks is for the power operation
    print(div)
print(lst)

Another way

You can do it also in a more pythonic way.

  • First line, returns a list with all powers of 2 lower than 99
  • Second line, maps each element to its remainders, converts it to the datatype set (to keep all unique elements), and finally converts it to list.
a = [x for x in [2**p for p in range(1, 11)] if x &lt; 99]
a = list(set(map(lambda x : 99 % x, a)))
print(a)

I would not suggest putting it all in one line like below because you lose readability.

a = list(set(map(lambda x : 99 % x, [x for x in [2**p for p in range(1, 11)] if x &lt; 99]))) # Don&#39;t do it

答案2

得分: 1

Here is the translated code:

你的 `div` 在每一步中都在增加如下所示
```plaintext
0 -> 2
1 -> 4 # 2*2
2 -> 16 # 4*4
3 -> 256 # 16 * 16

在第3步/循环中,div 的值大于 num,即 256 > 99,因此程序在 while 循环中结束,因此退出,你的输出变为 [1, 3]

要解决这个问题,你需要以2的倍数增加 div 的值。以下是代码示例:

>>> num = 99
>>> div = 2
>>> lst = []
>>> while div < num:
...     r = num % div
...     while r != 0 and r not in lst:
...             lst.append(r)
...     div = div * 2
... 
>>> print(lst)
[1, 3, 35]

性能稍微更好的代码示例,使用集合(set):

>>> num = 99
>>> div = 2
>>> lst = set()
>>> 
>>> while div < num:
...     r = num % div
...     lst.add(r)
...     div = div * 2
... 
>>> lst
{1, 3, 35}
>>> print(list(lst))
[1, 3, 35]

使用集合推导式:

from math import log, ceil
num = 99
result =  {num%(2**i) for i in range(1, ceil(log(num, 2)))}
print(result)
# {1, 3, 35}

使用具有字典属性的集合推导式,因为在那里顺序是保留的:

from math import log, ceil
num = 99
result =  {num%(2**i): 1 for i in range(1, ceil(log(num, 2)))}
print(result.keys())
# dict_keys([1, 3, 35]) # 使用 list(result.keys()) 以获取列表输出

<details>
<summary>英文:</summary>

your `div` is incrementing in each step as 

0 ->2
1 -> 4 # 22
2 -> 16 # 4
4
3 -> 256 # 16 * 16


here in step/loop 3, value of `div` is more than `num`, ie 256 &gt; 99 , hence program end in `while` loop and thus 
exit, and your output become `[1, 3]` only


to solve this, you need to increase value of `div` by multiple of 2. Below is code for you

>>> num = 99
>>> div = 2
>>> lst = []
>>> while div < num:
... r = num%div
... while r!=0 and r not in lst:
... lst.append(r)
... div = div *2
...
>>> print(lst)
[1, 3, 35]


little better performance code here isd for you wutgh using set 

>>> num = 99
>>> div = 2
>>> lst = set()
>>>
>>> while div < num:
... r = num%div
... lst.add(r)
... div = div*2
...
>>> lst
{1, 3, 35}
>>> print(list(lst))
[1, 3, 35]
>>>


using set comprehension

from math import log, ceil
num = 99
result = {num%(2**i) for i in range(1, ceil(log(num, 2)))}
print(result)

{1,3,35}

using set comprehension using dict property as order is metained there

from math import log, ceil
num = 99
result = {num%(2**i): 1 for i in range(1, ceil(log(num, 2)))}
print(result.keys())

dict_keys([1, 3, 35]) # use list(result.keys()) to get output in list


</details>



# 答案3
**得分**: 1

你应该在一个集合中构建你的唯一值集合,最后对集合进行排序以得到所需的输出。

```python
num = 99
unique = set()
div = 2

while div < num:
    unique.add(num % div)
    div *= 2

print(sorted(unique))

输出:

[1, 3, 35]
英文:

You should build your collection of unique values in a set. Finally sort the set to give the output as required

num = 99
unique = set()
div = 2

while div &lt; num:
    unique.add(num%div)
    div *= 2

print(sorted(unique))

Output:

[1, 3, 35]

答案4

得分: 0

以下是您要的代码部分的中文翻译:

老实说,过于复杂化只会让你很快迷失方向。

num = 99
div = 2
power = 1
lst = []

while div < num: # 我们只关心小于 num 的 div 值
div = div**power # 这逐渐将 div 提升到指数幂
power += 1 # 这会在每次循环中将 power 增加 1,其他有用的迭代操作符有 [-=,*=]
lst.append(num % div) # '将' num/div 的余数添加到 lst 中(*将其添加到列表中,不太关心索引)
print(lst) # 打印列表

这也会打印出 99,因为它试图找到 128 的余数,但如果您想学习的话,这可能是一个有趣的挑战。

英文:

Honestly, overcomplicating it is the best way to get really lost really quickly.

num = 99 
div = 2
power = 1
lst = []

while div &lt; num:              # We only care about div values less than num
    div = div**power          # This incrementally raises div to the power exponent
    power += 1                # This will increment power by + 1 for each loop, other useful iterative operators are [-=,*=]
    lst.append(num % div)     # &#39;Appends*&#39; the remainder of num/div to lst (*will add to the list without caring too much about index)
print(lst)                    # Prints the list

This will also print 99 as it trys to find the remainder of 128 as well, but that might be a fun challenge for you to figure out if you're trying to learn d:

huangapple
  • 本文由 发表于 2023年5月22日 17:25:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76304727.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定