Given a string with codon letters I can´t figure what the following program is explicitly doing. I know that it goes through the whole string but what is it doing exactly ?
s = "AVGGGKGDEMAWTWVRPMGVIDWEEGGVKLVAGLLP"
[i for i in range(1,len(s)) if s[i] in 'VE' and s[i-1]!= 'W'] ?
The response is [5, 28].
This list comprehension goes through string s one index at a time and checks 2 conditions:
Is the character at index i in the string 'VE'?
Is the character before the character at index i not equal to 'W'?
If both those conditions are True then i is added to a new list (which in this example isn't being saved).
The output is telling you the characters at index 5 and index 28 meet these conditions (the output doesn't seem to be right for this string though). Remember strings are 0 indexed, meaning the first letter of the string is accessed via s[0].
Additional info:
Strings
List Comprehensions
Related
I found this piece of code from a related question about reversing strings in python, but can someone please interpret it in plain English? Please note that I am still new to python and only learnt how to use while loops and functions yesterday :/ so I cant really put this into words myself cause my understanding isn't quite there yet.
anyways here is the code:
def reverse_string(string):
new_strings = []
index = len(string)
while index:
index -= 1
new_strings.append(string[index])
return ''.join(new_strings)
print(reverse_string('hello'))
Surely by knowing what it does, you can figure the code. In the while loop, the index value starts from the end of the string and counts down to 0. In each step, it adds that character (again, starting from the end) to the end of the list it is building. Finally, it combines the list into a string.
So, given 'abcd', the list gets built:
'abcd' #3 -> ['d']
'abcd' #2 -> ['d','c']
'abcd' #1 -> ['d','c','b']
'abcd' #0 -> ['d','c','b','a']
Well basically, the get the length of the string with the len method. Which will return you an integer value representing how long that string is.
They then use the length of this string and effectively iterate down to zero in a while loop. Using the -= operator.
Each iteration (meaning each time around the loop) it will take away from length until it reaches zero.
So lets use hello as an example input and go through this together.
reverse_string('hello') is how we would call the method, done in the print statement of your code.
We then enter the function and perform these steps:
We create a new empty array called new_strings.
We find the length of the initial string hello which returns us 5. Meaning that now index is equal to 5.
We create a while loop that keeps on going until index is no more using while(index): - a while loop like this treats a 0 value as falsy and will terminate upon reaching this. Therefore when index is 0 the loop will stop.
The first line of this loop performs index -= 1 which is the same as writing index = index - 1 so the very first loop through we get index = 5 - 1 and then now index is equal to 4.
Because Python then lets us access the character of a string using string[index] (and because this works from 0 -> n) performing hello[4] will in fact give us the character o.
We also append this character to the array new_strings meaning that as we go through the iterations to reach zero it will add each character backwards to this array giving us ['o', 'l', 'l', 'e', 'h']
Since index is now zero we leave the loop and perform a join operation on the array to yet again create a string. The command ''.join(new_strings) means that we wish to join the array we previously had without a separator. If we had done '#'.join(new_strings) we instead would have gotten o#l#l#e#h instead of olleh.
I hope this answer gives you some clarity.
Sure, It is very simple program. You should reffer string methods and string indexing in python to get clear idea. Let me explain this in deatial.
print(reverse_string('hello'))//The print function is calling another function
reverse_string and passing argument"hello".
def reverse_string(string):// The argument "hello" is stored in the variable
string in reverse_string function.
**new_strings = []** // created a new empty list
**index = len(string)** // len function returns the length of the argument
passed to the function. len("hello")=5 and assigned
to index. index=5.
while index: // while loop exicute until the condition get false .In this
example when index =0.in string the indexing start from 0 .For
example.
string[0]=h,string[1]=e,string[2]=l,string[3]=l,string[4]=o.
**index -= 1** //Note the last letter 'o' is in string[4] and the len
function returned 5 so we need to decrement index variable
to 4 so that it will pointing to string[4]=o
new_strings.append(string[index]) // append string[4] that is o and so on ...
return ''.join(new_strings)
Write a function that takes, as an argument, a list, identified by the variable aList. If the list only contains elements containing digits (either as strings as integers), return the string formed by concatenating all of the elements in the list (see the example that follows). Otherwise, return a string indicating the length of the list, as specified in the examples that follow.
I am just starting to learn how to code and this is my first CS class.
def amIDigits(aList):
for element in range(aList):
if element in aList.isdigit():
bList=[]
bList.append(aList)
return str(bList)
amIDigits([“hello”, 23]) should return the string “The length of the input is 2.”
amIDigits ([“10”, “111”]) should return the string “10111”
If I understand it right the output will be the joined digits even if they are not of the string format. So the best way is to use the all function (returns true if all elements of an iteration are true) and check if the string elements of the list are digits. If so, then return the join of all elements of the list converted to a string. Else, we return the length of the list using the new string formatting syntax (f represents string formatting and the {} return the result of an operation).
code:
def amIDigits(aList):
if all([str(i).isdigit() for i in aList]):
return ''.join(map(str,aList))
else:
return f'The length of the input is {len(aList)}.'
print(amIDigits(['hello', 23]))
print(amIDigits(['10', '111']))
print(amIDigits([55, 33]))
output:
The length of the input is 2.
10111
5533
First, I highly recommend having someone literally sit down and have you walk them through your thought process. It is more useful as a learner to debug your thought process than to have someone give you the answer.
One thing I noticed is that you created your empty list, bList, inside the for block. This will not work. You need to create an empty list to store things into before you begin for looping through the old list, otherwise you will be over-writing your new list every time it loops. So right now, your bList.append() statement is appending an element onto an empty list every time it runs. (You will get only the very last element in the aList stored into your bList.)
Another problem is that you use the range() function, but you don't need to. You want to look at each element inside the list. Range creates a sequence of numbers from 0 to whatever number is inside the parentheses: range() documentation. Your code tries to pass a list into range(), so it is invalid.
The "for blank in blank" statement breaks up whatever list is in the second blank and goes through each of its elements one at a time. For the duration of the for statement, the first blank is the name of the variable that refers to the element being looked at. so for example:
apples = ["Granny Smith","Red Delicious","Green"]
for apple in apples:
eat(apple) #yum!
The for in statement is more naturally spoken as "for each blank in blank:"
In python slicing ' If the first index is greater than or equal to the second the result is an empty string ' then why the following operation return string?
>>> msg = 'HelloWorld'
>>> msg[4:-2]
'oWor'
The quote you gave is either incorrect or incomplete:
If a negative number is used, it will be used as the reverse index on the file, meaning that [4:-2] is equivalent to [4:len(msg)-2] ie [4:8]
Note that if you use the reverse index to go further that the first index, you will indeed have an empty string.
msg[4:-8] # Equivalent to msg[4:1], by the same formula
>>> ''
Negative numbers in python slicing effectively work backwards from positive. They start at the end of the string and move forward. So what your code says is give me a string starting at the 4th index and goes until 2 from the end.
Indexes if negative they count from right. -1 is the last character. To access string from right index position we need to use - with index number. So for -2, it will be like take character till before l (for given example) and its total length must be 4. So it will be owor only.
>>> '12345'.count('')
6
Why does this happen? If there are only 5 characters in that string, why is the count function returning one more?
Also, is there a more effective way of counting characters in a string?
count returns how many times an object occurs in a list, so if you count occurrences of '' you get 6 because the empty string is at the beginning, end, and in between each letter.
Use the len function to find the length of a string.
That is because there are six different substrings that are the empty string: Before the 1, between the numbers, and after the 5.
If you want to count characters use len instead:
>>> len("12345")
5
How many pieces do you get if you cut a string five times?
---|---|---|---|---|--- -> 6 pieces
The same thing is happening here. It counts the empty string after the 5 also.
len('12345') is what you should use.
The most common way is to use len('12345'). It returns the number of characters in a given string - in this case 5.
Count and Len are two very different things. Len simply prints the length of the string (hence the name 'Len'), while Count iterates through the string or list and gives you the number of times an object occurs, which counts the beginning and end of the string as well as in between each letter.
It's the same reason why it makes sense for ''.count('') to return 1, not 0.
find('asdf','') finds an empty string in 'asdf' hence it returns 0.
Similarly, find('asdf','',3) starts to search for the string at index position 3 and hence return 3.
Since the last index is 3, find('asdf','',4) should return -1 but it returns 4 and starts to return -1 only if the starting index is more than or equal to (last_index)+2. Why is this so?
Because "asdf" without its first four characters still does contain "". A harder check comes into play when the index exceeds the length of the string, but having an index equal to the string is equivalent to "".find().
Here is how it works:
0 a 1 s 2 d 3 f 4
When you use 'asdf'.find(sub), it searches those five positions, labeled 0, 1, 2, 3, and 4. Those five. Those five. No more and no less. It returns the first one where 'asdf'[pos:pos+len(sub)] == sub. If you include the start argument to find, it starts at that position. That position. Not one less, not one more. If you give a start position greater than the greatest number in the list of positions, it returns -1.
In other words, the answer is what I already repeated in a comment, quoting another question answer:
The last position [for find] is after the last character of the string
Edit: it seems your fundamental misunderstanding relates to the notion of "positions" in a string. find is not returning positions which you are expected to access as individual units. Even if it returns 4, that doesn't mean the empty string is "at" position 4. find returns slice starts. You are supposed to slice the string starting at the given position.
So when you do 'asdf'.find('', 4), it starts at position 4. It finds the empty string there because 'asdf'[4:4+len('')]==''. It returns 4. That is how it works.
It is not intended that str.find has a one-to-one mapping between valid indexes into the actual string. Yes, you can do tons of other indexing like 'asdf'[100:300]. That is not relevant for find. What you know from find is that 'asdf'[pos:pos+len(sub)] == sub. You do not know that every possible index that would return '' will be returned by find, nor are you guaranteed that the number returned by find is a valid index into the string if you searched for an empty string.
If you have an actual question about some use of this functionality, then go ahead and ask that as a separate question. But you seem to already know how find works, so it's not clear what you're hoping to gain from this question.