For a section of my programming assignment I want to do the following.
In the level 1 I have an input number (N) which I'm dividing by another number(X).In the next level same input number (N) is divided by X*2. Likewise I want to go on calculating until the final result becomes less than or equal to 1.
For instance if X=8 and N=2 in first run I will divide 8/2=4
In the next run I will divide 8/4 which is 2
In the last run I will divide 8/8 which is 1
I'm trying to implement this in python. I have the basic idea of the code as follows:
def myFunc(n, x):
first_level=n/ x
next_level = n /x * 2
............
if result <=1:
break
myFunc(8, 2)
But I don't understand how to iterate calculating the possible next levels. Please help.
You can use a recursive function: Added the print to show that the result is equal to 1.
def myFunc(n, x):
result=n/ x
if result <=1:
print result
else:
myFunc(n,x*2)
myFunc(8, 2)
Or to get the levels you can use a global variable:
count = 1
def myFunc(n, x):
global count
count = count + 1
result=n/ x
if result <=1:
print result
else:
myFunc(n,x*2)
myFunc(8, 2)
print count
Here is a sample function that does this via iterating!
The key here is to set a temporary variable which keeps track of the current value of the loop, thus allowing you to make the division.
def myFunc(n, x):
i = 1
interim_result = n
while interim_result > 1:
interim_result = n / float(x**i) # I guess you're working with integers, but just in case
print "This is loop number: " + str(i) + " with result: " + str(interim_result)
i = i + 1
myFunc(8, 2)
Hope this is clear.
Related
I was writing the solution to this codewars problem however I've ran into a bit of an issue.
Problem statement:
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit, e.g.:
persistence(39) # returns 3, because 39=27, 27=14, 1*4=4 and 4 has only one digit
def persistence(n, t=1, x=0):
if len(str(n)) > 1:
number = [int(i) for i in str(n)]
for i in number:
t = t * i
if len(str(t)) > 1:
x += 1
return(persistence(t,x))
else:
return(x)
else:
return 0
I can't quite figure out what the error is in this code. My hunch is that it's either a parameter error or the way the return() value is placed.
In essence, the code for distilling an integer to it's multiples is correct, so I just added an extra parameter to persistence; setting x = 0 and making it so that each time the if condition was fulfilled it would increment that exact x value. Once the number was distilled, simply output x. Yet it continues to simply output 0 as the final answer. What's the problem here?
Edit: Solution was in the comments, didn't realise how the parameters were passing. Correct version is:
return(persistence(t,1,x))
Also had to set x = 1 for the logic to work on codewars.
There are 2 flaws in Your code:
return(persistence(t,x))
should be
return(persistence(t,1,x))
otherwise the value of x will be assigned to t and x will be defaulted to 0.
Then you must increment x directly after the first test, otherwise You will miss one iteration.
Another way to calculate this is not to switch over to strings, but to do it numerically:
def persistence(n):
iterations = 0; # no iterations yet
while n > 9: # while n has more than 1 digit:
product = 1 # neutrum for result product
while n > 0: # while there a digit to process:
digit = n % 10 # retrieve the right most digit
product *= digit # do the multiplication
n = n // 10 # cut off the processed digit
iterations += 1 # increment iterations
n = product # let n be the newly calculated product
return iterations # return the result
I think you your function's parameters work not as you expect them to do.
When you call function persistence(t, x), the first argument n should become t, and second argument x, should become new x. But in your function, x becomes new t because of their position.
It is quite useful to have bunch of print statements to reveal the bug.
def persistence(n, x=1, t=1):
print('x:', x)
if len(str(n)) > 1:
number = [int(i) for i in str(n)]
for i in number:
t = t * i
print('t:', t)
if len(str(t)) > 1:
x += 1
print('x has changed:', x)
return persistence(t, x)
else:
return x
else:
return 0
print(persistence(39))
print('---------------')
print(persistence(999))
print('---------------')
print(persistence(4))
Passes all test cases with two changes:
You were not updating your n with the new t everytime
Your x was being set to 0 every time. That should be set to 1 in the beginning (default value)
def persistence(n, t=1, x=1):
if len(str(n)) > 1:
number = [int(i) for i in str(n)]
for i in number:
t = t * i
if len(str(t)) > 1:
x += 1
return (persistence(n=t, x=x))
else:
return (x)
else:
return 0
Actually, you can write it without needing both parameters t and n. Just one n is fine as shown below:
def persistence(n, x=1):
if len(str(n)) > 1:
number = [int(i) for i in str(n)]
t = 1
for i in number:
t = t * i
if len(str(t)) > 1:
return x + (persistence(n=t, x=x))
else:
return (x)
else:
return 0
I'm new to programming and I'm trying to write a program in Python that will find the sum of the even numbers of the numbers below 4,000,000 in the Fibonacci sequence. I'm not sure what I'm doing wrong but nothing will print. Thanks for any help.
def fib():
listx = []
for x in range(4000000):
if x == 0:
return 1
elif x == 1:
return 1
else:
listx.append(fib(x - 1) + fib(x - 2))
return listx
def evens(fib):
y = 0
for x in fib():
if x % 2 == 0:
y += x
else:
continue
print (y)
Here's an approach that uses a generator to keep memory usage to a minimum:
def fib_gen(up_to):
n, m = 0, 1
while n <= up_to:
yield n
n, m = m, n + m
total = 0
for f in fib_gen(4000000):
if f % 2 == 0:
total += f
Another option:
def fib_gen(up_to, filter):
n, m = 0, 1
while n <= up_to:
if filter(n):
yield n
n, m = m, n + m
sum(fib_gen(4000000, lambda f: f % 2 == 0)) # sum of evens
sum(fib_gen(4000000, lambda f: f % 2)) # sum of odds
First things first, there appears to be some contention between your requirements and the code you've delivered :-) The text of your question (presumably taken from an assignment, or Euler #2) requests the ...
sum of the even numbers of the numbers below 4,000,000 in the Fibonacci sequence.
Your code is summing the even numbers from the first four million Fibonacci numbers which is vastly different. The four millionth Fibonacci number has, according to Binet's formula, north of 800,000 digits in it (as opposed to the seven digits in the highest one below four million).
So, assuming the text to be more correct than the code, you don't actually need to construct a list and then evaluate every item in it, that's rather wasteful on memory.
The Fibonacci numbers can be generated on the fly and then simply accumulated if they're even. It's also far more useful to be able to use an arbitrary method to accumulate the numbers, something like the following:
def sumFibWithCond(limit, callback):
# Set up initial conditions.
grandparent, parent, child = 0, 0, 1
accum = 0
# Loop until number is at or beyond limit.
while child < limit:
# Add any suitable number to the accumulator.
accum = accum + callback(child)
# Set up next Fibonacci cycle.
grandparent, parent = parent, child
child = grandparent + child
# Return accumulator when done.
return accum
def accumulateEvens(num):
# Return even numbers as-is, zero for odd numbers.
if num % 2 == 0:
return num
return 0
sumEvensBelowFourMillion = sumFibWithCond(4000000, accumulateEvens)
Of special note is the initial conditions. The numbers are initialised to 0, 0, 1 since we want to ensure we check every Fibonacci number (in child) for the accumulating condition. This means the initial value of child should be one assuming, as per the question, that's the first number you want.
This doesn't make any difference in the current scenario since one is not even but, were you to change the accumulating condition to "odd numbers" (or any other condition that allowed for one), it would make a difference.
And, if you'd prefer to subscribe to the Fibonacci sequence starting with zero, the starting values should be 0, 1, 0 instead.
Maybe this will help you.
def sumOfEvenFibs():
# a,b,c in the Fibonacci sequence
a = 1
b = 1
result = 0
while b < 4000000:
if b % 2 == 0:
result += b
c = a + b
a = b
b = c
return result
I'm new to programming and was asked to sum odd numbers from 1 to (2*n)-1 using a while loop.
This is my attempt:
def sum_odd_n(n):
while n<2*n:
sum = 0
if n%2==1:
sum = sum+n
return (sum)
May i know my mistake? Any help will be appreciated
The condition while n<2*n: is always true while n >= 0, you'll have an infinite loop. Try the following
def sum_odd(n):
value = 1
total = 0
while value < (2*n) - 1:
if value % 2 == 1:
total += value
value += 1
return total
>>> sum_odd(25)
576
For completeness the more pythonic way to handle this would be using sum with a generator expression
def sum_odd(n):
return sum(i for i in range(1, 2*n -1) if i%2 == 1)
The first hint would be to take a look at your condition in while loop:
while n < 2*n
Notice that this will always be true, because if n>0, then 2*n is always greater. If you need more help, write a comment ;)
UPDATE: I will just tell you what is wrong so if you want to try it out first on your own, stop reading. So basically you need another variable, let's say i that will loop through integers. Then you can do something like this:
def sum_odd_n(n):
i = n
sum = 0
while i < 2*n:
if i % 2 == 1:
sum += i
i += 1
print sum # for python3: print(sum)
>>> def sum_odd_n(n):
... return sum([2 ** i for i in range(0,n,1) ])
...
>>> sum_odd_n(2)
3
>>> sum_odd_n(5)
31
>>>
I'll try to point out the mistakes you have done, and try to offer corrections.
def sum_odd_n(n):
while n<2*n: # n will always be less than ('<') 2*n. For eg, if n=5, 5<10.
sum = 0 # you are resetting the sum at every iteration. We need to take this outside.
if n%2==1:
sum = sum+n
return (sum)
Here's what I think should work.
def sum_odd_n(n):
sum = 0 # sum is initialized here, so that it doesn't reset inside the loop
iterator = 0
while iterator<2*n
if iterator%2==1:
sum = sum+iterator # or sum += iterator
iterator = iterator + 1 # otherwise this will be an infinite loop, as iterator will always be 0.
return sum
Hope this works for you. :-)
This worked for me:
def sum_odd(n: int):
total = 0
for x in range(2*n):
if x%2==1:
total += x
return total
Define a function named nested_increasing_additions(n) which receives one positive integer (n) and returns a string as illustrated in the following examples:
If n is 3, the function should return the string:
1+..1+2+..1+2+3+..
If n is 5, the function should return the string:
1+..1+2+..1+2+3+..1+2+3+4+..1+2+3+4+5..+
What I think is, I can make n to a list [1,2,3] and use while loop or for loop to repeat n times. For the first loop it returns 1+.., for the second loop it returns 1+2.. somehow (which i don't know) it stops at 2 which is the same as the repeating time.
I don't know if I'm thinking it right. Need some help and explanations! Thank you!
Consecutive evaluations of these strings results in a sequence of tetrahedral numbers. For example, for input 5, the output evaluates to 35. This is the number of spheres you would need to build a tetrahedron of side length 5.
To see how it relates to the sum in the question, note that the discrete "volume" of the tetrahedron would be equal to the sum of the triangle "slices" from top to bottom.
35 = 1 + 3 + 6 + 10 + 15
= 1 + (1+2) + (1+2+3) + (1+2+3+4) + (1+2+3+4+5)
By a similar argument, the triangular numbers are made up of slices of consecutive integers.
Please excuse the maths, it was difficult (but not impossible) to adapt a closed-form solution into the desired output format.
def tetrahedral(n):
return n*(n+1)*(n+2)//6
def string_generator(n):
x = tetrahedral(n)
n = N = 1
while x > 0:
while n <= N:
yield str(n) + '+'
n += 1
x -= N*(N+1)//2
n = 1
N += 1
yield '..'
def nested_increasing_additions(n):
return ''.join(string_generator(n))
You can build the complete string step by step, and remember at each step what you have added last:
def nested_increasing_additions(n):
complete_string = ""
add_string = ""
for i in range(1,n+1):
add_string += str(i) + "+"
complete_string += add_string + ".."
return complete_string
print(nested_increasing_additions(1))
print(nested_increasing_additions(3))
print(nested_increasing_additions(5))
The output with python3 is:
1+..
1+..1+2+..1+2+3+..
1+..1+2+..1+2+3+..1+2+3+4+..1+2+3+4+5+..
def nested_increasing_additions(n):
l=['']
for i in range(1, n+1):
l.append(l[-1]+str(i)+'+')
return '..'.join(l[1:])
This returns a string without the .. at the end. If you want that, just do return '..'.join(l[1:]) + '..'
you can use something like this.
def nested_increasing_additions(n):
string = ""
for i in range(1,n+1): #1
for j in range(1,i+1): #2
string += str(j)+"+" #4
string += ".." #5
print(string)
here is a printout of nested_increasing_additions(4)
1+..1+2+..1+2+3+..1+2+3+4+..
i think it's self explanatory, nothing complicated.
How's this:
def nested_increasing_additions(n):
string = ""
new_string = ""
dot = ".."
for i in range(1, n+1):
new_string+=('{}+'.format(i))
string = string+new_string+dot
print(string)
return (string)
Output:
nested_increasing_additions(3)
'1+..1+2+..1+2+3+..'
Assuming you did want the ".." at the end of each returned string and that recursion is OK, here's a solution:
def nested_increasing_additions(n):
if n == 1:
return "1+.."
else:
return nested_increasing_additions(n-1) + '%s+..' % '+'.join(str(i) for i in range(1, n+1))
print(nested_increasing_additions(3))
print(nested_increasing_additions(5))
type(nested_increasing_additions(1))
Prints:
1+..1+2+..1+2+3+..
1+..1+2+..1+2+3+..1+2+3+4+..1+2+3+4+5+..
<type 'str'>
Explanation:
The first return and if (true) block ends the recursive call when the passed in argument value reaches 1 via subtraction from the other half.
The second half (else block) calls the next iteration with n subtracted by 1 and the string build of the current iteration (if n!=1).
The complicated looking code '%s+..' % '+'.join(str(i) for i in range(1, n+1)) is just concatenation of a list of numbers generated by the range function, turned into strings and "+.."
range(1, n+1) returns a list of integers starting with 1 until n+1 so range(1,3) yields [1,2]. This is passed to join which places a + between each number.
I can get the answer of cubes but I don't really know where to go from here to get the function to return back the answer and keep adding it to a sum! What do I have to do to make it keep adding to get a total?
def sumNCubes(n):
for i in range(n)
return (n-1)**3
def main():
number = int(raw_input("What number do you want to find the sum of cubes for?"))
n = number + 1
for i in range(number):
n = n - 1
print "The result of the sums is:", sumNCubes(n)
main()
You could simply do something like this:
def sumNCubes(n):
return sum(i**3 for i in range(1,n+1))
which uses a list comprehension to cube number in a range from 1-n+1 (1-n will not include n) then uses python built in sum function to sum all of the cubes.
you could then just pass in your input and print it:
def main():
number = int(raw_input("What number do you want to find the sum of cubes for?"))
#this doesn't do anything but change n to 0
#for i in range(number):
# n = n - 1
print "The result of the sums is:", sumNCubes(number)
main()
with input of, for example, 5, this will return:
>>> sumNCubes(5)
225
The answer is very simple. This will be given by recursive approach.
Here is the function to find sum of N numbers and you were very close in getting this
def sumNcubes(n):
if (n == 1):
return 1
else:
return n**3 + sumNcubes(n-1)
>>>sumNcubes(6)
441
Without using n**3
def sum_cubes (n):
b, c, sum = 1, 0, 0
for a in range(0, 6*n, 6):
sum += (c := c + (b := b + a))
return sum
Without a loop
def sum_cubes (n):
return (n*(n+1)//2)**2