python随机选取列表中的一个字符串_从列表中随机选择x个元素

I am trying to write a code that will randomly select between 1 and 4 elements of a list 50 times. The list I am working with is ['nu', 'ne', 'na', 'ku', 'ke', 'ka'].

So essentially, I want it to output something like

nukuna

ke

keka

nuka

nane

nanenu

nu

nukekanu

kunu

...

50 times

解决方案

In Python:

import random

input = [...] # Your input strings

output = ''

random.seed() # Seed the random generator

for i in range(0,len(input)):

N = 1+random.randrange(4) # Choose a random number between 1 and 4

for j in range(0,N): # Choose N random items out of the input

index = random.randrange(len(input)-j)

temp = input[index]

input[index] = input[len(input)-j-1]

input[len(input)-j-1] = temp

output += temp

output += ' '

print output

In C:

#include

#include

#include

#include

char* input[NUM_OF_INPUT_STRINGS] = {...}; // Your input strings

char output[MAX_SIZE_OF_OUTPUT+1];

// Seed the random generator

srand((unsigned int)time(NULL));

for (int i=0; i

{

// Set the output string empty

output[0] = 0;

// Choose a random number between 1 and 4

int N = 1+(rand()%4);

// Choose N random items out of the input

for (int j=0; j

{

int index = rand()%(NUM_OF_INPUT_STRINGS-j);

char* temp = input[index];

input[index] = input[NUM_OF_INPUT_STRINGS-j-1];

input[NUM_OF_INPUT_STRINGS-j-1] = temp;

strcat(output,temp);

}

// Print the output

printf("%s ",output);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值