This question already has answers here:
How to get the size of a string in Python?
(6 answers)
Closed 1 year ago.
we have just begun our unit on recursion, and I had a question regarding non-recursive functions and strings
I understand that strings are inherently recursive, as each character within a string has its own positive or negative index value, but I am a little unclear on how to create this function.
EDIT: Please disregard above text
What I meant to say:
I understand that a sequence is recursive in nature, that a string is a character followed by another string, just as a list is an element followed by another list.
Imagine we had a function called:
def flipside(s)
And when we input a string into our s parameter of the function, for example, the string:
'homework'
It takes the first half of the string (s) and moves it to the back while taking the second half of the string moving it the front, effectively generating the output:
'workhome'
I guess what I am having an issue with, is regarding string operations. If I do not know the length of s because it can take on any value due to it being a parameter, how do I create a non-recursive program to take 1//2 of s and move that half of the string to the back while simultaneously pushing the second half forward.
I have only gone so far as to set my base case:
def flipside(s):
if s == (''):
return 0
else:
fliprest =
return fliprest
Thank you, I would appreciate any information on the thought process behind your logic, or any feedback regarding any bad habits that I may be developing with how I have started off my code.
You can use slicing
def flipside(s):
return s[len(s)//2:] + s[:len(s)//2]
>>> flipside('homework')
'workhome'
Related
This question already has answers here:
Understanding slicing
(38 answers)
Closed 5 years ago.
Say I have x = 'abcde'. If I write x[::] I get 'abcde', If I write x[::2] I get 'ace'. So the spaces between the colons implies for the first space, "the start of the list" and for the second space "the end of the list". It's as if you were writing x[0:len(x)] right?
Okay, so when I write x[::-1] I get the list completely in reverse, i.e. 'edcba'. So what are the equivalent values I could substitute in?
x[len(x)-1:0:-1] won't work because the second space is not including that number, so I would get 'edcb' and if I went x[len(x)-1:-1:-1] it would simply do nothing because x[len(x)-1] == x[-1].
Yes, it will always work if I leave the colons in, my confusion comes is what does just having x[::] actually doing, what values is it actually substituting? Because if it were always just "the start of the list and the end of the list" then there's no way it would work for x[::-1], it would simply print nothing, and if it somehow knows to reverse it, then what values is it putting because even if we didn't have the problem of not being able to terminate at the right place (i.e. can't put 0 in the middle space because that wouldn't be include but can't put -1 because that's the end of the list) we have the problem that it should still start at 0, i.e. we should have
aedcb instead?
Can anyone shed light on the behind the scenes magic here?
Thank-you.
(Yes I googled for this, and tried to look it up in the docs and could find no explanation to this specific question)
edit: The answer to my question can be found in the non accepted answer of Understanding Python's slice notation, namely, https://stackoverflow.com/a/24713353/4794023.
Thanks guys
Slicing will include the element at start index, and will not include the stop index. Since a "stop" index of -1 already has a different meaning (used to wrap around to the end of the string) then you'll have to use a None instead:
>>> x[len(x)-1:None:-1]
'edcba'
I'm currently trying to learn python.
Suppose there was a a number n = 12345.
How would one go about changing every digit starting from the first spot and iterating it between (1-9) and every other spot after (0-9).
I'm sadly currently learning python so I apologize for all the syntax error that might follow.
Here's my last few attempts/idea for skeleton of the code.
define the function
turn n into string
start with a for loop that for i in n range(0,9) for i[1]
else range(10)
Basically how does one fix a number while changing the others?
Please don't give solution just hints I enjoy the thinking process.
For example if n =29 the program could check
19,39,49,59,69,79,89,99
and
21,22,23,24,25,26,27,28
Although you are new, the process seems far easy than you think.
You want to make that change to every digit of the number (let's say n=7382). But you cannot iterate over numbers (not even changing specific digits of it as you want to): only over iterables (like lists). A string is an iterable. If you get the way to do a int-str conversion, you could iterate over every number and then print the new number.
But how do you change only the digit you are iterating to? Again, the way is repeating the conversion (saving it into a var before the loop would make great DRY) and getting a substring that gets all numbers except the one you are. There are two ways of doing this:
You search for that specific value and get its index (bad).
You enumerate the loop (good).
Why 2 is good? Because you have the real position of the actual number being change (think that doing an index in 75487 with 7 as the actual one changing would not work well when you get to the last one). Search for a way to iterate over items in a loop to get its actual index.
The easiest way to get a substring in Python is slicing. You slice two times: one to get all numbers before the actual one, and other to get all after it. Then you just join those two str with the actual variable number and you did it.
I hope I didn't put it easy for you, but is hard for a simple task as that.
This question already has answers here:
Using 'try' vs. 'if' in Python
(9 answers)
Closed 6 years ago.
I have a function in which I would like to detect the first occurrence of any letter (given a group of letters) within a string and return the index of the letter(see below).
Time is critical so I am thinking of using a try/except method (see LetterDetect below).
Knowing that the try statement will fail most of the time, is this a bad practice? Secondly Would this be more efficient (time-wise) than checking every dictionary entry for the occurrence of each letter (as in LetterDetect2)?
Take the following function which looks:
def LetterDetect(s, letters):
Dct = {}
for l in letters:
Dct[ord(l)] = 0
for i in range(0, length(s)):
try:
Dct[ord(s[i])] +=1
return i
except:
pass
Versus:
def LetterDetect2(s, letters):
Dct = {}
for l in letters:
Dct[ord(l)] = 0
for i in range(0, length(s)):
if ord(s[i]) in Dct:
return i
LetterDetect("test", "abcdt")
LetterDetect2("test", "abcdt")
I appreciate any help, I am new to coding and Python. Thanks!
Using a dictionary seems like an odd way to solve this problem. Is there some specific reason you're using that?
The string method .find() https://docs.python.org/2/library/stdtypes.html#str.find seems like a much better solution:
def LetterDetect(s, letters)
for l in letters:
position = s.find(l)
if position != -1:
return position
return None
In addition to the basic problems with your design that John Gordon pointed out, I would like to respond directly to the question:
Using try/catch to achieve ordinary flow control is an abuse of its purpose. I can predict several ways this might bite you (the debugger might stop you on the exception, a future programmer might "correct" your code) but the basic rule is, use language features as they were designed.
As a practical matter, a try/catch will tend to be slow. The language runtime has to get involved and do all sorts of fancy things, none of which you actually need.
Exceptions should be, well, exceptional.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reverse a string in Python
Its been stumping me despite my initial thoughts that it would be simple.
Originally, I thought I would have have it print the elements of the string backwards by using slicing to have it go from the last letter to the first.
But nothing I've tried works. The code is only a couple lines so I don't think I will post it. Its extraordinarily frustrating to do.
I can only use the " for ", "while", "If" functions. And I can use tuples. And indexing and slicing. But thats it. Can somebody help?
(I tried to get every letter in the string to be turned into a tuple, but it gave me an error. I was doing this to print the tuple backwards which just gives me the same problem as the first)
I do not know what the last letter of the word could be, so I have no way of giving an endpoint for it to count back from. Nor can I seem to specify that the first letter be last and all others go before it.
You can do:
>>> 'Hello'[::-1]
'olleH'
Sample
As Mike Christensen above wrote, you could easily do 'Hello'[::-1].
However, that's a Python-specific thing. What you could do in general if you're working in other languages, including languages that don't allow for negative list slicing, would be something more like:
def getbackwards(input_string):
output = ''
for x in range(0,len(input_string),-1):
output += input_string[x]
return output
You of course would not actually do this in Python, but just wanted to give you an example.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Hi I'm trying to reverse a string with the following code. Does anyone see the bug here?
def reverse(string):
length = len(string)
last = length -1
middle = length/2
newstring = []
for i in range(middle):
newstring[i] = string[last -i]
newstring[last -i] = string[i]
return ''.join(newstring)
There are multiple bugs:
You can't index into an empty list: newstring[i] and newstring[last -i].
You always add characters in pairs, so the result (if other bugs are fixed) always has an even length, even if the input string had an odd length.
There may be more.
Lastly, I think you're making it too hard for yourself:
In [1]: 'abcdef'[::-1]
Out[1]: 'fedcba'
This uses the slicing syntax, which is start:stop:step. By omitting start and stop we're taking the entire string, and step=-1 simply means that we're taking the characters in reverse order.
You can't do newstring[last-i], right? That should return an index error.
How about this one:
def reverse(string):
tmp=[]
for c in string:
tmp.insert(0,c)
return ''.join(tmp)
You're going out of range because you're directly assigning to an index of an empty list. On the first pass you reference the nonexistent newstring[0].
Do not use the name "string". It is the name of a common Python module that you may end up importing. Looking at this, most people wouldn't know if you were referring to the module here or not.
If you want to do the whole manual list manipulation thing for the sake of pedagogy, you're better off treating the source string as a stack and the destination list as a queue, popping off the source and enqueueing on the destination:
def reverse(source):
source = list(source)
dest = []
while source:
dest.append(source.pop())
return ''.join(dest)
In general, you shouldn't have to use numeric indexing in Python for operations that affect the entire collection uniformly. If you find yourself in that situation you're most likely thinking too low-level.
I would personally use extended slice notation:
"hello world"[::-1]
Leaving off the first argument of a slice means "the beginning of the list". Leaving off the second argument of a slice means "the end of the list". The third argument represents the step by which the list is traversed. By stepping negatively you traverse the list in reverse.
Another way is:
"".join(reversed("abc"))
But probably is not as efficient as aix's Method to reverse a string.