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.
Related
Sorry if being so simple; as I searched elsewhere but nobody had pointed out to this specific problem. I'd like to learn python in a way that makes my code compact! So, to this end, I'm trying to make use of one-line (i.e., short) loops instead of multi-line loops, specifically, for loops. The problem arises when I try to use one-line if and else inside the one-line loops. It just doesn't seem to be working. Consider the following, for example:
numbers = ... # an arbitrary array of integer numbers
over_30 = [number if number > 30 for number in numbers]
This is problematic since one-line if does need else following it. Even though, when I add else to the above script (after if): over_30 = [number if number > 30 else continue for number in numbers], it turns into just another pythonic error.
I know that the problem is actually with one-line if and else, because python needs to identify a value that should be assigned to the lefthand operator. But, is there a work-around for the specific use-case of this schema as above?
They are different syntaxes. The one you are looking for is:
over_30 = [number for number in numbers if number > 30]
This is a conditional list comprehension. The else clause is actually a non-conditional list comprehension, combined with a ternary expression:
over_30 = [number if number > 30 else 0 for number in numbers]
Here you are computing the ternary expression (number if number > 30 else 0) for each number in the numbers iterable.
continue won't work since this is ternary expression, in which you need to return something.
val1 if condition else val2
You can try this way:
over_30 = [number for number in numbers if number > 30]
I am currently a beginner in Python. This is my problem: First, the program asks that you input a number.
For example, if I put 1, I get 1 out. If i put 2, i get 12 out. If I put 3, I get 123. If I put 4, I get 1234. That is the gist of this set of problem. However, I developed a mathematical equation that works if I put it through a loop:
if __name__ == '__main__': # ignore this part
n = int(input())
s = 1
while s > n:
z = s*10**(n-s)
s += 1
answer = z
if s == n:
print(z)
When I tried to run this code, I got nothing, even though I added print at the end. What is it that I am doing wrong here? For anyone answering the problem, introduce any concepts that you know that may help me; I want to learn it.
Please enlighten me. Don't exactly give me the answer....but try to lead me in the right direction. If I made a mistake in the code (which I am 100% sure I did), please explain to me what's wrong.
It's because your while loop condition is backwards. It never enters the loop because s is not bigger than n. It should be while s < n
Use a for loop using range() as in
for i in range(1, n+1):
where n is the input so that the numbers from 1 till n can be obtained.
Now use a print() to print the value of i during each iteration.
print() by default will add a newline at the end. To avoid this, use end argument like
print(var, end='')
Once you are familiar with this, you can also use list comprehension and join() to get the output with a single statement like
print( ''.join([str(i) for i in range(1, n+1)]) )
Take the input as you've done using input() and int() although you might want to include exception handling in case the input is not an integer.
See Error handling using integers as input.
Here is the solution:
Using string
a = int(input())
# taking the input from the user
res=''
# using empty string easy to append
for i in range(1,a+1):
# taking the range from 1 (as user haven't said he want 0, go up to
# a+1 number (because range function work inclusively and will iterate over
# a-1 number, but we also need a in final output ))
res+=str(i)
# ^ appending the value of I to the string variable so for watch iteration
# number come append to it.
# Example : 1-> 12-> 123-> 1234-> 12345-> 123456-> 1234567-> 12345678-> 123456789
# so after each iteration number added to it ,in example i have taken a=9
sol = int(res) #converting the res value(string) to int value (as we desire)
print(sol)
In one line, the solution is
a=int(input())
res=int(''.join([str(i) for i in range(1,a+1)]))
Try this,
n = int(input('Please enter an integer'))
s = 1
do:
print(s)
s+=1
while s == n
this works.
(Simple and Short)
#find highest number
def HighValue(arr, HighestValue=0):
if len(arr) > 0:
arrayValue = arr.pop()
if len(arr) == 0:
return HighestValue
elif HighestValue <= arrayValue:
HighestValue = arrayValue
return HighValue(arr, HighestValue)
else:
return HighValue(arr, HighestValue)
print HighValue([1,2,3,4,5,6,7,8,9])
This function returns the highest value of an array using recursion. It works, but I feel like I am writing more code than necessary. Does anyone have any advice as to whether I could have made this recursion algorithm simpler? I hope I am allowed to ask quesitons like that here. If not, let me know. I feel I will get better if I get feedback from more experienced programers.
Let me know what you think.
Since there are some programming design basics involved, I'll answer this instead of remanding it to CodeReview.
Yes, you're writing more code than needed. You don't need to force all of the mechanics yourself. Worry about the base case, the recursion step, and the return value. Everything else should be easy from there.
Don't pass the best value through the parameter list; just pass back the best value you have so far.
Don't pop things off the list; just call the routine with the tail of the list. Note that my solution strips elements off the beginning, instead of the end. You are welcome to reverse this logic.
If the list is only one element long, return it. When you get back to the parent call, return the higher of the end element or the returned value:
def HighValue(arr):
best = 0
if len(arr) > 0:
best = HighestValue(arr[1:])
return best if best > arr[0] else arr[0]
If you're not worried about execution time, you can elide best with an extra recursive call.
Please keep in mind that I am still fairly new to Python. I have this question which I have a fair bit of trouble understanding. I have made an attempt at this problem:
def Sample(A):
for i in range(len(A)):
if A == 1:
print A
elif A == (-1):
print A
Question:
Write a function where A is a list of strings, as of such print all the strings in A that start with '-1' or '1'
In your if and elif you are testing A, i.e. whether the whole list is equal to the value, which will never be True. Instead, test, each item in A. You can either stick with your index:
for i in range(len(A)):
if A[i] == ...
or, better, iterate over A directly:
for item in A:
if item == ...
Next, to test whether a string starts with a character, use str.startswith:
for item in A:
if item.startswith("1"):
...
Note that this uses the string "1", rather than the integer 1.
You're comparing if A equals 1 or -1, which is a bad start. You should be checking if i starts with either of those.
if i.startwith("1"):
Edit:
I completely edited my answer since I had misunderstood the question the first time.
You need to test for two cases does a_string in A start with '1' or start with -1.
Python offers a number ways to do this. First, is the string.startswith('something') method. This checks to see if the string startswith something you specified.
def Sample(A):
for each_string in A:
if each_string.startswith(('1','-1')):
print each_string
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)
> *****!!!!!