I'm making a game where you run your own coffee shop. You choose how many ingredients you want to buy, then it charges you for them as long as they don't cost too much.
Rather than add the variables up as numbers it comes up with this huge number that it 1000s of times larger than the expected value. I have no clue why (I'm fairly new to python so forgive me if it's obvious. This is also my first time using StackOverflow so if I've forgotten to add any info, let me know.)
var1 = 11
var 2 = 15
print(str(var1 + var 2))
float((NoStaff * 30))
where NoStaff = '1' is '111111111111111111111111111111' which then gets converted to a number.
You want
float(NoStaff) * 30
Additionally, you may want to address the following logic issues:
You can buy partial staff members (0.5)
Your bean count is reset every time you buy new beans
You get the beans/milk even if they cost too much
Related
I think if I know the answer to that question, I might be able to solve this. The code works with just one set of inputs. But if I input another set, it doesn't even acknowledge it. I think it would work if I hardcode another input() but is there a more dynamic way to capture the inputs?
Mad Libs are activities that have a person provide various words,
which are then used to complete a short story in unexpected (and
hopefully funny) ways.
Write a program that takes a string and an integer as input, and
outputs a sentence using the input values as shown in the example
below. The program repeats until the input string is quit and
disregards the integer input that follows.
Ex: If the input is:
apples 5
shoes 2
quit 0
the output is:
Eating 5 apples a day keeps the doctor away.
Eating 2 shoes a day keeps the doctor away.
My code:
UserEntered = input()
makeList = UserEntered.split()
get_item_1 = makeList[slice(0,1)][0]
get_item_2 = makeList[slice(1,2)][0]
if "quit" not in makeList:
print("Eating {} {} a day keeps the doctor away.".format(get_item_2,get_item_1))
1: Compare output 0 / 5 Output differs. See highlights below.
Input
> apples 5
> shoes 2
>quit 0
Your output:
Eating 5 apples a day keeps the doctor away.
Expected output:
Eating 5 apples a day keeps the doctor away.
Eating 2 shoes a day keeps the doctor away.
By the code in your question, it accepts only ONE line of input. You need to write the whole block of code multiple times or you can utilize looping with while in python.
For example, the process you can do step by step is:
Set the looping and make it infinite unless it receives quit
Put the whole code block in the looping (while True) block.
Add the stopping condition, i.e. when it receives quit 0.
Here's the code for the steps above.
while True: # Make an infinite loop.
# Put the whole block to make sure it repeats
makeList = UserEntered.split()
get_item_1 = makeList[slice(0,1)][0]
get_item_2 = makeList[slice(1,2)][0]
# Print when the input is not `quit 0`
if "quit" not in makeList:
print("Eating {} {} a day keeps the doctor away.".format(get_item_2,get_item_1))
# Stopping control/condition here, when it receives `quit 0`
else:
break
I'm building a media player for the office, and so far so good but I want to add a voting system (kinda like Pandora thumbs up/thumbs down)
To build the playlist, I am currently using the following code, which pulls 100 random tracks that haven't been played recently (we make sure all tracks have around the same play count), and then ensures we don't hear the same artist within 10 songs and builds a playlist of 50 songs.
max_value = Items.select(fn.Max(Items.count_play)).scalar()
query = (Items
.select()
.where(Items.count_play < max_value, Items.count_skip_vote < 5)
.order_by(fn.Rand()).limit(100))
if query.count < 1:
max_value = max_value - 1
query = (Items
.select()
.where(Items.count_play < max_value, Items.count_skip_vote < 5)
.order_by(fn.Rand()).limit(100))
artistList = []
playList = []
for item in query:
if len(playList) is 50:
break
if item.artist not in artistList:
playList.append(item.path)
if len(artistList) < 10:
artistList.append(item.artist)
else:
artistList.pop(0)
artistList.append(item.artist)
for path in playList:
client.add(path.replace("/music/Library/",""))
I'm trying to work out the best way to use the up/down votes.
I want to see less with downvotes and more with upvotes.
I'm not after direct code because I'm pretty OK with python, it's more of the logic that I can't quite nut out (that being said, if you feel the need to improve my code, I won't stop you :) )
Initially give each track a weight w, e.g. 10 - a vote up increases this, down reduces it (but never to 0). Then when deciding which track to play next:
Calculate the total of all the weights, generate a random number between 0 and this total, and step through the tracks from 0-49 adding up their w until you exceed the random number. play that track.
The exact weighting algorithm (e.g. how much an upvote/downvote changes w) will of course affect how often tracks (re)appear. Wasn't it Apple who had to change the 'random' shuffle of their early iPod because it could randomly play the same track twice (or close enough together for a user to notice) so they had to make it less random, which I presume means also changing the weighting by how recently the track was played - in that case the time since last play would also be taken into account at the time of choosing the next track. Make sure you cover the end cases where everyone downvotes 49 (or all 50 if they want silence) of the tracks. Or maybe that's what you want...
I'm writing a program in python to transform games from characteristic form into normal form. I've already read some answers to similar questions: most people say it's preferable to use a dictionary. But I think the problem remains if you want to give specific names to the keys.
Let's say I want to build a program for games with three players, that's easy:
v1 = int(raw_input("How much is worth the coalition v(1)?"))
v2 = int(raw_input("How much is worth the coalition v(2)?"))
v3 = int(raw_input("How much is worth the coalition v(3)?"))
v12 = int(raw_input("How much is worth the coalition v(1,2)?"))
v13 = int(raw_input("How much is worth the coalition v(1,3)?"))
v23 = int(raw_input("How much is worth the coalition v(2,3)?"))
v123 = int(raw_input("How much is worth the coalition v(1,2,3)?"))
# and then I continue with the program
But if I want to build a program for games with n players ...
Sure, I can build a a dictionary, but still, I don't know how to call every key the way I want it (v1, v2, v3,... ..., v123..n). Any ideas?
The easies way is to have a container class, createn an empty instance and add attributes to it as required:
class MyContainer(object):
pass
my_container = MyContainer()
my_container.first_var = 1
my_container.next_var = "Hello"
...
But there are certainly much better ways, depending on your application.
For Python3, you can/should omit the object base-class.
In case you want to create variable names dynamically (whyever that should be necessary here), you could use:
setattr(my_container, "a_string_with_the_name_of_the_attribute", "the value")
I am not an expert in Python, but I think that you should also represent each coalition $S$ by its unique integer representation, i.e. $\sum_{i \in S}\, 2^{i-1}$. For example, the coalition $S={3,4}$ is represented by $2^{3-1}+2^{4-1}=4+8=12$, whereas, coalition $S={2,3,4}$ is given by $2^{2-1}+2^{3-1}+2^{4-1}=2+4+8=14$. In Matlab all coalitions of a four-person TU game can be given through
N=2^n-1;
S=1:N
whereas $n=4$, and $N$ is the grand coalition ${1,2,3,4}$. This implies that you only need to specify the coalitional values by an array like
v = [0 0 5 0 0 0 40 0 10 40 100 100 160 190 250];
Of course, the coalition order is different from your approach. To see that, notice that coalition $S={1,2}$ is here located at position $3$ with a value of $5$ ($v({1,2})=5$), and coalition $S={3}$ at position $4$ with a value of zero ($v({3})=0$). I guess that under Python exists also a command like bitget under Matlab to single out which bits (players) belong to the number (coalition) $27$ for $n=5$.
For demonstration, let us compute the Shapley value for the above game $v$. We need only to pass the coalitional values to the function ShapleyValue() to get
>> sh_v=ShapleyValue(v)
sh_v =
29.5833 44.5833 73.7500 102.0833
More details are given by my Matlab Game Theory Toolbox that can be found here:
http://www.mathworks.com/matlabcentral/fileexchange/35933-mattugames
Using: Python 2.7.1 on Windows
Hello, I fear this question has a very simple answer, but I just can't seem to find an appropriate and efficient solution (I have limited python experience). I am writing an application that just downloads historic weather data from a third party API (wundergorund). The thing is, sometimes there's no value for a given hour (eg, we have 20 degrees at 5 AM, no value for 6 AM, and 21 degrees at 7 AM). I need to have exactly one temperature value in any given hour, so I figured I could just fit the data I do have and evaluate the points I'm missing (using SciPy's polyfit). That's all cool, however, I am having problems handling my program to detect if the list has missing hours, and if so, insert the missing hour and calculate a temperature value. I hope that makes sense..
My attempt at handling the hours and temperatures list is the following:
from scipy import polyfit
# Evaluate simple cuadratic function
def tempcal (array,x):
return array[0]*x**2 + array[1]*x + array[2]
# Sample data, note it has missing hours.
# My final hrs list should look like range(25), with matching temperatures at every point
hrs = [1,2,3,6,9,11,13,14,15,18,19,20]
temps = [14.0,14.5,14.5,15.4,17.8,21.3,23.5,24.5,25.5,23.4,21.3,19.8]
# Fit coefficients
coefs = polyfit(hrs,temps,2)
# Cycle control
i = 0
done = False
while not done:
# It has missing hour, insert it and calculate a temperature
if hrs[i] != i:
hrs.insert(i,i)
temps.insert(i,tempcal(coefs,i))
# We are done, leave now
if i == 24:
done = True
i += 1
I can see why this isn't working, the program will eventually try to access indexes out of range for the hrs list. I am also aware that modifying list's length inside a loop has to be done carefully. Surely enough I am either not being careful enough or just overlooking a simpler solution altogether.
In my googling attempts to help myself I came across pandas (the library) but I feel like I can solve this problem without it, (and I would rather do so).
Any input is greatly appreciated. Thanks a lot.
When I is equal 21. It means twenty second value in list. But there is only 21 values.
In future I recommend you to use PyCharm with breakpoints for debug. Or try-except construction.
Not sure i would recommend this way of interpolating values. I would have used the closest points surrounding the missing values instead of the whole dataset. But using numpy your proposed way is fairly straight forward.
hrs = np.array(hrs)
temps = np.array(temps)
newTemps = np.empty((25))
newTemps.fill(-300) #just fill it with some invalid data, temperatures don't go this low so it should be safe.
#fill in original values
newTemps[hrs - 1] = temps
#Get indicies of missing values
missing = np.nonzero(newTemps == -300)[0]
#Calculate and insert missing values.
newTemps[missing] = tempcal(coefs, missing + 1)
Lets say I have around 1,000,000 users. I want to find out what position any given user is in, and which users are around him. A user can get a new achievement at any time, and if he could see his standing update, that would be wonderful.
Honestly, every way I think of doing this would be horrendously expensive in time and/or memory. Ideas? My closest idea so far is to order the users offline and build percentile buckets, but that can't show a user his exact position.
Some code if that helps you django people :
class Alias(models.Model) :
awards = models.ManyToManyField('Award', through='Achiever')
#property
def points(self) :
p = cache.get('alias_points_' + str(self.id))
if p is not None : return p
points = 0
for a in self.achiever_set.all() :
points += a.award.points * a.count
cache.set('alias_points_' + str(self.id), points, 60 * 60) # 1 hour
return points
class Award(MyBaseModel):
owner_points = models.IntegerField(help_text="A non-normalized point value. Very subjective but try to be consistent. Should be proporional. 2x points = 2x effort (or skill)")
true_points = models.FloatField(help_text="The true value of this award. Recalculated with a cron job. Based on number of people who won it", editable=False, null=True)
#property
def points(self) :
if self.true_points :
# blend true_points into real points over 30 days
age = datetime.now() - self.created
blend_days = 30
if age > timedelta(days=blend_days) :
age = timedelta(days=blend_days)
num_days = 1.0 * age.days / blend_days
r = self.true_points * num_days + self.owner_points * (1 - num_days)
return int(r * 10) / 10.0
else :
return self.owner_points
class Achiever(MyBaseModel):
award = models.ForeignKey(Award)
alias = models.ForeignKey(Alias)
count = models.IntegerField(default=1)
I think Counterstrike solves this by requiring users to meet a minimum threshold to become ranked--you only need to accurately sort the top 10% or whatever.
If you want to sort everyone, consider that you don't need to sort them perfectly: sort them to 2 significant figures. With 1M users you could update the leaderboard for the top 100 users in real time, the next 1000 users to the nearest 10, then the masses to the nearest 1% or 10%. You won't jump from place 500,000 to place 99 in one round.
Its meaningless to get the 10 user context above and below place 500,000--the ordering of the masses will be incredibly jittery from round to round due to the exponential distribution.
Edit: Take a look at the SO leaderboard. Now go to page 500 out of 2500 (roughly 20th percentile). Is there any point to telling the people with rep '157' that the 10 people on either side of them also have rep '157'? You'll jump 20 places either way if your rep goes up or down a point. More extreme, is that right now the bottom 1056 pages (out of 2538), or the bottom 42% of users, are tied with rep 1. you get one more point, and you jumped up 1055 pages. Which is roughly a 37,000 increase in rank. It might be cool to tell them "you can beat 37k people if you get one more point!" but does it matter how many significant figures the 37k number has?
There's no value in knowing your peers on a ladder until you're already at the top, because anywhere but the top, there's an overwhelming number of them.
One million is not so much, I would try it the easy way first. If the points property is the thing you are sorting on that needs to be a database column. Then you can just do a count of points greater than the person in question to get the rank. To get other people near a person in question you do a query of people with higher points and sort ascending limit it to the number of people you want.
The tricky thing will be calculating the points on save. You need to use the current time as a bonus multiplier. One point now needs to turn into a number that is less than 1 point 5 days from now. If your users frequently gain points you will need to create a queue to handle the load.