简体   繁体   中英

how would i compare odd numbers in a sequence in python code?

I need to write a code that counts the number of pairs of adjacent odd numbers in a series of numbers entered by the user.

Say, for example, the user enters the series 3, 4, 5, 11, 6, 17, 9, 13, 12. There are three pairs of adjacent odd numbers: (5, 11), (17, 9), (9, 13).

here is an example of the expected input and output:

Enter the length of the sequence:

5

Enter number 1:

57

Enter number 2:

89

Enter number 3:

3

Enter number 4:

11

Enter number 5:

8

The number of pairs of adjacent odd numbers is: 3 

here is the begining of my code (however i am not sure how i would find odd numbers):

n = eval(input("Enter the length of the sequence: \n"))
string = ""
c = 0
for i in range(n):

I am not sure why you are using eval here or storing the inputs in a string as opposed to a list... The standard way to find out if a number is odd is to use the modulo operator % - an int n is odd if n % 2 != 0 .

Something like this should work.

n = int(input("Enter the length of the sequence: "))
numbers = []
for _ in range(n):
    numbers.append(int(input()))

c = 0
for i, j in zip(numbers, numbers[1:]):
    if i % 2 and j % 2:
        c += 1
print(c)

Use a % the modulus operator for finding odd numbers

x=int(input("Enter the number of numbers: "))
odd_l=[]
for i in range(1,x+1):
    y=int(input(f"Enter {i} number: "))
    if y%2==1:
        odd_l.append(y)
print("The number of odd number pairs is ",len(odd_l)//2)
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM