print pattern recursion - python

I need to write a recursive function printPattern() that takes an integer n as a parameter and prints n star marks followed by n exclamation marks, all on one line. The function should not have any loops and should not use multiplication of strings. The printing of the characters should be done recursively only. The following are some examples of the behavior of the function:
>>>printPattern(3)
***!!!
>>>printPattern(10)
**********!!!!!!!!!!
This is what I have at the moment
def printPattern(n):
if n < 1:
pass
else:
return '*'*printPattern(n)+'!'*printPattern(n)
I know I am completely off, and this would be easier without recursion, but it is necessary for my assignment.

Q: What's printPattern(0)?
A: Nothing.
Q: What's printPattern(n), for n>=1?
A: *, then printPattern(n-1), then !.
Now you should be able to do it. Just remember to think recursively.

Recursion is based on two things:
a base case
a way to get an answer based off something closer to the base case, given something that's not the base case.
In your case, the simplest base case is probably 0 - which would print thing (the empty string). So printPattern(0) is ''.
So how do you get closer to 0 from your input? Well, probably by reducing it by 1.
So let's say that you are currently at n=5 and want to base your answer off something closer to the base case - you'd want to get the answer for n=5 from the one for n=4.
The output for n=5 is *****!!!!!.
The output for n=4 is ****!!!!.
How do you get from the output of n=4 to n=5? Well, you add a * on the front and a ! on the end.
So you could say that printPattern(5) is actually just '*' + printPattern(4) + '!'.
See where this is going?

Try this:
def printPattern(n):
if n <= 0:
return ''
return '*' + printPattern(n-1) + '!'
print printPattern(5)
> *****!!!!!

Related

Should I use a for statement here or not?

I have this question and I want your expert answers about it, because I want to get better in programming.
"""
The parameter s_str is a string. The parameter n is an int > 0.
The function x() should return the last n characters of s_str if
s_str has a length >= n, or the empty string if s_str has a length < n
Example:
x('abcdef', 3) == 'def'
"""
So, I could build the exact code with or without the for statement and it would give me (print) the same values, but I don't know what is the more common way to do it. If I'd go for a for statement, I'd do this:
for i in s_str:
if len(s_str) >= n:
return a_str[-n:]
elif len(s_str) < n:
return ''
Is the idea of using a for statement wrong if you know in advance that you are not going to use i, in this case? I could easily remove the for statement and still get the right answer, so is that enough reason not to use it?
There are cases in which a for loop is justified even if you do not intend to use the loop index (e.g when you want to preform a certain task n times). Having said that, this problem can be solved in a more elegant way, as you have shown.
Also please note that your code iterates over the string len(str) times, except it returns in the first iteration, so the for loop in this case is redundant.
"so is that enough reason not to use it?"
Yes. Simple is better than complex.
You dont actually need a for loop
if len(a_str) >= n:
return a_str[-n:]
it is better and simple too.

Is str.replace() or combining two slices a better way to remove a character?

I am using CodingBat for practice exercises for the Python Language, I got to the "Warmup-1 > missing_char" exercise. The problem is as so:
Given a non-empty string and an int n, return a new string where the
char at index n has been removed. The value of n will be a valid index
of a char in the original string (i.e. n will be in the range
0..len(str)-1 inclusive).
The examples were:
missing_char('kitten', 1) → 'ktten'
missing_char('kitten', 0) → 'itten'
missing_char('kitten', 4) → 'kittn'
I wrote:
def missing_char(str, n):
return str.replace(str[n], "")
It returned all correct. As I usually do when I get my answers correct, I look and see how CodingBat answered it. They answered it in the following way:
def missing_char(str, n):
front = str[:n] # up to but not including n
back = str[n+1:] # n+1 through end of string
return front + back
Now, my question is the following: which answer is more viable? Is there setbacks to my method whereas CodingBat's method is more solid? Or is this just one of those "multiple approaches to things" kind of situation?
For the sake of posting a formal answer and as all previous comments suggest:
str.replace(char,"") will remove all occurences of the character regardless of their position.
str[:n]+str[n+1:] will only remove the n-th character.
So for that exercice str.replace(char,"") is not suitable.
You should be able to circumvent that problem by adding a count so that it only takes the first character:
def missing_char(str, n):
return str.replace(str[n], "",1)
I added a 1 so that it only takes the first occurrence of that character

Python Recursion Behavior

I have studied recursion, especially in Python, and think I get it.
I have learned this form:
def f_Listsum(numList):
if len(numList) == 1:
return numList[0] ## Triggers the unwinding of the recursion stack
else:
return numList[0] + f_Listsum(numList[1:]) ## Winds up the recursion stack with a shorter and shorter slice of org. list.
I get it. The recursive calls sort of "wind" things up, and then a stop or "trigger" causes the recursion to collapse into itself and consume the resulting values.
However I ran into this today:
def f_DecToBinary(v_Num):
if v_Num > 1:
f_DecToBinary(v_Num // 2)
print(v_Num % 2,end = '')
I wanted to substitute the function's "print" with a return of a string, or even a list of INTs, but I can't get it to work, as I don't understand how this recursion is operating. I see that it calls itself each time, and then initiates a collapse when v_Num == 1 or less, but it collapses to outside the "if" statement and then I get lost. When I try to assemble a STR or LIST from the collapse instead of just printing it, I errors or just the last digit returned.
My questions are: How does f_DecToBinary work/function, and how can I capture the output into a string?
Some examples:
print(f_Listsum([1,3,5,7,9])) ## 25
print()
f_DecToBinary(15) ## 1111
Thanks
Follow the typical flow through the function. It will call itself, which causes some output, then it prints a single digit. So the single digit comes at the end of the previous ones. To return the result instead of printing it, you need to take the result of the recursive call and add the current result to the end of it.
def DecToBinary(n):
if n >= 2:
return DecToBinary(n // 2) + str(n % 2)
else:
return str(n)

Odd Even String- Python

Write a function named evenOddString() that takes a single string parameter.
If the length of the string parameter:
is odd: evenOddString() should return the string parameter.
is even, evenOddString() should return the string parameter concatenated with itself.
This is my code so far:
def evenOddString():
len(var) % 2 != 0
First, your evenOddString() function needs to take a parameter. For example:
def evenOddString(the_string_parameter):
print(the_string_parameter)
To call that function, you would have something like:
evenOddString('abc123')
which would print out abc123 on the console. In your case, you will want check the length of the_string_parameter and do some stuff with it "if" the length is even or odd. The if and elif statements will be helpful. See http://docs.python.org/tutorial/controlflow.html for docs on flow control.
You also want to return a value back out of your function. If I wanted to return the string unchanged, I would do something like:
def evenOddString(the_string_parameter):
return the_string_parameter
Note that I'm being a little vague here as this sounds like a homework assignment and I don't want to simply write all the code for you. Since you sound like a new programmer just starting out and in need of a good tutorial, I highly recommend you work through http://learnpythonthehardway.org/
define a function that take a parameter - Your definition does not take a parameter
get the length of that parameter - No problems here
if the length is odd, return the return the parameter - Your condition is correct, but you're not doing anything with the condition
else: return the parameter concatenated with itself - not implemented
def control4OddString(myString):
if len(myString) % 2: return myString
else: return myString+myString

Python function to sum digits

I want function to take the last digit of each number in the list and sum them up all together. So forexample, the function below would return "10".
def getSumOfLastDigits(numList):
x = sum(int(num[-1:]) for num in numList)
print x
getSumOfLastDigits([1, 23, 456])
>>>10
Here is what i receive instead of the expected out "10"
def getSumOfLastDigits(numList):
x = sum(int(num[-1:]) for num in numList)
print x
getSumOfLastDigits([1, 23, 456])
Too much work.
def getSumOfLastDigits(numList):
return sum(x % 10 for x in numList)
x = sum(num%10 for num in numList)
You can't index into a number; a number isn't a sequence of digits (internally, it isn't represented in base 10). You can obtain the last digit of a number using mathematical manipulation instead: take the remainder when dividing by 10. We do this with the % operator.
Also:
Don't print the value in your function, return it. Let the calling code decide what to do with the value. Calculation and output are separate tasks, and should be kept separate.
Avoid indicating data types in variable names - yes, even in Python. It's not a good idea to build in assumptions that aren't actually necessary. You could use any kind of sequence here, for example. The simplest way to indicate that you have more than one number is to use the plural, numbers. That also means you use a full word, and people don't have to think about what 'num' is short for.
There is no need to assign the result of an expression to a temporary variable, if you are just going to use it once, and right away. The name x doesn't tell us anything, so cut it out.
get is considered an ugly prefix for function names by most Pythonistas. It should already be obvious that the function calculates and returns a value. Use noun-type names for those functions, and verb-type names for functions that are primarily intended to manipulate some existing data.
Thus:
def sum_of_last_digits(numbers):
return sum(number % 10 for number in numbers)
def getSumOfLastDigits(numList):
total=0
for item in numList:
newItem=str(item)
length=newItem[len(newItem)-1]
total+=int(length)
return total

Categories