Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมตรวจสอบค่า find(x, y) เป็นคู่หรือคี่ ใน Python

กำหนดอาเรย์ nums และคู่ (x, y) หาว่า find(x,y) เป็นคี่หรือคู่ โดย find() กำหนดดังนี้:

  • find(x, y) = 1 ถ้า x > y
  • find(x, y) = nums[x]^find(x+1, y) มิฉะนั้น

เช่น nums = [3,2,7], (x,y) = 1,2 ผลลัพธ์คือ even เพราะ: find(1,2) = nums[1]^find(2,3) = 2^7 = 128 (คู่)

วิธีแก้ปัญหา

  • even := True
  • ถ้า x > y หรือ nums[x] เป็นคี่: even := False
  • ถ้า x < len(nums)-1 และ x < y และ nums[x+1] == 0: even := False
  • ถ้า even: คืนค่า 'Even' มิฉะนั้น: คืนค่า 'Odd'

ตัวอย่างโค้ด

def solve(nums, x, y):
    even = True
    if x > y or (nums[x] % 2 == 1):
        even = False
    if x < len(nums) - 1 and x < y and nums[x+1] == 0:
        even = False
    if even:
        return 'Even'
    else:
        return 'Odd'

nums = [3, 2, 7]
x, y = 1, 2
print(solve(nums, x, y))

Input

[3,2,7], 1, 2

Output

Even