LMSouq
moodle-core Open

how to receive an unknown amount of inputs without an input that tells the code to stop?

MI
minyards
1 month ago
3 views
Problem Description
I'm supposed to write a code that receives two integers (m and n) and returns all the prime numbers between those numbers (essentially a range(m,n)). The original exercise is in Portuguese, but I tried to insert a translated version at the end for more context. My issue is that Moodle (where I'm submitting the code) runs tests to see if it's correct. In each test, it gives me various lines (each with different variations of m and n in a "m1 n1 " "m2 n2 " until "mz nz " for z lines) like this: --- Input --- 84 91 61 84 70 71 80 83 60 74 20 88 8 89 45 63 35 82 44 67 11 29 36 61 10 24 18 63 If every test had the same number of lines, I could do a loop (assuming I knew the number of lines), but it's all different. Test 1 has 14 lines, Test 2 has 4, Test 3 has 13, etc. I have literally no idea how to do this, since there's no input I could read that means "stop taking input" – it doesn't end with a blank input (```""```), the last one is an m,n pair. If I keep receiving input until there's no more lines, it throws me an EOF error. I know the basics from a previous class, but my current professor hasn't even taught lists in Python yet, so I'm assuming this has to be simple. I managed to get it running using ```try``` and ```except``` but I'm posting here because I wanna know if there's a simpler/different way to get it to work. My code without the try/except looks like this: ``` txt=input().split() m=int(txt[0]) n=int(txt[1]) prime=[] for i in range(m,n+1): divisors=[] for x in range(1,i+1): if i%x==0: divisors.append(x) if divisors==[1,i] or divisors==[1]: prime.append(i) print(str(prime).translate(str.maketrans({"[":"","]":"",",":""}))) ``` With the try/except: ``` ans=[] while True: try: txt=input().split() m=int(txt[0]) n=int(txt[1]) prime=[] for i in range(m,n+1): divisors=[] for x in range(1,i+1): if i%x==0: divisors.append(x) if divisors==[1,i] or divisors==[1]: prime.append(i) ans.append(str(prime).translate(str.maketrans({"[":"","]":"",",":""}))) except: for i in range(len(ans)): print(ans[i]) break ``` Exercise: "In this exercise, you must write a code capable of identifying all prime numbers inside a range of numbers. Remember that a number is prime if it is divisible by two numbers: 1 and itself. For example, 11 is prime because it can be exactly divided by 1 and 11. 12 isn't prime because it can be exactly divided by various numbers besides 1 and 12 (2, 3, 4 and 6). Input: Your code will receive as input various lines with two integer in each one. In each line, the numbers x1 and x2 will appear in crescent order,...

AI-Generated Solution

Powered by LMSouq AI · GPT-4.1-mini

✓ Solution Ready
Analyzing problem and generating solution…
Was this solution helpful?
Back to Knowledge Base