Python Forum
Random selection from list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Random selection from list
#1
Hi everyone,

This is not homework per se, but I am teaching myself(as everyone else has done before) python by taken courses, books, and online practices.

Here is a very basic exercise with the solution:
Quote:19. Write a Python program to get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchanged.

string = input('Type words here:')
def new_str(string):
    if len(string) >= 2 and string[:2] == 'Is': # string[:2] index for the first word == Is
        return str
    return 'Is ' + string
print(new_str(string))
Nothing too fancy about this! I found that I learn by expanding on basic exercises, so what I want to do is instead of just indexing 'Is' create a list and select randomly from the list.

import random 
string = input('Type your stantance ')

ask = ['Is', 'Do', 'Does', 'Are'] # this is a list and need to be string or tuple
st_ask = ''.join(ask)
p_ask = print(random.choices(st_ask))

def new_str1(string):
    if string.startswith(st_ask):
        return string
    else:
        return p_ask + string
Two problems here:
What code to use get the (random. )function to select from the list as in ask?
Apparently, I can not return p_ask + string and concatenate with a string
Reply
#2
print() returns None, so p_ask = print() doesn't do anything useful
x = print('Hi')
print(x)
Output:
None
Your use of random.choices was correct until you joined all the ask elements into a string.
import random
ask = ('Is', 'Do', 'Does', 'Are')
print(random.choices(ask, k=2))
Output:
['Do', 'Are']
My guess though is that you didn't want a list of choices, but a single choice:
import random
ask = ('Is', 'Do', 'Does', 'Are')
print(random.choice(ask))
Output:
Does
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  printing list of random generated rectangles Zatoichi 8 7,283 Feb-18-2018, 06:34 PM
Last Post: buran
  bubble sort random list atux_null 7 7,830 Nov-03-2017, 07:28 PM
Last Post: sparkz_alot
  List with Random Numbers AnjyilLee 5 9,258 Oct-14-2017, 09:22 PM
Last Post: buran
  Random Shuffle List simon 10 9,956 Oct-24-2016, 04:02 PM
Last Post: simon

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020