In this Exercise, you will sum the value of a string. Complete the recursive function
def sumString(st):
This function accepts a string as a parameter and sums the ASCII value for each character whose ASCII value is an even number.
I know how to sum all the values but the even numbers part is challenging.
def sumString(st):
if not st:
return 0
else:
return ord(st[0]+sumString(st[1:])]
I tried something but i am just confused at this point.
def sumString(st):
if not st:
return 0
t=[ord(st[0]),sumString(st[1:])]
for item in t:
if item%2==0:
return item+t
Maybe something like this?
def sumString(st):
if not st:
return 0
else:
out = ord(st[0]) if ord(st[0]) % 2 == 0 else 0
return out + sumString(st[1:])
print(sumString("abcd"))
Output:
198
The ASCII value for b is 98 and the ASCII value for d is 100. So 100 + 98 gives you the output.
When posting code which causes an error, make sure to include that error
TypeError: unsupported operand type(s) for +: 'int' and 'list' in this case.
No offense, but the code you have written is a hot mess. You create a list with the ord of the first char, then the output of the function.
I think you then attempt to check if both values are even (not needed), and then return the sum (which you dont do since the return statement is inside the loop).
To do this you only need to check the first value of the string, then hand the rest to the same function
def sumString(st):
if not st:
return 0
out = sumString(st[1:]) # get output of the rest of the string
if ord(st[0]) % 2 == 0: # check if first char in str is even
out += ord(st[0])
return out
Here a method recursive and non:
def recursive_sum_even_ascii(s):
if s:
first, *other = s
value = 0
if not ord(first) % 2:
value = ord(first)
return value + recursive_sum_even_ascii(other)
return 0
def sum_even_ascii(s):
return sum(ord(char) for char in s if not ord(char) % 2)
# test
s = "23"
out_rec = recursive_sum_even_ascii(s)
out = sum_even_ascii(s)
print(out_rec == out)
Related
Here is my python code:
class Solution():
def isPalindrome(self):
return str(self.x) == str(self.x)[::-1]
s1 = Solution()
s1.x = 121
s1.isPalindrome()
It checks to see if the input is a palindrome. I want to create a new object that has the x value 121 and when I execute the isPalindrom function, I want it to return either a true or false boolean answer.
Currently when I run this program, nothing gets outputted. I am a bit lost as to where to go from here, would appreciate help.
Just print out the return value of isPalindrome(), because if you have a line with only a return value (this case being a boolean), the compiler won't know what to do with it.
class Solution():
def isPalindrome(self):
return str(self.x) == str(self.x)[::-1]
s1 = Solution()
s1.x = 121
print(s1.isPalindrome())
You're not telling the program to print anything. Try using print to make it reveal the answer.
Along with printing results we can also make class more pythonic.
class Solution:
def __init__(self):
self.input = None
def is_palindrome(self):
if isinstance(self.input, str):
return self.input == self.input[::-1]
print("Error: Expects str input")
return False # or leave blank to return None
s1 = Solution()
print(s1.is_palindrome())
s1.input = "121"
print(s1.is_palindrome())
output
Error: Expects str input
False
True
The main idea here is divide number. let's take number 122. First of all you need store it in a variable, in this case r_num. While loop is used and the last digit of the number is obtained by using the modulus operator %. The last digit 2 is then stored at the one’s place, second last at the ten’s place and so on. The last digit is then removed by truly dividing the number with 10, here we use //. And lastly the reverse of the number is then compared with the integer value stored in the temporary variable tmp if both are equal, the number is a palindrome, otherwise it is not a palindrome.
def ispalindrom(x):
r_num = 0
tmp = x
while tmp > 0:
r_num = (r_num * 10) + tmp % 10
tmp = tmp // 10
if x == r_num:
return True
return False
I'm trying to complete a recursive function which given a number, returns a string where the returned value has duplicate of each digit
Example: if 507, returns 550077
if the number is only 0 then just return 0
also if it is a negative number, return the negative sign only once
Example: -507 returns -550077
I haven't yet implemented anything to recognize a negative number, I was just trying to get my function to work first
so far I have:
def double(x):
if x == 0:
return x
else:
x = str(x)
return x[0]*2 + double(x[1: ])
print(double(527))
however this returns IndexError: string index out of range
I had it working by printing the result instead of returning the result, but the problem I am trying to solve strictly wants the result returned, not printed. What am I doing wrong?
This works recursively, fixes the x==0 termination error, checks whether a character is a digit before doubling, and returns the final answer as an int (instead of a str).
def double(x):
x = str(x)
if len(x) == 0:
return ''
else:
first_char = x[0]
# only double if it's an integer
if first_char in map(str, range(10)):
first_char *= 2
return int(first_char + str(double(x[1: ])))
print(double(-527))
>>> -552277
Something like this might work.
def double(x):
if x == 0:
return x
else:
x = str(x)
l=[]
for a in x:
if a == '-':
l.append(a)
else:
l.append(a*2)
return ''.join(l)
I am making a recursive function that slices string until it is empty. When it is empty it alternatively selects the characters and is supposed to print or return the value. In this case I am expecting my function to return two words 'Hello' and 'World'. Maybe I have got it all wrong but what I don't understand is that my function doesn't let me print or return string. I am not asking for help but I'd like some explanation :) thanks
def lsubstr(x):
a= ''
b= ''
if x == '':
return ''
else:
a = a + x[0:]
b = b + x[1:]
lsubstr(x[2:])
#print (a,b)
return a and b
lsubstr('hweolrllod')
so I changed my code to this:
def lsubstr(x):
if len(x) <1:
return x
else:
return (lsubstr(x[2:])+str(x[0]),lsubstr(x[2:])+str(x[1]))
lsubstr('hweolrllod')
and what I am trying to make is a tuple which will store 2 pairs of characters and concatenate the next ones,
the error I get is
TypeError: Can't convert 'tuple' object to str implicitly
what exactly is going wrong, I have checked in visualization, it has trouble in concatenating.
The and keyword is a boolean operator, which means it compares two values, and returns one of the values. I think you want to return a tuple instead, like this:
...
return (a, b)
And then you can access the values using the indexing operator like this:
a = lsubstr( ... )
a[0]
a[1]
Or:
word1, word2 = lsubstr( ... )
Im trying to write a recursive function that gets as an input a string and a char. the function return the first index appearance of the char in the string. If the char doesnt appear it returns None.
I have a problem only with returning None. In my case when the char isnt in the string the function throws an error, any advice?
def char_first_index(s,c):
if len_rec(s)==0:
return None
if s[0]==c:
return 0
return 1+ char_first_index(s[1:],c)
You are creating a new slice at each iteration, and you have to add 1 for each recursion. Instead, recurse on the index:
def char_first_index(s, c, index = 0):
if len(s) == index:
return None
if s[index] == c:
return index
return char_first_index(s, c, index + 1)
If the character is not in the input, your function tries to perform 1+None, hence the error. Try this instead:
def char_first_index(s,c):
if len_rec(s)==0:
return None
if s[0]==c:
return 0
answer = char_first_index(s[1:],c)
if answer is not None:
return 1+answer
else:
return answer
Firstly I'm assuming len_rec is a recursive function that gets the length of the string; you haven't written it so I've just changed it to len() for testing.
Secondly, I'm not sure how this function is supposed to handle the character not being in the string, as that will mean trying to add None to a number.
Here is an amended function that still uses your count idea, but handles the case of a None being returned:
def char_first_index(s,c):
if len(s)==0:
return None
elif s[0]==c:
return 0
else:
count = char_first_index(s[1:], c)
if count != None:
return count + 1
else:
return None
value = 'bcdjbcdscv'
value = 'bcdvfdvdfvvdfvv'
value = 'bcvfdvdfvcdjbcdscv'
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
How to count the number of letters in a string with a list of sample? I get nothing in my python shell when I wrote the above code in my python file.
There is a built-in method for this:
value.count('c')
functions need to be called, and the return values need to be printed to the stdout:
In [984]: value = 'bcvfdvdfvcdjbcdscv'
In [985]: count_letters(value, 'b')
Out[985]: 2
In [987]: ds=count_letters(value, 'd') #if you assign the return value to some variable, print it out:
In [988]: print ds
4
EDIT:
On calculating the length of the string, use python builtin function len:
In [1024]: s='abcdefghij'
In [1025]: len(s)
Out[1025]: 10
You'd better google it with some keywords like "python get length of a string" before you ask on SO, it's much time saving :)
EDIT2:
How to calculate the length of several strings with one function call?
use var-positional parameter *args, which accepts an arbitrary sequence of positional arguments:
In [1048]: def get_lengths(*args):
...: return [len(i) for i in args]
In [1049]: get_lengths('abcd', 'efg', '1234567')
Out[1049]: [4, 3, 7]
First you should probably look at correct indenting and only send in value. Also value is being overwritten so the last one will be the actual reference.
Second you need to call the function that you have defined.
#value = 'bcdjbcdscv'
#value = 'bcdvfdvdfvvdfvv'
value = 'bcvfdvdfvcdjbcdscv'
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
x = count_letters(value, 'b')
print x
# 2
This should produce the result you are looking for. You could also just call:
print value.count('b')
# 2
In python, there is a built-in method to do this. Simply type:
value = 'bcdjbcdscv'
value.count('c')