Loops through a whole list - python

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.

Related

Delete object in array within another array while checking for valid index

The task is to delete an object from an array within another array (a touple if i'm correct). To bugproof i would need to check whether the index is actually valid. This means ranges from 0 to 4 (so input should be greater 0 smaller 4) and obviously not be a string or float of any kind.
I have tried to do that with my def function. i obviously want loopx to only be false if indeed both of the above mentioned criteria are met. otherwise i would want to jump to except. I felt like if that is what I've done but now been stuck for over an hour.
#Write a Python program to delete an existing item from the array
#function used to check for valid input
def valuecheck(checker):
loopx = True
while loopx:
try:
if checker == int(checker) and (checker>0 and checker<4):
#first it checks if the input is actually an integer
#checker = int(checker)
#checks if the input index number is within range of the array
loopx = False
else:
checker = input("Value isn't a valid input, try again: ")
return(checker)
#if input isn't an integer the below prompt is printed
except:
checker = input("Value isn't a valid input, try again: ")
#the example array is defined and printed
myarray = ['i', [1, 3, 5, 7, 9]]
print(myarray[1])
#input defined and checked by the loop
deletion = input("Please input the index of the element you want to remove (0 through 4). Indexes for the elements start at 0, increasing left to right: ")
deletion = valuecheck(deletion)
#pop is then used to remove the value with index "deletion" from the array
myarray[1].pop(deletion)
#finally the new array is printed
print ("This is the new array:",myarray[1])
Here is a version of the valuecheck() function that should do what you want:
def valuecheck(checker):
while True:
try:
checker = int(checker)
if checker > 0 and checker < 4:
return checker
checker = input("Value must be between 1 and 3, try again: ")
except:
checker = input("Value must be an integer, try again: ")
The main difference to your code is that the value in checker is converted to an integer before it is tested to check if it's in the range 1-3. That operation will throw an exception if checker doesn't contain the string representation of a valid integer.
Rather than using the loop variable loopx, the function simply returns when it finds a valid value.
Try this code (it contains only little differences respect yours):
#Write a Python program to delete an existing item from the array
#function used to check for valid input
def valuecheck(checker):
loopx = True
while loopx:
try:
if (int(checker)>=0 and int(checker)<=4):
loopx = False
else:
checker = input("Value isn't a valid input, try again: ")
except Exception as ex:
checker = input("Value isn't a valid input, try again: ")
return checker
#the example array is defined and printed
myarray = ['i', [1, 3, 5, 7, 9]]
print(myarray[1])
#input defined and checked by the loop
deletion = input("Please input the index of the element you want to remove (0 through 4). Indexes for the elements start at 0, increasing left to right: ")
deletion = valuecheck(deletion)
#pop is then used to remove the value with index "deletion" from the array
myarray[1].pop(int(deletion))
#finally the new array is printed
print ("This is the new array:",myarray[1])
Important: change the conditions in the if
In my opinion the condition is:
if (int(checker)>=0 and int(checker)<=4):
because your array contains 5 elements, so the indexes 0 and 4 are included.
def valuecheck():
prompt = "Please input the index of the element you want to remove (0 through 4). Indexes for the elements start at 0, increasing left to right: "
while True:
try:
checker = int(input(prompt))
if 0 <= checker <= 4:
return checker
prompt = "Value isn't in range [0,4], try again: "
except ValueError:
prompt = "Value isn't a valid integer, try again: "
#the example array is defined and printed
myarray = ['i', [1, 3, 5, 7, 9]]
print(myarray[1])
#input defined and checked by the loop
deletion = valuecheck()
#pop is then used to remove the value with index "deletion" from the array
myarray[1].pop(deletion)
#finally the new array is printed
print ("This is the new array:",myarray[1])
The function will only return with a value when it can convert the input string to an integer and it's between 0 and 4 (inclusive). In other cases it changes the prompt's text and the loop continues.
I also specified the type of exception in the except clause as your program won't exit if you press Ctrl+C (KeyboardInterrupt) if you don't specify.

To check whether an entered value exists in a List

This is my simple code. When a User enters a value, it has to be compared with the list I have used and should return the output as required. But when I execute the code and enter a value that is a part of the list, it returns the print statement under the else construct. Please help me with your suggestions
mylist=[1,2,3]
print('Enter the Rank:')
x=input()
if x in mylist:
print('You have passed')
else:
print('Sorry you have failed')
The items in mylist are ints. Input returns a string, so to compare them you need to convert one of them.
Either
x = int(input())
or
if int(x) in mylist

How do you convert a string to an integer in Python

"""
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))

try except structure don't work. user input integers and if not give an error.how to fix?

print ("please enter values as check([x,y,z])to find min and max")
def check(iterable):
try:
(iterable) = int(iterable)
except:
print("please Enter number")
else:
print("************************")
it = iter(iterable)
first = next(it) # Raises an exception if the input is empty
minimum = maximum = cumsum = first
n = 1
for x in it:
n += 1
cumsum += x
if x < minimum:
minimum = x
if x > maximum:
maximum = x
return "min:" + str(minimum), "max:" + str(maximum)
From what I can break down from what you wrote, the first thing you should be doing is prompting the user to input a list as such:
1,2,3,4
So your code should be written like this to accept this input:
user_input = input("please enter values as #,#,# to find min and max ")
From there, what you want to do is then call your check method with user_input:
check(user_input)
Inside your try/except for your check method, you must now determine how to convert your string which now looks like this:
# pure string
"1,2,3,4"
In to this:
# list of ints
[1, 2, 3, 4]
So, if you simply do this:
# Convert to a list of strings by splitting on comma
iterable = iterable.split(',')
# Iterate over array and convert each element to an int
for i, v in enumerate(iterable):
iterable[i] = int(iterable[i])
To simplify the above, you use what is called a list comprehension, and do this all in one line as such:
iterable = [int(x) for x in iterable.split(",")]
You will end up getting your list of ints. Now, if you end up providing an input like this:
1,a,5
The logic to convert to a list of ints will fail because 'a' is not a int and it will enter your except.
After that, you should be able to continue with the rest of your logic to determine how to get the max and the min.
So, your code should look something like this:
def check_user(user_input):
# code stuff
user_input = input("blah blah")
check_user(user_input)

Create an array and store in a different function

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.

Categories