iT邦幫忙

0

請問python中的變數問題

  • 分享至 

  • xImage

想請問要如何讓output的ch能夠在FlipOnePosition()後仍保持一樣的值呢?而s則為flip後的值
output:
Before [1 0 1 1 1]
After [1 0 1 1 1]
s [1 0 1 1 0]

import random
import numpy as np

def FlipOnePosition(pk,num):
    position = random.randint(0, num - 1)
    if pk[position] == 0:
        pk[position] = 1
    else:
        pk[position] = 0
    return pk

if __name__ == "__main__":
    ch = np.random.randint(0, 2, 5)
    print("Before",ch)
    s = FlipOnePosition(ch, 5)
    print("After",ch)
    print("s",s)
    
    '''
    output:
        Before [1 0 1 1 1]
        After [1 0 1 1 0]
        s [1 0 1 1 0]
    '''
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
海綿寶寶
iT邦大神 1 級 ‧ 2023-03-26 22:30:14
import random
import numpy as np

def FlipOnePosition(pk,num):
    ret = pk.copy()
    position = random.randint(0, num - 1)
    if ret[position] == 0:
        ret[position] = 1
    else:
        ret[position] = 0
    return ret

if __name__ == "__main__":
    ch = np.random.randint(0, 2, 5)
    print("Before",ch)
    s = FlipOnePosition(ch, 5)
    print("After",ch)
    print("s",s)

我要發表回答

立即登入回答