How do I align the user input in the output code? - python-3.x

I am currently taking Web, Pgm & DB Foundation and I am learning python but I am struggling with this assignment.
In the original assignment, you were to create an expense calculator (code below):
print("This program calculates and displays travel expenses", '\n')
user_budget = int(input("Enter Budget:"))
user_destination = input("Enter your travel destination:")
user_fuel = int(input("How much do you think you will spend on gas?"))
user_lodging = int(input("Approximately, how much will you need for accommodation/hotel?"))
user_meals = int(input("Last, how much do you need for food?"))
print('\n')
print('----------Travel Expenses----------')
print('Location:', user_destination)
print('Initial Budget:', user_budget)
print('Fuel:', user_fuel)
print('Accommodation:', user_lodging)
print('Food:', user_meals)
print('___________________________________')
user_total = (user_budget-(user_fuel+user_lodging+user_meals))
print('Remaining Balance:', user_total)
For the next assignment, we are asked to make the output look like this:
expected output:
I was able to figure out how to add the $ next to the output, but this is my first time ever learning python so I am pulling my hair out trying to figure out how to align the output as shown in the image above.
I've updated the code to this:
print('----------Travel Expenses----------')
print('Location:', user_destination)
print('Initial Budget:', "${:.2f}".format(user_budget))
print('Fuel:', "${:.2f}".format(user_fuel))
print('Accommodation:', "${:.2f}".format(user_lodging))
print('Food:', "${:.2f}".format(user_meals))
print('____________________________________')
user_total = (user_budget-(user_fuel+user_lodging+user_meals))
print('Remaining Balance:',"${:.2f}".format(user_total))
But I am completely lost as to how to align the output to the right.
Any help is greatly appreciated and if you could break it down barney style, that would be awesome.

Related

How to classify a data set in a neural network that is working

I made a neural network that shows me the probability that a comment is positive, calculated from 0 to 1.
In fact, I can now enter new data and it offers me results in this line
Dcnn(np.array([tokenizer.encode("I feel very happy with the product")]), training = False).numpy()
Then the result shows me something like this
array([[0.9083]] , dtype = float32)
as you can see i introduced a text , now i would like to make a loop to give it n texts. I would be happy if someone can help me
i am expecting to get the result of the comment for each comment something like this
Text 1: "......." ; prob: 0.0002
Text 2: "......." ; prob: 0.7840
This should be as simple as this:
for index, comment in enumerate(comments, 1):
pred_proba = Dcnn(np.array([tokenizer.encode(comment)]), training = False).numpy()[0][0]
print(f"Text {index}: '{comment}'; Probability: {pred_proba}")
Hope this helps!

connecting a variable output to send Keys string

I am trying to generate a random number that is six digits and then submit that 6 digit out put to a website.
here is my code:
send_code = self.chrome_browser.find_element_by_xpath("/html/body/div[1]/section/div/div/div[3]/form/span/button").click()
random_num = random.randrange(000000, 999999)
(f'{random_num:06}')
send_random_num = self.chrome_browser.find_elements_by_xpath('/html/body/div[1]/section/div/div/div[2]/form/div/input')
random_num.send_keys(Keys.random_num, Keys.ENTER)
the generating the random number is working but for some reason my send_random_num variable is not executing the right commands. I feel like I am formatting this wrong. Keys.(var) just isn't close to right so any suggestions? thanks (using selenium)
To me, it looks like you are using selenium. Maybe next time try adding that as a tag or clearly stating what module you are using. I believe this will work, and I took the liberty clarifying some of your variable names:
button = self.chrome_browser.find_element_by_xpath("/html/body/div[1]/section/div/div/div[3]/form/span/button")
button.click()
random_num = random.randrange(000000, 999999)
random_code = (f'{random_num:06}')
input = self.chrome_browser.find_elements_by_xpath('/html/body/div[1]/section/div/div/div[2]/form/div/input')
input.send_keys(random_code)

How to read starting N words from each rows in python3

I am reading excel which has free text in a column.Now after reading that file from pandas, I want to restrict the column having text to read just N words from starting for each rows. I tried everything but was not able to make it.
data["text"] = I am going to school and I bought something from market.
But I just want to read staring 5 words. so that it could look like below.
data["text"] = I am going to school.
and I want this same operation to be done bow each row for data["text"] column.
You help will be highly appreciated.
def first_k(s: str, k=5) -> str:
s = str(s) # just in case something like NaN tries to sneak in there
first_words = s.split()[:k]
return ' '.join(first_words)
Then, apply the function:
data['text'] = data['text'].apply(first_k)
data["text"] = [' '.join(s.split(' ')[:5]) for s in data["text"].values]

Python loop list in function call

This is my first question on StackOverflow. I have always found what I was looking for just googling, but this time I'm stuck and can't figure it out.
I'm a beginner programmer with python and still learning a lot.
I want to change a dateEdit box in a Userinterface with a small code to set det current date time.
the code looks like this.
self.dateEdit_2.setDateTime(QtCore.QDateTime.currentDateTime())
Now i want to change every dateEdit box the same, starting from 2 and going to 29, without typing every single line out.
i have tried to make a for loop with a filled list.
and i get it to print out what i want, but how does i get "set_date_numb" to be a attribute that does what i want.
hope you understand, Thanks.
dateTimeList = ['2','3','4','5','6','7','8','9',
'10','11','12','13','14','15','16','17','18','19','20',
'21','22','23','24','25','26','27','28','29']
indexval = 0
for i in range(len(dateTimeList)):
date_numb = (dateTimeList[indexval])
set_date_numb ='self.dateEdit_{}.setDateTime(QtCore.QDateTime.currentDateTime())'.format(date_numb)
print(set_date_numb)
indexval += 1
You could use getattr(), see the documentation here. Since the functions you are after are members of your instance you can grab them with their names as strings (which I think is the main problem you are facing):
dateTimeList = [str(x) for x in range(2,30)]
for dt in dateTimeList:
name = "dateEdit_{}".format(dt)
currentDateEdit = getattr(self, name)
currentDateEdit.setDateTime(QtCore.QDateTime.currentDateTime())

Pandas .rolling.corr using date/time offset

I am having a bit of an issue with pandas's rolling function and I'm not quite sure where I'm going wrong. If I mock up two test series of numbers:
df_index = pd.date_range(start='1990-01-01', end ='2010-01-01', freq='D')
test_df = pd.DataFrame(index=df_index)
test_df['Series1'] = np.random.randn(len(df_index))
test_df['Series2'] = np.random.randn(len(df_index))
Then it's easy to have a look at their rolling annual correlation:
test_df['Series1'].rolling(365).corr(test_df['Series2']).plot()
which produces:
All good so far. If I then try to do the same thing using a datetime offset:
test_df['Series1'].rolling('365D').corr(test_df['Series2']).plot()
I get a wildly different (and obviously wrong) result:
Is there something wrong with pandas or is there something wrong with me?
Thanks in advance for any light you can shed on this troubling conundrum.
It's very tricky, I think the behavior of window as int and offset is different:
New in version 0.19.0 are the ability to pass an offset (or
convertible) to a .rolling() method and have it produce variable sized
windows based on the passed time window. For each time point, this
includes all preceding values occurring within the indicated time
delta.
This can be particularly useful for a non-regular time frequency index.
You should checkout the doc of Time-aware Rolling.
r1 = test_df['Series1'].rolling(window=365) # has default `min_periods=365`
r2 = test_df['Series1'].rolling(window='365D') # has default `min_periods=1`
r3 = test_df['Series1'].rolling(window=365, min_periods=1)
r1.corr(test_df['Series2']).plot()
r2.corr(test_df['Series2']).plot()
r3.corr(test_df['Series2']).plot()
This code would produce similar shape of plots for r2.corr().plot() and r3.corr().plot(), but note that the calculation results still different: r2.corr(test_df['Series2']) == r3.corr(test_df['Series2']).
I think for regular time frequency index, you should just stick to r1.
This mainly because the result of two rolling 365 and 365D are different.
For example
sub = test_df.head()
sub['Series2'].rolling(2).sum()
Out[15]:
1990-01-01 NaN
1990-01-02 -0.355230
1990-01-03 0.844281
1990-01-04 2.515529
1990-01-05 1.508412
sub['Series2'].rolling('2D').sum()
Out[16]:
1990-01-01 -0.043692
1990-01-02 -0.355230
1990-01-03 0.844281
1990-01-04 2.515529
1990-01-05 1.508412
Since there are a lot NaN in rolling 365, so the corr of two series in two way are quit different.

Resources