print(i, end = ",") wont print the last i - python

I would like to take a number and print all even numbers up to and including the number, here's my current code,
def print_upto(number):
for i in range(0, int(number)):
if(i % 2 == 0):
print(i, end = ',')
my issue is that when I put print_upto(50) it prints from 0 all the way to 48, not 50. I am not sure how to get it to print 50, I have tried adding
elif(i == number) and (number % 2 == 0):
print(number)
however, this doesn't work either.
Thanks in advance

Just change to:
for i in range(0, int(number + 1))
range generates numbers up to, but not including the given number.

Related

How to remove the trailing , following a end=','

New to Python & the community. Navigating different exercises and I'm having trouble finding the solution. I need to remove the trailing, that follows when using end=','
Any wisdom or guidance is very appreciated!
low = 10000
up = 10050
for num in range(low, up + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num,end=',')
It looks like you're trying to print prime numbers in a given range. Arguably, mixing discovery of prime numbers and printing them is what causes the problem. With proper decomposition, this problem won't exist:
def generate_primes(low, up):
for num in range(max(low, 2), up+1):
if all(num % i for i in range(2, num)):
yield num
print(*generate_primes(low, up), sep=',')
As a positive side effect, you can now reuse prime generator in other parts of the program which don't require printing.
Also note that checking all numbers up to num is not necessary - if the number is composite one of the factors will be less or equal to sqrt(num). So, a faster prime generator would be something like:
def generate_primes(low, up):
for num in range(max(low, 2), up+1):
if all(num % i for i in range(2, int(num**0.5 + 1))):
yield num
Try this :
low = 10000
up = 10050
nums = []
for num in range(low, up + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
nums.append(str(num))
a = ",".join(nums)
print(a)
Essentially, just add all the elements that will be outputted in a list and then use the join function to convert them into a string and print it.
Solution
import sys
low = 10000
up = 10050
firstValuePrinted = 0
for rootIndex, num in enumerate(range(low, up + 1)):
if num > 1:
for subIndex, i in enumerate(range(2, num)):
if (num % i) == 0:
break
else:
print("", end = "," if firstValuePrinted==1 else "")
firstValuePrinted = 1
print(num, end = "")
sys.stdout.flush()
Explanation
Since we can't determine on which number num the loop will exit we can't exactly know the end condition. But we can figure out the starting number.
So based on that logic, instead of printing the "," at the end we actually print it at the start by using a variable to maintain if we have printed any values or not in the above code that is done by firstValuePrinted.
sys.stdout.flush() is called to ensure the console prints the output right away and does not wait for the program to complete.
Note: Don't forget to import sys at the start of the file.
Benefits when compared to other answers
This type of implementation is useful if you want to output the num variable continuously so as to not have to wait for all the numbers to be calculated before writing the value.
If you put all the values into an array and then print, you actually need large memory for storing all the numbers (if low and up is large) as well as the console will wait till the for loop is completed before executing the print command.
Especially when dealing with prime numbers if the low and up variables are far apart like low=0 and up=1000000 it will take a long time for it to be processed before any output can be printed. While with the above implementation it will be printed as it is being calculated. While also ensuring no additional "," is printed at the end.

Which is the most pythonic way for writing a prime number function using for and while loop?

I am about to execute a function which aim is to return a Prime/Not prime statement if its argument is or isn't a prime number. I succeeded using a for loop:
def prime1(n):
z = []
for i in range (1, n+1):
if (n/i).is_integer():
z.append(i)
i=i+1
if len(z) == 2:
print ("Prime")
else:
print ("Not prime")`
Then I tried to do the same but using the while loop:
def prime2(n):
z = []
i = 1
while i < int(len(range(1, n+1))):
if (n/i).is_integer():
z.append(i)
i=i+1
if len(z) == 2:
print ("Prime")
else:
print ("Not prime")
Unfortunately, my system continues to calculating without printing me an output.
Can you explain me where I have made a mistake?
The i = i + 1 does nothing in your for loop, since the value of i is overwritten with the next value of the iterator; effectively, the for loop is performing i = i + 1 for you on every iteration, whether or not i divides n. You need to do the same thing in your while loop:
while i < n + 1:
if (n/i).is_integer():
z.append(i)
i = i + 1
The most pythonic way I could think of is below:
def isPrime(n):
return all(n % i for i in range(2, int(n ** 0.5) + 1)) and n > 1
for i in range(1, 20):
print(isPrime(i))
Explanation:
all makes sure that every item in the given expression returns True
n % i returns True if n != 0 (even negative numbers are allowed)
int(n ** 0.5) is equivalent to sqrt(n) and as range always returns numbers up to n - 1 you must add 1
n > 1 makes sure that n is not 1
The problem in your code is that your i = i + 1 in the wrong scope
Your program checks if (n/i).is_integer() which returns False as n / 2 is not a integer
Improving your code:
Instead of (n/i).is_integer() you can use n % i == 0, which returns the remainder equals 0
Next you must place i = i + 1 in the outer scope
And personally, I was never a fan of i = i + 1. Use i += 1
I think the best way is using the code I have shown above.
Hope this helps!
Edit:
You can make it print 'Prime' or 'Not Prime' as follows:
def isPrime(n):
print('Prime' if all(n % i for i in range(2, int(n ** 0.5) + 1))
and n > 1 else 'Not Prime')
for i in range(1, 20):
isPrime(i)
You are increment the iterable variable i inside the if statement, so the variable is never incremented, stucking on an infinite loop.
When you used for it worked because the iterable changes itself after every full iteration of the block.
Moving the incremenf of i one identation block to the left (inside the while instead of for) will work just fine
Code adapted from https://www.programiz.com/python-programming/examples/prime-number
You don't need to check until num and you can go 2 by 2 if you don't have a database of prime numbers
import math
#num = 437
if num > 1:
# check for factors
for i in range(2, int(math.ceil(math.sqrt(num))), 2):
if (num % i) == 0:
print(num, "is not a prime number")
print(i, "times", num // i, "is", num)
break
else:
print(num, "is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(num, "is not a prime number")
Our preferred method should not be while loops if we don't need to use them, that being said, we could use list comprehensions:
def prime(n):
z = []
[z.append(i) for i in range(1, n+1) if (n/i).is_integer()]
[print("Prime") if len(z) == 2 else print("Not Prime")]
prime(101)
But lets take a loop at what you got your for loop:
for i in range (1, n+1):
if (n/i).is_integer():
z.append(i)
i=i+1
The line i = i + doesn't serve the purpose you intend, the loop is going to iterate from 1 to n+1 no matter what
Now the while loop:
while i < int(len(range(1, n+1))):
if (n/i).is_integer():
z.append(i)
# i=i+1 does not go inside if statement
i += 1
Now you do need to increment i but if that incrementing only occurs when the if conditions are met, then if the if condition is not met you are going to be stuck at the same i looping over it.
Also try using i += 1 means the same thing

Basic Loop/Python

I am supposed to write a program that displays numbers from 100 to 200, ten per line, that are divisible by 5 or 6 but NOT both. This is my code so far. I know it's a basic problem so can you tell me the basic code that I'm missing instead of the "shortcut" steps. Any help is appreciated!
def main():
while (num >= 100) and (num <= 200):
for (num % 5 == 0) or (num % 6 == 0)
print (num)
main()
This is how I would go about it. I would recommend using a for loop over a while loop if you know the range you need. You are less likely to get into an endless loop. The reason for the n variable is since you said you needed 10 numbers per line. The n variable will track how many correct numbers you find so that you know when you have ten results and can use a normal print statement which automatically includes a newline. The second print statement will not add a newline.
n = 0
for i in range(100,201):
if (i%5 == 0 or i%6 == 0) and not (i%5 == 0 and i%6 == 0):
n += 1
if n%10 == 0:
print(i)
else:
print(str(i) + ", ", end="")
You should init every variable using in the code
While (condition) will break when the condition false. Since your condition depends on num, but num is never changed in your code, infinity loop will happen. You need to add num = num + 1 at the end of your loop block.
It's supposed to use if not for for each iterator here. And the condition you used for your problem is wrong to.
Should be like this:
def main():
num = 100
while (num >= 100) and (num <= 200):
if ((num % 5 == 0) or (num % 6 == 0)) and (num % 30 != 0):
print (num)
num = num + 1
main()

Python script for finding keith numbers not working

I am trying to make a python program that will find keith numbers. If you don't what keith numbers are, here is a link explaining them:
Keith Numbers - Wolfram MathWorld
My code is
from decimal import Decimal
from time import sleep
activator1 = 1
while (activator1 == 1):
try:
limit = int(raw_input("How many digits do you want me to stop at?"))
activator1 = 0
except ValueError:
print "You did not enter an integer"
limitlist = []
activator2 = 1
while (activator2 <= limit):
limitlist.append(activator2)
activator2 += 1
print limitlist
add1 = 0
add = 0
count = 9
while 1:
sleep (0.1)
numbers = list(str(count))
for i in limitlist:
if (i > 0) & (add < count):
add = sum(Decimal(i) for i in numbers)
lastnumber = int(numbers[-1])
add1 = lastnumber+int(add)
numbers.reverse()
numbers.pop()
numbers.append(add1)
print add1
print add
print count
print numbers
if (add1 == count):
print"________________________________"
print add1
print count
elif (i > 0) & (add > count):
count += 1
break
It doesn't output any errors but it just outputs
18
9
9
[18]
Could someone please tell me why it doesn't just repeatedly find Keith numbers within the number of integers range?
You have it in front of you:
add1 = 18
add = 9
count = 9
numbers = [18]
You're in an infinite loop with no output. You get this for once. After this, i runs through the values 1, 2, and 3. Each time through the for loop, all three if conditions are False. Nothing changes, you drop out of the for loop, and go back to the top of the while. Here, you set numbers back to ['9'], and loop forever.
I suggest that you learn two skills:
Basic debugging: learn to single-step through a debugger, looking at variable values. Alternately, learn to trace your logic on paper and stick in meaningful print statements. (My version of this is at the bottom of this answer.)
Incremental programming: Write a few lines of code and get them working. After you have them working (test with various input values and results printed), continue to write a few more. In this case, you wrote a large block of code, and then could not see the error in roughly 50 lines. If you code incrementally, you'll often be able to isolate the problem to your most recent 3-5 lines.
while True:
# sleep (0.1)
numbers = list(str(count))
print "Top of while; numbers=", numbers
for i in limitlist:
print "Top of for; i =", i, "\tadd =", add, "\tcount =", count, "\tadll =", add1
if (i > 0) & (add < count):
add = sum(Decimal(i) for i in numbers)
lastnumber = int(numbers[-1])
add1 = lastnumber+int(add)
numbers.reverse()
numbers.pop()
numbers.append(add1)
print "add1\t", add1
print "add\t", add
print "count\t", count
print "numbers", numbers
if (add1 == count):
print"________________________________"
print add1
print count
elif (i > 0) & (add > count):
count += 1
print "increment count:", count
break
Prune has already given you good advices! Let's put a little example of what he meant though, let's say you got an algorithm which determine whether n is a keith number or not and also a test loop to print some keith numbers:
def keith_number(n):
c = str(n)
a = list(map(int, c))
b = sum(a)
while b < n:
a = a[1:] + [b]
b = sum(a)
return (b == n) & (len(c) > 1)
N = 5
for i in range(N):
a, b = 10**i, 10**(i + 1)
print("[{0},{1}]".format(a, b))
print([i for i in filter(keith_number, range(a, b))])
print('-' * 80)
such snippet gives you this:
[1,10]
[]
--------------------------------------------------------------------------------
[10,100]
[14, 19, 28, 47, 61, 75]
--------------------------------------------------------------------------------
[100,1000]
[197, 742]
--------------------------------------------------------------------------------
[1000,10000]
[1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909]
--------------------------------------------------------------------------------
[10000,100000]
[31331, 34285, 34348, 55604, 62662, 86935, 93993]
--------------------------------------------------------------------------------
Wow, that's awesome... but wait, let's say you don't understand the keith_number function and you want to explore a little bit the algorithm in order to understand its guts. What about if we add some useful debug lines?
def keith_number(n):
c = str(n)
a = list(map(int, c))
b = sum(a)
print("{0} = {1}".format("+".join(map(str, a)), b))
while b < n:
a = a[1:] + [b]
b = sum(a)
print("{0} = {1}".format("+".join(map(str, a)), b))
return (b == n) & (len(c) > 1)
keith_number(14)
print '-' * 80
keith_number(15)
that way you'll be able to trace the important steps and the algorithm will make sense in your head:
1+4 = 5
4+5 = 9
5+9 = 14
--------------------------------------------------------------------------------
1+5 = 6
5+6 = 11
6+11 = 17
Conclusion: I'd advice you learn how to debug your own code instead asking strangers about it ;-)
I hope this solves your problem , and also I'm actually new here , so basically I solved it with the use of lists I hope u can understand :)
def kieth(n):
n1 = n[::-1]
f = [0]
[f.insert(0, int(x)) for x in n1]
for x in range(1, int(n)):
if f[-2] == int(n):
break
else:
f.insert(-1, sum(f[-abs(len(n1)) - 1:-1]))
return True if int(n) in f else False
n = input(" enter a number ")
print("is a kieth number " if kieth(str(n)) else "not a keith")

Print statements in a for loop

I am working on a function which takes a positive integer N and computes the following sum:
1 - 2 + 3 - 4 + 5 - 6 + .... N.
My professor said we can not use "math formulas" on this, so how could I go about it?
I thought about using a for loop, but I don't know how or what to write for the print statement. This is what I have so far:
n=int(input("enter N="))
for i in range(1, n+1, 1):
if i % 2 == 0:
# I'm not sure what print statement to write here
I tried print(i= "+" i+1) and just weird stuff like that, but I get errors and am lost after that.
what i have now
n=int(input('enter N='))
total=0
print("sum",)
for i in range(1, n+1, 1):
if i % 2 == 0:
count=count - i
print("-", i)
else:
count=count + i
print("+", i, end=" ")
print("=", total)
#still get errors saying name count not defined and unsupported sperand for +:
First, to accumulate the sum as described, and to do it by looping instead of "using math formulas", you want to do this:
n=int(input("enter N="))
total = 0
for i in range(1, n+1, 1):
if i % 2 == 0:
????
else:
????
print(total)
You should be able to figure out what the ???? are: you need to do something to total for each i, and it's different for even and odd.
Now, if you want it to print out something like this:
sum 1 - 2 + 3 - 4 + 5 - 6 + .... N = X
You can print things out along the way like this:
n=int(input("enter N="))
total = 0
print ("sum", end=" ")
for i in range(1, n+1, 1):
if i % 2 == 0:
print("-", i, end=" ")
????
else:
if i == 1:
print(i, end=" ")
else:
print("+", i, end=" ")
????
print("=", total)
If you want to keep negative and positive totals separately and then add them, as you mentioned in an edit, change total = 0 to ntotal, ptotal = 0, 0, then change each of the ???? parts so one works on one total, one on the other.
All of the above is for Python 3. If you want to run it in Python 2, you need to turn those print function calls into print statements. For the simple cases where we use the default newline ending, that's just a matter of removing the parentheses. But when we're using the end=" ", Python 2's print statement doesn't take keyword parameters like that, so you instead have to use the "magic comma", which means to end the printout with a space instead of a newline. So, for example, instead of this:
print("+", i, end=" ")
You'd do this:
print "+", i,
Again, for Python 3, you don't have to worry about that. (Also, there are ways to make the exact same code run in both Python 2 and 3—e.g., use sys.stdout.write—which you may want to read up on if you're using both languages frequently.)
You're most of the way there already. I'm not sure why you think you need to put a print statement inside the loop, though. You only want one result, right? You already have if i % 2 == 0 - which is the case where it's even - and you want to either add or subtract based on whether the current i is odd or even. So keep a running tally, add or subtract in each loop iteration as appropriate, and print the tally at the end.
You see the difference between what happens with odd and even numbers, which is good.
So, as you cycle through the list, if the number is even, you do one operation, or else you do another operation.
After you've computed your result, then you print it.
There are a lot of explanations in the answers already here. So I will try to address the different ways in which you can compute this sum:
Method 1:
def mySum(N):
answer = 0
for i in range(1, N+1):
if i%2:
answer += i
else:
answer -= i
return answer
Method 2:
def mySum(N):
answer = 0
for i in range(1, N+1, 2):
answer += i
for i in range(2, N+1, 2):
answer -= i
return answer
Method 3:
def mySum(N):
pos = range(1, N+1, 2)
neg = range(2, N+1, 2)
return sum(pos) - sum(neg)
Method 4:
def mySum(N):
return sum([a-b for a,b in zip(range(1, N+1, 2), zip(2, N+1, 2))])
Method 5:
def mySum(N):
return sum([i*-1 if not i%2 else i for i in range(1,N+1)])
Method 6:
def mySum(N):
return sum(map(lambda n: n*[-1, 1][i%2], range(1, N+1)))
Again, these are only to help prime you into python. Others have provided good explanations, which this is not meant to be
count = 0
print "0"
for i in range(1, n+1, 1):
if i % 2 == 0:
count = count - i
print "-" , i
else:
count = count + i
print "+" , i
print "=", count

Categories