How can I interact with the values of a generator expression? For instance:
def sumValues(*args):
# compute the sum of values
sumValues(abs(x) for x in range(0,10))
When the range is known (e.g., we know the range is [0,10)), we can put a for loop, but what if the range is unknown?
it depend on how you want your function to be called, if you want to call it with list, generator, or more generally a iterable (anything that can be used in a for-loop) and imitate the behavior of the build-in sum then
def my_sum(iterable):
total = 0
for x in iterable:
total += x
return total
and use like
my_sum(range(10))
my_sum(abs(x) for x in range(0,10))
my_sum([1,2,3,4,5,6])
if you want to imitate the behavior of max and use it as above and also like my_sum(1,2), my_sum(1,2,3), my_sum(1,2,3,4,5,6,7), etc. then
def my_sum(*argv):
total = 0
values = None
if len(argv) == 1:
values = argv[0]
else:
values = argv
for x in values:
total += x
return total
I figured. Here's the answer:
def sumValues(*args):
# compute the sum of values
total = 0
for item in args[0]:
total += item
return total
print(sumValues(abs(x) for x in range(0,10)))
[output] => 45
Related
Wrote this code in comp sci class and I cant get it to work, it always returns as false every time I run it. Its supposed to be a recursive binary search method... Any idea why it only returns false?
arr = [1,10,12,15,16,122,132,143,155]
def binarysearch(arr,num):
arr2 = []
if (len(arr) == 1):
if (arr[0] == num):
return 1
else:
return 0
for i in range (len(arr)/2):
arr2.append(0)
if (arr[len(arr)/2]>num):
for x in range (len(arr)/2,len(arr)):
arr2[x-(len(arr)/2)]=arr[x]
return binarysearch(arr2,num)
if(arr[len(arr)/2]<num):
for x in range(0, len(arr) / 2 ):
arr2[x] = arr[x]
return binarysearch(arr2, num)
num = raw_input("put number to check here please: ")
if(binarysearch(arr,num)==1):
print "true"
else:
print "false"
You're doing vastly more work than you need to on things that Python can handle for you, and the complexity is masking your problems.
After your base case, you have two if statements, that don't cover the full range—you've overlooked the possibility of equality. Use if/else and adjust the ranges being copied accordingly.
Don't create a new array and copy stuff, use Python's subranges.
Don't keep repeating the same division operation throughout your program, do it once and store the result.
If you want to print True/False, why not just return that rather than encoding the outcome as 0/1 and then decoding it to do the print?
Recall that raw_input returns a string, you'll need to convert it to int.
The end result of all those revisions would be:
def binary_search(arr,num):
if (len(arr) == 1):
return (arr[0] == num)
mid = len(arr) / 2
if (arr[mid] > num):
return binary_search(arr[:mid], num)
else:
return binary_search(arr[mid:], num)
num = int(raw_input("put number to check here please: "))
print binary_search(arr,num)
The function should accept a single list as a parameter. The function should return an integer value as the result of calculation. If there are no positive and even integer values in the list, your function should return 0.
My current code:
def main():
print (sum_positive_even([1,2,3,4,5]))
print (sum_positive_even([-1,-2,-3,-4,-5]))
print (sum_positive_even([1,3,5,7,9]))
def sum_positive_even(list):
for num in list:
if num < 0:
list.remove(num)
for num in list:
if num % 2 == 1:
list.remove(num)
result = sum(list)
return result
main()
The output should be like:
6
0
0
I'm confused where I should put the 'return 0'.
Thanks TA!
Deleting from a list while you iterate over it is a Bad Idea - it's very easy to get hard-to-track-down bugs that way. Much better would be to build a new list of the items you want to keep. You don't need a special case of returning 0; the general approach should be able to handle that.
Also, it's better not to use list as a variable name in Python, because that's the name of a built-in.
A modification of your approach:
def sum_positive_even(lst):
to_keep = []
for num in lst:
if num > 0 and num % 2 == 0:
to_keep.append(num)
return sum(to_keep)
Since the sum of an empty list is 0, this covers the case where there are no positive even numbers.
I'm trying to generate a random integral and assign it to the variable.
import random
import time
Op = lambda: random.randint(1300, 19000)
op = "https://duckduckgo.com/html?q="
variable = int(Op())
grow = 0
while x < 3:
print(Op())
grow = grow + 1
time.sleep(1)
In here everything works fine, function "print" prints different result every time with 3 attempts.
However when I want to format this code like this:
Op = lambda: random.randint(1300, 19000)
op = "https://duckduckgo.com/html?q="
Op1 = int(Op())
pop = str("{}{}").format(op, Op1)
grow = 0
while grow < 3:
print(pop)
grow = grow + 1
time.sleep(1)
Then the function print gives me the same number three times.
For example:
>>>https://duckduckgo.com/html?q=44543
>>>https://duckduckgo.com/html?q=44543
>>>https://duckduckgo.com/html?q=44543
And I would like to get three random numbers. For example:
>>>https://duckduckgo.com/html?q=44325
>>>https://duckduckgo.com/html?q=57323
>>>https://duckduckgo.com/html?q=35691
I was trying to use %s - %d formatting but the result is the same.
Because you never changes the value of 'pop'.
In you first example you are creating instance of Op in every iteration but in second example you created instance once outside the loop and print the same value.
Try this:
Op = lambda: random.randint(1300, 19000)
op = "https://duckduckgo.com/html?q="
grow = 0
while grow < 3:
pop = str("{}{}").format(op, int(Op()))
print(pop)
grow = grow + 1
time.sleep(1)
Lambda functions are by definition anonymous. If you need to "remember" a lambda's procedure, just use def statement. But actually you don't even need this:
import random
import time
url_base = "https://duckduckgo.com/html?q={}"
grow = 0
while grow < 3:
print(url_base.format(random.randint(1300, 19000))
grow = grow + 1
time.sleep(1)
Your main problem is that you are trying to assign fixed values to variables and expect them to behave like procedures.
You need to apply randomness at every iteration. Instead you calculate a random number once and plug it in to every loop.
Write a function iterate with the following arguments:
f: a function
start: a numeric starting value
tol: a numerical tolerance (default value 1e-6)
itmax: a maximum number of iterations (default value 1000)
Starting from the initial value, your function should keep repeating calls to the function (e.g. y=f(y)) until the absolute value of f(y)-y is less than tol or the number of iterations is equal to itmax. For example, if start=1.01, f is math.sqrt, and tol=1e-4, the sequence would look like this:
On step 6, the absolute value of the difference is less than the tolerance (1e-4), so the function returns [6, 1.0000777399813863].
Tests (should all be True):
def approx_equal(x,y,tol=1e-8):
"""helper function: test whether all elements of
x and y are equal within tolerance
"""
if len(x) != len(y):
return(False)
for i in range(len(x)):
if (abs(x[i]-y[i])>tol):
return(False)
return(True)
def disc_logist(x):
"""discrete logistic function"""
return(1.5*x*(1-x))
print(approx_equal(iterate(disc_logist,0.5),[15, 0.33333433255312184]))
print(approx_equal(iterate(disc_logist,0.5,tol=1e-8),[22, 0.33333334113969143]))
def half(x):
"""just what it says"""
return(x/2)
print(approx_equal(iterate(half,1000),[29, 9.313225746154785e-07]))
import math
print(approx_equal(iterate(math.sqrt,1.01,tol=1e-4),[6, 1.0000777399813863]))
print(approx_equal(iterate(math.cos,0),[34, 0.7390855263619245]))
print(approx_equal(iterate(math.cos,0,tol=1e-8),[46, 0.7390851366465718]))
print(approx_equal(iterate(math.cos,0,itmax=5),[5, 0.7013687736227565]))
This is what i have so far:
def iterate(f,start,tol=1e-6,itmax=1000):
"""function should keep repeating calls to the function until the absolute
value of f(y)-y is less than tol or number of iterations is equal to itmax
:f: a function
:start: a numeric starting value
:tol: a numerical tolerance
:itmax: a maximum number of iterations"""
import math
y=start
for i in range(itmax):
y_2=f(y)
if abs(y_2 - y) <tol:
return y
else:
y=y_2
The answer for your immediate problem is to return not a single number, but a two element list containing first the number of iterations and second the answer - note that the instructions say (my emphasis):
On step 6, the absolute value of the difference is less than the tolerance (1e-4), so the function returns [6, 1.0000777399813863].
def iterate(f,start,tol=1e-6,itmax=1000):
"""function should keep repeating calls to the function until the absolute
value of f(y)-y is less than tol or number of iterations is equal to itmax
:f: a function
:start: a numeric starting value
:tol: a numerical tolerance
:itmax: a maximum number of iterations"""
import math
y=start
for i in range(itmax):
y_2=f(y)
if abs(y_2 - y) <tol:
# Return the successful value - the last result, not the last input
return [i, y_2]
else:
y=y_2
# Return the next answer
return [itmax, f(y)]
This will get approx_equal() working, but I haven't tested it completely to see if all the results match up.
I just need ideas on how would i add up the odd positional numbers only. For example, if i had 012345678905, i would only need to add 0, 2,4, 6, 8 etc. What I currently have is basically a module (yet to be completed), and this program is asking me valadiate UPC-12 numbers. Im completly confused, as im not entirely sure what i'm doing. I haven't learned "len" (somthing like that) yet.
# Gets the digit of the number using the specified position
def get_digit(number, position):
return number / (10**position) % 10
def is_UPC12(number):
sum_odd = 0
sum_even = 0
#loops through the UPC code and checks every odd position and adds the numbers
for num in range(1, 13, 2):
sum_odd += get_digit(number, num)
sum_odd *= 3
#loops through the UPC code and checks every even position and adds the numbers
for num in range(2, 13, 2):
sum_of_even += even
sum_even += get_digit(number, num)
Sum = sum_of_odd + sum_of_even_two
#subtracts 10 from the last digit of the sum, and if it's equal to the last digit of number then it returns True.
if 10 - get_digit(Sum , 0) == get_digit(number , 0):
return True
elif 10 - get_digit(Sum , 0) == 10 and get_digit(number , 0) == 0:
return True
else:
return False
Have you considered using the modulus % operator? Ex. x % 2 = 0 is an even number.
One approach (not necessarily the best) is:
# get the number to be tested
test_number = raw_input("Enter number to validate: ")
# set an initial 'sum' value at zero
sum = 0
# iterate through the characters in the input string, only selecting odd position characters
for i in range((len(test_number)+1)/2):
# a test print statement to check that it's working
print test_number[i*2]
# add the value of the character (as int) to 'sum'
# note that this doesn't deal with exceptions
# (if the input is not numeric, it will throw an error)
sum += int(test_number[i*2])
# get the final sum
print "sum: " + str(sum)
EDITED - alternate approach
Another way is:
test_number = raw_input("Enter number to validate: ")
sum = 0
odd_numbers = test_number[::2]
for char in odd_numbers:
sum += int(char)
print "sum: " + str(sum)
where "odd_numbers" is a new string composed of the alternate characters from the original string (using the slice method with a step-size of 2).