So these are the examples I got:
def bottom_up(n):
if n == 0:
pass
else:
bottom_up(n-1)
print(n)
and this one, which is fine:
def top_down(n):
if n == 0:
pass
else:
print(n)
top_down(n-1)
I have an understanding of recursion, so that isn't the problem. My problem is the result for bottom_down():
bottom_up(5)
1
2
3
4
5
I've asked other students and my teacher(math teacher, because my school won't hire a computer science teacher since I'm the only one doing computer science), and I don't know what to search on google.
I highly encourage you to walk through the functions yourself to see how it works, but the difference is in the order of the print statement and the recursive call.
The first function has the recursive call before the print statement, so that means it has to go down to the base case in order to start printing the numbers. This means it will start at the smallest number and go up and back to the starting number.
The second function has the print statement before the recursive call, which means that it will print the number then take a step closer to the base case. Once the base case is reached, the recursive calls go back up, and exit as there is nothing after them.
Hope this helped.
Pass is a placeholder for code.
Need more context in what you are trying to do.
bottom_up(5) is looping
So before bottom_up(5) prints 5 it will run the function bottom_up(4), bottom_up(3), bottom_up(2), bottom_up(1), bottom_up(0) and so on....
bottom_up(0) and and negative n will pass and not print anything.
So the first thing to print will be bottom_up(1) then bottom_up(2) and so on until 5.
Related
So this is my line of code so far,
def Adder (i,j,k):
if i<=j:
for x in range (i, j+1):
print(x**k)
else:
print (0)
What it's supposed to do is get inputs (i,j,k) so that each number between [i,j] is multiplied the power of k. For example, Adder(3,6,2) would be 3^2 + 4^2 + 5^2 + 6^2 and eventually output 86. I know how to get the function to output the list of numbers between i and j to the power of K but I don't know how to make it so that the function sums that output. So in the case of my given example, my output would be 9, 16, 25, 36.
Is it possible to make it so that under my if conditional I can generate an output that adds up the numbers in the range after they've been taken to the power of K?
If anyone can give me some advice I would really appreciate it! First week of any coding ever and I don't quite know how to ask this question so sorry for vagueness!
Question now Answered, thanks to everyone who responded so quickly!
You could use built-in function sum()
def adder(i,j,k):
if i <= j:
print(sum(x**k for x in range(i,j+1)))
else:
print(0)
The documentation is here
I'm not sure if this is what you want but
if i<=j:
sum = 0
for x in range (i, j+1):
sum = sum + x**k #sum += x**k for simplicity
this will give you the sum of the powers
Looking at a few of the answers posted, they do a good job of giving you pythonic code for your solution, I thought I could answer your specific questions:
How can I get my function to add together its output?
A perhaps reasonable way is to iteratively and incrementally perform your calculations and store your interim solutions in a variable. See if you can visualize this:
Let's say (i,j,k) = (3,7,2)
We want the output to be: 135 (i.e., the result of the calculation 3^2 + 4^2 + 5^2 + 6^2 + 7^2)
Use a variable, call it result and initialize it to be zero.
As your for loop kicks off with x = 3, perform x^2 and add it to result. So result now stores the interim result 9. Now the loop moves on to x = 4. Same as the first iteration, perform x^2 and add it to result. Now result is 25. You can now imagine that result, by the time x = 7, contains the answer to the calculation 3^2+4^2+5^2+6^2. Let the loop finish, and you will find that 7^2 is also added to result.
Once loop is finished, print result to get the summed up answer.
A thing to note:
Consider where in your code you need to set and initialize the _result_ variable.
If anyone can give me some advice I would really appreciate it! First week of any coding ever and I don't quite know how to ask this question so sorry for vagueness!
Perhaps a bit advanced for you, but helpful to be made aware I think:
Alright, let's get some nuance added to this discussion. Since this is your first week, I wanted to jot down some things I had to learn which have helped greatly.
Iterative and Recursive Algorithms
First off, identify that the solution is an iterative type of algorithm. Where the actual calculation is the same, but is executed over different cumulative data.
In this example, if we were to represent the calculation as an operation called ADDER(i,j,k), then:
ADDER(3,7,2) = ADDER(3,6,2)+ 7^2
ADDER(3,6,2) = ADDER(3,5,2) + 6^2
ADDER(3,5,2) = ADDER(3,4,2) + 5^2
ADDER(3,4,2) = ADDER(3,3,2) + 4^2
ADDER(3,3,2) = 0 + 3^2
Problems like these can be solved iteratively (like using a loop, be it while or for) or recursively (where a function calls itself using a subset of the data). In your example, you can envision a function calling itself and each time it is called it does the following:
calculates the square of j and
adds it to the value returned from calling itself with j decremented
by 1 until
j < i, at which point it returns 0
Once the limiting condition (Point 3) is reached, a bunch of additions that were queued up along the way are triggered.
Learn to Speak The Language before using Idioms
I may get down-voted for this, but you will encounter a lot of advice displaying pythonic idioms for standard solutions. The idiomatic solution for your example would be as follows:
def adder(i,j,k):
return sum(x**k for x in range(i,j+1)) if i<=j else 0
But for a beginner this obscures a lot of the "science". It is far more rewarding to tread the simpler path as a beginner. Once you develop your own basic understanding of devising and implementing algorithms in python, then the idioms will make sense.
Just so you can lean into the above idiom, here's an explanation of what it does:
It calls the standard library function called sum which can operate over a list as well as an iterator. We feed it as argument a generator expression which does the job of the iterator by "drip feeding" the sum function with x^k values as it iterates over the range (1, j+1). In cases when N (which is j-i) is arbitrarily large, using a standard list can result in huge memory overhead and performance disadvantages. Using a generator expression allows us to avoid these issues, as iterators (which is what generator expressions create) will overwrite the same piece of memory with the new value and only generate the next value when needed.
Of course it only does all this if i <= j else it will return 0.
Lastly, make mistakes and ask questions. The community is great and very helpful
Well, do not use print. It is easy to modify your function like this,
if i<=j:
s = 0
for x in range (i, j+1):
s += x**k
return s # print(s) if you really want to
else:
return 0
Usually functions do not print anything. Instead they return values for their caller to either print or further process. For example, someone may want to find the value of Adder(3, 6, 2)+1, but if you return nothing, they have no way to do this, since the result is not passed to the program. A side note, do not capitalize functions. Those are for classes.
I am provided with a value N. I am to calculate the sum of all squares up to and including N. In math this is commonly called ∑Ni=0i2. It must be calculated in a loop. I have tried everything I can think of, even break statements, but I haven't been able to get it to work.
This is the closest I've come
Ans = 1
for i in range(N):
if i == N:
Ans = Ans*N
print (Ans)
I've made sure everything is indented and that my print statement is outside the loop, I think I am using the wrong formula, but I can't think of a better one. Can someone point me in the right direction?
Try this. You can set the upper value with num, and it prints the answer. sum acts on an iterable here rather than a list.
num=5
print(sum(e**2 for e in range(num+1)))
I am in intro programming class and I just started learning the loops. My question asks about the average value of the inputs and it supposed to be done with while-loops. When the user inputs end instead of a number, that signifies the end of the loop and calculates the average value. The program should print the average value and return it. Also, if the user does not input any number and directly inputs end, the program should print "No numbers were entered". I tried creating the loop, but I do not know what I am missing for my loop to be running.
Also, I am not allowed to use any inbuilt functions like sum, ave, etc.
Here is the code I've written so far
def avgOfTheSum():
total = 0
avg = 0
count = 0
while True:
number = input("Enter next number:")
if number != 'end':
num = float(number)
total = total + num
count = count + 1
average = total/count
else:
print("The Average is:",average)
break
return average
a few tips from my not-so-experienced point of view :
when you increment a variable, eg. 'total = total + num', you can do so with a more compact way : use 'total += num' which does exactly the same thing and lightens your code. Some people find it ugly though, so use it if you will.
You first declared a variable named 'avg' but you then later use 'average', which leads to an error when trying to print 'average' which was not defined because the first 'if' statement was bypassed.
You should use one naming for the average. Either 'avg' or 'average' is okay but remember your code must be easy to understand so try not to squeeze things too much, especially if someone is reviewing it when you are finished.
Use one name and stick to it. That way you don't have an error when the user inputs something that isnt handled by your code.
You could add safe nets to ensure the user passes a number but the most simple ways need to use python built-ins.
You could add something like (not python do not write it like so)
if count = 0
then print 'no numbers entered'
then either :
break if you want to quit the application
or pass if you want to force the user to enter a number (enforcing a new loop)
Hope it helped you a little bit !
It prints diga and digb but doesnt work with c! Any help? It's supposed to be a Denary to Binary converter but only 1-64, once i've cracked the code will increase this! Thanks so much
denaryno=int(input("Write a number from 1-64 "))
if 64%denaryno > 0:
diga=0
remaindera=(64%denaryno)
if 32/denaryno<1:
digb=1
remainderb=(denaryno%32)
else:
digb =0
if 16/remainderb<1:
digc=1
remainderc=(denaryno%16)
else:
digc=0
if 8/remainderc<1:
digd=1
remainderd=(denaryno%8)
else:
digd=0
if 4/remainderd<1:
dige=1
remaindere=(denary%4)
else:
dige=0
if 2/remaindere<1:
digf=1
remainderf=(denary%2)
else:
digf=0
if 1/remainderf<1:
digg=1
remainderg=(denary%1)
else:
digg=0
print (str(diga)+str(digb))
You only set digc in one of the top if/else statement. If 32/denaryno<1 is True, you don't set digc at all.
Set digc at the top of the function (to 0 or whatever else you want it to be). This applies to all the digit variables, digd, dige, etc.
What you really should do, instead, is use a list of digits, and append either a 0 or a 1 to that list every time you divide the number by a factor.
You may want to take a look at the divmod() function; it returns both the quotient and the remainder. You could also do with some looping here to slash the number of if statements needed here:
number = int(input("Write a number from 1-64 "))
digits = []
factor = 64
while number:
quotient, number = divmod(number, factor)
digits.append(quotient)
factor //= 2
print(''.join(map(str, digits)))
Wow that was a lot of work, you don't have to do all that.
def bin_convert(x, count=8):
return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))
here are the functions comprising this one from easy->important
str() returns a string
range() is a way to get a list from 1 number to another. Written like this range(count-1, -1, -1) counts backwards.
"".join() is a way to take an iterable and put the pieces together.
map() is a way to take a function and apply it to an iterable.
lambda is a way to write a function in 1 line. I was being lazy and could have written another def func_name(y) and it would have worked just as well.
>> is a way to shift bits. (which I believe understanding this one is the key component to understanding your problem)
I want to create a program that will take a positive integer n, then create a list consisting of n random numbers between 0 and 9. Once I find that, I want to return the average of those numbers. Am I on the right track?
import random
def randomNumbers(n):
n > 0
myList = random.randrange(0,9)
I know I haven't gotten to the second part yet.. but is this how I start out?
This is my final code:
import random
def randomNumbers(n):
myList = []
for i in range(n):
myList.append(random.randrange(0, 9))
return sum(myList)/len(myList)
Could someone direct me to a page where it talks about a for and while loops and when to use them?
The equals sign (=) is only used to set the value of the "entire variable" (like myList). You want a list, which will then have values added to it, so start with this:
myList = []
to make it an empty list.
Now you had the right idea about repeating something while n > 0- but the ideal way is to use a for loop:
for i in range(n): # repeats the following line(s) of code n times
myList.append(random.randrange(0,9))
To find the average, take the sum and divide by the number of items (n).
If you are using Python 2.x, then note that an integer divided by another integer will round to an integer, so you should convert into a float (decimal) before division:
average = sum(myList)*1.0/n
For Python 3.x, int/int gives a float like you might expect:
average = sum(myList)/n
To return a value, use the return statement:
return average
It helps to break down what you're trying to do, if it's too complicated in a single explanation.
Take a positive integer, n
create a list of n length
each element should be a number 0-9
return the average of that list.
Let's tackle this one at a time:
take a positive integer, n
def randomNumbers(n):
if type(n)==int and n>0:
when you say def randomNumbers(n): you're saying
Hey, computer, this is a function called "randomNumbers",
and it's going to be called with a single thing in parentheses
and we're going to call that `n` from now on.
Here's what that function does:
But you haven't ensured that n is an integer greater than 0. It's just a thing. So we need to ensure that it is. if type(n)==int and n>0: does that by checking that the type of n is int and that n's value is positive (greater than 0).
That's the first bullet point done. Next is creating a list of n length with each element being an integer numbered 0-9. These should be random[1].
result=list()
for i in range(n):
result.append(random.randint(0,9))
This is less complicated than it seems. You start by creating a list that you'll call result (or whatever you want, I don't care). The for loop is just saying:
Hey, computer, you're gonna do the same thing a number of times,
and that number is "until you've counted from 0 to n times".
And when you do that, "i" is going to represent where you are
in that "0 to n" range. Here's what you're gonna do all those times:
So what are you going to do n times? You're going to append a random integer between 0 and 9 to that list we just called result. That's what result.append(random.randint(0,9)) does.
So next you want to return the average of that list. Well, the average of a list is the sum of the numbers in the list divided by the length.
return sum(result)/float(len(result))
sum and len can take any iterable, like a list, or a set, or whatever you please, and give you the sum, length, or whatever else you ask for. These are great tools to learn about. So do it. Elsewhere, preferably, frankly.
Now, if you've been really attentive, you'll see that so far we have this:
import random # I added this secretly, sorry!
def randomNumbers(n):
if type(n)==int and n>0:
result=list()
for i in range(n):
result.append(random.randint(0,9))
return sum(result)/float(len(result))
Which is great! That's what you need; try print(randomNumbers(5)) and you'll get exactly what you're looking for: the average of a bunch of random numbers.
But what if you try print(randomNumbers('foo'))? You probably get None, right? That's because it didn't fit in with the if statement we wrote, and so it never went down that path! You need to write an else statement so things that aren't positive integers still get some love.
else:
return "That's no good. Try a positive integer instead"
Stupid, but it works. Someday you'll learn about raising exceptions and all that smooth Jazz, but until then, it's fine just to say
Hey, computer, if n wasn't up to my stratospheric expectations,
then just spit back this message. I'll understand.
So at the end of the day you've got
import random
def randomNumbers(n):
if type(n)==int and n>0:
result=list()
for i in range(n):
result.append(random.randint(0,9))
return sum(result)/float(len(result))
else:
return "That's no good. Try a positive integer instead"
There's some stuff you can do with this code to make it more efficient. To make you curious, I'll give an example:
from random import randint
def randy(n:int):
return sum({randint(0,9) for i in range(n)})/n if n>0 else "Try again."
That gets into list comprehensions, sets, function annotations, and other stuff that you don't need to worry about. And frankly, that line of code might be too convoluted for good "Pythonic" code, but it's possible, which is cool.
Keep at it, and don't get discouraged. Python makes an effort to explain what you did wrong, and the community is generally pretty good if you've done your due diligence. Just don't abuse them(/us) by asking for help without seeking answers on your own first.
[1]technically they're pseudorandom but true randomness is hard to produce.
You are not on the right track. See this variate for the track.
import random
def randomNumbers(n):
l = random.sample(xrange(10), n)
return sum(l)/len(l)
Could be done more concisely with a list comprehension:
myList = [randrange(0, 9) for x in xrange(n)]
average = sum(myList) / len(myList)
You should think about making use of Numpy. This would make your task easy.
import numpy as np
def myfunc(n):
x = np.random.randint(low=0, high=10, size=n)
return np.mean(x)