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.
Related
The purpose of this program is to find the smallest and largest values in a list. The moment the user inputs a negative number, the program should stop. Here is the code I have written so far:
user_inputs = []
number = int(input())
for i in range(number):
value = int(input())
if i >= 0:
user_inputs.append(value)
else:
break
print(min(user_inputs))
print(max(user_inputs))
As you can see, I am new to programming and still struggling to find the logic behind loops. Surely, this code is ridden with mistakes and any helpful improvements is much appreciated. Thanks in advance.
Brother one mistake that you have done is that you are using
for i in range(number):
basically by doing this you are telling compiler that repeat the code in for loop for "number" of times and obviously number would change every time user inputs a new number resulting in error
The right way to make the code do what you want is :
user_inputs = []
while True:
number = int(input('Enter a positive number : '))
if number >= 0 :
user_inputs.append(number)
else:
print(user_inputs)
print('Smallest number in list is : ',min(user_inputs))
print('Largest number in list is : ',max(user_inputs))
break
Here while loop will run continuously until a negative number has been input, so when a negative number is input the while loop woulb break .
You are checking
i
when you should be checking
value
you have to compare value
i.e. if value >= 0
you are using i which is the number of iteration
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.
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()
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
This program creates an array in main and prompts the user to enter 5 integers and stores them in a array in a different function. It then creates a function that accepts the array and returns a true if the array contains only odd numbers or false if it does not. Print a message indicating the results being either the array contains both odd and even numbers or the array contains only odd numbers.
I keep getting TypeError:Unsupported operand types for /: 'list' and 'int'.
def main():
integer = 5
intArray = [0] * integer
for index in range(integer):
intArray[index] = int(input("Enter integers:"))
print(intArray)
fibArray(integer)
containsOnlyOdds(intArray)
return intArray
def fibArray(num):
fibArray = [0] * num
for index in range(num):
print(num)
def containsOnlyOdds(notEven):
average = (notEven / 2) % 2
for odd in range(average):
if notEven %2 != 0:
print('This array contains only odd numbers')
else:
print('This array contains odd and even numbers')
main()
Even without seeing your indentation, I can give you a simple way to check for all odds:
def check_list(lst):
for num in lst:
if num % 2 == 0:
return False
return True
The check_list() function takes a list argument and checks if each number in the list is divisible by 2. If a number is, clearly it is even and the function returns False. This is efficient because as soon as it finds an even number, it exits, rather than searching the entire list.
Now that you fixed your formatting:
It appears that you are trying to divide a list by a factor of 2 in your containsOnlyOdds function. It is not possible to divide a list, you need to set up a loop to loop through each index of the list, and then check if each number is divisible by 2 or not.