Error when removing random item from list - python

I'm getting an error when I try to run this that says:
ValueError: list.remove(x): x not in list
This error, however, does not always occur. I think that is because it only happens when the random number that comes back has already been removed but I don't know for sure or how to fix it. All help greatly appreciated.
def main():
numbers = [1,2,3,4,5,6,7,8,9,10,]
count = 0
while count <= 3: #how many numbers to remove
count += 1
remove(numbers)
print (numbers)
done = input ("Enter to exit.")
def remove(numbers):
import random
randnum = random.randint(1,10)
numbers.remove(int(randnum))
main()

Wait until you get a number that is in the list:
def remove(numbers):
import random
randnum = random.randint(1, 10)
while randnum not in numbers:
randnum = random.randint(1, 10)
numbers.remove(randnum)
You can also use random.choice (thanks #WillemVanOnsem) and pick an element that you know exists:
def remove(numbers):
import random
numbers.remove(random.choice(numbers))

So, I believe the problem here is two fold. (1) that the random number you are generating is greater than the current list after removing a few items and (2) python lists are zero based.
So, for the first problem, it you have already removed 2 items previously and the random number generator creates 9, the 9 position will no longer be there. So, you need to generate the random number based on the current length of the list:
randnum = random.randint(0,len(numbers) -1)
This should guarantee that the random number is in the list and should be available.
For the second problem, there is a zero position (the first position on the array) that needs to be taken into account. So, if you have ten positions in the python list, the indexes for those positions would be 0 through 9, NOT 1 through 10. So when you try to remove position 10, it does not exist. Start your random number generator at 0 (as shown above) and end it at one less than the length. That should cover all possible positions in the list.
Hope this helps.

You cannot delete one item two times. It's not exist.
Meybe use Try: except: statement.

Related

how do i keep track of how many times a number is rolled?

I am not sure how to do a school assignment. I am pretty new to python and for this project, i need to have the user input a number and have the dice roll that amount of times. but i also need to keep track of how many times each number is rolled. i have found something that i would find very helpful, but im not sure how i should do it in python. I've never used java or any other program besides python. im just not sure where to start. Any help is appreciated!
Thanks!!
link to what i have found that would come in handy:
Dice roll array and method calling
You're going to need to keep count for six different numbers. Many data structures can accommodate this. For instance, a list would work. Let's say you have a function roll() that returns a random integer between 1 and 6 inclusive. Then you could use something like this:
count = [0, 0, 0, 0, 0, 0]
rolls = 100
i = 1
while i <= rolls:
r = roll()
count[r-1] = count[r-1]+1
i = i + 1
print(count)
What this is doing is creating a list called count with six elements, representing the number of times each number on the dice has been rolled. We then run a loop for the number of times you want to throw the dice. Each time the loop is run, a random integer is generated and stored in r. For example, say on one iteration of the loop, the random integer generated is 2. Then the count[1] is incremented (note it's count[1] and not count[2] because the list is indexed from 0 to 5). Once the loop is over you can print your list, which will show how many times each number came up.
A place that I would start would be importing the random module to get random integers from 1-6 since they are on a standard dice.
import random
Now take the user input:
number = input('Enter the amount of rolls ')
You need to create a loop that runs the amount of times that the user picked, which turns out to be a quite simple "for" loop. Next, we need to create two random integers between 1 and 6 twice each time. The roll will be equal to those two random numbers added together:
for i in range(int(number)):
first = random.randint(1,6)
second = random.randint(1,6)
roll = first + second
Now, we have to keep track of each number and how many times it was rolled. The possibilities are the numbers 2 through 12. To check the count of these numbers, I would add all of the rolls to a list and then do the list.count to check each number. The code should end up being something like this:
import random
number = input('Enter the amount of rolls ')
all = []
for i in range(int(number)):
first = random.randint(1,6)
second = random.randint(1,6)
roll = first + second
all.append(roll)
for i in range(2,13):
count = all.count(i)
print(str(i) + ' appeared ' + str(count) + ' times!')
Hope this helped. I'm kind of new too so I'm in the same place as you.
To answer the question in the title, the simplest way is with a Counter. Create it at the start:
from collections import Counter
count = Counter()
Then each time you roll a die, add to the count :
result = roll()
count[result] += 1
Then at the end, you have your totals. Say for example we rolled 3 ones and 2 sixes:
print(count) # -> Counter({1: 3, 6: 2})

python:Write a program that keeps reading positive numbers from the user [duplicate]

This question already has answers here:
Storing multiple inputs in one variable
(5 answers)
Closed 2 months ago.
hi i am very new to programming and was doing my 6th assignment when i started to draw a blank i feel as thou its really simple but i cant figure out how to continue and would appreciate some advice
showing the correct code would be cool and all but i would really appreciate feed back along with it more so then what to do and if so where i went wrong
down below is what im supposed to do.
Write a program that keeps reading positive numbers from the user.
The program should only quit when the user enters a negative value. Once the
user enters a negative value the program should print the average of all the
numbers entered.
what im having trouble with is getting the number to remember okay user entered 55 (store 55) user entered 10 (store 10) user enter 5 (store 5) okay user put -2 end program and calculate. problem is its not remembering all previous entry's its only remembering the last input (which i guess is what my codes telling it to do) so how do i code it so that it remembers all previous entry's
and here is the code i have so far
number = 1
while ( number > 0):
number = int(input("enter a number. put in a negative number to end"))
if number > 0 :
print (number)
else:
print (number) # these are just place holders
If you really want to remember all previous entries, you can add them to a list, like so:
# before the loop
myList = []
# in the loop
myList = int(input("enter a number. put in a negative number to end"))
Then you can easily compute the mean of the numbers by iterating over the list and dividing by the length of the list (I'll let you try it yourself since its an assignment).
Or, if you want to save (a little) memory, you can add them each time to a variable and keep another variable for the count.
You can use a simple list in order to keep track of the numbers that have been inserted by the user. This list may then get processed in order to calculate the average when every number got read in ...
# This is a simple list. In this list we store every entry that
# was inserted by the user.
numbers = []
number = 1
while ( number > 0):
number = int(input("enter a number. put in a negative number to end "))
if number > 0 :
print (number)
# save the number for later usage.
numbers.append(number)
# calculate average
if len(numbers) == 0:
print("You have not inputted anything. I need at least one value in order to calculate the average!")
else:
print("The average of your numbers is: %s" % (sum(numbers) / len(numbers)))
What you need is an list which can store multiple values. It is often use with loops to insert/get value from it.
For instance,
number = 1
numbers = []
while ( number > 0):
number = int(input("enter a number. put in a negative number to end"))
if number > 0 :
numbers.append(number)
print (numbers)
What you get is a list of numbers like [4, 10, 17] in ascending order as append() will add number to the back of the list. To get individual numbers out of the list:
numbers[0]
Note that the index inside the bracket starts from 0, so for instance you have a list with [4, 10, 17]. You should use the below 3 to get each of them:
numbers[0]
numbers[1]
numbers[2]
Or even better, with a loop.
for x in numbers:
print (x)

using the main function to display only the odd numbers in a list

I am trying to make a list that only displays the odd numbers between 1 and 12, but I have to use the def main function. I have looked all over and have tried everything I could. I'm not sure why, but I've always had trouble using the def main function. Here is where i'm at now with my program.
print("I will display the odd numbers between 1 and 12.")
def main( ):
for num in [0,1,2,3,4,5,6,7,8,9,10,11,12]:
odd = num[::2]
main( )
print (odd)
Anyone have any advice or see what I am doing wrong?
You're pretty close. Start by getting rid of your for-loop, because what you want to do is to assign the list [0,1,2,3,4,5,6,7,8,9,10,11,12] to the variable num, not iterate over the individual numbers in the list.
Then you'll notice that num[::2] actually gives you the even numbers, so change that to num[1::2]. Lastly, you have to move print (odd) inside the main function, because the variable odd is only defined within that function.
The end result should look like this:
def main():
print("I will display the odd numbers between 1 and 12.")
num = [0,1,2,3,4,5,6,7,8,9,10,11,12]
odd = num[1::2]
print (odd)
main()
If you want to keep the loop, you'll have to check each number individually and append it the list of odd numbers if it's odd:
odd = [] # make an empty list
for num in [0,1,2,3,4,5,6,7,8,9,10,11,12]: # for each number...
if num % 2: #...check if it's odd with a modulo division
odd.append(num) # if yes, add it to the list
print(odd)
Python implicitly defines the main() function, unlike C++ and some others. The problem in your code is not in the definition of main(). If you read the error message:
TypeError: 'int' object is not subscriptable
you may get an idea that something is wrong with types. With the code snippet you've provided, you're iterating over a list of numbers (Python has a function range() specifically for the purpose of generating a sequence of numbers) and with each iteration, the number (type int) is stored in the variable num. And you're trying to use slicing, which is made for iterables. int is not an iterable. You don't need a for loop in your case. This will do the trick:
print("I will display the odd numbers between 1 and 12.")
num = [0,1,2,3,4,5,6,7,8,9,10,11,12]
odd = num[1::2] # first index is one to get the odd numbers
print(odd)
well you have much to learn, but in this particular case you use the range function to get the numbers, and even make it more general by asking the user for a number with input, like this
def odd_number(n):
print("I will display the odd numbers between 1 and",n)
odd = list(range(1,n+1,2))
print(odd)
def main():
n = int(input("choose the max number to display odd number: "))
odd_number(n)
odd_number(12)
main()

Python Lottery number and checker

I am attempting to create a random number generator for any number of numbers in a line and then repeating those random numbers until a "target" number is reached.
The user will enter both the number of numbers in the sequence and the sequence they are shooting for. The program will run the random numbers over and over until the target sequence is hit, then the program will spit out the number of repetitions it took.
My problem is that it keeps going on forever, seemingly never hitting the break function because num doesn't equal target or something.
So far I have this and i think i am pretty close
#Module to get amount of numbers in the sequence
def getRange():
Range =int(input("How many digits in your number?"))
return Range
#Target Sequence input
def getTarget():
Target= []
Target =input("What is your target sequence?")
return Target
def lotteryNo(Range):
import random
integer = []
for number in range(0 , Range):
integer.append(random.randint(0, 9))
return integer
def printDigits(Range,Target):
print("Your target list is",Target)
for rep in range(10000000):
num=(lotteryNo(Range))
print(num)
if num == Target:
rep=rep + 1
print("The number of repetitions is",rep)
break
else:
rep=rep+1
def main():
Range=getRange()
Target=getTarget()
printDigits(Range,Target)
main()
#End
The issue with your comparison is that you're testing Target which is a string against num which is a list of integers. That will never match, no matter what integers and what string you're dealing with. You need to compare two like-types to get a meaningful result.
It looks like you wanted your getTarget function to return a list, since you're initializing Target to an empty string. However, when you overwrite it with Target = input(...), the list is discarded.
You probably want something like Target = list(map(int, input())), which converts each character of the input string to an integer and then packs them all into a list. Another way of writing that would be Target = [int(digit) for digit in input()].
One further suggestion, unrelated to your current issue: Python's common naming convention is to use lower_case_names_with_underscores for variable and function names, reserving UpperCaseNames for classes. You don't have to follow this convention, but it's probably a good idea if you're going to share your code with anyone. You can read PEP 8 for more style suggestions.
Your problem is because one of your numbers is a list and the other is a string from input.
Change Target to get an int
def getTarget():
Target =int(input("What is your target sequence?"))
return Target
Change lotteryNo to get an int
def lotteryNo(Range):
import random
integer = 0
for number in range(0 , Range):
integer += random.randint(0, 9) * (10**number)
return integer
And your if num == Target: comparison should now work as it is comparing two variables of the same type.

Finding numbers that are multiples of and divisors of 2 user inputted numbers

I have an assignment for Python to take 2 user inputted numbers (making sure the 1st number is smaller than the second) and to find numbers that are multiples of the first, and divisors of the second.. I'm only allowed to use a while loop (new condition my teacher added today..) I've done it with a for loop:
N_small = int(input("Enter the first number: "))
N_big = int(input("Enter the second number: "))
numbers = ""
if N_small > N_big:
print("The first number should be smaller. Their value will be swapped.")
N_small, N_big = N_big, N_small
for x in range(N_small, N_big+1, N_small):
if N_big % x == 0:
numbers += str(x) + " "
print("The numbers are: ", numbers)
I'm not asking for the answer to how to do this with a while loop - but I just need a hint or two to figure out how to start doing this... Can anyone enlighten me?
Thanks
You can convert any for loop into a while loop trivially. Here's what a for loop means:
for element in iterable:
stuff(element)
iterator = iter(iterable)
while True:
try:
element = next(iterator)
except StopIteration:
break
stuff(element)
Of course that's not what your teacher is asking for here, but think about how it works. It's iterating all of the values in range(N_small, N_big+1, N_small). You need some way to get those values—ideally without iterating them, just with basic math.
So, what are those values? They're N_small, then N_small+N_small, then N_small+N_small+N_small, and so on, up until you reach or exceed N_big+1. So, how could you generate those numbers without an iterable?
Start with this:
element = N_small
while element ???: # until you reach or exceed N_big+1
stuff(element)
element ??? # how do you increase element each time?
Just fill in the ??? parts. Then look out for where you could have an off-by-one error that makes you do one loop too many, or one too few, and how you'd write tests for that. Then write those tests. And then, assuming you passed the tests (possibly after fixing a mistake), you're done.
You don't have to iterate over all the numbers, only the multiples...
small, big = 4, 400
times = 1
while times < big / small:
num = times * small
if big % num == 0: print(num)
times += 1

Categories