ดังนั้นฉันจึงตัดสินใจเข้าร่วมโปรแกรมการแข่งขันบน CodeChef ฉันเห็นปัญหาที่ต้องพยายาม แต่ฉันได้รับข้อผิดพลาดรันไทม์ (NZEC) อยู่เรื่อย ๆ และฉันไม่รู้ว่าทำไมเพราะฉันคิดว่าข้อผิดพลาดนั้นเกิดขึ้นเฉพาะเมื่อฉันเรียกใช้รายการอาเรย์ที่ถูกผูกไว้และการวนซ้ำไม่รู้จบซึ่งใช้หน่วยความจำมากเกินไป
ปัญหา
1.) รับ 2 อินพุต A และ B
2.) ขอบเขต: 1 ≤ B ‹ A ≤ 10000
3.) จากนั้นฉันทำ A-B และ แก้ไขคำตอบหลักเดียว
4.) จากนั้นฉันก็คืนมัน
หมายเหตุ: กำหนดเวลาคือ 1 วินาที ขนาดซอร์สโค้ดสูงสุด 50,000 ไบต์
e.g
input A >> 95
input B >> 50
output >> 35
คำตอบที่แท้จริงคือ 45 แต่เราตั้งใจจะเปลี่ยนคำตอบหนึ่งหลัก
นี่คือวิธีแก้ปัญหาของฉัน
from random import randint
test1 = True
test2 = True
while test1:
A = int(input("Enter a number: "))
if (A>=1) and (A<=10000):
test1 = False
else:
print("Number must be greater or equal to 1 and less than or equalts to 10,000")
while test2:
B = int(input("Enter a second number: "))
if (B>=1) and (B<=10000) and (B<A):
test2 = False
else:
print("Number must follow rules as above BUT must be less than your first")
solution = str(A-B)
range1 = randint(0, len(solution)-1)
range2 = randint(0,9)
replacement = list(range(0,10))
new_solution = solution.replace(solution[range1], str(replacement[range2]))
print(new_solution)