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)
Related
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've made this function for a HW but every time I run it python returns no result,
What am I doing wrong?.
mult
def mult( n, m ):
""" input two strings
output the product of those numbers
"""
if n==0 or m==0:
return
elif m<0:
m=abs(m)
m+m
mult(n-1,m)
return
else:
m+m
mult(n-1,m)
return
In Python return is a transtive verb. It is sort of like the verbs "say" or "go"
say what? go where? return what?
You seem to think of return as something which simply returns execution flow to the caller (perhaps returning the value of the last calculated expression) but it doesn't work that way.
def add(x,y):
return x+y
returns the sum of x and y
def add(x,y):
x+y
return
returns nothing (which is called None in Python). It computes the sum of x and y but then discards the result.
Think about return as "give to the guy who called me".
def four():
return 4
print("four is ", four()) # four is 4
So, if I need a four, I can call my handy new function: print("four is ", four()). print() calls four() to get a result. If I define four() with an empty return statement, it won't give me anything.
def four():
4
return
print("four is ", four()) # four is None
return with recursion is the same "giving to the caller" principle, only more complicated.
def add(n,m):
"""add two integers together. The second integer
cannot be negative"""
if m == 0:
return n
else:
return 1 + add(n, m-1)
For simplicity's sake, the second number cannot be less than 0. Now, think about the algorithm, and how the return <something> affects it. If m is zero, then n + 0 == n, so we only need to return n. Otherwise, we're adding one to our eventual answer and subtracting one from m.
add(2, 3) becomes
1 + add(2, 2)(the return means "give to the guy who called me" which is add(2, )), which becomes 1 + 1 + add(2, 1), which becomes 1 + 1 + 1 + add(2, 0), and when we see zero in that second spot, we just replace it with the first number, so it becomes 1 + 1 + 1 + 2 which is 5.
import math
def is_prime(num):
if num < 2:
return False
for i in range(2, int(math.sqrt(num))+ 1):
if num % i == 0:
return False
return True
Primes seems to be a popular topic but in the book in which I am learning Python, I am on chpt 6 out of 21 and in the iteration chapter which it teaches while loops. I have not learned for loops yet although I understand what they do. So, let's say I have not learned for loops yet and am given only if/elif/else statements and the while loops as my tools. How can I change the for line of code into something more simple using the above tools? While asking this question I quickly came up with this code:
def formula(num):
i = 2
while i >= 2:
return int(math.sqrt(num)+ 1)
def is_primetwo(num):
i = 2
if num < 2:
return False
formula(num)
if num % i == 0:
return False
return True
It works but would this be a simple version of the for loop or is there something even more simple where I do not have to wrap a function within a function?
Absolutely, you do not need a function to replace a for loop.
So you've got this
for i in range(2, int(math.sqrt(num))+ 1):
which is your for loop. Take a second to think what it's doing.
1.) It's taking the variable i, and it's starting it at a value of 2.
2.) It's checking whether to do the loop every time by checking if i is less than the (square root of num) plus 1
3.) Every time through the loop, it adds one to i.
We can do all of these things using a while loop.
Here's the original
for i in range(2, int(math.sqrt(num))+ 1):
if num % i == 0:
return False
let's rename the second and third lines loop contents just so we're focusing on the looping part, not what logic we're doing with the variables i and num.
for i in range(2, int(math.sqrt(num))+ 1):
loop contents
ok, now let's just rearrange it to be a while loop. We need to set i to 2 first.
i = 2
Now we want to check that i is in the range we want
i = 2
while i <= int(math.sqrt(num) + 1):
loop contents
Now we're almost set, we just need to make i actually change, instead of staying at a value of 2 forever.
i = 2
while i <= int(math.sqrt(num) + 1):
loop contents
i = i + 1
Your example seemed to do some of these elements, but this way is a simple way to do it, and no extra function is necessary. It could be the range() function that is confusing. Just remember, the for loop is doing three things; setting a variable to an initial value, checking a condition (one variable is less than another), and incrementing your variable to be one large than previously to run the loop again.
How about something like:
from math import sqrt
def is_prime(num):
if (num < 2):
return False
i = 2
limit = int(sqrt(num) + 1)
while (i <= limit):
if num % i == 0:
return False
i = i + 1
return True
Not sure if this is what you want, but the for loop:
for i in range(2, int(math.sqrt(num))+ 1):
if num % i == 0:
return False
return True
can be expressed as:
i = 2
while i < int(math.sqrt(num))+ 1):
if num % i == 0:
return False
i += 1
return True
Probably a good idea to determine int(math.sqrt(num))+ 1) once:
i = 2
n = int(math.sqrt(num))+ 1)
while i < n:
if num % i == 0:
return False
i += 1
return True
The Question:
5.Now write the function is_odd(n) that returns True when n is odd and False otherwise.
Finally, modify it so that it uses a call to is_even to determine if its argument is an odd integer.
I had to write a function for is_even(n) that returns True when n even and False otherwise. Here is my code:
def is_even(n):
return n % 2 == 0
def is_odd(n):
if is_even(n):
print "This is an even integer."
else:
print "This is an odd integer."
return n % 2 != 0
My Question:
I am a total beginner and find programming very hard but I love it for some reason, but why does this not work? I defined the function is_even(n) and is_odd(n), put is_even(n) into the is_odd(n) function, wrote and if/else else statement making if the function is_even is equal to true it should print out it is an even integer... When I put in is_odd(3); it prints out "This is an even integer" and returns True even though it should print out "This is an odd integer."
Update:
I changed my code to this and works fine.
def is_even(n):
return n % 2 == 0
def is_odd(n):
if is_even(n) == False:
print "This is an odd integer."
return n % 2 != 0
You're encountering IndentationError because you're being inconsistent with your indentation. As soon as you indent in Python, you have created a new block. You do this after block-introducing keywords, like if, while, for, etc. Python doesn't care how many spaces or tabs or whatever you use before your first block, but once you make the choice the first time, you must keep using the same number. I've added a line to your posted code to show you:
See how the r in return aligns with the f in if? It needs to align with the i. In this example your if is not at the proper indentation level relative to the first block, producing the error in question.
I am fairly new to Python and am trying to create my own small program. Im having trouble with the replace function. I want to replace every even position in a string with its position number, and a problem occurs when the position becomes greater than 10; it just keeps replacing every character after 10 with an even number. Here is my code
def replaceEvenUntil(st,n):
for i in range(len(st)):
if i % 2 == float(0):
st = st.replace(st[i], str(i), n)
return st
>>> replaceEvenUntil("abcdefghijklmnop", 100)
'0b2d4f6h8j101214161820'
Where in my code have I made my error?
A few things:
float and str are functions in Python. You don't need to write int(0) or str('foo').
str.replace('a', 'b') replaces all occurrences of a with b. You don't really want that.
You're re-assigning st in the loop, but the size of st may change (10 is two characters), so you'll get off-by-one errors as the strings grow larger than 10 characters long.
I would construct a temporary string instead:
def replaceEvenUntil(s, n):
result = ''
for i in range(min(n, len(s))):
if i % 2 == 0:
result += str(i)
else:
result += s[i]
return result
Or with enumerate():
def replaceEvenUntil(s, n):
result = ''
for i, c in enumerate(s):
if i <= n and i % 2 == 0:
result += str(i)
else:
result += s[i]
return result