How do I print fibonacci numbers in a column format [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need some help, trying to print in the following format:
00: 0
01: 1
02: 1
03: 2
04: 3
05: 5
06: 8
07: 13
08: 21
09: 34
10: 55
My codes:
import math
import time
start_time = time.time()
golden_ratio = (1 + math.sqrt(5)) / 2
def main():
num = int(input("How many Fibonacci numbers should I print? "))
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print(format(round((val)),'3d'))
main()

def main():
stnum = input("How many Fibonacci numbers should I print? ")
dig = len(stnum)
num = int(stnum)
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
#print(format(round((val)),'3d'))
print(f"{number:0{dig}d}: {val:.0f}")
dig is the number of digits of the amount of Fibonacci numbers: if you ask for 100 Fibonacci numbers, dig is 3. I use formatted string literals (available since python 3.6) to format the output.
{number:0{dig}d} prints the integer number with dig leading 0.
{val:.0f} prints a float with no digits after the dot.
If you have an older version of python and formatted string literals are not available, replace the print statement with this:
print("{}: {:.0f}".format(str(number).zfill(dig), val))

import math
import time
start_time = time.time()
golden_ratio = (1 + math.sqrt(5)) / 2
def main():
num = int(input("How many Fibonacci numbers should I print? "))
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print('{}: {:.0f}'.format(number, val))
main()

import math
import time
start_time = time.time()
golden_ratio = (1 + math.sqrt(5)) / 2
def main():
num = int(input("How many Fibonacci numbers should I print? "))
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print(format(number, '02d'), ': ', format(round((val)),'3d'))
main()

Related

swap output the order of the digits

I have one code here
and need to change the order of the digits
import math
def sucet_cisel(number):
bla: int = 0
while number > 0:
xyzpremenna = number % 10
bla += xyzpremenna
number = (number - xyzpremenna) / 10
return bla
def digit_root(n):
if n == 0: return 0
return (n - 1) % 9 + 1
if __name__ == '__main__':
n = int(input("od čisla:"))
m = int(input("do čisla:"))
for i in range(1,m + 1):
sucet: int = math.floor(sucet_cisel(n*i))
t=(n*i)*(2)
x=' ';
print(n,"*",i,"=",n*i,(x*4),"*2","=",t,sep='')
they need to add () to this code so that in each result where there are 4 numbers they are moved
therefore print (t) need this script to run at that number
t=(ni)(2)
and the result of this to turn into this code
val = list(str(i))
digit = val.pop(-3)
new = int(''.join(val+[digit]))
od čisla:2554
do čisla:4505
2554*4505=11505770 *2=23011540
23011540
23011405
the script stops at the number I enter where is the problem?
20*1=20 *2=40
20*2=40 *2=80
20*3=60 *2=120
20*4=80 *2=160
20*5=100 *2=200
20*6=120 *2=240
20*7=140 *2=280
20*8=160 *2=320
20*9=180 *2=360
20*10=200 *2=400
20*11=220 *2=440
20*12=240 *2=480
20*13=260 *2=520
20*14=280 *2=560
20*15=300 *2=600
20*16=320 *2=640
20*17=340 *2=680
20*18=360 *2=720
20*19=380 *2=760
20*20=400 *2=800
this makes a code if I give
n = int (input ("from number:"))
m = int (input ("to number:"))
n20
m20
however, if in this script there is i
val = list (page (s))
digit = val.pop (-3)
new = int (''. join (val + [digit]))
does it calculate only one result where is the error?
Very similar to the answer from Tim Roberts, but using slices and format strings.
n = 12345678
s = str(n)
x = int(f"{s[:-5]}{s[::-1][:4]}")
s is '12345678', s[:-5] is '1234', s[::-1] is '87654321', and s[::-1][:4] is '8765'. Put it all together and x is 12348765.
OK, let's rewrite your problem to "given a number of greater than 4 digits, I want that same number but with all permutations of the last 4 digits.
import itertools
def permute(number):
val = str(number)
prefix = val[:-4]
for combo in itertools.permutations(val[-4:]):
yield int(prefix+''.join(combo))
print(list(permute(12345678)))

Calculating total value of changed coins in sys.argv module in Python [duplicate]

This question already has answers here:
Are the values of sys.argv strings? I need lists
(6 answers)
Closed 1 year ago.
I have an issue in returning the total value of coins in Dollars using sys.argv module using Pycharm in Python running the code from Command prompt. User passes arguments (number of coins - 9 quarters, 7 dimes, 3 nickels, and 6 pennies) from command line. The sum supposed to return in Dollars, but my code does not return sum, repeats the arguments instead. Here is the code:
import sys
sum = 0
for i in range(1,5):
sum = int((sys.argv[1]) * 2 + (sys.argv[2]) * 3 + (sys.argv[3]) * 4 + (sys.argv[4]) * 5)
print('Result: ', sum)
The error in Command prompt is:
(base) E:\>python egg.py 9 7 3 6
Result: 99999999999999999999999997777777777333336
Your problem is that sys.argv stores all arguments as strings. When multiplying strings in python, it copies the string to the specified number. The actual solution should look like this:
sum = int(sys.argv[1]) * 2 + int(sys.argv[2]) * 3 + int(sys.argv[3]) * 4 + int(sys.argv[4]) * 5
This converts the variable to integers before multiplying them which should yield the right answer.

calculate years compound interest python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
So i have this task, i need to create formula in python, I have all the program running good, but i just can't think of the formula to count years, that's compound interest
what i need to count is how many years will it take to get to the target(lets say from 1500 to 2000)
Got this formula t = ln(A/P) / n[ln(1 + r/n)], but i don't get the right answer
https://www.thecalculatorsite.com/articles/finance/compound-interest-formula.php
Also tried this
https://www.algebra.com/algebra/homework/logarithm/logarithm.faq.question.117944.html
update.
Thanks for help! answer in comments for those who have same issue
This might work:
from math import log
p_start = 1500 # Beginning principal
r = 4.3 # Interest rate
p_end = 2000 # Ending principal
"""
# Lambda function
# n == number of compounding periods per year.
# Default n is 12, or monthly compounding
# Formula Breakdown
round((
log(A / P) /
(n * (
log(1 + (r/n))
)
)
# Add 0.5 to account for needing to round up.
) + 0.5
# Round to zero decimal places
, 0)
"""
get_time = lambda A, P, r, n=12: round((log(A / P) / (n * (log(1 + (r/n))))) + 0.5, 0)
# If interest rate isn't a percentage, convert it
if r > 0:
r /= 100
get_time(p_end, p_start, r, 1) # 7.0 using n = 1, or compounded once per year.
EDIT: Adding solution for comment below:
def calculate_years_to_target(principal, rate, target, n=12):
if rate > 0:
rate /= 100
years = round((math.log(target / principal) / (n * (math.log(1 + (rate/n))))) + 0.5, 0)
return years
calculate_years_to_target(1500, 4.3, 2000, 1)
Compound Interest Calculator:
import math
P = float(input("Enter the initial deposit: "))
A = float(input("Enter the final amount: "))
N = float(input("Enter the number of times the interest is applied per time period: "))
T = float(input("Enter the number of time periods elapsed: "))
interestRate = N*(pow(A/P, 1/(N*T))-1)*100
print("The interest rate is " + str(interestRate) + "%.")

Python - User Input For Arithmetic Progression [duplicate]

This question already has answers here:
accepting multiple user inputs separated by a space in python and append them to a list
(4 answers)
Closed 7 years ago.
I am trying to create a function that calculates the sum of an artithmetic sequence. I know how to set up the mathematical calculations but I don't know how to take input from the user to actually perform them.
How can I take user input (like below) such that the three ints on each line are read as A, B, N, with A being the first value
of the sequence, B being the step size and N the number of steps.
8 1 60
19 16 69
17 4 48
What should come next?
def arithmetic_progression():
a = raw_input('enter the numbers: ')
with raw_input you generally get a string
>> a = raw_input('enter the numbers')
you enter the numbers 8 1 60, so a will be a string '8 1 60'. Then you can split the string into the 3 substrings
>> b = a.split()
This will return you a list ['8', '1', '60']. Out of this you can get your numbers
>> A = int(b[0])
>> B = int(b[1])
>> N = int(b[2])
To read multiple lines you could add a function similar to this
def readlines():
out = raw_input('enter the numbers\n')
a = 'dummy'
while(len(a)>0):
a = raw_input()
out += '\n' + a
return out
This function would read any input and write it to the out string until you have one empty line. To get the numbers out of the string just do again the same as for a single line.
Sum to n terms of AP is: Sn = (n/2) [ 2a + (n-1)d ]
def arithmetic_progression():
inp = raw_input('enter the numbers: ').split(' ')
if not len(inp) == 3: # in case of invalid input
return arithmetic_progression() # prompt user to enter numbers again
a = float(inp[0])
d = float(inp[1])
n = float(inp[2])
s = ( (2 * a) + ((n - 1) * d) ) * (n / 2)
print('Sum to n terms of given AP is: ' + str(s))
arithmetic_progression()

Should I do anything to make my code more pythonic? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
This is a very simple piece of code that I wrote but if there is a way to make it more pythonic then I would love to know. Thanks!
def money():
current_salary = float(input("What is your current salary? "))
years = int(input("How many years would you like to look ahead? ")) + 1
amount_of_raise = float(input("What is the average percentage raise you think you will get? "))
amount_of_raise = amount_of_raise * 0.01
while years > 1:
years = years - 1
new_salary = current_salary + (current_salary * amount_of_raise)
current_salary = new_salary
print('Looks like you will be making', new_salary,' in ', years,'years.')
money()
Extended assignment operators
amount_of_raise = amount_of_raise * 0.01
years = years - 1
x = x * y can be shortened to x *= y. Same thing for -.
amount_of_raise *= 0.01
years -= 1
Iteration and counting
while years > 1:
years = years - 1
Counting down causes your printouts to display backwards. I would count up. The Pythonic way to count uses range:
for year in range(1, years + 1):
print('Looks like you will be making', new_salary,' in ', years,'years.')
Computing new salary
new_salary = current_salary + (current_salary * amount_of_raise)
current_salary = new_salary
I'd probably just simplify that to:
current_salary += current_salary * amount_of_raise
Or even better is to give a 5% raise by multiplying by 1.05. In code that is:
current_salary *= 1 + amount_of_raise

Categories

Resources