We have to use a previously made function (the mega_calculator) to calculate the average amount of property damage for 10 buildings. however, we need to find out which building is going to be the most destroyed, but we keep getting error messages about comparing functions to ints. for some reason, the y variable(used to store mega_calculator values) is being labeled as a function, and the if statements aren't being triggered.
We are trying to use a for loop but it doesn't change anything. We also tried asserting inside mega_calculator that the return value must be an integer type, but that didn't do anything. we tried saving the average value as a variable and asserting that as an integer type but that didn't do anything.
What should I do for that?
Any help is loved and appreciated greatly. We must have the weird function setup, so unfortunately I can't just make a nice simple while loop.
def mega_calculator(fn, repeat=1000):
def helper(*args):
total = 0
for _ in range(repeat):
total += fn(*args)
return total / repeat
return helper
def worst_hurricane(odds): """odds is a predefined function that tells us a random amount of property damage"""
index_variable = 1
big_boom = 0
place = 0
while index_variable <= 10:
y = mega_calculator(odds,50) """checking odds of damage for skyscrapers only, and finding the average after 50 times is what the function cal to mega_calculator does"""
print("building", a, "will have", y, "dollars of damage")
if y > big_boom:
big_boom = y
place = index_variable
elif y == big_boom:
place = max(place, index_variable)
index_variable +=
return place
`
mega_calculator is returning a function named helper, that you can call. Try code like this:
calculator = mega_calculator(odds)
y = calculator(50)
You also probably want to unindent index_variable += 4 positions to the left, and change it to index_variable += 1.
Here is what you are trying to do:
I am using some dummy function called, just to make you understand:
>>> def mega_calculator(some_function):
... def helper(*args):
... return some_function(*args)
... return helper
...
>>> def odds(*args):
... print args
...
>>> x = mega_calculator(odds)
>>> x
<function helper at 0x10c8f18c0>
>>>
>>> x = mega_calculator(odds)(['Here', 'are some' , 'argument'])
(['Here', 'are some', 'argument'],)
>>>
Related
Hi :) my question is basically what the title says. How do i create a function that calls another function ten times and only if all those times the function2 returns True function 1 prints “good job”
For example:
def function_one(s) #returns true if string is increasing
x = all(x <= y for x, y in itertools.pairwise(seq))
return x
Function 2 should only print good job if function one returns true when called ten times.
I tried:
s = random.randint(0,10)
for i in range (10):
if function_one(s) == True:
print (“Good job”)
But this prints it the second function one is true, no matter how many other falses there were prior. Please help :)
Just use all as you did in function_one.
Here is an example with a different function_one:
import random
# make example reproducible
random.seed(0)
# dummy function that returns True with p=0.9
# and also prints an indicator ./× for True/False
def function_one():
# return True with a probability of 9/10
n = random.random() > 0.1
print('⋅' if n else '×', end='')
return n
def function_two():
if all(function_one() for _ in range(10)): # important stuff here
print(' Good job')
else:
print(' failed!')
# repeat the experiment a few times
for i in range(5):
function_two()
output:
⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ Good job
⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ Good job
⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ Good job
⋅⋅⋅⋅⋅× failed!
⋅⋅⋅⋅× failed!
You can use a list and then min:
lst=[]
for i in range (10):
s = random.randint(0,10)
lst.append(function_one(s))
if min(lst) == True:
print (“Good job”)
Note that the random.randint(0,10) should be inside the loop otherwise you use the same value all the time
You need to "link" all 10 calls to function 1. For example this should do what you want (I left the s assignment at its original position since I don't know what it's for. Perhaps it should be in the for loop):
def func2 ():
s = random.randint(0,10)
flag = True
for i in range (10):
newtry = function_one(s)
flag = flag and newtry
if flag:
print (“Good job”)
I am trying to simulate a baseball game to learn more about python and programming in general... I ran into an interesting learning point in programing... and was wondering if someone could explain this error...
import random
rosterHome = []
rosterAway = []
class Player:
def __init__(self, number, battingAverage):
self.number = number
self.battingAverage = battingAverage
class Game:
def __init__(self):
self.inning = 0
self.homeScore = 0
self.awayScore = 0
self.outs = 0
def createStats():
for i in range(40):
stats = random.random()
x = Player(i, stats)
rosterHome.append(x)
for y in range(40):
stats = random.random()
y = Player(i, stats)
rosterAway.append(y)
def startGame():
Game.createStats()
Game.inning = 0
Game.homeScore = 0
Game.awayScore = 0
Game.outs = 0
Game.playInning()
def playInning():
totalHits = 0
if Game.inning >= 10:
print('Game is Over')
return
while Game.outs < 3:
for i in rosterHome:
x = rosterHome[i]
if x.battingAverage > random.random():
totalHits += 1
player += 1
print('batter ', player, ' got a hit')
else:
Game.outs += 1
player += 1
print('batter ', player, ' got out')
print('there are ', Game.outs, ' outs.')
Game.startGame()
x = rosterHome[i]
TypeError: list indices must be integers or slices, not Player
TLDR:
List indices must be integers or slices
The interpreter says "Hey, I see you're trying to access an item in a List by its index, but indices should be of type integer, however, you passed a value of type Player"
In Python and most programming languages, to reference an item in a List/Array, one way would be by index. Lists are zero-indexed, so the first item is of index 0, the second index 1, and so on.
Given an Array
my_array = ["bread", "foo", "bar"]
my_array[0] # would give you "bread"
my_array[1] # would give you "foo"
my_array[2] # would give you "bar"
However in your case, if we trace back up from where the error occurred, right here:
x = rosterHome[i]
You want to ask, what is the value of i? above this line is a for loop, and i represents each value in a list called rosterHome. So what the heck is in rosterHome anyways?
Moving up into your createStats method where you populated the rosterHome list, we see that you're pushing an instance of Player into the rosterHome list.
x = Player(i, stats)
rosterHome.append(x)
So rosterHome really isn't a list of numbers but instead a list of Player instances. You might want to review and try again, maybe accessing the number property of the Player object instead.
The error happens because rosterHome is a list of instances of the Player class, so when you iterate on the list (for i in rosterHome) each element will be an instance of said class (i is a Player). If you want to access the number of each player you'll have to access the attribute number of your Player instances, but it seems like actually you want to find the player instance. This means, you don't even need to lookup the value in the table, just use the value of the for loop. I'll use a different naming of variables to improve readability:
while Game.outs < 3:
for player in rosterHome:
# x wanted to access a player, but we don't need to do that actually
if player.battingAverage > random.random():
# ...
else:
# ...
This part of the answer considers that you actually want to meet both requirements (number of outs and iterate players once):
player_index = 0
while Game.outs < 3 and player_index< len(rosterHome):
player = rosterHome[player_index]
if player.battingAverage > random.random():
# ...
else:
# ...
if Game.outs == 3:
# Reached 3 outs
else:
# No players left and game outs < 3
Here is my python code:
class Solution():
def isPalindrome(self):
return str(self.x) == str(self.x)[::-1]
s1 = Solution()
s1.x = 121
s1.isPalindrome()
It checks to see if the input is a palindrome. I want to create a new object that has the x value 121 and when I execute the isPalindrom function, I want it to return either a true or false boolean answer.
Currently when I run this program, nothing gets outputted. I am a bit lost as to where to go from here, would appreciate help.
Just print out the return value of isPalindrome(), because if you have a line with only a return value (this case being a boolean), the compiler won't know what to do with it.
class Solution():
def isPalindrome(self):
return str(self.x) == str(self.x)[::-1]
s1 = Solution()
s1.x = 121
print(s1.isPalindrome())
You're not telling the program to print anything. Try using print to make it reveal the answer.
Along with printing results we can also make class more pythonic.
class Solution:
def __init__(self):
self.input = None
def is_palindrome(self):
if isinstance(self.input, str):
return self.input == self.input[::-1]
print("Error: Expects str input")
return False # or leave blank to return None
s1 = Solution()
print(s1.is_palindrome())
s1.input = "121"
print(s1.is_palindrome())
output
Error: Expects str input
False
True
The main idea here is divide number. let's take number 122. First of all you need store it in a variable, in this case r_num. While loop is used and the last digit of the number is obtained by using the modulus operator %. The last digit 2 is then stored at the one’s place, second last at the ten’s place and so on. The last digit is then removed by truly dividing the number with 10, here we use //. And lastly the reverse of the number is then compared with the integer value stored in the temporary variable tmp if both are equal, the number is a palindrome, otherwise it is not a palindrome.
def ispalindrom(x):
r_num = 0
tmp = x
while tmp > 0:
r_num = (r_num * 10) + tmp % 10
tmp = tmp // 10
if x == r_num:
return True
return False
I am trying to create a function called "odd_even" which takes my already created list (named "nums") and determines the number of odd and even numbers, and then returns the variables to me. However when I run this code I get:
NameError: name 'odd' is not defined
How do I fix this? If you can give me any useful pointers on the "return" function that would also be greatly appreciated.
import random
def main():
nums = []
for x in range(10):
nums.append(random.randrange(1,26))
def odd_even(given_list):
odd = 0
even = 0
for x in given_list:
if x % 2 == 0:
even += 1
else:
odd += 1
return odd
return even
odd_even(nums)
print("List had ", odd, "odds and ", even, "evens.")
main()
You are doing 2 things wrong.
First, you are trying to return two values but on different lines. You cant do this, to do this, do so as a tuple:
def odd_even(given_list):
odd = 0
even = 0
for x in given_list:
if x % 2 == 0:
even += 1
else:
odd += 1
return odd, even
Second, you call the function but dont store the value(s) of return. So you need change:
odd_even(nums) to odd, even = odd_even(nums)
By trying to execute:
print("List had ", odd, "odds and ", even, "evens.")
The main() is looking for variables odd and even, but they dont exist in main(), they exist locally in odd_even() (hence why you are calling return as to return them to the calling function. The reason you only see an error with respect to odd is because it is the first variable in that print() that the interpreter encounters an error on.
The only way around this without correct use of return is to declare them as global. But that is a bad idea so don't do that, keep things local on the stack!
You have some syntactic errors. Python...unlike many programming languages is whitespace conscious. This means you need to be careful with your indentation and spacing. More traditional languages like Java and C use brackets {} to define a scope, and semicolons ; to figure out line termination.
Perhaps you copied it poorly, but from what I see, it appears as though you are defining the function odd_even() within the function main(). That is, the definition of odd_even() is tabbed to the right, which means that its definition is within the function main. I assume that you want main to call the function odd_even(). Thus, you must tab it back over to the left so that it is at the same indentation level as main().
For this reason I use horizontal lines (see below) to clearly outline the scope of functions. This is good for me when I write in Python because otherwise it can be very unclear where one function ends, and where another begins.
Also, it appears as though you have 2 return statements. If you want to return 2 values, you should encompass it within an object. To get around this, there are two simple solutions that come to mind. You can make the odd_even() function access global variables (not recommended)...or you can return an array (any number of values back) or a tuple (exactly 2, but this is python specific).
Below is an implementation of both:
import random
# Declare global variables outside the scope of any function
odd = 0
even = 0
#-------------------------------------------------------------------------------
def main():
nums = [1,2,3,4,5,6,7,8,9,10]
return_value = odd_even(nums)
# Get the individual values back
o = return_value[0]
e = return_value[1]
# You can use the global variables
print("List had ", odd, "odds and ", even, "evens.")
# Or you can get the array back
print("List had ", o, "odds and ", e, "evens.")
#-------------------------------------------------------------------------------
def odd_even(given_list):
# This means we are referencing the variables odd and even that are global
global odd
global even
# Loop through the array
for x in given_list:
if x % 2 == 0:
even += 1
else:
odd += 1
return [odd, even]
#-------------------------------------------------------------------------------
main()
possibleRequests = ['test', 'test1']
def inboxReader():
global inbox
tempInbox = []
tempInbox = inbox.inboxMessage #inboxMesage remains filled?
print(inbox.inboxMessage, 'inboxReader')
i = 0
while (i < len(tempInbox)):
if (tempInbox[i] in possibleRequests):
print('THIS IS WORKING')
#print(i)
i+=1
I want to be able to have possible requests point towards a method to run rather than have a long list of if statments. What am I able to do in order to have a variable point towards and run a method.
Cheers,
Marc
You can first create a dictionary of functions then refer to it with tempInbox[i]. Example code below:
def func_a(x):
return x
def func_b(x):
return x*10
tempInbox = (2,3)
fn_dict = {"a":func_a,"b":func_b}
print fn_dict["a"](tempInbox[0]) # returns 2
print fn_dict["b"](tempInbox[1]) # returns 30