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
Related
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
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.
For example, if given a number 3, the program will print
1
1 2 2
1 2 2 3 3 3
OK,what I have tried like this:
n = eval(input("Enter a positive integer: "))
a=1
for i in range(1,n+1):
for j in range(1,a+1):
print(j," ",sep="",end="")
a+=1
print()
It will print like:
1
1 2
1 2 3
You were close. Your problem is that you need to use j to print the current number j times. Thankfully, Python makes this easy by using sequence multiplication. That is, Python allows you to multiply a sequence - like a string - by a number. The contents of the string is replicated the amount of times it was multiplied by:
>>> 'a' * 3
'aaa'
>>> '1' * 4
'1111'
Thus, you can convert the current integer j to a string, and multiplied the string by j:
for j in range(1, a + 1):
print((str(j) + ' ') * j, sep='', end="")
With the above change your code now outputs:
Enter a positive integer: 3
1
1 2 2
1 2 2 3 3
Here are a few more ways you can improve your code.
Avoid eval like the black plague. It's very dangerous security-wise. Of course, you probably don't even have to worry about this now, but better not get in the habit. There's always a Better Way TM. In this case, use the built-in function int.
Rather than keeping an explicit counter with a, use the built-in function enumerate.
With the above improvements, your code becomes:
n = int(input("Enter a positive integer: "))
for a, i in enumerate(range(1, n + 1), 1):
for j in range(1, a + 1):
print((str(j) + ' ') * j, sep='', end="")
print()
You're missing a key thing in the code you've given (as below):
n = eval(input("Enter a positive integer: "))
a=1
for i in range(1,n+1):
for j in range(1,a+1):
print(j," ",sep="",end="")
a+=1
print()
Within the for j in range(...) loop, where you actually print out each number, you only print the each number out once, rather than j times (where j is the current number).
You can fix this by using a special behavior of Python (string 'multiplication').
n = eval(input("Enter a positive integer: "))
a = 1
for i in range(1, n+1):
for j in range(1, a+1):
print('{} '.format(j) * j, end="")
a += 1
print()
Here is a method that does what you're requesting.
def numbers(n: int) -> None:
for i in range(1, n+2):
for j in range(1, i):
print(j * (str(j) + ' '), end='')
print()
First, we loop over all numbers from 1 to n+1.
Then, we loop over all numbers from 1 to the current number we are working with, minus one (that's why we have the n+2 in the outer loop).
Now we have all the information we need to print our line: we are printing j times the value of j followed by a space, appending it to whatever was printed on this line already before.
Finally, after finishing our line, we print a newline, so we can start fresh in the next outer loop.
Hope this helps!
You are definitely on the right track. Let's look closer at your code:
n = eval(input("Enter a positive integer: "))
a=1
for i in range(1,n+1):
for j in range(1,a+1):
print(j," ",sep="",end="")
a+=1
print()
i is going iterate from 1 to n. That's a good intuition, as we need every number.
j is going iterate from 1 to a. A way to debug the code is to work through an example. Let's say i will iterate in range(1, 3). The first time in the loop, j will iterate in range(1, 2) and it'll print "1". The second time, j will iterate in range(1, 3) and it'll print "1 2". There's our problem; we wanted 2 to print out twice!
i is actually the number we want to print, j is the number of times we want to print the number. We actually don't need the a variable:
n = int(input("Enter a positive integer: "))
message = ""
for i in range(1, n + 1):
for j in range(0, i):
message += str(i) + " "
print(message)
We can condense this further. I try to think of it in my head first, and then code it.
"I want 1 once, 2 twice, 3 thrice, etc.". This means, we don't even need an inner loop. You know how many times you want to print i... i times!
message = ""
for i in range(1, n + 1):
message += (str(i) + " ") * i
print(message)
Also, notice the style in your code. PEP8 has guidelines for how to write proper Python code. Notice:
Using "int" is better than "eval" if possible, because you only want your program to take numbers.
Spacing in parenthesis "range(1, a+1)" is better than "range(1,a+1)".
Variable declarations like "a = 1" is better than "a=1".
These best practices will make your code more readable :)
>>> print(*[' '.join(map(str, [n for n in range(1, n+1) for n in [n]*n])) for n in range(1, n+1)], sep='\n')
1
1 2 2
1 2 2 3 3 3
I have to write a python program which allows a user to input an odd integer, n, greater than or equal to three. The program outputs an x with n rows and n columns. *My professor said using nested for loops would be ideal for this. The X is printed using *'s *
I have been experimenting over the past couple days and have had little success.
This is my starting code for the program and after that it's just blank, like my mind. If you could provide some explanation as to how the code works that would be amazing.
num=int(input("Please type in an odd integer."))
if num%2==0:
print("Your number is incorrect")
This should do it:
Python 2
N = 5
for i in range(N):
for j in range(N):
if (i == j) or ((N - j -1) == i):
print '*',
else:
print ' ',
print ''
Python 3
N = 5
for i in range(N):
for j in range(N):
if (i == j) or ((N - j -1) == i):
print('*', end = '')
else:
print(' ', end = '')
print('')
(thanks to Blckknght for Python 3 knowledge)
You're looping through all the rows in the outer loop, then all the columns or cells in the inner. The if clause checks whether you're on a diagonal. The comma after the print statement ensures you don't get a new line every print. The 3rd print gives you a new line once you're finished with that row.
If this is helpful / works for you; try making a Y using the same approach and post your code in the comments below. That way you could develop your understanding a bit more.
I'll give you a hint :
n = int(input("Please type in an odd integer."))
for i in range(n):
print('x', end='')
print()
This prints a x, n times on the same line and then go back to next line.
I'll let you figure out how you print this same line n times.
Using single for loop:
for i in range(num):
a = [' '] * num
a[i] = '*'
a[num-i-1] = '*'
print(''.join(a))
Using nested for loops:
for i in range(num):
s = ''
for j in range(num):
if j in [i, num-i-1]:
s += '*'
else:
s += ' '
print(s)
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")