CS Circles - Python - Lists - It's Natural exercise - python

Here is a problem that I am having trouble solving:
Write a function naturalNumbers which takes a positive integer n as input, and returns a list [1, 2, ...] consisting of the first n natural numbers.
Here is the code that I have so far:
def naturalNumbers(x):
x = input()
myList = []
for i in range (0, x):
return myList = myList + [i]
print(myList)
I'm really confused as to when to put return for functions.

you are working very hard
the function range() returns a an object castable to list, so all you need to do is
def naturalNumbers(x):
return list(range(1,x + 1)) #didnt notice we are in python 3
0 is not considered a natural number

Your are mixing both your 'main' code and the function that you are being asked to write.
let your function be only for your list generating function naturalNumbers.
and use a different main function.
you can ignore the main method and the if __name__ = '__main__'
this is just to run correctly with good form.
# this method outputs a list from 0 to x
def naturalNumbers (x):
l = list[]
for i in range(0, x+1):
list.append(i)
return l
def main():
x = input()
# should check if x is an integer (defensive programming)
print (naturalNumbers(x))
if __name__ = "__main__"
main()
also depending on the definition used natural numbers can start form 0 or 1

Return is the output from a function. Without the return the function doesn't 'give back' anything to where it was called.
def naturalNumbers(n):
return [x for x in range(0,n)]
print(naturalNumbers(5))
The above print statement uses the output of natural numbers and will print [0,1,2,3,4].
Say we remove the return and just assign it to a value.
def naturalNumbers(n):
numbers = [x for x in range(0,n)]
#assignment rather than return, we could do other operations.
print(naturalNumbers(5))
#returns None
The above print statement prints 'None' as this is the default return value in Python

def naturalNumbers(n):
n = input()
myList = []
for i in range(1, n + 1):
myList.append(i)
return myList
Or use list comprehension:
def naturalNumbers(n):
n = input()
myList = [i for i in range(1, n + 1)]
return myList
return is the end of a function, it should be outside of a loop.

Try this simple method:
def naturalNumbers(n):
myList = []
for i in range(0,n):
myList = myList+[i+1]
return myList

Related

python *args and lists

I have this assignment:
Define a function that takes in an arbitrary number of arguments, and returns a list containing only those arguments that are even. Don't run the function simply provide the definition.
What I've tried:
def myfunc(*args):
return list(args%2==0)
It should be as follows:
def a (*args):
l = []
for i in args:
if i%2 == 0:
l.append(i)
return l
def myfunc(*args):
a=[]
for num in args:
if (num%2 == 0):
a.append(num)
return a `
I think this should work.
def a (*args):
l = []
for i in args:
if i%2 == 0:
l += [i]
return l
Not sure if it is requires to be as arguments like in range(), iba4read's post shuld work just fine. Just in case i'll give you an examplie with a list, note that a ´tuple´ not alwais works as a list.
import random
array = []
for r in range(random.randint(2, 10)):
array.append(r)
def even_numbers_of(array):
new_array = []
for i in array:
if i % 2 == 0:
new_array.append(i)
return new_array
print(even_numbers_of(array))

Cannot return the values in the list

I want to return the final value of the list which is new_list[3] but it return nothing at the end. I can get the final value of new_list[3] by using print function. I am quite confusing about the return function. Is it possible it return new_list[times] when the 2 for loop is ended?
original_list = [100,300,400,900,1500]
def filter_list(_list,times):
L = len(_list)
new_list = [list(_list) for k in range(times+1)]
for k in range (0,times):
for j in range (0,L):
if j == 0: #exclude the term [j-1] because new_list[-1] is not exist
new_list[k+1][j] = int(new_list[k][j]*0.2 + new_list[k][j+1]*0.5)
elif j == L-1: #exclude the term [j+1] because new_list[L] is not exist
new_list[k+1][j] = int(new_list[k][j-1]*0.4 + new_list[k][j]*0.2)
else:
new_list[k+1][j] = int(new_list[k][j-1]*0.4 + new_list[k][j]*0.2 + new_list[k][j+1]*0.5)
return (new_list[times])
filter_list(original_list,3)
A function is able to "return" a value back to the scope that called it. If this variable is not stored or passed into another function, it is lost.
For instance:
def f(x):
return x + 1
f(5)
will not print anything since nothing is done with the 6 returned from the f(5) call.
To output the value returned from a function, we can pass it to the print() function:
print(f(5))
or in your case:
print(filter_list(original_list, 3))
This is what the return function does:
A return statement ends the execution of the function call and "returns" the result, i.e. the value of the expression following the return keyword, to the caller. If the return statement is without an expression, the special value None is returned.
You are returning the item but not assigning it to anything
x = filter_list(original_list,3)
print(x)
What this will do is assign whatever you return from your function call to a variable in this case x and then your variable will hold whatever you returned so now
Heres a simple model to visualize this
def something():
x = 1
return x
def something_print():
x = 1
return print(x)
a = something()
print(a)
something_print()
(xenial)vash#localhost:~/python/stack_overflow$ python3.7 fucntion_call.py
1
1

Simple list function in Python

I am trying to append values (x) to a list if the numbers are divisible by 2 and then print out that list. Seems pretty simple. The following runs but returns None:
x = []
def test():
while x in range(0,100):
if x % 2 == 0:
x.append()
print(test())
Use for to iterate a range - not while.
You have ambiguous meaning to x - both as iteration variable and as a list.
You need to pass the value to append.
You need to return a value so it would be printed through the print statement - otherwise None is the default.
Fixed:
x = []
def test():
for i in range(0,100):
if i % 2 == 0:
x.append(i)
return x
print(test())
Other notes:
You can only use this once. The next call for test would return a list twice the size, since x is a global variable. I believe this is unintended and can be solved by putting the x = [] inside the function.
A list comprehension like [x for x in range(100) if x % 2 == 0] would be much better.
Problems and Fixes
Your have several problems with your code:
You named your list x and your iterate variable x.
You never append a value to your list.
You never return a list from test. Rather than appending to a global list, make a local list in test and return that list.
You're using a while loop when you should be using a for loop.
After the above changes, you code look likes:
def test():
even_numbers = []
for number in range(0, 100):
if number % 2 == 0:
even_numbers.append(number)
return even_numbers
print(test())
Improvements
Note there are better ways to do this. In this case, a list comprehension is a better choice. List comprehensions can be used to avoid the common pattern of building a list of values - such as your case:
def test():
return [n for n in range(0, 100) if n % 2 == 0]
print(test())
Generally you should pass the variable to the function and return it from the function instead of relying on global variables:
def test(x):
...
return x
However while x in range(0, 100) won't work because it will check if x (an empty list) is contained in the range object. But the range only contains numbers so the while loop body will never execute. So you could use a for-loop instead:
def test(x):
for i in range(0, 100):
if i % 2 == 0:
x.append(i)
return x
But you could also use the fact that range supports a step and remove the if by just using step=2:
def test(x):
for i in range(0, 100, 2):
x.append(i)
return x
At this point you could even just extend (append an iterable to) the list:
def test(x):
x.extend(range(0, 100, 2))
return x
You could also use a step of 2 to avoid if tests :
x = []
def test():
for i in range(0,100,2):
x.append(i)
return x
Or use a list comprehension :
x = []
def test():
x = [i for i in range(0,100,2)]
return x
Or use the range it's self as a list:
x = []
def test()
x = list(range(0,100,2))
return x
Rename your inner x variable for simplicity. Use x.append(n) instead of x.append(). Finally, print the variable not the method.
You should either change the list variable or the iteration variable(x in while loop) . and append function works like this list.append(value).

File's Data keeps getting overwritten by function

for some reason I am running into an issue where my function call seems to be overwriting the data read in from the file without me asking it to. I am trying to get the sum of the original list but I keep getting the sum of the squared list.
CODE:
def toNumbers(strList):
for i in range(len(strList)):
strList[i] = strList [int(i)]
return strList
def squareEach(nums):
for i in range(len(nums)):
nums[i] = eval(nums[i])
nums[i] = nums[i]**2
return nums
def sumList(nums):
b = sum(nums)
return b
def main():
file=open("numbers.txt","r").readline().split(" ")
print(str(squareEach(file)))
print(str(sumList(file)))
Your squareEach function modifies the original list which is passed to it.
To see what's going, consider adding a print between your function calls.
def main():
file=open("numbers.txt","r").readline().split(" ")
print(str(squareEach(file)))
print(str(file))
print(str(sumList(file))
EDIT:
The simplest fix would be to use a different list for storing your square numbers inside squareEach function
def squareEach(nums):
squares = []
for i in range(len(nums)):
num = eval(nums[i])
squares[i] = num**2
return squares
There are more efficient ways as suggested in other answers, but in your case, this appears to be the simplest fix.
The list nums is modified in squareEach method. Consider storing the results in a different list variable of the below sort:
def squareEach(nums):
sq = list()
for i in range(len(nums)):
sq.append(str(int(nums[i])**2))
# nums[i] = str(int(nums[i])**2)
return sq
I am not sure whether i am helping . But whatever you are trying to do can be done as follows
file=open("numbers.txt","r").readline().split(" ")
print ([int (m)**2 for m in file])
print (sum([int(m) for m in file]))
And if you want functions
def squareEach(file):
print ([int (m)**2 for m in file])
def sumList(file):
print (sum([int(m) for m in file]))
file=open("numbers.txt","r").readline().split(" ")
squareEach(file)
sumList(file)

How can I add the outcome of a function to a list in python?

def b():
a = int(input("Look up to: ")) // set the range to scan for primes
for num in range(0, a):
if prime(num) == True:
print(num)
print("adding to list")
return num
list = [num]
list.append(num)
else:
print(num, "is not a prime")
So how can I append the outcome to "list" for each new prime?
Forgot to mention the function to check if num is prime:
def prime(num):
for j in range (2, num):
if (num % j) == 0 :
return False
return True
Few points:
Once you return is executed, the value it is applied to is returned to whoever called the function and the code after return never executes.
You're shadowing the built-in function list() which returns a new list by calling a local variable list.
The list is constantly reconstructed by calling [num] which is a shorthand for creating a new list containing only num. What you want to do is update it using append.
Fixing the code, it may look something like:
def get_primes():
a = int(input("Look up to: "))
# 'primes' is a more suitable name for a list of primes
# we're only creating the list *once*, and we're not shadowing 'list'
primes = list()
for candidate in range(0, a):
if prime(candidate) == True:
print(candidate)
print("adding to list")
primes.append(candidate)
else:
print(num, "is not a prime")
# use return to return a result
return primes
You can test this by calling get_primes().
Tip: you could use filter to do the same thing get_primes does:
a = int(input("Look up to: "))
print(filter(prime, range(0, a)))
A minor note about the difference between list and [] is that you can change list's behaviour, which gives finer control, while []'s generated code calls BUILD_LIST directly (harder to change):
>>> dis.dis(lambda: [])
1 0 BUILD_LIST 0
3 RETURN_VALUE
>>> dis.dis(lambda: list())
1 0 LOAD_GLOBAL 0 (list)
3 CALL_FUNCTION 0
6 RETURN_VALUE
It really does not matter in this case, but #Thrustmaster suggested using [] in the comments since it some may see it as cleaner.
Oh, lot of minor syntax errors. Let me list them down..
Python comments do not start with //, but with #. Ref. code line no: 2
list is a keyword in python, you should not use that in your variable declaration. Line ref: 8.
After you do a return, the code after that line will not be executed. Line Ref: 7.
You should not initialize list inside the for loop. It is getting initialized in every iteration.
Instead of if prim(num) == True:, you can simply write if prim(num):.
That said, the correct code should look as follows:
def b():
a = int(input("Look up to: ")) # set the range to scan for primes
primes = [] #Your list
for num in range(0, a):
if prime(num):
print(num)
print("adding to list")
primes.append(num)
else:
print(num, "is not a prime")
return primes
Hope it helps .. :)
Your code looks to be a mix of C and Python (don't use // as comments).
I assume your program is looking for prime numbers up to n. Here is how one might go about implementing this:
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def find_primes(a, b):
primes = []
for i in range(a, b):
if is_prime(i):
primes.append(i)
return primes
You're almost there. The strange thing about your code is where you've placed the return statement. Try this:
def b():
primesList = []
a = int(input("Look up to: "))
for num in range(0, a):
if prime(num) == True:
print(num)
print("adding to list")
primesList.append(num)
else:
print(num, "is not a prime")
return primesList
Notice that your original return statement would have ended your function early, in fact even before your list would have had the chance to append any prime number at all. The other important point here is that you should never shadow a built-in type (list in this case), or other built-in functions (like map, sorted, etc.).
It's also enough to simply initialize the primesList once and append the num integers inside the for loop.
The other answers are good and address the main issue that you had with rebinding your list variable and failing to return the primes list from function b().
I think it's worth mentioning that a list comprehension can be used to succinctly code the prime list generation:
def prime(num):
for j in range (2, num):
if (num % j) == 0 :
return False
return True
def get_primes(low, high):
return [n for n in range(low, high+1) if prime(n)]
>>> a = input("Look up to: ")
11
>>> get_primes(0, a)
[0, 1, 2, 3, 5, 7, 11]
>>> get_primes(5, a)
[5, 7, 11]
Notes:
Passing the "up to" value into the function is more flexible than
prompting for it in the function.
"Up to" should be inclusive, e.g. get_primes(0, 11) should include 11 in the result. Therefore you need to add one to the upper value when calling range().
Passing low and high allows you to generate primes for arbitrary ranges.
You can wrap the list comprehension with set() to have the result returned as a set.

Categories