Print the integers from 1 up to n (given number) - python

so if the function is:
function(n)
what can i do to if i want.
function(5)
to return as
1
2
3
4
5
I'm thinking towards creating an empty list, but i don't know what to append into the list to get the number 1 up to 'n'

You can try
def function(n):
for x in range(0, n):
print x+1
if you want to print the values, or
def function(n):
returnlist = []
for x in range(0, n):
returnlist.append(x+1)
return returnlist
to return a list.
The for x in range(0, n): part of the code is called a for loop. It repeats itself n times, and x is incremented by one each time is repeats. You can then use x to accomplish different tasks within your code. In this case, we're simply taking its value plus one and printing it or appending it to a list. We have to add one to the value because x is zero based, although it doesn't have to be. We could just as easily have written for x in range(1, n+1): and not have had to add one to the x value.

Here is a simple example:
def function(n):
for i in range(1, n+1):
print i

Related

Range function won't skip a value even when defined(Python)

I am trying to find the odd numbers in a range of numbers, and adding them all up.
I set my variable which is the range of numbers (5)
I then made a function which had the for statement, looking for the numbers in range from 1 to 1+num(this is for including the number) and the comma after that to skip every other number.
Then I printed the total sum, and outside of the function I called the function.
num = 5
def sumOfOdds():
sum = 0
for i in range(1, 1+num, 1):
sum = sum+i
print(sum)
sumOfOdds()
I tried to read other ways to fix this, but was unable to find a solution.
The third parameter in the range is the incremental value of the iterator which means that you want it to be 2, not 1, as you want to skip every other number. (By default its value is 1).
def sumOfOdds():
sum = 0
for i in range(1, 1+num, 2): # Here we set it to 2
sum = sum+i
print(sum)
For more info on range() visit https://docs.python.org/3/library/stdtypes.html#range
This is an easy fix. the third argument in range should be 2, not 1.
num = 12
def sumOfOdds():
sum = 0
for i in range(1, 1+num, 2):
sum = sum+i
print(sum)
sumOfOdds()
To add to the provided response, I would add that there's a more pythonic way to write it using the reduce function:
def sumOfOdds():
return reduce(lambda x, y: x + y, range(1, 1 + num, 2))
Also, let's say you'd like to pass the list to iterate as a parameter, you can use the following writing in Python
def sumOfOdds(values):
return reduce(lambda x, y: x + y, values[::2])
sumOfOdds(range(1, 1 + num))
Where in python [x:y:i] means: start at iterable index of x, end at iterable index of y-1, skip every i values. So [::2] means start at the beggining, end at the end, and skip every 2 values.

Python While Loop Square

I am a beginner at Python and I'm trying to use a while loop to sum up all of the squared n values in a given n value range.
Code:
def problem2(n):
x = 0
y = 0
while x < n:
y = (n**2)+y
x+=1
return y
For some reason, this equation returns the input number cubed.
Can someone explain why this happens and how to fix it?
You need to perform the ** on x, the value that is being incremented:
def problem2(n):
x = 0
count = 0
while x < n:
count += pow(x, 2)
x += 1
return count
You keep squaring the same number n, instead of the one being incremented x.
def sum_of_squares(n):
sum = 0
for x in range(0, n):
sum += x*x
return sum
You also don't really need the while loop, avoiding having to manually keep track of which variable is the counting variable and which one is the result variable (which is what you are confusing, as explained e.g. by #Ajax1234 in their answer).
It is a lot more Pythonic to use the built-in function sum, a generator expression and range:
def problem2(n):
return sum(x**2 for x in range(n))
This would be a lot more readable and better (unless of course you are being forced to use while).
Looks good. You're almost there.
It makes it the cube root because you add y to (n**2) everytime. Because you code runs until x !< n it runs n times. That means that you add n**2 to n**2*n.
That means that it gives 1(n**2)*(n-1)(n**2) which equals n(n**2) = n**3
Hope this was clear enough.

if block in python not executed with True statement

I just started learning python with small scripts. I came across a quiz to determine a list to be symmetric if the first row is the same as the first column,
the second row is the same as the second column and so on.
def symmetric(block):
n = len(block)
i = 0
for i in range(n-1):
j = 0
for j in range(n-1):
if (block[i][j] != block[j][i]):
return False
j +=1
i +=1
return True
So the result of
print symmetric([["cat", "dog", "fish"],
["dog", "dog", "dog"],
["fish","fish","cat"]])
should be False.
However, this code always return True, and in debugger I can see block[i][j] != block[j][i] returns True but the if block is not executed. Is there anything wrong with the comparison or the if block is not correctly composed?
The main reason why it fails is because you should write range(n) instead of range(n-1) (the upperbound is exclusive). Like:
def symmetric(block):
n = len(block)
for i in range(n):
for j in range(n):
if block[i][j] != block[j][i]:
return False
return True
Nevertheless, there are several weird things about this function:
you initialize i = 0 and j = 0. That is not necessary: in Python, the for loop will declare the variable for you;
you perform increments/decrements on i and j, this is again not necessary. A for loop enumerates over the iterable/generator and assigns each value to i and j;
usually one does not write parenthesis for if statements.
Furthermore you can actually make this code more elegant using a two-liner with the all(..) builtin function:
def symmetric(block):
n = len(block)
return all(block[i][j] == block[j][i] for i in range(n) for j in range(n))
This is a more declarative and more explicit style of writing code. Since here the code is almost self-explaining: "return whether all block[i][j] == block[j][i] for i in range(n) and for j in range(n)"
Finally like #Błotosmętek says in their comment, you do not have to check block[2][0] == block[0][2] if you have already checked block[0][2] == block[2][0]. So you can improve performance (about half) by writing:
def symmetric(block):
n = len(block)
return all(block[i][j] == block[j][i] for i in range(n) for j in range(i))
You should use range(n) rather than range(n-1); sequences generated by range do not include the upper bound.
def symmetric(block):
n = len(block)
for i in range(n):
for j in range(n):
print i, j
if (block[i][j] != block[j][i]):
return False
return True
print symmetric([["cat", "dog", "fish"],
["dog", "dog", "dog"],
["fish","fish","cat"]])
In python you don't have to declare or increment the variable used for looping, python "for-loop" is intelligent enough to do it for us.
You also have to study how the range function works in python, range() can be called in three ways,
range(N-number of times to loop): range will return a list of N integers starting from 0 to N-1.
range(S-start position, N-end position): In this case range will return a list of (N-S) integers starting from S to N-1.
range(S-start position, N-end position, K-steps): here range will return a list of (N-S)/K integers starting from S to N-1 with an interval of K.
In your case when you said range(n-1) your loop was iterating only on indices 0,1 skipping index 2, no wonder you were getting True every time.

Making a for loop print with an index

I made a program which displays a user-provided number of the fibonacci series. I wanted to format it into an indexed list, but I don't what could I use to do so. I found the enumerate() function, but seems it only works for premade lists, whereas mine is generated accordingly to the user.
Do I use a for loop to generate a variable along with the series, then put the variable in the for loop that prints the numbers, like so:
print("{0}. {1}".format(index_variable, wee(n)))
or am I going an entirely wrong road here?
def fib(n):
x = 0
y = 1
for i in range(n):
yield y
tmp = x
x = y
y += tmp
def main():
n = input('How many do you want: ')
for i, f in enumerate(fib(n)):
print("{0}. {1}".format(i, f)
Make a generator that yields the values you want and then pass that to enumerate

My way of finding the sum of all the multiples of 3 or 5 below 1000

I want to find multiples of 3 or 5 below 1000 using the code below:
a=[]
b=[]
def multiples_of_3():
i=1
for i in range(330):
m=i*3
if(m<1000):
a.append(m)
def multiples_of_5():
j=1
for j in range(330):
k=j*5
if(k<1000):
b.append(k)
if __name__ == "__main__":
multiples_of_3()
multiples_of_5()
print sum(a) + sum(b)
Result- 262355
Result is not right. It should be 233168 . How am I going wrong with the logic here?
You are looping over the wrong ranges and adding multiples of 15 twice.
I believe that this is the smallest change to your program that makes it work:
a=[]
b=[]
def multiples_of_3():
i=1
for i in range(334): # stops at 1 less than the value passed to `range`
m=i*3
if(m<1000):
a.append(m)
def multiples_of_5():
j=1
for j in range(330): # could change to 201 and still work
k=j*5
if(k<1000):
b.append(k)
if __name__ == "__main__":
multiples_of_3()
multiples_of_5()
print sum(set(a+b))
But you should probably rethink your approach. Using global variables is generally a bad idea - looking at the call multiples_of_3(), there is no way to know what the subroutine is doing with those multiples; the variable a is not referenced anywhere, yet before the line and after the line it has two different values. So for starters, I would turn the subroutines into pure functions - have them return the arrays instead of modifying globals.
As minor stylistic points, you also don't need to use different variable names inside the two functions, since they're all local. You don't need to assign anything to i before the loops (the loop will create the variable for you), and you don't need parentheses around the condition in Python's if statement (the colon takes care of delimiting it):
def multiples_of_3():
a = []
for i in range(334):
m = i * 3
if m < 1000:
a.append(m)
return a
def multiples_of_5():
a = []
for i in range(201):
m = i * 5
if m < 1000:
a.append(m)
return a
if __name__ == "__main__":
a = multiples_of_3()
b = multiples_of_5()
print sum(set(a+b))
You could also combine the two multiples_of functions into a single generic one that takes a parameter telling it what to return multiples of:
def multiples_of(k):
result = []
for i in range(1000/k+1):
multiple = i * k
if multiple < 1000:
result.append(multiple)
return result
You could even turn the maximum value into an optional parameter:
def multiples_of(k, under=1000):
result = []
for i in range(under/k+1):
multiple = i * k
if multiple < under:
result.append(multiple)
return result
Either way, your main part becomes this:
a = multiples_of(3)
b = multiples_of(5)
print sum(set(a+b))
Finally, just as a point of reference, it is possible to do the whole thing as a one-liner. Here I've switched from building up the list of multiples by actually doing the multiplication, to just looping over all the numbers under 1000 and testing them for divisibility by either 3 or 5:
print sum([n for n in range(1000) if n%3==0 or n%5==0])
Shouldn't for j in range(330): be for j in range(200): since you're using multiples of 5?

Categories

Resources