Помогите пожалуйста написать программу на питон, которая будет находить в одномерном массиве минимальное чётное число и максимальное нечётное число.
Программа в основном написана, но не получается найти минимальное чётное число.
n=int(input("Введите количество элементов, которые будут в списке:"))
b=[]
for i in range(0,n):
a=int(input("Элемент:"))
b.append(a)
c=[]
d=[]
for i in b:
if(i%2==0):
c.append(i)
else:
d.append(i)
c.sort()
d.sort()
count1=0
count2=0
for k in c:
count1=count1-1
for j in d:
count2=count2+1
print("Минимальное четное число:",c[count1+1])
print("Максимальное нечетное число",d[count2-1])
Kromster
13.5k12 золотых знаков43 серебряных знака72 бронзовых знака
задан 14 мая 2021 в 5:29
4
n = int(input("Введите количество элементов, которые будут в списке:"))
b = []
for i in range(n):
a = int(input("Элемент:"))
b.append(a)
c = []
d = []
for i in b:
if i % 2 == 0:
c.append(i)
else:
d.append(i)
c.sort()
d.sort()
print("Минимальное четное число:",c[0])
print("Максимальное нечетное число",d[-1])
ответ дан 14 мая 2021 в 5:42
DanisDanis
19.1k5 золотых знаков20 серебряных знаков55 бронзовых знаков
3
Approach
Avoid using if-stmts
to find maximum. Use python builtin max
. Use either generator or filter
to find only the odd numbers.
Using builtins like this is safer/more reliable because it is simpler to compose them, the code is well-tested, and the code executes mostly in C (rather than multiple byte code instructions).
Code
def find_largest_odd(*args):
return max(arg for arg in args if arg & 1)
or:
def find_largest_odd(*args):
return max(filter(lambda x: x & 1, args))
Test
>>> def find_largest_odd(*args):
... return max(arg for arg in args if arg & 1)
...
>>> print find_largest_odd(1, 3, 5, 7)
7
>>> print find_largest_odd(1, 2, 4, 6)
1
and:
>>> def find_largest_odd(*args):
... return max(filter(lambda x: x & 1, args))
>>> print find_largest_odd(1, 3, 5, 7)
7
>>> print find_largest_odd(1, 2, 4, 6)
1
If you pass an empty sequence or provide only even numbers, you will get a ValueError
:
>>> find_largest_odd(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in find_largest_odd
ValueError: max() arg is an empty sequence
References
- filter
- max
- generators
answered Mar 31, 2013 at 19:19
hughdbrownhughdbrown
47.4k20 gold badges85 silver badges107 bronze badges
Incase anyone is looking for a simple solution using condition statements
x,y,z = 4,1,6
largest = None
if x%2:
largest = x
if y%2:
if y > largest:
largest = y
if z%2:
if z > largest:
largest = z
if largest:
print "largest number is" largest
else
print "there are no odd numbers"
answered Oct 25, 2013 at 17:03
AfDevAfDev
1,24019 silver badges21 bronze badges
1
try:
largest = max(val for val in (x,y,z) if val % 2)
print(largest)
except ValueError:
print('Even')
Note that sorted
is a O(n log n)
operation, while max
is O(n)
. The speed difference may not matter for sequences that are this short, but it is good practice to use the best tool for the job.
answered Mar 31, 2013 at 18:24
unutbuunutbu
832k180 gold badges1770 silver badges1659 bronze badges
This is the finger exercise from Ch.2 of Introduction to Computation and Programming Using Python by John V. Guttag. It’s the recommended text for the MITx: 6.00x Introduction to Computer Science and Programming. The book is written to be used with Python 2.7.
‘Write a program that examines three variables x,y and z, and prints the largest odd number among them. If none of them are odd, it should print a message to that effect.’
At this point the book has only introduced variable assignment and conditional branching programs and the print function. I know as I’m working through it. To that end this is the code I wrote:
if x%2 == 0:
if y%2 == 0:
if z%2 == 0:
print "None of them are odd"
else:
print z
elif y > z or z%2 == 0:
print y
else:
print z
elif y%2 == 0:
if z%2 == 0 or x > z:
print x
else:
print z
elif z%2 == 0:
if x > y:
print x
else:
print y
else:
if x > y and x > z:
print x
elif y > z:
print y
else:
print z
It seems to work for all the combinations I have tried, but it would be useful to know if it can be shortened bearing in mind my points from paragraph three. I appreciate it has been aswered, but by providing this answer, other users are more likely to come across it when searching for answers to the question in the book.
answered Nov 8, 2013 at 23:05
something like this:
def get_max_odd(*lis):
try:
return sorted(i for i in lis if i%2)[-1] #IndexError if no odd item found
except IndexError:
return "even"
In [8]: get_max_odd(1,2,3)
Out[8]: 3
In [9]: get_max_odd(2,4,6)
Out[9]: 'even'
In [10]: get_max_odd(2,5,6)
Out[10]: 5
In [11]: get_max_odd(2,4,6,8,9,10,20)
Out[11]: 9
answered Mar 31, 2013 at 18:41
Ashwini ChaudharyAshwini Chaudhary
243k58 gold badges460 silver badges503 bronze badges
it would be better to filter the numbers, then sort them.
numbers = [x, y, z]
sorted_odd_nums = sorted((x for x in enumerate(numbers) if x[1]%2),
key = lambda x:x[1],
reverse=True)
if not sorted_odd_nums:
# all numbers were even and filtered out.
elif sorted_odd_nums[0][0] == 0:
# x is the biggest odd number
elif sorted_odd_nums[0][0] == 1:
# y is the biggest odd number
elif sorted_odd_nums[0][0] == 2:
# z is the biggest odd number
what it does:
enumerate(numbers)
returns a sequence of (index, item)
pairs. since original list was [x, y, z]
, we can keep the track of x
, y
, z
even after filter and sort.
(x for x in enumerate(numbers) if x[1]%2)
filters above enumeration if the second item in given tuple is not an even number.
sort( ... , key=lambda x:x[1], reverse=True)
sorts filtered items using value of their second-indexed item(which is original number) in descending order.
user input
to read from user, the easiest way is using raw_input
(py2) / input
(py3k).
number = int(raw_input('enter a number: '))
using only if-statements
you’d have to nest if-statements. like:
if x%2: # x is odd
if y%2: # y is odd
if z%2: #z is odd
if x>y and x>z: #x is the biggest odd number
elif y>z and y>x: #y is the biggest odd number
elif z>x and z>y: #z is the biggest odd number
else: #z is even
if x>y: #x is the biggest odd number
else: #y is the biggest odd number
else: #y is even
if z%2: #z is odd
...
answered Mar 31, 2013 at 18:24
thkangthkang
11.1k14 gold badges65 silver badges83 bronze badges
11
I am working my way through the same book by Guttag (and Python 2.7). Others reading it may take cognisance that lists (or slicing them) haven’t been introduced yet though I have used one in my solution (I think it works fine!?!). And you don’t really need to reverse the list order if you would rather slice from the end instead of the beginning of the list.
First I created an empty list (lst). But before I use it I check if all of x, y and z are not odd (Guttag asks if ‘none of them are odd’). Then, each variable in turn is checked to see if its odd and if it is, it gets added to the list. I sorted the list in a descending order (i.e. largest odd numbers to the front).. then check to make sure that it has at least one element (no point in printing an empty list) and then print the first element.
x,y,z = 111,45,67
lst = []
if x%2==0 and y%2==0 and z%2==0:
print 'none of x,y or z is an odd number'
else:
if x%2!=0:
lst.append(x)
if y%2!=0:
lst.append(y)
if z%2!=0:
lst.append(z)
lst.sort(reverse = True)
if len(lst)!=0:
print lst[:1]
answered Mar 26, 2014 at 12:56
CallumHCallumH
7311 gold badge7 silver badges22 bronze badges
Here is my solution:
def get_max_odd(x, y, z):
odd_nums = []
if x % 2 == 1:
odd_nums.append(x)
if y % 2 == 1:
odd_nums.append(y)
if z % 2 == 1:
odd_nums.append(z)
if odd_nums == []:
return 'None of x, y, z are odd numbers'
else:
return max(odd_nums)
print(get_max_odd(120, 111, 23))
I was not able to complete this excercise using ONLY the material presented
thus far in the book. In fact, I don’t think it’s possible to having a
working program without it being over 100 lines. Please let me know if you
have found a way to make it work with ONLY the material presented thus far
answered Sep 3, 2017 at 21:24
1
In the first 4 line of code we are asking the user to enter a number and converting that number to an integer
x = input("enter a number:")
y = input("enter another number: ")
z = input("enter another number: ")
x,y,z = int(x),int(y),int(z)
if x %2 !=0: # check whether x is odd
if y%2 !=0: # if x is odd check y
if z%2 != 0: # if y is odd then check z
if x>z and x > y: # comparing the 3 numbers as all are odd to get largest
print("x is largest")
elif y>z:
print("y is largest")
else:
print("z is largest")
else: # if z is not an odd number then the above comparisons cannot be done #
#so we placed this else if z is not odd then the below comparisons will be executed
if x>z and x > y:
print("x is largest")
elif y>z:
print("y is largest")
else: # if y is also not an even and x is odd then x is largest irrespective of others
print("x is largest")
elif y%2 != 0: # similar way if x is not odd then the above loop will not run so this gets executed when x is even
if z%2 != 0:
if y>z:
print("y is largest")
else:
print("z is largest")
elif z%2 !=0:
print("z is largest")
else:
print("all the numbers are even")
answered Feb 26, 2018 at 8:28
2
def odd(x,y,z):
l=[x,y,z]
even=[]
for e in l:
if e%2!=0:
even.append(e)
even.sort()
if len(even)==0:
return(print('No odd numbers'))
else:
return(even[-1])
odd(1,2,3)
kdoteu
1,5271 gold badge20 silver badges26 bronze badges
answered Mar 29, 2018 at 7:57
2
As per in the comments, the post by AfDev and others will throw a TypeError if x is even, as it will attempt
if y > None:
Edit: The commentor’s solution (initialising largest = 0 instead of largest = None) will not work either if the highest odd is negative.
The question from the book assumes no knowledge of lists or loops so here’s my solution:
x, y, z = 2, -5, -9
largest = None
if x % 2 != 0:
largest = x
if y % 2 != 0:
if largest == None or y > largest: # if None it will not attempt 2nd conditional
largest = y
if z % 2 != 0:
if largest == None or z > largest:
largest = z
print(largest) # prints -5
answered Jul 7, 2021 at 13:36
Ben HallBen Hall
871 silver badge6 bronze badges
This is the first script I have written in my career after contemplating on it since yesterday evening.
Actually I was looking for answer to refer as I was constantly getting errors but could not find anything satisfactory, here is one from me 🙂
x = 333312
y = 221569
z = 163678
if x%2 ==0 and y%2==0 and z%2==0:
print "Only even numbers provided."
elif x%2==0:
if y%2!=0 and z%2!=0:
if y > z:
print y
else:
print z
else:
if y%2!=0:
print y
if z%2!=0:
print z
elif y%2==0:
if x%2!=0 and z%2!=0:
if x > z:
print x
else:
print z
else:
if x%2!=0:
print x
if z%2!=0:
print z
elif z%2==0:
if x%2!=0 and y%2!=0:
if x > y:
print x
else:
print y
else:
if x%2!=0:
print x
if y%2!=0:
print y
else:
if x>y and x>z:
print x
elif y>z:
print y
else:
print z
answered Jan 11, 2015 at 8:31
I am also currently going through the book and came across this problem. I used an approach similar to some of the solutions above. However, instead of just printing the largest value, the program prints the variable holding the largest value as well.
The difference here becomes that rather than checking if x > y
, x > z
, etc., the program also checks for equality (i.e. x >= y
, x >= z
, etc.). For multiple equal values, the program will print all the variables that share the highest odd value.
Finger Exercise 2.2
Write a program that examines three variables- x, y, and z- and prints the
largest odd number among them.
If none of them are odd, it should print a message to that effect.
x, y, z = 5,7,7
if x%2 == 1 or y%2 == 1 or z%2 == 1: #at least one of the variables is odd
if x%2 == 1:
if y%2 == 1:
if z%2 == 1: #x, y, and z are all odd
if x >= y and x >= z:
print "x =", x, "is the largest odd number!"
if y >= x and y >=z:
print "y =",y, "is the largest odd number!"
if z >= x and z >= y:
print "z =", z, "is the largest odd number!"
else: #z is even, but x and y are still odd
if x >= y:
print "x =", x, "is the largest odd number!"
if y >= x:
print "y =",y, "is the largest odd number!"
elif z%2 == 1: #y is even, but x and z are odd
if x >= z:
print "x =", x, "is the largest odd number!"
if z >= x:
print "z =", z, "is the largest odd number!"
else: #x is the only odd number
print "x = ", x, "is the largest odd number!"
if x%2 != 1 and y %2 == 1: #x is not odd but y is odd
#could have done an elif here. But this makes the code easier to follow
if z%2 == 1:#z is also odd
if y >=z:
print "y =",y, "is the largest odd number!"
if z >= y:
print "z =", z, "is the largest odd number!"
else: #z is even. Hence, y is the only odd number
print "y =", y, "is the largest odd number!"
if x%2 != 1 and y%2 != 1 and z%2 == 1:#z is the only odd number
print "z =", z, "is the largest odd number!"
else:
print "No odd number was input!"
spenibus
4,31911 gold badges26 silver badges35 bronze badges
answered Oct 18, 2015 at 0:34
This answers the last finger exercise in the Ch.02 of the book by Prof. John Guttag mentioned in earlier posts. Using lists seemed helpful to me. The same method can be used for the previous finger exercise in the same chapter.
import math
a=int(input("Enter first integer: ")) # Manual entering of ten integers#
b=int(input("Enter second integer: "))
c=int(input("Enter third integer: "))
d=int(input("Enter fourth integer: "))
e=int(input("Enter fifth integer: "))
f=int(input("Enter sixth integer: "))
g=int(input("Enter seventh integer: "))
h=int(input("Enter eighth integer: "))
i=int(input("Enter ninth integer: "))
j=int(input("Enter tenth integer: "))
master=[a,b,c,d,e,f,g,h,i,j]
def ifalleven(a): # Finding whether every integer in the list if even or not.#
i=0
list=[]
while i<len(a):
if a[i]%2==0:
list.append(a[i])
i=i+1
return len(list)==len(a)
def findodd(a): # Finding the greatest odd integer on the list.#
i=0
list=[]
while i<len(a):
if a[i]%2!=0:
list.append(a[i])
i=i+1
print (max(list))
def greatoddoreven(list): # Finding the greatest odd integer on the list or if none are odd, print a message to that effect.#
if ifalleven(list)==True:
print ('No odd numbers found!')
else:
findodd(list)
greatoddoreven(master)
answered Apr 17, 2016 at 6:35
DevangDevang
331 silver badge6 bronze badges
I am learning Python and programming as well. My answer for this exercise as follow. Working through finger exercise from Ch.2 of Introduction to Computation and Programming Using Python by John V. Guttag.
x, y, z = 55, 90, 87
if x%2 == 1 and y%2 == 1 and z%2 == 1:
if x > y and x > z:
print (x)
elif y > z and y >x:
print (y)
else:
print (z)
else:
print ('none of them are odd')
answered Oct 6, 2016 at 18:42
nannynanny
573 silver badges8 bronze badges
0
num1 = 7
num2 = 16
num3 = 300
x1=0
x2=0
x3=0
if num1%2 != 0:
x1=1
if num2%2 != 0:
x2=1
if num3%2 != 0:
x3=1
if (num1*x1 > num2*x2) and (num1*x1 > num3*x3):
largest = num1
elif (num2*x2 > num1*x1) and (num2*x2 > num3*x3):
largest = num2
elif (x3):
largest = num3
else:
print("no one is odd")
if(x1!=0 or x2!=0 or x3!=0):
print("The largest odd number between",num1,",",num2,"and",num3,"is",largest)
answered Jan 2, 2017 at 3:56
1
x=input('x= ')
y=input('y= ')
z=input('z= ')
largest = None
if x%2 == 0 and y%2 == 0 and z%2 == 0:
print('none of them is odd')
else:
if x%2 != 0:
largest = x
if y%2 != 0:
if y > largest:
largest = y
if z%2 != 0:
if z > largest:
largest = z
print(largest)
answered Feb 25, 2017 at 5:33
just finished working the same problem. My answer seems different from the other ones but seems to be working fine.( Or am I missing something?!) so here is an alternative:
With only if/else:
x = 4
y = 7
z = 7
if x%2 and y%2 and z%2 == 1:
if x > y and x > z:
print x
elif y > z:
print y
else:
print z
elif x%2 and y%2 == 1:
if x > y:
print x
else:
print y
elif x%2 and z%2 == 1 :
if x > z:
print x
else:
print z
elif y%2 and z%2 == 1:
if y > z:
print y
else:
print z
elif x%2 == 1:
print x
elif y%2 == 1:
print y
elif z%2 == 1:
print z
else:
print "there are no odd numbers"
as far as I know it works with negative, numbers, big numbers, … if not let me know!
answered Mar 8, 2017 at 5:46
stefstef
231 silver badge5 bronze badges
Here is my “rookie” version of the solution. Basically the problem requires the analysis of all possible combinations of X, Y, Z depending on user input (eg., cases such as one odd and two even numbers, etc.).
I first eliminated the two most obvious cases when all numbers are even and at least one of the numbers is zero. The code is missing only the part when at least two numbers are equal. The rest is straightforward…
There is definitely a much refined approach to the problem (see below for cases with more combinations of ingredient variables using sorting and reverse comparison) but this is what I could accomplish with my basic knowledge of Python.
print('This program will find the largest odd number among the three entered.nSo, let's start...n')
x = int(input('Enter the 1st number: '))
y = int(input('Enter the 2nd number: '))
z = int(input('Enter the 3rd number: '))
strToPrint = ' is the largest odd number.'
if x==0 or y==0 or z==0:
print('nNo zeroes, please. Re-run the program.')
exit()
if x % 2 == 0 and y % 2 == 0 and z % 2 == 0:
print('nAll numbers are even.')
elif x % 2 != 0 and y % 2 != 0 and z % 2 != 0: # all numbers are odd; start analysis...
if x > y and x > z:
print(str(x) + strToPrint)
if y > x and y > z:
print(str(y) + strToPrint)
if z > y and z > x:
print(str(z) + strToPrint)
elif x % 2 != 0 and y % 2 == 0 and z % 2 == 0: # only X is odd.
print(str(x) + strToPrint)
elif y % 2 != 0 and x % 2 == 0 and z % 2 == 0: # only Y is odd.
print(str(y) + strToPrint)
elif z % 2 != 0 and x % 2 == 0 and y % 2 == 0: # only Z is odd.
print(str(z) + strToPrint)
elif x % 2 != 0 and y % 2 != 0 and z % 2 == 0: # only X and Y are odd.
if x > y:
print(str(x) + strToPrint)
else:
print(str(y) + strToPrint)
elif x % 2 != 0 and y % 2 == 0 and z % 2 != 0: # only X and Z are odd.
if x > z:
print(str(x) + strToPrint)
else:
print(str(z) + strToPrint)
elif x % 2 == 0 and y % 2 != 0 and z % 2 != 0: # only Z and Y are odd.
if y > z:
print(str(y) + strToPrint)
else:
print(str(z) + strToPrint)
Below is the “non-rookie” version of the same program for any (reasonable) number of integers, which is shorter and more compact compared to the previous version. I used a list of ten integers for demonstration only, but the list can be extended.
int_list = [100, 2, 64, 98, 89, 25, 70, 76, 23, 5]
i = len(int_list) - 1 # we'll start from the end of a sorted (!) list
int_list.sort() # sort the list first
# print(int_list) # just to check that the list is indeed sorted. You can uncomment to print the sorted list, too.
while i >= 0: # prevent 'out of range' error
if int_list[i] % 2 != 0: # check if the list item is an odd number
break # since the list is sorted, break at the first occurence of an odd number
i -= 1 # continue reading list items if odd number isn't found
print('The largest odd number is: ' + str(int_list[i]) + ' (item #' + str(i) + ' in the sorted list)')
answered Sep 27, 2018 at 11:26
1
How’s this for an answer? Is it too long?
x, y, z = eval(input('Please enter the numbers for x, y, z: '))#allows you to enter three numbers each separated by a comma
print('x =', x)#Shows you what the value of x is
print('y =', y)#Shows you what the value of y is
print('z =', z)#Shows you what the value of z is
if x%2 != 0:#Checks to see if x is odd is true
if y%2 != 0:#Checks to see if y is odd is true
if z%2 != 0:#Checks to see if z is odd is true
if x > y and x > z:# Now in this situation since all the numbers are odd, all we have to do is compare them to see which is the largest in the following lines
print('x is the largest odd number')
elif y > z:
print('y is the largest odd number')
else:
print('z is the largest odd number')
elif x > y:# we refer back to the line if z%2 != 0 and in this new situation, it is false therefore z is not odd in this case and x and y are the only odd numbers here
print('x is the largest odd number') # we check to see if x is the largest odd number, if x is not largest odd number then proceed to the next line
else:
print('y is the largest odd number') # here, y is the largest odd number
elif z%2 != 0:# refer back to the sixth line at the beginning, if y%2 = 0.In this new situation, y is not odd so the only variables we're comparing now are x and z only
if x > z:
print('x is the largest odd number')
else:
print('z is the largest odd number')
else:
print('x is the largest odd number')# when both y and z are not odd, by default x is the largest odd number here
elif y%2 != 0:# Refer back to the fifth line, if x%2 != 0, in this new situation, the statement if x%2 != 0 is false therefore we proceed to checking if the next variable y is odd right here
if z%2 != 0:#Since y is odd, check to see if z is odd,
if y > z:#then if previous statement is true check to see now if y is bigger and print('y is the largest odd number') if so
print('y is the largest odd number')
else:
print('z is the largest odd number')# here y is not largest odd number so by default z is the largest
else:# this line occurs when z is not odd which pretty much leaves y to be the only odd number and is therefore largest odd number by default
print('y is the largest odd number')
elif z%2 != 0:# this line occurs when both x and y is not odd which leaves z to be the largest odd number
print('z is the largest odd number')
else:# this line occurs when all the numbers are not odd; they are even. Remember in this program, our main objective is to determine the largest number only among the odd numbers if there are any odd numbers at all, and if there are no odd numbers we show that there are none. (We do not take into account even numbers at all since that's not what the question is about)
print('There are no odd numbers')
Dharman♦
30.3k22 gold badges84 silver badges132 bronze badges
answered Feb 21, 2017 at 16:28
1
Here is my interpretation, I am doing the same task which is part of the Book Introduction to Computation and Programming Using Python, 2nd ed, John Guttag
# edge cases 100, 2, 3 and 100,2,-3 and 2,2,2
x = 301
y = 2
z = 1
# what if the largest number is not odd? We need to discard any non-odd numbers
# if none of them are odd - go straight to else
if (x % 2 != 0) or (y % 2 != 0) or (z % 2 != 0):
#codeblock if we have some odd numbers
print("ok")
# initialising the variable with one odd number, so we check each in turn
if (x % 2 != 0):
largest = x
elif (y % 2 != 0):
largest = y
elif (z % 2 != 0):
largest = z
# here we check each against the largest
# no need to check for x as we did already
if (y % 2 != 0):
if y > largest:
largest = y
if (z % 2 != 0):
if z > largest:
largest = z
print("The largest odd number is:", largest)
print("The numbers were", x, y, z)
else:
print("No odd number found")`
answered Nov 13, 2020 at 14:57
AtanasAtanas
401 silver badge7 bronze badges
Here is my code for Guttag’s Finger exercise 2:
def is_odd(x):
"""returns True if x is odd else returns False"""
if x % 2 != 0:
return(True)
else:
return(False)
def is_even(x):
"""returns True if x is even else returns False"""
if x % 2 == 0:
return(True)
else:
return(False)
def largest_odd(x, y, z):
"""Returns the largest odd among the three given numbers"""
if is_odd(x) and is_odd(y) and is_odd(z):
return(max(x, y, z))
elif is_odd(x) and is_odd(y) and is_even(z):
return(max(x, y))
elif is_odd(x) and is_even(y) and is_odd(z):
return(max(x, z))
elif is_even(x) and is_odd(y) and is_odd(z):
return(max(y, z))
elif is_odd(x) and is_even(y) and is_even(z):
return(x)
elif is_even(x) and is_odd(y) and is_even(z):
return(y)
elif is_even(x) and is_even(y) and is_odd(z):
return(z)
else:
return("There is no odd number in the input")
answered Dec 25, 2020 at 6:54
Assuming we aren’t going to use something fancy 🙂 like the max and sort functions in python…I think it’s safe to say than an “assignment” statement is fair game….we do after all have to assign x,y and z.
As such: I created my own variable called “largest” initialized as zero.
I assign that variable the first odd number of x,y,z (interrogated in that order).
Then I simply check the remaining values and if each one is greater than “largest” and is also an odd number then I make it the value of “largest” — and check the next value.
Once all the values are checked, “largest” holds the value of the largest odd number or zero (which means I never did find an odd number and I print a message to that effect.
This is the same method you could use to read an arbitrary number (perhaps 10) of values from a user and print the largest odd one after all values are entered. Just check each value as it’s entered against the current “largest” one.
Yes, you do need to be careful to support negative odd numbers — you need to handle the assignment of “largest” to the first odd number whether or not it’s greater than zero.
answered Oct 6, 2013 at 4:29
It’s actually easier for me to to think about this problem with more values rather than only 3 (x,y,z). Suppose I show you a list of words Apple, dog, Banana, cat, monkey, Zebra, elephant… etc. Let’s say there are 26 words denoted by variables a,b,c,d,e,f…x,y, and z.
If you need to find the “largest word” (in dictionary order) that begins with a lowercase letter, you don’t need to compare every word with every other word. Our brains don’t typically sort the entire list into order and then pick from the end either…well…mine doesn’t anyway.
I just start at the front of the list and work my way through it. The first time I find a word that starts with a lowercase letter…I memorize it and then read until I get another lowercase word — then I check which is larger and memorize just that word…. I never have to go back and check any of the others. One pass on the list and I’m done. In the list above…my brain immediately discards “Zebra” because the case is wrong.
answered Oct 6, 2013 at 5:01
The question asks to print out the largest odd number from 3 variables -x, y, and z, and since it’s chapter 2 which only goes as far as describing conditionals I’m guessing the ans should be provided by using only conditionals.
The program can be completed by exhaustively writing all the possible combinations of odd or even. Since there is 3 variables and at any one time these variables can be either odd or even there is 2^3 = 8 combinations/ conditionals.
This can be shown by using a Truth Table but instead of using True and False we use ‘O’ for odd and ‘E’ for even.
The table will look like this Odd-Even Table
Each row is a conditional in the code which checks ‘oddness/evenness’. Inside each of these conditionals you will then check which variables is the largest odd number using nested conditionals for this.
x = int(input('Enter an integer: '))
y = int(input('Enter another integer: '))
z = int(input('Enter a final integer: '))
print('x is:', x)
print('y is:', y)
print('z is:', z)
print('n')
if x % 2 == 1 and y % 2 == 1 and z % 2 == 1:
print('First conditional triggered.')
if x > y and x > z:
print(x, 'is the largest odd number.')
elif y > x and y > z:
print(y, 'is the largest odd number.')
elif z > x and z > y:
print(z, 'is the largest odd number.')
else:
print(x, 'is the largest odd number.')
# This else clause covers the case in which all variables are equal.
# As such, it doesn't matter which variable you use to output the
# largest as all are the largest.
elif x % 2 == 1 and y % 2 == 1 and z % 2 == 0:
print('Second conditional is triggered.')
if x > y:
print(x, 'is the largest odd number.')
elif y > x:
print(y, 'is the largest odd number.')
else:
print(x, 'is the largest odd number.')
elif x % 2 == 1 and y % 2 == 0 and z % 2 == 1:
print('Third conditional is triggered.')
if x > z:
print(x, 'is the largest odd number.')
elif z > x:
print(z, 'is the largest odd number.')
else:
print(x, 'is the largest odd number.')
elif x % 2 == 1 and y % 2 == 0 and z % 2 == 0:
print('Fourth conditional is triggered.')
print(x, 'is the largest odd number.')
elif x % 2 == 0 and y % 2 == 1 and z % 2 == 1:
print('Fifth conditional is triggered.')
if y > z:
print(y, 'is the largest odd number.')
elif z > y:
print(z, 'is the largest odd number.')
else:
print(y, 'is the largest odd number.')
elif x % 2 == 0 and y % 2 == 1 and z % 2 == 0:
print('Sixth conditional is triggered.')
print(y, 'is the largest odd number.')
elif x % 2 == 0 and y % 2 == 0 and z % 2 == 1:
print('Seventh conditional is triggered.')
print(z, 'is the largest odd number.')
else:
print('Eight conditional is triggered.')
print('There is no largest odd number as all numbers are even.')
This method works fine for 3 variables but the complexity and amount of conditionals needed can rise sharply with more variables being added.
answered Sep 13, 2016 at 3:36
Just done this excercise and this seems like an efficient way of doing it although it doesn’t seem to handle negative numbers (I don’t think it’s supposed to at this level though):
x, y, z = 7, 6, 12
xo = 0
yo = 0
zo = 0
if x%2 == 0 and y%2 == 0 and z%2 == 0:
print("None of the numbers are odd.")
if x%2 == 1:
xo = x
if y%2 == 1:
yo = y
if z%2 == 1:
zo = z
if xo > yo and xo > zo:
print(xo)
if yo > xo and yo > zo:
print(yo)
if zo > xo and zo > yo:
print(zo)
answered Dec 7, 2019 at 15:01
DiagonaliDiagonali
1091 silver badge10 bronze badges
This is how I did it..hope it helps.
x = 2
y =4
z=6
# Conditional program to print the smallest odd number
if x %2 == 1 or y% 2 == 1 or z% 2 == 1 : #checks if at least one is odd
if x<y and x< z: # checks if x is least
print x
elif y<z: # x is not least,so proceeds to check if y is least
print y
else:
print z #prints z, the least number
else:
print "None of the numbers are odd"
If you want the largest odd number, just reverse the signs.
answered May 11, 2015 at 11:53
karthik2k2karthik2k2
611 silver badge3 bronze badges
0
I just read the beginning of a Python text, and I’m pretty sure I found the most exhaustive method to solving this problem:
if x%2!=0 and y%2!=0 and z%2!=0 and x>y and x>z:
print(x)
elif x%2!=0 and y%2!=0 and z%2!=0 and y>x and y>z:
print(y)
elif x%2!=0 and y%2!=0 and z%2!=0 and z>x and z>y:
print(z)
elif x%2==0 and y%2!=0 and z%2!=0 and y>z:
print(y)
elif x%2==0 and y%2!=0 and z%2!=0 and z>y:
print(z)
elif x%2!=0 and y%2!=0 and z%2==0 and y>x:
print(y)
elif x%2!=0 and y%2!=0 and z%2==0 and x>y:
print(x)
elif x%2!=0 and y%2==0 and z%2!=0 and x>z:
print(x)
elif x%2!=0 and y%2==0 and z%2!=0 and z>x:
print(z)
else:
print('none of them are odd')
Rob♦
27.3k15 gold badges82 silver badges97 bronze badges
answered Sep 8, 2017 at 6:13
1
0 / 0 / 0 Регистрация: 04.04.2018 Сообщений: 17 |
|
1 |
|
Нечетная и наибольшая цифры04.06.2018, 18:29. Показов 4327. Ответов 4
Есть трехзначное число, нужно:
0 |
hitomy 318 / 115 / 16 Регистрация: 07.10.2012 Сообщений: 529 |
||||
04.06.2018, 20:57 |
2 |
|||
1 |
Semen-Semenich 4466 / 3146 / 1112 Регистрация: 21.03.2016 Сообщений: 7,833 |
||||
04.06.2018, 21:45 |
3 |
|||
1 |
Jabbson 5887 / 3345 / 1033 Регистрация: 03.11.2009 Сообщений: 9,974 |
||||
05.06.2018, 02:38 |
4 |
|||
0 |
Vigi 628 / 468 / 179 Регистрация: 28.05.2012 Сообщений: 1,399 |
||||
05.06.2018, 05:14 |
5 |
|||
найти и вывести нечетную цифру этого числа в связи c условием задания Jabbson, немного подстроил ваш код.
0 |
Решение на python задач с номером 25 егэ по информатике на поиск максимального элемента массива
В задачах с номером 25 егэ по информатике на поиск максимального элемента необходимо организовать ввод массива с клавиатуры, найти максимальный элемент массива, удовлетворяющий определенному условию. Разберем пример программы на python, которая ищет максимальный четный и максимальный нечетный элемент массива.
Код на Python для ввода с клавиатуры массива заданного размера. Подробно о работе с массивами в Python
a = []
n=10
for i in range(0, n):
a.append(int(input()))
Для максимального четного и нечетного элемента введем переменные и сначал присвоим им занечния первого элемента массива
maxc=a[0]
maxn=a[0]
В цикле for переберём все элементы массива и с помощью оператора условия в python if
сравним каждый нечетный элемент массива с текущим значением максимума, если этот элемент будет больше, то текущему максимуму присвоим значение этого элемента массива.
Чтобы проверить, является ли переменная четной, в условии нужно использовать выражение
переменная%2==0
Чтобы проверить, является ли переменная нечетной, в условии нужно использовать выражение
переменная%2!=0
Чтобы одновременно выполнялись оба условия, в условии if необходимо использовать логическую операцию and Подробно об условиях If в python
for i in range(0, n):
if a[i]%2==0 and a[i]>maxc:
maxc=a[i]
if a[i]%2!=0 and a[i]>maxn:
maxn=a[i]
Полная программа на Python, которая ищет максимальный четный и нечетный элемент массива
a = []
n=10
for i in range(0, n):
a.append(int(input()))
maxc=a[0]
maxn=a[0]
for i in range(0, n):
if a[i]%2==0 and a[i]>maxc:
maxc=a[i]
if a[i]%2!=0 and a[i]>maxn:
maxn=a[i]
print(‘максимальный четный элемент’,maxc)
print(‘максимальный нечетный элемент’,maxn)
Разберем решение на python задачи с номером 25 егэ по информатике на поиск максимального элемента массива.
Дан целочисленный массив из 10 элементов. Элементы массива могут принимать целые значения от 0 до 10000 включительно Необходимо написать программу, которая позволяет найти и вывести максимальное значение среди двухзначных элементов массива, делящихся на 7. Если в исходном массиве нет элемента, значение которого является трёхзначным числом и при этом кратно 7, то вывести сообщение «Не найдено».
Организуем ввод массива с клавиатуры в python
a = []
n=10
for i in range(0, n):
a.append(int(input()))
max=1
Введем переменную max в которую будем записывать максимальное значение двузначных элементов массива. присвоим ей в начале программы значение 1. Если элементы удовлетворяющие нужному нам условию не будут найдены, то значение переменной max останется равным 1, это будет говорить о том что элементы не найдены
В цикле for перебираем все элементы массива и ищем максимум среди двузначных чисел
Двузначные элементы лежат в диапазоне от 10 до 99. Чтобы элемент был двузначным и делился на 7 в операторе условия необходимо, чтобы выполнялось сразу три условия одновременно
a[i]>9, a[i]<100, a[i]%7==0
Чтобы выполнялись все три условия необходимо в операторе условия If использовать логическую операцию and
for i in range(0, n):
if a[i]>9 and a[i]<100 and a[i]%7==0:
max=a[i]
В конце программы производится проверка найден ли хотя бы один элемент удовлетворяющий условию задачи, если элементы не найдены то выводится сообщение элементы не найдены
if max==1:
print(‘элементы не найдены’)
else:
print(‘максимальный элемент ‘, max)
Полная программа на python для поиска максимального двузначного элемента массива кратного 7
a = []
n=10
for i in range(0, n):
a.append(int(input()))
max=1
for i in range(0, n):
if a[i]>9 and a[i]<100 and a[i]%7==0 and a[i]>max:
max=a[i]
if max==1:
print(‘элементы не найдены’)
else:
print(‘максимальный элемент ‘, max)
Перейти к курсу python
Полезно почитать по теме решение на python задач с номером 25 егэ по информатике на тему массивы
Решение задач на python на массивы с накопителем
Решение задач на python на массивы на пары элементов массива
Поделиться:
Комментарии ()
Нет комментариев. Ваш будет первым!
read_count = 0
largest_odd = Nonewhile read_count < 10:
user_input = input('Enter any number')try:
user_input = int(input('Enter a number'))
except ValueError:
print("user input {} is not a number".format(user_input))
continueif user_input & 1:
if largest_odd is None:
largest_odd = user_input
largest_odd = max(largest_odd, user_input)read_count += 1
if largest_odd is None:
print("No odd numbers found")
else:
print("Largest odd number found was {}".format(largest_odd))
Теперь позвольте немного largest_odd
об этом, мы объявили переменные read_count
и largest_odd
чтобы отслеживать количество чисел, которые мы видели, и то, что было самым большим нечетным. Обратите внимание, что я специально выбрал, чтобы сделать largest_odd = None
в случае, когда мы не видим нечетное число.
Затем мы зацикливаемся до тех пор, пока пользователь не введёт действительное число 10 раз.
Логика try-catch
слишком утомительна для вас, но она помогает защитить программу от сбоев из-за плохого ввода от пользователя. Попробуйте открыть оболочку Python и запустить int('x')
. Вы поймете, почему я хочу поймать ValueError
после этого.
Сначала строка, if user_input & 1
может ввести в заблуждение, но это очень быстрый способ определить, является ли число нечетным или нет. Конечно, вы можете сделать user_input % 2 == 1
но все, что вам действительно нужно проверить, – это установить первый (user_input % 2 == 1
бит или LSB), который мы используем побитно AND
с номером 1
.