Parse a decimal from an integer - python

My code/project: I'm learning Python and trying to create a pace calculator for some marathon training.
My problem: How do I separate/parse the decimal from the final number calculated?
Example: Using the following input values
#[Minutes, Seconds, Distance in miles]
[17, 37, 3.1]
#17 * 60 = 1020; 1020 + 37 = 1057; 1057/3.1 = 340.96
the entire code would give me an answer of 340.96 seconds. If I divide that by 60 to find out the exact Minutes/seconds; the answer becomes 5.68.
I need to take that ".68" and multiply it by 60 to get actual seconds because it represents 68% of a minute.
recordMinutes = int(input("What is your total minutes? "))
for steps in range(1):
converted = recordMinutes * 60
recordSeconds = int(input("What is your total seconds leftover? "))
for steps in range(1):
combined = converted + recordSeconds
distance = float(input("What is the distance? "))
paceRaw = combined/distance
paceBasic = (paceRaw/60)
#This is where I would multiply the ".68" by 60
pace = (#decimal remainder * 60) + #whole number
print ("You need to run %d per mile " % pace)

Use divmod.
>>> divmod(340.96, 60)
(5.0, 40.95999999999998)

A good practice for you as the beginner would be to do this without any libraries or methods:
>>> s = 5.68
>>> s = s*100
568.0
>>> s = s%100
68.0
>>> s/100
0.68

Related

It is not working as expected. How can i fix this code?

I want the code to increase my semi_annual_income every six months, by making the the semi_annual income increase every six months with by specific percentage. so it was suppose to be according to my math 1000(1.2)^i/6 this equation would increase my income by 0.2 every 6 months where the i is divisible by 6.
I tried to both the expressions when I use the expression 1000(1.2)^i/6 it will give me a very huge number. and the expression 1000(1 +0.2) is giving me the exact answer that 1000(1 + 0.2) should have given me.
number_of_months = 0
total_cost = 100000
semi_annual_income = 1000
starting_salary = 10
semi_annual_rise = 0.2
while semi_annual_income < total_cost:
for i in range(100):
if float(i)%6 == 0:
power_number = float(i)/6
# i am using this to make it increase the semi_annual income just only every six months
semi_annual_income = semi_annual_income *(float(1) + float(semi_annual_rise))
print(power_number)
print(semi_annual_income)
#semi_annual_income = (semi_annual_income *(float(1) + float(semi_annual_rise))** float(power_number))
#The above written code is giving me a very huge number i want it to give me the answer as 1000(1 + 0.2)^i/6
break
I got the answer I wanted from the code but I don't understand why is it giving me the answer without the power and the one with the power is not giving me the answer.
number_of_months = 0
total_cost = 100000
semi_annual_income = 1000
starting_salary = 1000
semi_annual_rise = 0.2
number_of_months = 0
while semi_annual_income < total_cost:
for i in range(1,100):
if float(i)%6 == 0:
power_number = float(i)/6# i am using this to make it increase the
semi_annual income just only every six months
number_of_months = number_of_months + 1
semi_annual_income = starting_salary *(float(1) +
float(semi_annual_rise))**(power_number)
print(power_number)
print(semi_annual_income)
print(number_of_months)
# I think my mistake was the i used semi_annual-income instead of starting salary, this code works as i wanted it to be.
break

Given Time in minutes, print it in hours and minutes

In Question, Given Time is in minutes that requires to be converted into hours and minutes.
Sample :
Input - 53
Output - 0 53
num = int(input())
if num < 60:
print('0'+" "+str(num))
else:
if num>=60:
time = num*(1/60)
time1 = (format(time, '.2f'))
print(str(time1).replace('.',' '))
The easiest way to do this is using integer division (//) and modulo (%):
def printAsHoursAndMinutes(timeInMinutes):
hours = timeInMinutes // 60
minutes = timeInMinutes % 60
print("{} {}".format(hours, minutes)) #edited to match the requested output format
// will return the integer part of the devision, % returns the rest. With 130 as input, the above code will print "2 10", for 5 as input, it prints "0 5".
[Edit:] This works for any nonegative integer. If you want to support negative integers too, add the following condition just before the print:
if(timeInMinutes < 0):
hours = hours + 1
minutes = 60 - minutes
This allows us to handle inputs like -65 to print "-1 5".
For floating point numbers, things migth get a bit ugly because % is not 100% acurate (e.g. 60.1 results in 1.0 0.10000000000000142). This even happenes when using divmod as mentioned by #CristiFati in the comments to the question, so there is no real way around it and we'd need a more advanced handling or a custom modulo method but that is off-topic here.
As per shown in picture...
You may try this..
def HoursandMinutes(Minutes):
Minutes = Minutes % (24*3600)
Hour = Minutes // 60
Minutes %= 60
print("%d %d" % (Hour, Minutes))
When you call this function
OUTPUT
HoursandMinutes(52)
0 52
HoursandMinutes(70)
1 10
HoursandMinutes(90)
1 30
HoursandMinutes(105)
1 45

How to use the final value of two different function to get another value in python?

I want to develop an electric calculator which :
Converts money into units(KWh).
It also takes user input to determine how many electric component he/she uses in home in order to determine average electricity consumption per day.
After having those in inputs and calculation it will also show how many day he/she can have against the money he/she recharged(Ex: for 10$ he can have 100 Kwh, if average use per day is 10 KWh how many day he can have? [day=100kwh/10kwh=10 days]
I have solved 1 and 2 problem using two function, now i want to use the final value of those two function to get the day. i was trying to divide the final of those function. is it possible to divide the value of those function?
1. this function converts money into units in KWh
def money_to_unit():
recharge=int(input("Enter yor recharge amount : "))
amount=recharge-(recharge*(5/100)) # after deducting 5% vat
unit=0
if amount<=300: #300 is max value for using 75 Kwh
unit=amount/4 # 4 is the slab rate for 0-75 Kwh
elif amount<=981.25: #981.25 is max value for using 200 Kwh
unit=75+((amount-300)/5.45) #5.45 is the slab rate for 76-200 Kwh
elif amount<=1551.25: #1551.25 is max value for using 300 Kwh
unit=75+125+((amount-681.25)/5.7) #5.7 is the slab rate for 201-300 Kwh
elif amount<=2153.25:
unit=75+125+100+((amount-1551.25)/6.02)
elif amount<=4013.25:
unit=75+125+100+100+((amount-2153.25)/9.30)
else:
unit=75+125+100+100+200+((amount-4013.25)/10.7)
print("Useable amount is :"+ " "+str(round(amount,2))+" "+"Taka")
print("Useable unit is: "+" "+str(round(unit,2))+" "+"Kwh")
money_to_unit()
2. to determine the average use per day in KWh
def comp():
light=int(input("Enter the number of light :"))
watt=int(input("Enter the watt : "))
hour=int(input("Enter the agerage use of light in hour per day : "))
consumption=(light*watt*hour)/1000
print("you total consumption is"+ " " + str(consumption)+ " " + "Kwh per day")
comp()
3. divided money_to_unit() by comp(). how to do it?
(1).for 500 taka, usable amount is 475 taka, usable unit is 107.11 Kwh
(2).for 5 light of 20 w per hour using 6 hour a day, average use is 0.6 Kwh per day.
(3). day = 107.11 Kwh/0.6 Kwh = 178.5 day
Both of your function should return the calculated value that you want to use for further calculations (instead of just printing it).
def money_to_unit():
/* function definition */
return round(amount,2), round(amount,2)
and
def comp():
/* function definition */
return consumption
Then you can simply call the functions like this:
x, y = money_to_unit()
z = comp()
and finally you can perform any extra calculation you want with x,y,z like:
result = x/z
/* or */
result2 = y/z
def money_to_unit():
# all your previous code
return round(unit,2)
def comp():
# all your previous code
return consumption
and perhaps:
money_unit = money_to_unit()
consumption = comp()
day = money_unit / consumption
print(round(day,1), "{}".format("day"))
OUTPUT:
178.5 day
Use return. Give functions specific tasks to do, not only wrapping around some scripts.
1.Define two functions for first step:
def recharge_to_amount(recharge, vat):
return recharge * (1 - vat)
and
def amount_to_kwh(amount):
if amount <= 300:
return amount / 4
elif amount <= 981.25:
return 75 + ((amount - 300) / 5.45)
elif amount <= 1551.25:
return 75 + 125 + ((amount - 681.25) / 5.7)
elif amount <= 2153.25:
return 75 + 125 + 100 + ((amount - 1551.25) / 6.02)
elif amount <= 4013.25:
return 75 + 125 + 100 + 100 + ((amount - 2153.25) / 9.30)
else:
return 75 + 125 + 100 + 100 + 200 + ((amount - 4013.25) / 10.7)
2.Define another function for second step:
def consumption(light, watt, hour):
return light * watt * hour / 1000
3.Define last function:
def days(watt, cons):
return watt / cons
And perform your calculation:
amount = recharge_to_amount(500)
kwh = amount_to_kwh(amount)
consumption = consumption(5, 20, 6)
days = days(kwh, consumption)

Print pi to a number of decimal places

One of the challenges on w3resources is to print pi to 'n' decimal places. Here is my code:
from math import pi
fraser = str(pi)
length_of_pi = []
number_of_places = raw_input("Enter the number of decimal places you want to
see: ")
for number_of_places in fraser:
length_of_pi.append(str(number_of_places))
print "".join(length_of_pi)
For whatever reason, it automatically prints pi without taking into account of any inputs. Any help would be great :)
The proposed solutions using np.pi, math.pi, etc only only work to double precision (~14 digits), to get higher precision you need to use multi-precision, for example the mpmath package
>>> from mpmath import mp
>>> mp.dps = 20 # set number of digits
>>> print(mp.pi)
3.1415926535897932385
Using np.pi gives the wrong result
>>> format(np.pi, '.20f')
3.14159265358979311600
Compare to the true value:
3.14159265358979323846264338327...
Why not just format using number_of_places:
''.format(pi)
>>> format(pi, '.4f')
'3.1416'
>>> format(pi, '.14f')
'3.14159265358979'
And more generally:
>>> number_of_places = 6
>>> '{:.{}f}'.format(pi, number_of_places)
'3.141593'
In your original approach, I guess you're trying to pick a number of digits using number_of_places as the control variable of the loop, which is quite hacky but does not work in your case because the initial number_of_digits entered by the user is never used. It is instead being replaced by the iteratee values from the pi string.
For example the mpmath package
from mpmath import mp
def a(n):
mp.dps=n+1
return(mp.pi)
Great answers! there are so many ways to achieve this. Check out this method I used below, it works any number of decimal places till infinity:
#import multp-precision module
from mpmath import mp
#define PI function
def pi_func():
while True:
#request input from user
try:
entry = input("Please enter an number of decimal places to which the value of PI should be calculated\nEnter 'quit' to cancel: ")
#condition for quit
if entry == 'quit':
break
#modify input for computation
mp.dps = int(entry) +1
#condition for input error
except:
print("Looks like you did not enter an integer!")
continue
#execute and print result
else:
print(mp.pi)
continue
Good luck Pal!
Your solution appears to be looping over the wrong thing:
for number_of_places in fraser:
For 9 places, this turns out be something like:
for "9" in "3.141592653589793":
Which loops three times, one for each "9" found in the string. We can fix your code:
from math import pi
fraser = str(pi)
length_of_pi = []
number_of_places = int(raw_input("Enter the number of decimal places you want: "))
for places in range(number_of_places + 1): # +1 for decimal point
length_of_pi.append(str(fraser[places]))
print "".join(length_of_pi)
But this still limits n to be less than the len(str(math.pi)), less than 15 in Python 2. Given a serious n, it breaks:
> python test.py
Enter the number of decimal places you want to see: 100
Traceback (most recent call last):
File "test.py", line 10, in <module>
length_of_pi.append(str(fraser[places]))
IndexError: string index out of range
>
To do better, we have to calculate PI ourselves -- using a series evaluation is one approach:
# Rewrite of Henrik Johansson's (Henrik.Johansson#Nexus.Comm.SE)
# pi.c example from his bignum package for Python 3
#
# Terms based on Gauss' refinement of Machin's formula:
#
# arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + ...
from decimal import Decimal, getcontext
TERMS = [(12, 18), (8, 57), (-5, 239)] # ala Gauss
def arctan(talj, kvot):
"""Compute arctangent using a series approximation"""
summation = 0
talj *= product
qfactor = 1
while talj:
talj //= kvot
summation += (talj // qfactor)
qfactor += 2
return summation
number_of_places = int(input("Enter the number of decimal places you want: "))
getcontext().prec = number_of_places
product = 10 ** number_of_places
result = 0
for multiplier, denominator in TERMS:
denominator = Decimal(denominator)
result += arctan(- denominator * multiplier, - (denominator ** 2))
result *= 4 # pi == atan(1) * 4
string = str(result)
# 3.14159265358979E+15 => 3.14159265358979
print(string[0:string.index("E")])
Now we can take on a large value of n:
> python3 test2.py
Enter the number of decimal places you want: 100
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067
>
This is what I did, really elementary but works (max 15 decimal places):
pi = 22/7
while True:
n = int(input('Please enter how many decimals you want to print: '))
if n<=15:
print('The output with {} decimal places is: '.format(n))
x = str(pi)
print(x[0:n+2])
break
else:
print('Please enter a number between 0 and 15')
As this question already has useful answers, I would just like to share how i created a program for the same purpose, which is very similar to the one in the question.
from math import pi
i = int(input("Enter the number of decimal places: "))
h = 0
b = list()
for x in str(pi):
h += 1
b.append(x)
if h == i+2:
break
h = ''.join(b)
print(h)
Thanks for Reading.
Why not just use:
import numpy as np
def pidecimal(round):
print(np.round(np.pi, round))

Issues with displaying time results in Python

I have written a code to take in a running pace value (min/km), convert it to speed (km/hr) and then depending on the slope gradient and whether the direction of travel is up or downhill the lost speed is calculated (km/hr). The new running speed is then displayed along with the new running pace and the time your route is altered by.
The issue is when I input a pace such as 3:50 (min/km) with an uphill slope of 1% the new running pace is 3:60 (min/km). How do I get the script to tick over to 4:00 in this case? Also if 3:55 (min/km) is input the new running pace given is 4:5 (min/km) when it should read as 4:05 (min/km). How do i edit this?
The script is:
import math
print('Q1')
SurveyPace = input("Running Pace (min/km): \n "). split(":")
SurveyPace = float(SurveyPace[0])*60 + float(SurveyPace[1])
Speed = 3600/SurveyPace
print("Original running speed =","%.2f" % round(Speed,2), 'km/hr')
print("--------------------------------------------------------")
print('Q2')
SlopeDirection = int(input('For Uphill press 1 \nFor Downhill press 2 \n '))
print("--------------------------------------------------------")
print('Q3')
SlopeGradient = float(input('Percentage gradient(without the % symbol)?\n '))
print("--------------------------------------------------------")
print('CALCULATED RESULTS')
print("--------------------------------------------------------")
if SlopeDirection == 1:
Change = - 0.65 * SlopeGradient
if SlopeDirection == 2:
Change = + 0.35 * SlopeGradient
print ('This route alters your speed by \n', Change,'km/hr')
print("--------------------------------------------------------")
AdjustedSpeed = Speed + Change
AdjustedPace = 3600/AdjustedSpeed
PaceSecs = round(AdjustedPace % 60)
PaceMins = math.floor(AdjustedPace/60)
print("New running speed is \n","%.2f" % round(AdjustedSpeed,2), 'km/hr')
print("--------------------------------------------------------")
print("New running pace is \n", str(PaceMins) + ":" + str(PaceSecs), 'min/km')
print("--------------------------------------------------------")
print("This route alters your pace by \n", int(PaceSecs + (PaceMins*60)) - SurveyPace, "sec/km") #Prints the time change incured
print("--------------------------------------------------------")
Thanks
You can do this with the built-in function divmod:
# Round the AdjustedPace to seconds
AdjustedPace = round(3600/AdjustedSpeed)
minutes, seconds = divmod(AdjustedPace, 60)
print(minutes)
print(seconds)
This will lead to:
#Pace = 3:50
#4
#0
#Pace = 3:55
#4
#5
I would do this with timedelta objects from datetime:
import datetime
inp = raw_input('Enter your pace in minutes per km (min:km):')
mins, kms = inp.split(':')
time = datetime.timedelta(minutes=int(mins))
If you enter 60 minutes, for example, will give you:
> time
datetime.timedelta(0, 3600)
And then you can perform math operations on it and it stays correct:
> time / 2
datetime.timedelta(0, 1800)
Or if you want minutes just divide it by 60, hours divide it by 3600. You can also add and subtract timedelta objects from each other, or from datetime objects if you want timestamps. Or if your divisor leaves a remainder:
> new = time / 17
> new
datetime.timedelta(0, 3600)
> new.seconds
200
> new.microseconds
764706
Which you could then use to round if you wanted. It's a good way to make sure your time always stays accurate.

Categories