Producing a list of squares from 1 to n [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Write a function called squares that takes in a parameter named n. If n is a positive integer, the function returns a list consisting of the squares of the numbers from 1 through n. Otherwise (i.e., if n is not a positive integer) the function should return an empty list.
This function to work correctly even if the function is called with nonsensical arguments. In other words, function calls such as squares('Iowa'), squares(range(10)), and squares([1, 2, 3]) should return an empty list.
def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x:
ans+=1
if ans *ans == x:return ans;
return -1;
def square(n):
i=0
blist= []
ans = list(range(1, n ))
if (n < 0):
return blist
if isinstance(ans, str):
return blist
while( i < len(ans)):
if(sqrt(ans[i])!= -1):
blist.append(ans[i])
i = i+1
return blist
i = square('boy')
print(i)

To define a function, you do
def squares(n): # Where n is the parameter/argument
To check if n is an integer or a string (like Iowa) or a list (like range(10)), use isinstance (Hint: the function returns True or False). Use an if/else statement here to determine the function either returns an empty list [] or to continue:
Use another if/else statement to determine whether a number is positive or negative (if it's bigger than 0 it's positive, else it's negative)
To get the squares of a number, well, how would you figure out what two squared is? Or three squared?
**
You can then use a list comprehension to get the squares of every number between one and n (but how would you get a list of numbers between one and n? You'll need a range or something)
Don't forget to return the items ;)

Related

how exactly is the recursion working in this code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have this code , and it is not mine , I saw it online and i am wondering how is the recursion working , can someone please explain !
(this function accepts a list of integers(distances) and a value 'r' lets say 10) and it returns all the possibilities of how we can reach 100 using the distances) lets say the list is [3,5,2,5] and the value r is 10 ! so to make 10 we need [5,5] or [3,2,5] ,this is the code:
def greedy(r, distances):
if r < 0:
return []
if r == 0:
return [[]]
solutions = []
for last_distance in d:
combos = greedy(r - last_distance, d)
for combo in combos:
combo.append(last_distance)
if(not solutions.__contains__(combo)):
solutions.append(combo)
return solutions
i hope i made my self clear
I'd suggest using python print function
print("")
At multiple locations to actually see the recursion happening. You would get a better idea than someone trying to explain it to you.
Although the function itself is quite simple. For every element in distances, the function subtracts the element from the required r value and checks the value with the if conditions.
If r value is zero ie, the for some elements in distance, their sum is r, a multi list is returned, which furthermore has the said elements.
At the end, the complete list of elements whose sum adds to r are appended to solution list and returned.
Say that given a list distances0 of length n, you are able to return all tuples i1,..,infrom the list that sums to a number r for any number r.
You would like to do the same for a list distances of length n+1.
Since you know how to solve the problem for a list of size n, you will do the following: for every element last_distance of distances, return all tuples i1,...,in that sums to r-last_distance from a list distances0 which is similar to distances but without the element last_distance (and hence of length n).
I think there might be some mistakes in the code, here should be a working version:
def greedy(r, distances):
if r < 0:
return []
if r == 0:
return [[]]
solutions = []
for i in range(len(distances)):
d = distances[:i]+distances[i+1:]
last_distance = distances[i]
combos = greedy(r - last_distance, d)
for combo in combos:
combo.append(last_distance)
if(not solutions.__contains__(combo)):
solutions.append(combo)
return solutions

Converting a C function to Python function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
this function searches the number of an element in an array and returns the number of the element in the array if it exists or returns -1 if the input number does not exist on the array
int iSearch (int st[],int len,int no)
{
int i;
for (i=1;i<=len;i++) //len=lenth of the array , no = the number that we want to search in the array , st[] = the array
if (st[i]==no)
return i;
return -1;
}
and i want to write the python version of this function but since i use lists instead of arrays in python, i dont know how to write it in python.
i wrote the code below in python but it doesn't work
def iSearch(list,lenth,no):
x=0
for x in range (lenth):
if (list(x) == no)
return i
else
return -1
Here's the loop equivalent:
def iSearch(lst,no):
for i,x in enumerate(lst):
if x == no:
return i
return -1
There is, however, function lst.index(no) which is doing what you need, but in a more efficient way:
def iSearch(lst,no):
if no in lst:
return lst.index(no)
return -1
Or with the try/except (probably the fastest):
def iSearch(lst,no):
try:
return lst.index(no)
except ValueError:
return -1
It would help if you included the error you got next time.
Your code has some issues: 1. "list" is the name of an already existing object 2. You're only checking if the first item is the desired object, because at that point, both branches return. 3. accessing an element of a list requires square brackets, not parentheses.
This appears to work:
def linear_search_c(l,length,num):
for x in range(0,length):
if (l[x] == num):
return x
return -1
As an aside, there are better list searching methods than linear search if the array is sorted: binary search

Check whether an element occurs in a list using recursion [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
def check(x,num,i):
for n in range(len(x)):
if x[i] == num:
return True
else:
return(check(x,num,i+1))
return False
def User(x,num):
return(check(x,num,0))
User([2,6,1,9,7,3],5,0)
this should out put false since 5 is not in the list
checks whether an element occurs in a list recursively
so for example:
Input: a list L read from the keyboard, for example L = [2,6,1,9,7,3]
an element e, for example e = 9
but for some reason, i get an error when the number is not in the list
The beauty (and purpose) of recursion is that you do not need the loop:
def check(x, num, i):
if not x[i:]: # index past length
return False
if x[i] == num:
return True
return(check(x, num, i+1))
You can also do without the index parameter:
def check(x, num):
if not x:
return False
return x[0] == num or check(x[1:], num)
I don't exactly understand what you're doing, but this is a bizarre combination of recursion and iteration. If you're going to use recursion, it's worthwhile, at least for a basic recursive problem like this, to avoid iteration. Try something like this
def check(x, num, i = 0):
if i >= len(x):
return False
elif x[i] == num:
return True
else:
return check(x, num, i + 1)
This solution will work perfectly fine and is tail recursive so it will work quickly and optimally.
The way this works is it checks if the index, i, is out of bounds. If so, then it returns False. If it is in bounds, it checks if x[i] is equal to the number. If so, it returns True. If it is not, it returns check with the index increased and thus the recursion works.
First of all, your for loop doesn't make any sense. You never use that n and never go into the loop a second time, as you always return something in the first iteration. The return statement after the for loop is also unreachable, so your code could as well be
def check(x,num,i):
if x[i] == num:
return True
else:
return(check(x,num,i+1))
Then the actual issue is, that if you have a list with 5 elements for example, which does not contain the element searched for, you ask what the 6th is, although there is no 6th element, thus the error. You'd have to check whether the list contains 6 elements. So you check whether it has more than 5, return false if it does and continue if it doesn't. (Alternatively you could also check this at the start of the whole function)
def check(x,num,i):
if x[i] == num:
return True
else:
if len(num)>i:
return False
else:
return(check(x,num,i+1))
What you've done then is nothing but a overcomlicated, recursive for-Loop. You just increase i and compare, until you find the element or i is bigger than the list length. So this is equivalent to
def check(x,num):
for i in range(len(num)):
if x[i]==num:
return True
return False
It is very important that the return False is AFTER the for-Loop, as you only return, if you didn't find the element, even after iterating over the WHOLE list.
Also you can avoid indices. With a for-Loop you can directly iterate over the elements in a list:
def check(x,num):
for elem in num:
if elem==num:
return True
return False
This makes the variable elem become every element in you list, one after another.

Recursively return a tuple of numbers 0 to n in python [duplicate]

This question already has answers here:
Python Recursion: Range
(5 answers)
Closed 7 years ago.
So what I'm trying to do is basically make a recursive function that returns a tuple of numbers from 0 to a given number n that does not use range(), loops or lists. The problem reads as this:
"Define a recursive function called rec_range() that takes a natural number n and returns a tuple of numbers starting with 0 and ending before n. So rec_range(5) returns (0,1,2,3,4) and rec_range(1) returns (0,)."
The problem is that I have no idea how to make a function that returns a tuple. I know how to get a factorial of a number n using recursion, but we never went over how to return multiple numbers in a tuple.
The only thing I have right now is this:
def rec_range(n):
"""Takes a natural number n and returns a tuple of numbers starting with 0 and ending before n.
Natural Number -> tuple"""
if n == 0
return (,)
elif n == 1:
return (0,)
else:
???
Sorry if the answer to this is actually really obvious I'm very new to programming
You want to append tuples together, so use + and recurse over your function lowering the value by 1 . In addition, just return (or return None) for n == 0. Really the n == 0 call is unnecessary and your code could be more idiomatic, but I'll leave that to you.
def rec_range(n):
"""Takes a natural number n and returns a tuple of numbers starting with 0 and ending before n.
Natural Number -> tuple"""
if n == 0:
return
elif n == 1:
return (0,)
else:
return rec_range(n-1) + (n-1,)
Outputs:
>>>rec_range(4)
(0, 1, 2, 3)

Python list arithmetic [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a list of integers for example: [30,21,32,32,41,20,21,32,21,20]
I have a variable of X, X has a value within the range of the list.
How can I find the sum of all the elements in the list to the number of X.
For example if x was 4 I would want: 30+21+32+32
Another way to go is to use the takewhile function from itertools:
>>> import itertools
>>> sum(itertools.takewhile(lambda x: x<5, range(10)))
10
In your case:
>>> l = [1,2,3,4,5,6,7,8,9]
>>> x = 5
>>> sum(itertools.takewhile(lambda i: i < x, l))
10
if you want till the 5th element, maybe use enumerate and zip:
>>> sum(zip(*(itertools.takewhile(lambda i: i[0]<x-1, enumerate(l))))[1])
10
If you're a beginner, you should learn that the common way to carry out a task is to define a function
A function needs a name and usually needs one or more arguments, in this example sum_until is the name and l and n are the arguments.
Following the definition, there is some code that does the task for generical values of l and n. Eventually the function returns the result of the computation, here the statement return sum.
Note the commented # return sum at the end of the function definition. You should try to control what to do in exceptional cases, here what we want to do when n is not found into l. One option is to return the sum of all the numbers in l, another one is to return a value that is impossible for a summation, and the second one is exactly my choice.
def sum_until(l,n):
"returns the sum of the numbers in l that occur before the appearance of n"
sum = 0:
for num in l:
if num == n:
return sum
sum = sum + num
# return sum
return None
Now, we have to use the function. This is achieved calling the function, that is you call its name and tell it on which actual values you need to operate the sum:
print(sum_until([2,4,6,8,5,10,12], 5))
print(sum_until([2,4,6,8,5,10,12], 3))
Output
20
None
If you want to sum the x first elements:
>>> l = [1,2,3,4,5,6,7,8,9]
>>> x = 5
>>> result = sum(l[:x])
>>> result
15
My answer may be not efficient, but I it is very straightforward.

Categories

Resources