how to generate a list based on index value - python

i am trying to generate a list consisting of 0's based off of user prompt. if they enter a one then the one index will be replaced with a one, if they enter a two the two index will be replaced with a one, etc. i am able to generate a random list of one's and zero's but i am having trouble with the input.
here is what i have so far:
import random
def askTheUser():
number = input("Do you want to roll again? Pick a number or numbers thru 0 and 5:")
myList = []
aList = [1,0]
for i in range(5):
myList.append(random.choice(aList))
if number == 1:
return myList[1] = 0
if number == 2:
return myList[2] = 0
return myList
print(askTheUser())

I think you are replacing by 0 not 1, also input is taking string not int so try to cast it
and list index is 0 based so the right code should be:
import random
def askTheUser():
number = input("Do you want to roll again? Pick a number or numbers thru 0 and 4:")
myList = []
aList = [1,0]
for i in range(5):
myList.append(random.choice(aList))
myList[int(number)] = 1
return myList
print(askTheUser())

I am not sure what exactly your program should do. I tried to follow description more than your code (expected input and output would be welcome).
Here is my piece:
from __future__ import print_function # make it work also in python 2.x
import random
def askTheUser():
# don't use magic numbers, use 'constant-like' variables
MAX = 5
# try to avoid too long lines if possible
msg = "Do you want to roll again? " +\
"Pick a number or numbers thru 0 and {}: ".format(MAX)
# you should use raw_input() for asking user, input() is very unsafe
number = raw_input(msg)
# initialize with random [0,1]
myList = [random.randint(0,1) for i in range(MAX)]
try:
# you need to convert string to int
i = int(number, 10)
# negative indexes can be valid ;o)
# let's not allow for that in this case, throwing error
if i < 0:
raise IndexError
myList[i] = 1
# you may expect ValueError if string was not valid integer
# or IndexError if it was beyond range (0, MAX)
except (IndexError, ValueError):
print ("That was wrong value:", number) # if you want, message user
pass
finally:
return myList
if __name__ == '__main__':
print(askTheUser())
If you want to accept multiple values at once, you should use split() on input and process them in loop.
Good luck.

Related

Why doesn't this code read the number correctly?

# Inport functions.
from random import randint
from random import seed
# Generate numbers. The first seed is based off of how many milliseconds have passed since Epoch (1970). Aka theres no way to perfectly predict this.
seed(randint(0,100))
x = randint(0,100)
seed(randint(0,100))
y = randint(0,100)
seed(randint(0,100))
z = randint(0,100)
seed(randint(0,100))
a = randint(0,100)
seed(randint(0,100))
b = randint(0,100)
list = [a,b,x,y,z]
# Input number.
input = int(input('Input a whole number from 0 - 100.'))
# Simple check loop. 5 times since theres 5 numbers.
for x in list:
'# If input matches first item in list
if input == list[0]:
'# Set Y to 1 than stop looping.
Y = 1
break
else:
'# Otherwise delete the first item in the list and try again.
Y = 0
del list[0]
# Than if Y is one print bingo, otherwise print try again.
if Y == 1:
print('Bingo!')
else:
print('Try again.')
This py3 code always prints 'Try again.' I've tried forcefully setting x to 9 but it doesn't work, can anyone diagnose this? I've made sure it was properly indented in codesculpter3, anyone know why it doesn't work?
There were quite a few errors (see the comments). But in particular, you have used list and input as variables. The code is also appending a list that it is iterating over, which can lead to errors (hint: if you ever do this, then create a new list).
This is a "pythonic" version of the code that would work:
import random
# random list of 5 numbers (0 to 100)
my_list = [random.randint(0,100) for x in range(5)]
got_it = 0 # variable for correct guess
for x in my_list:
y = int(input('Input a whole number from 0 - 100.'))
if y == x:
got_it = 1
print('bingo !')
break
if got_it == 0:
print('try again')

Counting program for fibonacci sequence Python

I think what I am trying to do is display a select section from a defined list. Currently this is what I am working with:
#fibonacci sequence algorithm, user stops by either
#entering a maximum Fibonacci value not to exceed or
#a total count that the sequence of numbers must not
#exceed. Use a loop that allows User to repeat program
#as much as they wish, asking if they would like to
#repeat the program each time. Validate that User input
#is either a yes or a no and only allow User to continue
#once a correct response has been given.
import array
array.listOfFibSeq = ['0','1','1','2','3','5','8','13','21','34','55','89','144','...']
startingNumber = ''
endingNumber = ''
continueYes = ''
def getStartingNumber():
print('Please enter a valid starting number of the Fibonacci Sequence')
print(listOfFibSeq)
startingNumber = input()
def getEndingNumber():
print('Please enter a valid ending number the the Fibonacci Sequence')
print(listOfFibSeq)
endingNumber = input()
I'm unsure of how to go about this, but I believe I'm trying to display (for example) 3 through 89 in the Fibonacci sequence or do something like:
lsitOfFibSeq.remove(<3) and listOfFibSeq.remove(>89)
or should I try to display a range of the Fib Sequence with a for loop?
There is no reasonable way to precompute the fibonacci sequence before the user enters a range — you should do this dynamically.
A naive approach would be to have a function that computes the sequence for a given (a, b), all the way to end, discarding everything up to start.
I prefer the generator approach:
import itertools
def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
# Print the first 10 values of the sequence
for i in itertools.islice(fib(), 0, 10):
print(i)
Or, in your case, something like:
start = input('Start index: ')
end = input('End index: ')
for i in itertools.islice(fib(), int(start), int(end)):
print(i)
if input('Continue [y/n]: ').rstrip() == 'n':
break

How to read a specific number of integers and store it in a list in python?

Lets suppose I want to first input the total number of integers I am going to enter.
N = 5, I must be able to read exactly 5 integers and store it in a list
for i in range(5):
lst = map(int, raw_input().split())
doesn't do the job
In most primitive way, you can do it in following way.
n = int(raw_input())
numbers = map(int, raw_input().split())[:n]
We can help more if you tell us the context in which you are asking the problem. I doubt if you are using it for some competitive programming problem.
Actually, problem in your code is that you are reading a line and making list from it. But you are doing this FIVE times. Also, you can read lot more than five numbers if they are in single line.
Sa far as I understand, you need the following
lst=[]
for n in range(5):
lst.append(int(raw_input("Input a number: ").split()))
print repr(lst)
inp = raw_input # Python 2.x
# inp = input # Python 3.x
def get_n_ints(prompt, n):
while True: # repeat until we get acceptable input
s = inp(prompt)
try:
vals = [int(i) for i in s.split()]
if len(vals) == n:
return vals
else:
print("Please enter exactly {} values".format(n))
except ValueError:
# a string couldn't be converted to int
print("Values need to be integers!")

Using random.randint help in python

The following code is my attempt at simulating a lottery.
import random
def lottery(numbers):
lottoNumbers = [randint('0,100') for count in range(3)]
if numbers == lottoNumbers:
print('YOU WIN $10,000')
else:
print('YOU LOSE,DUN DUN DUNNN!')
return numbers
def main():
numbers = int(input('Enter a number: '))
if numbers == lottoNumbers:
numbers = lottery(numbers)
else:
numbers = lottery(numbers)
main()
Hey guys I've gotten this far with the help you've given me. I'm trying to write the code so that 3 lotto numbers at random will be chosen. Then the user must enter 3 of his/her own lotto numbers. If they get all 3 correct then they win the whole prize, if they get the 3 numbers but not in the correct order they win some of the prize. Obviously if they guess all wrong then a print statement would state that. What I'm confused about is how can I write the code so that the user can enter 3 numbers to try matching the random lottery numbers. I also want to print the 3 lottery numbers after the user inputs his/her choices. Any ideas guys?
Thanks for your help everyone.
You seem a bit confused about what the role of the arguments in a function are. You've said that your randm function takes the argument "number", but then you haven't actually used it anywhere. The next time number appears, you've assigned it a completely new value, so any value passed to randm isn't actually being used.
Also, the function is trying to return x, when x hasn't been assigned within the function. Either you already have a global variable called x already defined, in which case the function will just return that variable, or the function will just fail because it can't find the variable x.
Here's a quick example I've done where you pass their three numbers as a list as an argument to the function.
import random
theirNumbers=[5,24,67]
def checkNumbers(theirNumbers):
lottoNumbers = []
for count in range(3)
lottoNumbers.append(random.randint(0,100))
winning = True
for number in theirNumbers:
if not each in lottoNumbers: winning=False
if winning == True: print("Winner!")
There are a few things wrong with your implementation, to name a few:
if you are trying to compare the output of the function randm to x, you will need to include a return value in the function, like so:
def randm():
return return_value
You appear to be printing all the values but not storing them, in the end you will only end up with the final one, you should attempt to store them in a list like so:
list_name = [randint(0,100) for x in range(x)]
This will generate randint(0,100) x times in a list, which will allow you to access all the values later.
To fix up your code as close to what you were attempting as possible I would do:
import random
def randm(user_numbers):
number = []
for count in range(3):
number.append(random.randint(0, 100))
print(number)
return user_numbers == number
if randm(x):
print('WINNER')
If you are looking for a very pythonic way of doing this task,
you might want to try something like this:
from random import randint
def doLotto(numbers):
# make the lotto number list
lottoNumbers = [randint(0,100) for x in range(len(numbers))]
# check to see if the numbers were equal to the lotto numbers
if numbers == lottoNumbers:
print("You are WinRar!")
else:
print("You Lose!")
I'm assuming from your code (the print() specifically) that you are using python 3.x+
Try to post your whole code. Also mind the indentation when posting, there it looks like the definition of your function would be empty.
I'd do it like this:
import random
def lottery():
win = True
for i in range(3):
guess = random.randint(1,100)
if int(raw_input("Please enter a number...")) != guess:
win = False
break
return win
Let so do this in few steps.
First thing you should learn in writing code is to let separate pieces of code( functions or objects) do different jobs.
First lets create function to make lottery:
def makeLottery(slotCount, maxNumber):
return tuple(random.randint(1,maxNumber) for slot in range(slotCount))
Next lets create function to ask user's guess:
def askGuess(slotCount, maxNumber):
print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
while True: #we will ask user until he enter sumething suitable
userInput = raw_input()
try:
numbers = parseGuess(userInput,slotCount,maxNumber)
except ValueError as err:
print("please ensure your are entering integer decimal numbers separated by space")
except GuessError as err:
if err.wrongCount: print("please enter exactly {count} numbers".format(count = slotCount))
if err.notInRange: print("all number must be in range from 1 to {max}".format(max = maxNumber))
return numbers
here we are using another function and custom exception class, lets create them:
def parseGuess(userInput, slotCount,maxNumber):
numbers = tuple(map(int,userInput.split()))
if len(numbers) != slotCount : raise GuessError(wrongCount = True)
for number in numbers:
if not 1 <= number <= maxNumber : raise GuessError(notInRange = True)
return numbers
class GuessError(Exception):
def __init__(self,wrongCount = False, notInRange = False):
super(GuessError,self).__init__()
self.wrongCount = wrongCount
self.notInRange = notInRange
and finally function to check solution and conratulate user if he will win:
def checkGuess(lottery,userGuess):
if lottery == userGuess : print "BINGO!!!!"
else : print "Sorry, you lost"
As you can see many functions here uses common data to work. So it should suggest you to collect whole code in single class, let's do it:
class Lottery(object):
def __init__(self, slotCount, maxNumber):
self.slotCount = slotCount
self.maxNumber = maxNumber
self.lottery = tuple(random.randint(1,maxNumber) for slot in range(slotCount))
def askGuess(self):
print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
while True: #we will ask user until he enter sumething suitable
userInput = raw_input()
try:
numbers = self.parseGuess(userInput)
except ValueError as err:
print("please ensure your are entering integer decimal numbers separated by space")
continue
except GuessError as err:
if err.wrongCount: print("please enter exactly {count} numbers".format(count = self.slotCount))
if err.notInRange: print("all number must be in range from 1 to {max}".format(max = self.maxNumber))
continue
return numbers
def parseGuess(self,userInput):
numbers = tuple(map(int,userInput.split()))
if len(numbers) != self.slotCount : raise GuessError(wrongCount = True)
for number in numbers:
if not 1 <= number <= self.maxNumber : raise GuessError(notInRange = True)
return numbers
def askAndCheck(self):
userGuess = self.askGuess()
if self.lottery == userGuess : print "BINGO!!!!"
else : print "Sorry, you lost"
finally lets check how it works:
>>> lottery = Lottery(3,100)
>>> lottery.askAndCheck()
take a guess, write 3 numbers separated by space from 1 to 100
3
please enter exactly 3 numbers
1 10 1000
all number must be in range from 1 to 100
1 .123 asd
please ensure your are entering integer decimal numbers separated by space
1 2 3
Sorry, you lost
>>> lottery = Lottery(5,1)
>>> lottery.askAndCheck()
take a guess, write 5 numbers separated by space from 1 to 1
1 1 1 1 1
BINGO!!!!

Python: Select Only Parts of an input?

Sorry...I'm kind of a programming noob. I was looking at some problem sets online and I found THIS ONE. I wrote this much:
import random
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
(f,g,h,i,j)=x=input("Your 5 Chosen Numbers:")
My problem is that I don't know how to make the program print something like "Please enter 5 numbers separated by only a comma" if more or less than five are entered. Also how would I do that if I wanted it to display a different message every other time they made that mistake?
Try this approach:
input_is_valid = False
while not input_is_valid:
comma_separated_numbers = raw_input("Please enter a list of 5 numbers,separated by commas: ")
numbers = [int(x.strip()) for x in comma_separated_numbers.split(",")]
if len(numbers) != 5:
print "Please enter exactly 5 numbers"
else:
input_is_valid = True
Looking at your link I'd say:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
other_numbers = sorted(ri(1,53) for i in range(5))
print 'your numbers:','\t',other_numbers,'\t','powerball:','\t',powerball
It seems that's more or less what he asks from you.
If I'm correct, you want the user to submit his series so to see if its one of the sets extracted (amirite?)
then it could be fine to do:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
while True:
myset = raw_input('your 5 numbers:').split()
if len(myset) != 5:
print "just five numbers separated ny a space character!"
else:
myset = sorted(int(i) for i in myset)
break
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
numbers = sorted(ri(1,53) for i in range(5))
print 'numbers:','\t',numbers,'\t','powerball:','\t',powerball
if numbers == myset:
print "you won!" ##or whatever the game is about
else:
print "ahah you loser"
EDIT: beware this doesn't check on random generated numbers. So it happens one number can appear more than once in the same sequence. To practice you may try avoiding this behavior, doing so with a slow pace learning some python in the way it could be:
make a set out of a copy of the list "numbers" -- use set()
if its length is less than 5, generate another number
check if the new number is in the list
if it is, then append it to the list. if its not unique yet, GOTO point 1 :-)
sort the whole thing again
there you go
happy reading the docs!
My proposition:
import random
import sys
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
bla = ["\nPlease enter 5 numbers separated by only a comma : ",
"\nPlease, I need 5 numbers separated by only a comma : ",
"\nPLEASE, 5 numbers exactly : ",
"\nOh gasp ! I said 5 numbers, no more nor less : ",
"\n! By jove, do you know what 5 is ? : ",
"\n==> I warn you, I am on the point to go off : "]
i = 0
while i<len(bla):
x = raw_input(warn + bla[i])
try:
x = map(int, x.split(','))
if len(x)==5:
break
i += 1
except:
print "\nTake care to type nothing else than numbers separated by only one comma.",
else:
sys.exit("You wanted it; I go out to drink a beer : ")
(f,g,h,i,j)=x
print f,g,h,j,i
.
Some explanation:
.
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.
http://docs.python.org/reference/compound_stmts.html#index-801
.
.
x = map(int, x.split(','))
means that the function int() is applied to each element of the iterable which is the second argument.
Here the iterable is the list x.split(',')
Hence, x is a list of 5 integers
In Python 3, there is no more raw_input() , it has been replaced by input() that receives characters, as raw_input() in Python 2.
.
.

Categories

Resources