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
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 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).
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
Im trying to implement this function.
def eq_chars(s,i):
"""Returns: length of sequence of equal characters starting at s[i].
Examples: eq_chars('aaaxxyx',0) is 3 and eq chars('aaaxxyx',5) is 1
Precondition: s is a string, 0 <= i < len(s).""
"
My code thus far has been this:
for i in range(len(s)):
accumulator = 0
if s[i] == s[i+1]:
accumulator = accumulator + 1
return accumulator
else:
pass
I know there is a problem in the beginning of the for loop. I stands for the index which will be given to us. Can you possibly change variables? What am I doing wrong? Any help is appreciated
The problem is that you are returning when the if statement is satisfied and at the beginning of the loop you are losing the value of i. The correct code should be:
def eq_chars(s, i):
accumulator = 1
for j in range(i, len(s) - 1):
if s[j] == s[j+1]:
accumulator += 1
else:
break
return accumulator
This function start from the given index, and checks if the next character is the same with the current one. If it finds a match it increases the count. When a non-matching character is seen, it stops the loop and returns the count.