short Question in Code:
i=0
k_start[i]
[8515]
i=1
k_start[i]
139253
How can i avoid the parenthesis in this example? Or Why at least do they appear with when i is 0?
Edit: Sorry for this bad Question, the problem was that i had a list of lists.
I'm not sure why your first element is coming out as a sub-list but you can get rid of the brackets (in this one specific case) by calling k_start[0][0]... Try printing k_start to see what the whole array looks like. That way you can see what is happening and perhaps find a more general solution. It's hard to do from the outside without more info, such as upstream code or a printout of the array.
Related
For a string, we want to make it all lower case and remain only alphabetical or space element.
The right answer is
But for my code I think they are the same but did not work as well.
The first one is the right answer and the second one is my code. Could you help me figure out what happened? Thanks
Your return statement is nested inside the for loop, so it returns the value immediately.
You need to decrease the indentation of the return statement, so that the value is returned after the loop is completed.
Check Python Reference Manual - 2.1.7 Indentation
This question already has answers here:
Remove all occurrences of a value from a list?
(26 answers)
Closed 2 years ago.
So I want to execute only while loop statements, without putting anything inside them. For example, I have an array arr from which I have to remove multiple occurrences of some element. The instant the condition statement returns an error, while loop should end.
arr=[1,2,4,2,4,2,2]
This removes only one 2:
arr.remove(2)
I need to run this as long as it does not return error. (C++ has a semicolon put after while to do this).
I want something like this
while(arr.remove(2));
Three things.
First, it's not considered good practice in Python – it's not "pythonic" – to use an expression for its side effects. This is why, for example, the Python assignment operator is not itself an expression. (Although you can do something like a = b = 1 to set multiple variables to the same value, that statement doesn't break down as a = (b = 1); any such attempt to use an assignment statement as a value is a syntax error.)
Second, modifying data in place is also discouraged; it's usually better to make a copy and make the changes as the copy is constructed.
Third, even if this were a good way to do things, it wouldn't work in this case. When the remove method succeeds, it returns None, which is not truthy, so your loop exits immediately. On the other hand, when it fails, instead of returning a false value, it throws an exception, which will abort your whole program instead of just the loop, unless you wrap it in a try block.
So the list comprehension probably is the best solution here.
The way you are looking to solve this does not yield the results you are looking for. Since you are looking to create a new list, you are not going to want to use the remove function as per #Matthias comment. The idiomatic way to do it would be something along the lines of this:
arr=[1,2,4,2,4,2,2]
arr = [x if x != 2 for x in arr]
So I want to execute only while loop statements, without putting anything inside them.
That's really not necessary. Don't try to copy other language's syntax in Python. Different languages are designed with different objectives and hence, they have different syntax (or grammar of the language). Python has a different way of doing things than C++.
If you want to focus on the effectiveness of the program, then that's the different story. See this for more information on this.
Unfortunately, remove doesn't return anything (it returns None). So, you can't have anything that would look neat and clean without putting anything inside while.
Pythonic way to remove all occurrence of a element from list:
list(filter((2).__ne__, arr))
Or
arr = [x for x in arr if x != 2]
Or
while 2 in arr:
arr.remove(2)
you can use:
arr = [1,2,4,2,4,2,2]
try:
while arr.pop(arr.index(2)):
pass
except ValueError:
pass
print(arr)
#[1, 4, 4]
I am assuming you want to remove all occurrences of an element. This link might help you.
click here
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:
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.