How can I improve this code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

How can I improve this code

Can you tell me more ways in which I can write this code more easily https://sololearn.com/compiler-playground/cChomnOH3PaB/?ref=app

23rd Jan 2024, 5:31 PM
Prathmesh Angad Phad
Prathmesh Angad Phad - avatar
2 Answers
+ 2
Prathmesh Angad Phad , I can suggest some things for readability. Give your file a shorter name (the end is invisible). Make the name describe the program better, such as "primes" or "primes < n", since "...See The Magic" tells us nothing about primes, and perhaps implies a graphical surprise. When you write a comment, include a space after the # and use normal sentence case, not all caps. Use double empty lines to separate top level code blocks such as function definitions. Use single empty lines sparingly to separate blocks of related statements inside a function or elsewhere. Use no blank lines within a block of related statements, unless one is so long that it wraps, in which case, an empty line can help the eye see the wrapping in the playground. Choose names that are informative but not redundant. For example, prime_list = [] might better be called, primes = [] since it will potentially hold multiple numbers and we already know it's a list by the [].
23rd Jan 2024, 6:43 PM
Rain
Rain - avatar
+ 3
The easiest solution to your code is using library function from sympy. from sympy import primerange n = int(input()) print(list(primerange(1, n))) (these 3 lines are the complete code) You can also have a look at other algorithms to find all prime numbers within a range. These can have much better performance, especially when the range gets larger. I suggest you check the Sieve of Eratosthenes, and try to code it yourself. https://en.m.wikipedia.org/wiki/Sieve_of_Eratosthenes
23rd Jan 2024, 6:20 PM
Tibor Santa
Tibor Santa - avatar