Im new to programming and python. I need help with coding a geometric progression thats supposed to calculate the progression 1,2,4,8,16... Heres what I have so far:
def work_calc (days_worked, n):
temp=int(1)
if days_worked<2:
print (1)
else:
while temp <= days_worked:
pay1 = (temp**2)
pay = int(0)
pay += pay1
temp +=1
print ('your pay for ',temp-1,'is', pay1)
main()
Right now it gives me this output: 1, 4, 9, 16, 25
i need : 1,2,4,8,16,32...
im writing code that basically should do this:
Example:
Enter a number: 5
your value 1 is: 1
your value 2 is : 2
your value 3 is : 4
your value 4 is : 8
your value 5 is : 16
your total is: 31
Thanks in advance for your help and guidance!
P.S: Im like a dumb blonde sometimes(mostly) when it comes to programming, so thanks for your patience..
As I said, looks like you need powers of 2:
def work_calc (days_worked, n):
for temp in range(days_worked):
print ('your pay for ', temp + 1, 'is', 2 ** temp)
if you want to print strings (not tuples as you're doing now):
def work_calc (days_worked):
for temp in range(days_worked):
print 'your pay for {} is {}'.format(temp + 1, 2 ** temp)
>>> work_calc(5)
your pay for 1 is 1
your pay for 2 is 2
your pay for 3 is 4
your pay for 4 is 8
your pay for 5 is 16
Just to note - your code is calculating squares of temp, not powers of 2 that's why is not working
I understand this is probably overkill for what you are looking to do and you've been given great advice in the other answers in how to solve your problem but to introduce some other features of python here are some other approaches:
List comprehension:
def work_calc(days):
powers_of_two = [2**x for x in range(days)]
for i, n in enumerate(powers_of_two):
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(sum(powers_of_two)))
This is compact and neat but would hold the whole list of 2^n in memory, for small n this is not a problem but for large could be expensive. Generator expressions are very similar to list comprehensions but defer calculation until iterated over.
def work_calc(days):
powers_of_two = (2**x for x in range(days))
total = 0
for i, n in enumerate(powers_of_two):
total += n
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(total))
Had to move the total to a rolling calculation and it still calculates 2**n each time, a generator function would avoid power calculation:
import itertools
def powers_of_two():
n = 1
while True:
yield n
n *= 2
def work_calc(days):
total = 0
for i, n in enumerate(itertools.islice(powers_of_two(), days)):
total += n
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(total))
As I said overkill, but hopefully introduces some of the other features of python.
Is this a homework question? (insufficient rep to comment)
In the sequence 1,2,4,8,16,32 each term is double the previous term.
So, you can keep a record of the previous term and double it to get the next one.
As others have mentioned, this is the same as as calculating 2^n (not, as I previously stated, n^2) , where n is the number of terms.
print ('your pay for 1 is' 1)
prevpay = 1
while temp <= days_worked:
pay1 = prevpay*2
pay = int(0)
pay += pay1
temp +=1
prevpay = pay1
print ('your pay for ',temp-1,'is', pay1)
That is all too complicated. Try always to keep things as simple as possible and especially, keep your code readable:
def main():
i = int(input("how many times should I double the value? "))
j = int(input("which value do you want to be doubled? "))
double_value(i,j)
def double_value(times,value):
for i in range(times):
i += 1
value = value + value
print(f"{i} --- {value:,}")
main()
Hope I could help.
Related
My task is to find how many times we need to multiply digits of a number until only one digit left and count how many "turns" we need to take until that 1 digit left.
Example:
39 -> 3*9=27 -> 2*7=14 -> 1*4=4, so the answer should be 3.
So far I got:
def persistence(n):
count = 1
sum = int(str(n)[0:1]) * int(str(n)[1:2])
while(n > 0 or sum > 9):
sum = int(str(sum)[0:1]) * int(str(sum)[1:2])
count = count + 1
print(sum)
print("how many times: " + count)
persistence(39)
So how I approached this task:
I take first 2 digits convert them to str and multiply them.
Already with first sum I go to while loop and keep repeating that.
So, my problem is that I keep getting this:
How can I solve it? Or should I try to approach this task differently?
You only have a couple of problems.
The while loop keeps checking n. It only needs to check sum
The final print tries to add an int to a str. Just use print arguments instead.
def persistence(n):
count = 1
sum = int(str(n)[0:1]) * int(str(n)[1:2])
while sum > 9:
sum = int(str(sum)[0:1]) * int(str(sum)[1:2])
count = count + 1
print(sum)
print("how many times: ", count)
persistence(39)
Output as expected.
However, you should not use sum as the name of a variable. You can reuse n instead:
def persistence(n):
count = 1
n = int(str(n)[0:1]) * int(str(n)[1:2])
while n > 9:
n = int(str(n)[0:1]) * int(str(n)[1:2])
count = count + 1
print(n)
print("how many times: ", count)
This should work.
def returnLength(n):
return len(str(n))
def returnProduct(n, pro=1):
n = str(n)
for i in n:
pro *= int(i)
return pro
n = int(input())
c = 0
while returnLength(n) != 1:
n = returnProduct(n)
c += 1
print(c)
So basically at the start my program had Achilles heel, because it's failed when I had 3+ digit number. I read every suggestion very carefully and my final code went like this:
def persistence(n):
def returnLength(n):
return len(str(n))
def returnProduct(n, pro=1):
n = str(n)
for i in n:
pro *= int(i)
return pro
c = 0
while n > 9:
n = returnProduct(n)
c += 1
print(c)
However, I still couldn't pass the test nevertheless everything worked fine on VScode and I did some random manual testing (I'm practicing at codewars.com and a lot of people wrote that on this task's test might have a bug). It might be that I can have only one def. I will try to figure that out. Once again, thank you all.
The program asks the user for a number N.
The program is supposed to displays all numbers in range 0-N that are "super numbers".
Super number: is a number such that the sum of the factorials of its
digits equals the number.
Examples:
12 != 1! + 2! = 1 + 2 = 3 (it's not super)
145 = 1! + 4! + 5! = 1 + 24 + 120 (is super)
The part I seem to be stuck at is when the program displays all numbers in range 0-N that are "super numbers". I have concluded I need a loop in order to solve this, but I do not know how to go about it. So, for example, the program is supposed to read all the numbers from 0-50 and whenever the number is super it displays it. So it only displays 1 and 2 since they are considered super
enter integer: 50
2 is super
1 is super
I have written two functions; the first is a regular factorial program, and the second is a program that sums the factorials of the digits:
number = int(input ("enter integer: "))
def factorial (n):
result = 1
i = n * (n-1)
while n >= 1:
result = result * n
n = n-1
return result
#print(factorial(number))
def breakdown (n):
breakdown_num = 0
remainder = 0
if n < 10:
breakdown_num += factorial(n)
return breakdown_num
else:
while n > 10:
digit = n % 10
remainder = n // 10
breakdown_num += factorial(digit)
#print (str(digit))
#print(str(breakdown_num))
n = remainder
if n < 10 :
#print (str(remainder))
breakdown_num += factorial(remainder)
#print (str(breakdown_num))
return breakdown_num
#print(breakdown(number))
if (breakdown(number)) == number:
print(str(number)+ " is super")
Existing answers already show how to do the final loop to tie your functions together. Alternatively, you can also make use of more builtin functions and libraries, like sum, or math.factorial, and for getting the digits, you can just iterate the characters in the number's string representation.
This way, the problem can be solved in a single line of code (though it might be better to move the is-super check to a separate function).
def issuper(n):
return sum(math.factorial(int(d)) for d in str(n)) == n
N = 1000
res = [n for n in range(1, N+1) if issuper(n)]
# [1, 2, 145]
First I would slightly change how main code is executed, by moving main parts to if __name__ == '__main__', which will execute after running this .py as main file:
if __name__ == '__main__':
number = int(input ("enter integer: "))
if (breakdown(number)) == number:
print(str(number)+ " is super")
After that it seems much clearer what you should do to loop over numbers, so instead of above it would be:
if __name__ == '__main__':
number = int(input ("enter integer: "))
for i in range(number+1):
if (breakdown(i)) == i:
print(str(i)+ " is super")
Example input and output:
enter integer: 500
1 is super
2 is super
145 is super
Small advice - you don't need to call str() in print() - int will be shown the same way anyway.
I haven't done much Python in a long time but I tried my own attempt at solving this problem which I think is more readable. For what it's worth, I'm assuming when you say "displays all numbers in range 0-N" it's an exclusive upper-bound, but it's easy to make it an inclusive upper-bound if I'm wrong.
import math
def digits(n):
return (int(d) for d in str(n))
def is_super(n):
return sum(math.factorial(d) for d in digits(n)) == n
def supers_in_range(n):
return (x for x in range(n) if is_super(x))
print(list(supers_in_range(150))) # [1, 2, 145]
I would create a lookup function that tells you the factorial of a single digit number. Reason being - for 888888 you would recompute the factorial of 8 6 times - looking them up in a dict is much faster.
Add a second function that checks if a number isSuper() and then print all that are super:
# Lookup table for single digit "strings" as well as digit - no need to use a recursing
# computation for every single digit all the time - just precompute them:
faks = {0:1}
for i in range(10):
faks.setdefault(i,faks.get(i-1,1)*i) # add the "integer" digit as key
faks.setdefault(str(i), faks [i]) # add the "string" key as well
def fakN(n):
"""Returns the faktorial of a single digit number"""
if n in faks:
return faks[n]
raise ValueError("Not a single digit number")
def isSuper(number):
"Checks if the sum of each digits faktorial is the same as the whole number"
return sum(fakN(n) for n in str(number)) == number
for k in range(1000):
if isSuper(k):
print(k)
Output:
1
2
145
Use range.
for i in range(number): # This iterates over [0, N)
if (breakdown(number)) == number:
print(str(number)+ " is super")
If you want to include number N as well, write as range(number + 1).
Not quite sure about what you are asking for. From the two functions you write, it seems you have solid knowledge about Python programming. But from your question, you don't even know how to write a simple loop.
By only answering your question, what you need in your main function is:
for i in range(0,number+1):
if (breakdown(i)) == i:
print(str(i)+ " is super")
import math
def get(n):
for i in range(n):
l1 = list(str(i))
v = 0
for j in l1:
v += math.factorial(int(j))
if v == i:
print(i)
This will print all the super numbers under n.
>>> get(400000)
1
2
145
40585
I dont know how efficient the code is but it does produce the desired result :
def facto():
minr=int(input('enter the minimum range :')) #asking minimum range
maxr=int(input('enter the range maximum range :')) #asking maximum range
i=minr
while i <= maxr :
l2=[]
k=str(i)
k=list(k) #if i=[1,4,5]
for n in k: #taking each element
fact=1
while int(n) > 0: #finding factorial of each element
n=int(n)
fact=fact*n
n=n-1
l2.append(fact) #keeping factorial of each element eg : [1,24,120]
total=sum(l2) # taking the sum of l2 list eg 1+24+120 = 145
if total==i: #checking if sum is equal to the present value of i.145=145
print(total) # if sum = present value of i than print the number
i=int(i)
i=i+1
facto()
input : minr =0 , maxr=99999
output :
1
2
145
40585
I've been self-teaching Python for the last month. I have an interview for a coding course and need help on writing a program which uses a while loop.
The task is as follows:
Write a program that asks the user to type in 5 numbers, and that outputs the largest of these numbers and the smallest of these numbers. So, for example, if the user types in the numbers 2456 457 13 999 35, the output would be:
The largest number is 2456
The smallest number is 13
Thanks for your help.
Here you go
numbers = [] #this will be the list in which we will store the numbers
while len(numbers) < 5: #len return the length of your list, we want our while loop to repeat 5 times
numbers.append(double(input("enter number: "))) # adds the inputed number to the list
print("The largest number is",max(numbers),"The smallest number is",min(numbers))
Next time you ask questions, please include at least some of your progress so that everyone is willing to help you.
When you learn a language, a good coding style is also important.
Here is an answer for you. I hope you can learn something. You can also try using max() and min() with a list.
input_times = 5
max_num, min_num = -float('inf'), float('inf')
while input_times:
input_times -= 1
try:
num = int(input('Please enter a number:\n'))
if num < min_num:
min_num = num
if num > max_num:
max_num = num
except:
print("Please input an integer!")
input_times += 1
print('The largest number is {max_num} The smallest number is {min_num}'.format(
max_num = max_num, min_num = min_num))
def max_min():
my_list = []
for i in range(1, 6):
temp_val = input("Enter number {}: ".format(i))
my_list.append(int(temp_val))
max_val = max(my_list)
min_val = min(my_list)
return "max value is {} and min value is {}".format(max_val, min_val)
print(max_min())
I am in a beginner programming course. We must do an exercise where we make a change maker program. The input has to be between 0-99 and must be represented in quarters, dimes, nickles, and pennies when the input is divided down between the four. I wrote a code that involved loops and whiles, but he wants something more easy and a smaller code. He gave me this as a way of helping me along:
c=int(input('Please enter an amount between 0-99:'))
print(c//25)
print(c%25)
He told us that this was basically all we needed and just needed to add in the dimes, nickles, and pennies. I try it multiple ways with the dimes, nickles, and pennies, but I cannot get the output right. Whenever I enter '99', I get 3 for quarters, 2 for dimes, 1 for nickles, and 0 for pennies. If anyone would be able to help me, that would be wonderful!
I'm now sure about what you want to achieve. Using the modulo operator you could easily find out how many quarters, dimes, nickles and pennies.
Let's just say you input 99.
c=int(input('Please enter an amount between 0-99:'))
print(c//25, "quarters")
c = c%25
print(c//10, "dimes")
c = c%10
print(c//5, "nickles")
c = c%5
print(c//1, "pennies")
this would print out:
3 quarters
2 dimes
0 nickles
4 pennies
n = int(input("Enter a number between 0-99"))
q = n // 25
n %= 25
d = n // 10
n %= 10
ni = n // 5
n %= 5
c = n % 5
print(str(q) +" " + str(d) +" " + str(ni) + " " + str(c))
I hope this helps? Something like this but don't just copy it. Everytime you divide by 25 10 5 you must lose that part because it's already counted.At the end print what ever you want :).
The actual trick is knowing that because each coin is worth at least twice of the next smaller denomination, you can use a greedy algorithm. The rest is just implementation detail.
Here's a slightly DRY'er (but possibly, uh, more confusing) implementation. All I'm really doing differently is using a list to store my results, and taking advantage of tuple unpacking and divmod. Also, this is a little easier to extend in the future: All I need to do to support $1 bills is to change coins to [100, 25, 10, 5, 1]. And so on.
coins = [25,10,5,1] #values of possible coins, in descending order
results = [0]*len(coins) #doing this and not appends to make tuple unpacking work
initial_change = int(input('Change to make: ')) #use raw_input for python2
remaining_change = initial_change
for index, coin in enumerate(coins):
results[index], remaining_change = divmod(remaining_change, coin)
print("In order to make change for %d cents:" % initial_change)
for amount, coin in zip(results, coins):
print(" %d %d cent piece(s)" % (amount, coin))
Gives you:
Change to make: 99
In order to make change for 99 cents:
3 25 cent piece(s)
2 10 cent piece(s)
0 5 cent piece(s)
4 1 cent piece(s)
"""
Change Machine - Made by A.S Gallery
This program shows the use of modulus and integral division to find the quarters, nickels, dimes, pennies of the user change !!
Have Fun Exploring !!!
"""
#def variables
user_amount = float(input("Enter the amount paid : "))
user_price = float(input("Enter the price : "))
# What is the change ?? (change calculation)
user_owe = user_amount - user_price
u = float(user_owe)
print "Change owed : " + str(u)
"""
Calculation Program (the real change machine !!)
"""
# Variables for Calculating Each Coin !!
calculate_quarters = u//.25
# Using the built-in round function in Python !!
round(calculate_quarters)
print "Quarters : " + str(calculate_quarters)
u = u%0.25
calculate_dime = u//.10
round(calculate_dime)
print "Dime : " + str(calculate_dime)
u = u%0.10
calculate_nickels = u//.05
round(calculate_nickels)
print "Nickels : " + str(calculate_nickels)
u = u%0.5
calculate_pennies = u//.01
round(calculate_pennies)
print "Pennies : " + str(calculate_pennies
Code for the change machine works 100%, its for CodeHs Python
This is probably one of the easier ways to approach this, however, it can also
be done with less repetition with a while loop
cents = int(input("Input how much money (in cents) you have, and I will tell
you how much that is is quarters, dimes, nickels, and pennies. "))
quarters = cents//25
quarters_2 = quarters*25
dime = (cents-quarters_2)//10
dime_2 = dime*10
nickels = (cents-dime_2-quarters_2)//5
nickels_2 = nickels*5
pennies = (cents-dime_2-quarters_2-nickels_2)
I am planning to create a program which basically lists the Fibbonacci sequnce up to 10,000
My problem is that in a sample script that I wrote I keep getting the error 'int' object is not iterable
My aim is that you enter a number to start the function's loop.
If anyone would help out that would be great
P.S I am a coding noob so if you do answer please do so as if you are talking to a five year old.
Here is my code:
def exp(numbers):
total = 0
for n in numbers:
if n < 10000:
total = total + 1
return total
x = int(input("Enter a number: "), 10)
exp(x)
print(exp)
numbers is an int. When you enter the number 10, for example, the following happens in exp():
for n in 10:
...
for loops through each element in a sequence, but 10 is not a sequence.
range generates a sequence of numbers, so you should use range(numbers) in the for loop, like the following:
for n in range(numbers):
...
This will iterate over the numbers from 0 to number.
As already mentioned in comments, you need to define a range -- at least this is the way Python do this:
def exp(numbers):
total = 0
for n in range(0, numbers):
if n < 10000:
total = total + 1
return total
You can adjust behavior of range a little e.g. interval is using. But this is another topic.
Your code is correct you just need to change :
for n in numbers:
should be
for n in range(0, numbers)
Since you can iterate over a sequence not an int value.
Good going, Only some small corrections and you will be good to go.
def exp(numbers):
total = 0
for n in xrange(numbers):
if n < 10000:
total += 1
return total
x = int(input("Enter a number: "))
print exp(x)