Write a function named powPosInt. This function will take two integer input parameters, named x and p. This function will compute the value of x to the power of p, where p >= 0, which is defined as x to the power of p = x × · · · × x
| {z }
p times
or 1 if p is 0.
The function will return this computed result. This function should not produce any console output.
For computing x to the power of p
, I am requiring that you implement the calculations using a while loop and an accumulator variable.
Examples of values you should test with: x = 2, p = 3 should return 8. x = 1, p = 4
should return 1. x = 7, p = 0 should return 1. x = −3, p = 2 should return 9.
x = −3, p = 3 should return −27.
This is what I have so far, I am having trouble figuring out how to put a while loop within this function. I am asking on here for help as my TEACHER will not assist, (he wants us to treat his class like the real world where we will have to figure out solutions on our own... why pay his salary right?)
def powPosInt(x,p):
number = p
count = 0
while (number != 0):
answer = (x**p)
count = count + 1
if (p<0):
answer = (x**(1/abs(p)))
return answer
Using accumulation means you need to create a variable that will store the result, and while loop will multiply it by x each step. You shouldn't use the ** operator.
steps = 0
result = 1
while (steps < p):
result *= x
steps += 1
def powPosInt(x,p):
number = p
count = 0
while (number != 0):
answer = (x**p)
count = count + 1
if (p<0):
answer = (x**(1/abs(p)))
return answer
I see a number of problems here:
A loop for calculating powers will be using repeated multiplication, not exponentiation. The intent here is to assume Python doesn't have an exponentiation operator, otherwise this assignment would be futile.
There's no reason to handle negative powers, the specifications clarly call for p >= 0. Hence your final if block is unnecessary.
This is a style issue only: you should get into the habit of using meaningful variable names. The only situation in which I use single-letter variables nowadays is a short-lived, non-nested, loop where the variable name is irrelevant (and I use i for that). For any other situation, I use explanatory names (yes, not even j or k for nested loops). And I'm even starting to move away from using i for these simple cases.
Having said all that, I'd suggest revisiting your solution to take those into account.
Once you've done so, you can refer to the code below for one solution:
def powPosInt(myBase, myPower):
result = 1
for _ in range(myPower):
result *= myBase
return result
And, if you wanted to go for extra credits(a), you could put in place contractual checks to ensure callers are doing the right thing:
def powPosInt(myBase, myPower):
if type(myBase) != int: raise TypeError("Base must be an integer")
if type(myPower) != int: raise TypeError("Power must be an integer")
if myPower < 1: raise ValueError("Power must be >= 1")
result = 1
for _ in range(myPower):
result *= myBase
return result
(a) Or risk losing marks for being a smart-alec. This depends very much on the personality of your teacher :-)
My code is as follows.
import random
times_to_repeat = 10**6
circle_radius = 1
times_to_iterate = 100
def in_circle(x, y):
return x**2 + y**2 < circle_radius**2
def pi_approximator():
points_in_circle = 0
for a in range(times_to_repeat):
x = random.random()
y = random.random()
if in_circle(x, y):
points_in_circle += 1
pi_approx = (points_in_circle / times_to_repeat) * 4
print(pi_approx)
def pi_iterator():
for b in range(times_to_iterate):
pi_calculator()
pi_iterator()
The purpose is to create an approximation of pi using randomly generated points around a circle.
I've got that down, but I'm trying to make it more precise by iterating the function many times and then averaging it out.
I've found plenty of information on how to sum up a list that you make manually, but I'm having difficulty finding any information on how to add the values from a function together.
My desired output would be to take the values from pi_iterated(), add them all together, and divide them by times_to_iterate in order to get the average approximate value of pi over all of my iterations.
I've tried a few things, but they have mostly just been shots in the dark and all have failed so I didn't see any point in including them with my code.
I can supply people with the failed attempts I've made if they need it though.
In pi_approx calculation use float to get the correct value and you have to save the value rather than just printing. So you can return it and store it in a list. Average of that list gives will be your desired output
def pi_approximator():
...
...
pi_approx = (float(points_in_circle) / times_to_repeat) * 4
return (pi_approx)
def pi_iterator():
result = []
for b in range(times_to_iterate):
result.append(pi_approximator())
print float(sum(result))/len(result)
pi_iterator()
So I understand this simple for loop:
sum = 0
for number in {1,2,3,4}:
sum = sum + number
print sum
>>>
1
3
6
10
>>>
Then here is a neat little code that combines a for loop and a function I found on the interwebs:
def sum_list(l):
sum = 0
for number in l:
sum = sum + number
return sum
print sum_list([1, 7, 4])
>>>
12
What I don't understand is how python interprets this code (rather how Python knows to add the 3 arguments 1,7,4 together).
I would really help if you can break it down for me!
To tack on another question for you guys to review:
sum = 0
for number in {1,2,3,4}:
sum = sum + number
return sum
Spits out an error. print sum will list the results as 1,3,6,10
Error says: Syntaxerror: 'return' outside of function
[EDIT] #sshashank124
For example: This code spits out 3 answers. It prints out:
sum = 0
for number in {1,7,4}:
sum = sum + number
print sum
>>>
1
8
12
>>>
But this:
def sum_list(l):
sum= 0
for number in l:
sum = sum + number
print sum
print sum_list([1, 7, 4])
>>>
12
none
Spits out only 1 answer, 12. My question is why that occurs.
for number in l:
This iterates over the l, and number will have each and every element of l on every iteration. You can check that like this
for number in l:
print number
# 1
# 7
# 4
You are adding those numbers to the sum variable. You can check that like this
sum = 0
for number in l:
sum = sum + number
print sum
# 1
# 8
# 12
I believe you are doing this for educational purpose. If you actually wanted to find the sum of an iterable, then you can use the builtin sum function, like this
sum([1, 7, 4])
It knows to add them together, because you tell it to do that.
Let me rewrite the code a bit to show what's happening. Rewrite one, adding 1,7,4 and then 2,8,5, but adding more numbers requires more lines:
sum = 0
sum = sum + 1
sum = sum + 7
sum = sum + 4
print sum
sum = 0
sum = sum + 2
sum = sum + 8
sum = sum + 5
print sum
Rewrite two - using a loop. Two lines shorter, but it can now handle lists of more items - adding four, five, even ten numbers, without adding more lines of code, just by making the lists longer:
sum = 0
for number in [1,7,4]:
sum = sum + number
print sum
sum = 0
for number in [2,8,5]:
sum = sum + number
print sum
Rewrite three - moving the lists out of the loop. The code got longer again, but something interesting happened - see how the loop code is now identical both times:
myList = [1,7,4]
sum = 0
for number in myList:
sum = sum + number
print sum
myList = [2,8,5]
sum = 0
for number in myList:
sum = sum + number
print sum
Rewrite four - now it's identical, why does it have to be there twice? Can't we ... write it once, and use it twice? That way if we need to change it, we only have to change it in one place. Yes - make it a function and call the function:
def sum_list():
sum = 0
for number in myList:
sum = sum + number
print sum
myList = [1,7,4]
sum_list()
myList = [2,8,5]
sum_list()
Rewrite five - what's happening above works fine, because you called everything 'myList' it all works. But if you write bigger programs like that it gets messy fast - one myList could be several pages of code away from another, we'll tend to forget that something pages and pages away could be affecting things. So we humans can keep track of what's going on, we need to clearly and explicitly give the function something to work on, and not have it just reaching far away and pulling things out of the rest of the code.
def sum_list(working_list): # working_list is whatever the function gets
sum = 0 # by a different name
for number in working_list:
sum = sum + number
print sum
myList1 = [1,7,4]
sum_list(myList1)
myList2 = [2,8,5]
sum_list(myList2)
See in the above code, I've called them myList1 and myList2 - yet whatever you give to the function, the function sees it called 'working_list'. The names don't have to match.
But because sum_list has it's own name for whatever you give it, you don't have to have a name for what you give it. You can just give it a list directly without a name:
def sum_list(working_list):
sum = 0
for number in working_list:
sum = sum + number
print sum
sum_list([1,7,4])
sum_list([2,8,5])
The next move is, once you're feeding things into sum_list, sum_list is looking away and writing to the screen. We can't have that. For the sake of humans tracking what's happening, that's a bad idea - you want to give functions some work to do and have them give you back an answer. That way you know you can use them anytime you need, without worrying about them printing to the screen unexpectedly. That's where 'return' comes in:
def sum_list(working_list):
sum = 0
for number in working_list:
sum = sum + number
return sum
result = sum_list([1,7,4])
print result
result = sum_list([2,8,5])
print result
Now sum_list is a self contained adder, it does nothing else. You can trust it. It's not reading from names all over your code, it's only reading explicitly what you gave to it. It's not writing to the screen at surprise times, or anything. You give it a list, you get a result, it's isolated, limited, controlled, predictable, easy to work with, easy to reuse. And like the list names, if all you do is get the result and print it, you don't need to give that a name either:
def sum_list(working_list):
sum = 0
for number in working_list:
sum = sum + number
return sum
print sum_list([1,7,4])
print sum_list([2,8,5])
Edit: I hope that explains several of your questions.
What that code is doing
Why it prints one answer instead of three - because you are giving it one thing (a list).
Why it makes no sense to use return on its own - because you have to call a function and then return from the function, and you can bring something back with you or you can go somewhere and bring nothing back (function with no return). But you can't bring something back if you don't go anywhere first.
In Python you will realise that when you initialise a variable you don't need to assign a type to it, you can just initialise anything in there.
in this case l was interoperated as an object, or an array to be specific.
as for the loop.
for number in l:
is like a for each statement, it goes through each of the elements. and stores it in number, then iterates after the block is executed, moving on to the next l.
Hope that helped? (if i understand your question.
The for number in l: line takes each of the elements in [1,7,4] and adds them to the sum variable which represents the total sum of the elements in the list.
This is what it looks like:
Take first element of l: 1
Add to sum --> sum is now 1
Take second element of l: 7
Add to sum --> sum is now 8
Take third element of l: 4
Add to sum --> sum is now 12
Return sum --> sum is 12
Might I suggest that sum([1,7,4]), the builtin python method would also work.
I am trying to save the results of 10 function calls into a list. however, when I want to access this numerical data, I keep getting type errors, because the list is really a list of function calls. How do I make it do stuff so I can have numbers to do compare?
I tried setting temp variable to result of each spot in the list, but it still shows as a function.
Output should show the average for different # of dice, and return the best amount of dice to roll
def calculator(fn, num_samples=1000): # this is the function I'm trying to call
def print_and_return(*args):
total3 = 0
for _ in range(num_samples):
total3 += (fn(*args))
return float(total3)/num_samples
return print_and_return
def find_average(dice=six_sided):
avglist = []
k, spot = 0, 0
bob = roll_dice(k+1, dice)
passed_function = calculator(bob, 1000)
print(passed_function)
while k <= 10:
avglist.append((passed_function)) # <==trying to save the results when I check with 1-10 dice rolls
if k == 0:
spot = 1
else:
temp = 0
max = 0
i = 0
while i <= len(avglist):
temp = avglist[i]
if max > temp:
max = temp
i +=1
if (avglist[k] > temp):
spot = k
print(k, "dice scores", avglist[k], "on average")
k +=1
return spot
You are not calling passed_function. Calling a function with no arguments still reqires the ().
Your calculator function returns a function, not a plain value. You therefore need to call passed_function in order to get your result.
Based on the arguments to your call to roll_dice, it looks like you want the k argument to vary in the loop. As written now, it will not. I suspect you are tripping yourself up a bit. The code could be written a whole lot simpler without so many function references being passed around.
I have a quick question. I have the following code...
def abc(c):
a = 1
my = set()
while a <= c:
b = randrange(1, 365)
my.add(b)
a = a + 1
print(my)
Now c is in my main function. c is a integer that the user is prompted for. For instance, if c = 10, then as long as a < 10 it will run the while loop and print out the set with 10 numbers randomly generated between 1 and 365. The only problem is that it's not printing out the set my correctly.
a = a+1 should be what you want.
a + 1 just increments the value of a, but does not store it anywhere. So, using a = a+1, will increment the value of a and update the value of a.
The second part: You are generating the random numbers and storing them in a set, and printing them at last. To print each and every element in the list, use:
for i in my:
print i
This will print each value in the set