Write a recursive function, len - python

Write a recursive function, len, that accepts a parameter that holds a string value, and returns the number of characters in the string.
The length of the string is:
0 if the string is empty ("")
1 more than the length of the string beyond the first character
This is what I got so far:
def len(string):
if len(string) == ""
return 0
else:
return string[len(string)+1]
What am I doing wrong? Thx

len() is supposed to return an integer. I think they're looking for something like this:
def len(string):
if string == "":
# 0 if the string is empty
return 0
else:
# one more than the length of the string beyond the first character
return 1 + len(string[1:])

You forgot to reduce the problem on your recursive call. You programmed an infinite recursion. The critical statement is to recur on a shorter string:
return len(string[1:]) + 1

Related

How to return the middle character of a string in python? [duplicate]

This question already has answers here:
Return middle part of string
(2 answers)
Closed 1 year ago.
Full problem:
Write a function named mid that takes a string as its parameter. Your function should extract and return the middle letter. If there is no middle letter, your function should return the empty string. For example, mid("abc") should return "b" and mid("aaaa") should return "".
Question:
How come at the very end print(x) and everything works as expected, but return x breaks the program with the following:
IndexError: list index out of range
import math
def mid(string):
enum = list(enumerate(string))
lastnum = enum[-1][0] + 1
if lastnum % 2 == 0:
return ""
else:
middle = math.floor(len(enum)/2)
x = enum[middle][1]
print(x)
return x
mid("asaba")
Here's an example of how I would approach it:
def mid(string):
if len(string) % 2 == 0:
return ""
else:
offset = int(len(string) / 2)
return string[offset: offset + 1]
mid("abc")
mid("asaba")
Your code fails on edge cases, specifically when given the empty string, but I found during my tests that it works for strings like "asaba", "aaaa", and "abc" but throws the error when given "". The reason for this is because lastnum = enum[-1][0] + 1 will give an index that does not exist for the empty string. The way to fix this would be to add a condition at the beginning of your function that checks if it's an empty string, so like this:
if len(string) == 0:
return ""
import math
def mid(string_1):
string_2 = ''
if len(string_1) %2 == 0:
return string_2
else:
string_2 = string_1[math.floor(len(string_1)/2)]
return string_2
print(mid("abc"))
I've done the function in this way and it works fine, the logic is the following:
If the length of the string is even return an empty string ""
If the length of the string is odd then returns the middle character, this is done by finding the index in the middle:
string_2 = string_1[math.floor(len(string_1)/2)]

even and uneven letter, TypeError: not all arguments converted during string formatting

def ul(a):
if a %2 == 0:
print(a.upper())
else:
print(a.lower())
ul(input())
I get following error:
TypeError: not all arguments converted during string formatting
I want to write every even letter in uppercase and every uneven letter in lowercase
What I'm doing wrong?
What you are now doing with this function is check whether the input (a string) is divisible by 2. This is not really what you wanted to do and it raises an error because strings are not modulo divisible.
You should better loop through the indices of the input string to fill a second string with upper and lower case letters:
def ul(s):
outstring = ''
for i in range(len(s)): ## For each index of the string
if i%2==0:
outstring += s[i].upper() ## Even indices become upper case
else:
outstring += s[i].lower() ## Odd indices become lower case
print(outstring)
ul(input("Enter a string: "))
You are trying to get mode of string as I understand. You should use len(a).
def ul(a):
if len(a) %2 == 0:
print(a.upper())
else:
print(a.lower())
ul(input())
Try this
def ul(a):
a = a.lower()
if ord(a) %2 == 0:
print(a.upper())
else:
print(a.lower())
if you want user to enter only Alphabets, then try this
def ul(a):
if ord(a) >= 110 and ord(a) < 123:
a = a.lower()
if ord(a) %2 == 0:
print(a.upper())
else:
print(a.lower())
else:
print("Please enter Alphabets only")
Input will give you a string. You want to use the modulo operator %, which is exactly how you usually find the evenness of a number. So, you are on the right track!
What actually happens is that Python interprets your % as the format operator (probably has a fancy name).
number = 2
print("Number %d is this" % number)
>>> Number 2 is this
Strings in Python are immutable, so you can't just change the string that easily.
Try this Replacing every 2nd character in a string , where you construct a new string by adding all the individual characters together.
def ul(word):
new = []
for i in range(len(word)):
if i%2 == 0:
new += word[i].upper()
else:
new += word[i].lower()
print("".join(new))
This will go through the string character by character, transform the individual character based on if it is even or not, and then construct a list "new", that holds all the individual characters. In the end, just join it, so create a new string out of the list.
There are more pythonic ways to do this using list comprehension, but for now this is easier to read and understand.

How to uppercase even letter and lowercase odd letter in a string?

I am creating a function that takes in a string and returns a matching string where every even letter is uppercase and every odd letter is lowercase. The string only contains letters
I tried a for loop that loops through the length of the string with an if statement that checks if the index is even to return an upper letter of that index and if the index is odd to return a lowercase of that index.
def my_func(st):
for index in range(len(st)):
if index % 2 == 0:
return st.upper()
else:
return st.lower()
I expected to have even letters capitalize and odd letter lowercase but I only get uppercase for the whole string.
Some issues in your code:
Currently you are returning from the function on the first index itself, i.e index=0 when you do return st.lower(), so the function will stop executing after it encounters the first index and breaks out of the for loop
Doing st.lower() or st.upper() ends up uppercasing/lowercasing the whole string, instead you want to uppercase/lowercase individual characters
One approach will be to loop over the string, collect all modified characters in a list, convert that list to a string via str.join and then return the result at the end
You also want to refer to each individual characters via the index.
def my_func(st):
res = []
#Iterate over the character
for index in range(len(st)):
if index % 2 == 0:
#Refer to each character via index and append modified character to list
res.append(st[index].upper())
else:
res.append(st[index].lower())
#Join the list into a string and return
return ''.join(res)
You can also iterate over the indexes and character simultaneously using enumerate
def my_func(st):
res = []
#Iterate over the characters
for index, c in enumerate(st):
if index % 2 == 0:
#Refer to each character via index and append modified character to list
res.append(c.upper())
else:
res.append(c.lower())
#Join the list into a string and return
return ''.join(res)
print(my_func('helloworld'))
The output will be
HeLlOwOrLd
You can store your operations beforehand and use them in join with enumerate:
def my_func(st):
operations = (str.lower, str.upper)
return ''.join(operations[i%2](x) for i, x in enumerate(st))
print(my_func('austin'))
# aUsTiN
Tweaking your code a bit, You can use the 'enumerate' and keep appending to the string based on the condition evaluations( for me this was easier since I have been coding in java :))
def myfunc(st):
str=''
for index, l in enumerate(st):
if index % 2 == 0:
str+=l.upper()
else:
str+=l.lower()
return str
def myfunc(str):
rstr = ''
for i in range(len(str) ):
if i % 2 == 0 :
# str[i].upper()
rstr = rstr + str[i].upper()
else:
#str[i].lower()
rstr = rstr + str[i].lower()
return rstr
l = 'YourString'
li=[]
for index,i in enumerate(l):
if index % 2 == 0:
i=i.lower()
li.append(i)
elif index % 2 == 1:
i=i.upper()
li.append(i)
print(''.join(li))
Use this enumerate method to perform your operation
return will terminate your function, so there isn't much point of the loop
st is the whole string, so st.upper() will yield the whole string in upper case.
You can use a bitwise and (&) to check for odd positions. The enumerate function will give you both the positions and the characters so you can easily use it in a list comprehension:
def upLow(s):
return "".join(c.lower() if i&1 else c.upper() for i,c in enumerate(s))
upLow("HelloWorld") # HeLlOwOrLd
The below code should do what you are looking for.
def myfunc(name):
str=""
lc=1;
for character in name:
if(lc%2==0):
str+=character.upper()
else:
str+=character.lower()
lc+=1
return str
def myfunc(a):
newString = ''
for count, ele in enumerate(a, 0):
if count %2 == 0:
newString += (a[count].lower())
else:
newString += ((a[count].upper()))
return newString
You can deconstruct string into collection of characters, apply transformations and reconstruct string back from them
Logic:
First enumerate() over the string to generate key-value pairs of characters and their positions
Then use comprehensions to loop over them and use conditional statement to return odd position characters in lower() case and even position in upper()
Now you have the list ready. Just join() it with an empty string '' to convert the list into a string
Code:
str = 'testing'
''.join([y.upper() if x%2 ==0 else y.lower() for x,y in enumerate(str)])

How do I use for loops with functions for string input in python?

I'm having trouble with creating a function that takes an argument of a string and returns just the numbers in type str. My code looks something like this.:
def check_if_number(number_string):
for ch in number_string:
if ch.isdigit():
num = number_string[ch]
return num
print(check_if_number('1655t'), end='')
It should print: 1655
You should add each char to a string if it is a digit :
def check_if_number(number_string):
digit_string = ""
for ch in number_string:
if ch.isdigit():
digit_string += ch
return digit_string
print(check_if_number('1655t'))
# 1655
Note that you can also use the re library :
import re
re.sub("\D", "", "1655t")
#1655
This code replace every non-digit character (matched by \D) by an empty string.
Have a look at this question to find more way to do it
You can do this :
def check_if_number(number_string):
num = ""
for ix in number_string :
if ix.isdigit():
num += ix
return int(num)
This function will return 1655, if the input is 1655t. You return from the function once you scan the complete string and append all ints to a string.
The easy way would be just using filter and concatenating the filtered letters in the end:
def check_if_number(number_string):
return ''.join(filter(str.isdigit, number_string))
Assuming all numbers are together (i.e. No letters exist between digits like "1e234g7"),
def check_if_number(number_string):
num = ''
for ch in number_string:
if ch.isdigit():
num += ch
return num
print(check_if_number('1655t'), end='')
This will return a string that only has digits in it. If you want to return a type int, then simply do return int(num).
If you want to take floats into account as well:
def check_if_number(number_string):
num = ''
for ch in number_string:
if ch == '.' or ch.isdigit():
num += ch
return num
print(check_if_number('1655t'), end='')
Similarly, this will return a string. If you want type float, simply do return float(num).
I tried not to deviate too much from what you already had... I hope this helps.
I'm uncertain what check_leap_year() function is so I just commented it out and called the function you gave us instead.
When you pass anything into a function in order to manipulate it and spit it back out different than it came in you should create a new variable for the changed data set.
In this case I used num = ""
By initiating an empty string inside of the function I can now add the data that pass my condition to that new, empty string.
isdigit() returns a boolean. So instead of using if x.isdigit: get in the habit of checking the boolean. Try if x.isdigit() is True instead.
Return your finished new string AFTER it is finished. Make sure your return statement is indented correctly or you are only going to return one number instead of all of them. The return should be outside of the loop so that it will only return once the loop is done.
num_string = "1a2s3d4f5g666hhh777jjj888kkk9l0"
def check_if_number(number_string):
num = ""
for ch in number_string:
if ch.isdigit() is True:
num += ch
return num
print(check_if_number(num_string))
Output:
>>> 1234566677788890

Recursive function check(s) that take a string representing a password as input and returns all the characters that are digits ( 0 -9)

I'm working on a problem which is below and my code. I could use some help.
Write a recursive function check(s) that take a string representing a password as input and returns all the characters that are digits (0 -9)
def check(s):
if not s.idigit():
return
else:
return check(s.isdigit())
def check(s):
if len(s) == 0:
return ''
elif s[0].isdigit():
return s[0] + check(s[1:])
else:
return check(s[1:])
For the example
print(repr(check('12a3z-4!')))
this prints
'1234'
which is what you want. There are other ways to write this code but this is probably simplest for a beginner in Python.
From your last comment, you may want to print out the digits in the password, from largest to smallest, each on a separate line, and you don't care about returning anything from a function. If that's what you want, try
def check(s):
if len(s) > 0:
check(s[1:])
if s[0].isdigit():
print(s[0])
check('31a4z-2!')
This prints
2
4
1
3
Recursion has two main parts:
Base case: what to return when you hit the most trivial input.
Recursion case: how to reduce the problem to something simpler.
Here, your base case is
if s == '':
return ''
Your recursion case depends on whether or not the leading character is a digit. If it is, you want to add it to the string you build; if not, you have nothing to add. Either way, you call your routine on the remainder of the string:
add = ''
if s[0].isdigit():
add = s[0]
After this, call the routine on the rest of the string. When that returns, combine its return value with add, and return that to the calling program.
Does that move you along?

Categories