How to run a while loop in python using a Lambda - python

I am trying to learn Python and currently studying while loops and I am embarrassed to even ask this question cause I feel I should be able to do this, but I am very confused.
def summation(n, term):
"""Return the sum of numbers 1 through n (including n) wíth term applied to each number.
Implement using recursion!
>>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3
225
"""
assert n >= 1
"*** YOUR CODE HERE ***"
counter = 1
while counter <= n:
Also if there is any suggestions on where to practice while loops etc I will take any and all feedback, I have tried to google this but I cannot find anything.

This is how you can do it with a while loop:
def summation_while(n, term):
assert n >= 1
counter = 1
total = 0
while counter <= n:
total += term(counter)
counter += 1
return total
Test:
summation_while(5, lambda x: x**3)
Output:
225
You can also do this by summing a generator expression:
def summation_generator(n, term):
return sum(term(i) for i in range(1, n+1))

Related

Summation of multiples

I am learning python and can't get my head around this program.
I just can't seem to find the right loop to get the result.
Q:Create a Python function named sum Of Multiples that has two integer parameters x and n.
Example:sum Of Multiples(3,5);
Expected output:46
This is simple math, the sum is equivalent to 1 + x*(1+2+3+...+n), so 1 + x*(n*(n+1)//2):
def sumOfMultiples(x,n):
print(1+x*n*(n+1)//2)
sumOfMultiples(3, 5)
46
sum = 1 + x + 2x + 3x + ... +
could be written as sum = 1+x(0+1+2+3+...)
so just use a for loop from 0 to n or n+1 depending on where you're supposed to stop and multiply the result with x. Or even shorter use sum and range:
def sumOfMultiples(x, n):
print(1+sum(range(n+1))*x)
The question basically is asking you to sum all n mutliples of x. So just do this,
def sumOfMultiples(x, n):
m_sum = 1
for i in range(1, n+1):
m_sum += i*x
return m_sum
sumOfMultiples(3,5)
You can also do this,
sumOfMultiples = lambda x,n: sum([1] + [x*i for i in range(1, n+1)])
sumOfMultiples(3,5)
Let's just say this should get the job done, but not really optimized:
def sumOfMultiples(x,n):
x_muti = [1]
for i in range(1,n+1):
x_muti.append(x*i)
print(sum(x_muti))
sumOfMultiples(3,5)

return the only number in the range that is missing from the array

I am trying to use hash table to solve this question. The question description is: "Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array."
My approach so far is to import the dictionary and use it as a list. Then I am enumerating through the integer array that is given to me. So, for now, nums=[0,1,2,3,4,6]. I have to return number 5 as the missing number. After enumerating, I am trying to go over the items of the dictionary and see which number is missing. If the length of the v is none inside the index, then I will return this line int((((length * (length+1))/2) - sums))
from collections import defaultdict
class Solution(object):
def missingNumber(self, nums):
d = defaultdict(list)
length = len(nums)
sums = sum(nums)
for numbers, index in enumerate(nums):
d[index].append(numbers)
for k,v in d.items():
if len(v) == 0 :
return int((((length * (length+1))/2) - sums))
I am confused about how to show the if statement. Like how from the list it can be recognized that 5 is missing. Also, if there are more than 2 numbers are missing, then what approach will be the best to take? As if the example was: nums = [0,1,2,6,8]
Pardon for not having enough knowledge. I am just a beginner trying to practice questions everyday.
If you can use sum then no loop is required:
sum1 = sum(nums)
sum2 = sum(range(n))
missing_num = sum2 - sum1
Can we assume more than simply that the list contains indices with one missing? If, for example, we know that the list is sorted, we can get a logarithmic time solution using a binary search.
def bsearch(x: list[int]) -> int:
"""Return missing index in a sorted list."""
low, high = 0, len(x)
while low < high:
mid = (low + high) // 2
if x[mid] == mid:
# lower half have matching indices; explore upper
low = mid + 1
else:
# mid's value is too high; lower half has missing index
high = mid
return low
It exploits that below the missing value, i == x[i], but after the missing value, the array values are off by one, i == x[i] + 1. By testing the middle point in an interval, we can work out whether the missing element is to the left or right, and by doing this, we get a O(log n) solution.
If the elements are not sorted, you can of course sort them first and then do a binary search. A comparison sort would take O(n log n) and a bucket/radix sort O(n). There is nothing much good to say about first sorting the elements, then, as others have suggested, you can get the answer in O(n) without sorting.
I can try to explain that solution in a little more detail.
The sum of all numbers up to n is n * (n+1) // 2.
sum(range(n+1)) == n * (n+1) // 2
So
n*(n+1)//2 = 0 + 1 + 2 + ... + i-1 + i + i+1 + ... + n
The sum of the numbers that actually appear is sum(x), so if i is missing:
sum(x) = 0 + 1 + 2 + ... + i-1 + 0 + i+1 +... + n
Subtract the latter from the former and you get the missing value:
n*(n+1)//2: 0 + 1 + 2 + ... + i-1 + i + i+1 + ... + n
- sum(x): -(0 + 1 + 2 + ... + i-1 + 0 + i+1 + ... + n)
= 0 + 0 + 0 + ... + 0 + i + 0 + ... + 0
= i
so the solution is
def general_solution(x: list[int]) -> int:
return len(x) * (len(x) + 1) // 2 - sum(x)
Computing len(x) * (len(x) + 1) // 2 takes constant time, but sum(x) takes O(n), so the total running time is O(n).
If your array is sorted, the binary search approach will be much faster, but if the array is not sorted, a linear time solution isn't bad. There will certainly not be need for anything slower than O(n).
Hey this is my solution.
Subtract the sum of the elements in the list from the sum of the consecutive numbers you have (n * (n+1) / 2) and you will get the result.
class Solution:
def MissingNumber(self, nums):
l = len(nums)
total = l * (l + 1) / 2
sum_giv_list = sum(nums)
return total - sum_giv_list
You don't need a dict, you can do it in a for loop
for i in range(n)
if i not in nums:
return i
if you are not told what n is then you can do something like:
for i in range(nums[-1])
if i not in nums:
return i
if there are a possibility of more than one number missing then you can add them to a list before returning them
missing_nums = []
for i in range(nums[-1]):
if i not in nums:
missing_nums.append(i)
return missing_nums

How to find the sum of this series using loops

x - x^2/fact(2) + x^3/fact(3) ... -x^6/fact(6)
I tried various ways, even used nested 'for' loops, but I can't seem to figure out the code, any help?
you could try this; order defines how many terms should be taken into account:
def taylor(x, order=3):
x_n = x
fact = 1
sign = 1
res = 0
for n in range(2, order+2):
res += sign * x_n/fact
x_n *= x
fact *= n
sign = -sign
return res
for comparison (because this is the same function):
from math import exp
def real_funtion(x):
return 1-exp(-x)

Project Euler/Python: find sum of multiples of 3 and 5. Program not proceeding past input

I'm new to programming and i'm doing the Project Euler challenges to give me a reason to learn.
Find below my very simple python code
x = 1
thirdDivide = 0
fifthDivide=0
total = 0
print('Enter the max value')
maxValue = input()
while (x != maxValue):
thirdDivide = x / 3
fifthDivide = x / 5
if (thirdDivide).is_integer():
total = total + x
x = x + 1
elif (fifthDivide).is_integer():
total = total + x
x = x + 1
print ("The sum of the multiples of 3 and 5 between 0 and " + maxValue + " is " + total)
When I run it it asks for my max value, then ceases doing anything.
Thanks!
Assuming you are in Python 3, the fixes for using strings instead of floats, or floats instead of strings, infite loop is following:
x = 1
thirdDivide = 0
fifthDivide=0
total = 0
maxValue = float(input('Enter the max value: '))
while (x != maxValue):
thirdDivide = x / 3
fifthDivide = x / 5
if (thirdDivide).is_integer():
total = total + x
elif (fifthDivide).is_integer():
total = total + x
x = x + 1
print("The sum of the multiples of 3 and 5 between 0 and " + str(maxValue) + " is " + str(total))
Note, I dont check for correctness of your algoritm and whether it calculates what it is supposed to do. But now it produces some results and compiles.
You can solve it with a functional approach using filter and reduce:
def f(acc, v): return acc + v
def g(x): return x % 3 == 0 or x % 5 == 0
print reduce(f, filter(g, range(1000)))
How it works:
filter: takes two arguments:
The first is a function g applied for every element of range(1000). g takes one argument x and check if is multiple of 3 or 5 (checking the remainder of the modulo operation %).
The second is the range from 0 to 1000.
reduce: takes two arguments:
The first is a function f that takes two arguments: an accumulator acc and a variable v that represents the current element in the list.
The second argument is the filtered range returned before by filter.
Output:
with range(10) = 23
with range(1000) = 233168
Using lambda functions (same logic just different syntax):
print reduce(lambda acc, v: acc + v, filter(lambda x: x % 3 == 0 or x % 5 == 0, range(1000)))
You only increment x if thirdDivide.is_integer() or fifthDivide.is_integer() are true. So if neither it true, you'll just loop infinitely on the same value of x.
If neither thirdDivide nor fifthDivide is an integer, x is never updated -- you enter an infinite loop. You need to make sure you have a "base case" so that the iteration variable is always changing. Here's a slightly cleaner algorithm:
total = 0
for i in range(0, x):
if i % 3 == 0 or i % 5 == 0:
total += i
I think you'll find that for most iteration, for loops are easier to reason about. Happy coding!
As many said before, you are stuck in an infinite loop with x not being incremented. If you added a "else" statement at the end and printed the output you could see what they are talking about. You can do this in one line of code.
print(sum(x for x in range(maxValue) if x % 3 == 0 or x % 5 == 0))

Python for-loop counter error

I am attempting to script a short code to figure out the number of days it takes to reach a given principal in the bank due to daily interest. Using my code below does not yield any errors when run in IDLE, but the counter returns 0. Any ideas what I missed?
def main():
# irrelevant code elided by msw, Bal, Int and Tar are numeric
counter = 0
for i in range(0):
if (Bal * Int) == Tar:
print '1'
else:
counter + 1
print counter
I'm not sure what you're getting at with this loop:
for i in range(0):
if (Bal * Int) == Tar:
print '1'
else:
counter + 1
range(0) is an empty list, so the loop won't execute at all.
counter + 1 simply calculates one more than counter, it won't increment counter, you probably mean counter += 1
There's nothing in the loop that changes at each iteration, so if you ever get into it, it will be an infinite loop.
I believe the formula to calculate final balance with interest is:
Final = Principal * ( 1 + interest ) ** interest_period
Assuming I got this correct, then you can find out how many interest periods it will take by:
def how_long(start_money, interest_rate, final_money):
day = 0
money = start_money
while True:
if money >= final_money:
break
day += 1
money = start_money * (1 + interest_rate)**day
return day, money
In [5]: def test():
...: for i in range(0):
...: return '1'
...:
...:
In [6]: x = test()
In [7]: print x
------> print(x)
None
See the return value is 'None'.
I don't know what are you trying to do. But The basic mistake is the Argument of range(x) function. The range(0) always return empty list.
That's because you put range(0) which is an empty loop. Perhaps you could consider a while loop?
Your loop for i in range(0) doesn't actually execute. range(0) returns an empty list [] which will skip the body of your for loop.
Please explain what you think this does? Please update your question with an English-language explanation of how many times you think this look will work.
counter = 0
for i in range(0):
if (Bal * Int) == Tar:
print '1'
else:
counter + 1
Hint. The answer is zero. The question is "why?" and "what were you trying to do?"
You have been told the three or more problems with your code. If there's no particular reason to use a loop, it's better calculated with a formula:
future_value = present_value * (1 + interest_rate_per_period) ** number_of periods
or, for short,
f = p * (1 + i) ** n
f / p = (1 + i) ** n
log(f / p) = n * log(1 + i)
n = log(f / p) / log(i + i)
Example: I have $5000; how many years will it take to grow to $10000 at 10% per annum?
>>> from math import log
>>> f = 10000.0
>>> p = 5000.0
>>> i = 0.1
>>> n = log(f / p) / log(1 + i)
>>> n
7.272540897341713
>>>

Categories