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.
Related
I have a pretty simple function where the user is asked to input a list of numbers, then a second input for a second number. If any single number in the first argument is larger than the second argument, then it will return True, and if none of the numbers in the first argument in larger, it should return false. Seems simple enough but I'm struggling to get it to loop through the entire list before it returns the boolean value. A new problem I'm having throws up an error and says I'm trying to compare int's to lists with the > operator.
def num_gt(list_num, single_num):
#breakpoint()
for i in list_num :
if i > single_num :
return True
else:
return False
list_num = (input("Please enter list numbers: "))
single_num = (input("Please enter single number: "))
list_num = list(map(int, list_num))
single_num = list(map(int, single_num))
Not sure where I'm goinging wrong here. The inputs get converted to lists of integers, and stepping through it shows its return lists as it should. Any help appreciated
You need to not cast your single num to a list as it is a single value.
Remove the line.
single_num = list(map(int, single_num))
And replace with:
single_num = int(single_num)
Your function is also slightly wrong as it will only check one value then always return. It should instead check all the values and only if all of them are smaller then return false.
def num_gt(list_num, single_num):
#breakpoint()
for i in list_num :
if i > single_num :
return True
return False
Now your function will check all the values and then if none of them return True, it will return False at the end.
"""
A trimorphic number is a number whose cube ends in the number itself.
For example:
Input: 4
Output: true (4^3 is 64, which ends in 4)
Input: 24
Output: true (24^3 = 13824)
Input: 249
Output: true (249^3 = 15438249)
Write a program to check if the user input is a trimorphic number or not.
"""
num = int(input("Enter a number:"))
print(num)
num_cube = pow(num, 3)
str(num_cube)
print(num_cube[len(num_cube) - 1:] == num)
I tried running the code and I got a TypeError at line 22 (the last line) even though I converted the variable num_cube to a string in order to slice it. Why does it not work?
You should use the endswith function to check whether the last "n" characters in the cube are equal to the string representation of the number you are passed.
You could thus do:
print(str(num_cube).endswith(num))
The way you have currently implemented it, you are "hard coding" the expected length of the number read from the stdin and are thus assuming it to always be of length 1.
To correct your code, you would do the following:
>>> num = "24"
>>> num_cube = str(pow(int(num), 3))
>>> num_cube[len(num_cube) - len(num):] == num
True
>>> num_cube[-len(num):] == num # negative indexing
True
str(num_cube) is not assigned, so you are converting it but still using num_cube which is an int, hence the TypeError. Also, you need to compare it to another string, not to to num which is another integer:
print(str(num_cube)[-3:] == str(num))
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 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.
Note: This is not my homework. Python is not taught in my college so i am doing it my myself from MITOCW.
So far i have covered while loop, input & print
Q) Write a program that asks the to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered it should print a message to the effect
How can i compare those 10 number without storing them in some list or something else? Coz i haven't covered that as if yet.
print "Enter 10 numbers: "
countingnumber=10
while countingnumber<=10:
number=raw_input():
if number % 2 == 0:
print "This is odd"
countingnumber=countingnumber+1
else:
print "This is even. Enter the odd number again"
i think the program will look something like this. But this has some unknown error & How can i compare all the numbers to get the largest odd number without storing those 10 numbers in the list.
print "Enter 10 numbers: "
countingNumber = 1
maxNumber = 0
while countingNumber<=10:
number=int(raw_input())
if (number % 2 == 0):
countingNumber = countingNumber+1
if (maxNumber < number):
maxNumber = number
else:
print "This is even. Enter the odd number again"
print "The max odd number is:", maxNumber
you can just define a maxnum variable and save the max in it! also you must use int(raw_input()) instead raw_input()
print "Enter 10 numbers: "
maxnum=0
for i in range(10):
number=int(raw_input())
if number%2 == 0:
print "This is odd"
if number>maxnum:
maxnum=number
else:
print "This is even. Enter the odd number again"
print "max odd is :{0}".format(maxnum)
DEMO:
Enter 10 numbers:
2
This is odd
4
This is odd
6
This is odd
8
This is odd
12
This is odd
14
This is odd
16
This is odd
100
This is odd
2
This is odd
4
This is odd
max odd is :100
Whenever I do input, I like to make sure I don't leave room for human error giving me bugs.
Because I put in extra checks I break code into a lot of separate function. This also gives code the quality of being non-coupled. ie) You can reuse it in other programs!!
def input_number():
while true:
input = raw_input("Enter Value: ")
if not input.isdigit():
print("Please enter numbers only!")
else:
return int(input)
Designing the input function in this fashion gives the code no opportunity to crash. We can now use it in a function to get odd numbers!
def input_odd_number():
while true:
input = input_number()
if input % 2 == 0:
print("Please enter odd numbers only!")
else:
return input
Now we can finally move onto the main code. We know we need ten numbers so lets make a for loop. We also now we need to hold onto the largest odd number, so lets make a variable to hold that value
def largest_odd(count = 10): // its always nice to make variables dynamic. The default is 10, but you can change it when calling!
max_odd = input_odd_number() // get the first odd number
for i in range(count - 1): // we already found the first one, so we need 1 less
new_odd = input_odd_number()
if new_odd > max_odd:
max_odd = new_odd
print("The largest odd value in '{}' inputs was: {}".format(count, max_odd)
In your solution are multiple flaws.
A syntax error: The colon in number=raw_input():.
raw_input returns a string and you have to cast it to an int.
Your while loop just runs one time, because you start with 10 and compare 10 <= 10. On the next iteration it will be 11 <= 10 and finishes.
Also you have mixed odd an even. even_number % 2 gives 0 and odd_number % 2 gives 1.
To get the biggest value you only need a additional variable to store it (See biggest_number in my solution). Just test if this variable is smaller then the entered.
You ask again if the number is odd, but you should take every number and test only against odd numbers.
A working solution is:
print "Enter 10 numbers"
count = 0
max_numbers = 10
biggest_number = None
while count < max_numbers:
number=int(raw_input("Enter number {0}/{1}: ".format(count + 1, max_numbers)))
if number % 2 == 1:
if biggest_number is None or number > biggest_number:
biggest_number = number
count += 1
if biggest_number is None:
print "You don't entered a odd number"
else:
print "The biggest odd number is {0}".format(biggest_number)
If you wonder what the format is doing after the string take a look in the docs. In short: It replaces {0} with the first statement in format, {1} with the second and so on.
here is the correct code for that:
print "Enter 10 numbers: "
countingnumber=1
MAX=-1
while countingnumber<=10:
number=int(raw_input())
if number%2==1:
if number>MAX:
MAX=number
if MAX==-1:
print "There Weren't Any Odd Numbers"
else:
print MAX
here are some notes about your errors:
1- you should cast the raw input into integer using int() function and the column after calling a function is not needed and therefor a syntax error
2- your while loop only iterates once because you initial counting number is 10 and after one iteration it would be bigger than 10 and the while body will be skipped.
3-an even number is a number that has no reminder when divided by 2 but you wrote it exactly opposite.
4- you don't need to print anything in the while loop, you should either print the biggest odd number or print "There Weren't Any Odd Numbers".
5- an additional variable is needed for saving the maximum odd number which is MAX.
Last note: in the code provided above you can combine the two ifs in the while loop in to one loop using 'and' but since you said you are a beginner I wrote it that way.