Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Say for example I have the following string:
Hello
And my job is to shift all the letters over by however many spots I am told to, and lets say it is 1, so the result would be:
elloH
But my program returns it as
elloh
What I want to know is, how can I get a list with the indices of where a capital letter is, so I can make the letters at that same spot in the new string uppercase?
I think you would do it by converting the String to a list through list(string) and then iterate through the list so, and whenever the item in the list returns true for isUpper(), then store the index of that in a list. I just am not able to write it in python.
I will assume that your question is regarding:
And my job is to shift all the letters over by however many spots I am told to
In that case, try:
def shift(s, n):
return s[n:] + s[:n]
Examples:
>>> shift('Hello', 1)
'elloH'
>>> shift('Hello', 2)
'lloHe'
This appears to be the output that you were looking for.
How to get indices of the capital letters in a string:
def getindices(s):
return [i for i, c in enumerate(s) if c.isupper()]
Examples:
>>> getindices('Hello')
[0]
>>> getindices('HeLlO')
[0, 2, 4]
To add to the solution by #John1024
This supports any number to rotate by
def shift(s, n):
return s[n%len(s):] + text[:n%len(s)]
>>> shift('Hello', 51)
'elloH'
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm trying to make three different functions to decrypt an encrypted string. The follow conditions are :
(1) if the character "T" (uppercase) is found, it implies that the next three characters must be
lowercase vowels.
(2) If rule 1 is met, the position will be a continuous 6-digit number from the fourth position with
respect to the "T" character. The odd ones correspond to the first coordinate field and the pairs
to the second coordinate field.
For example:
Taeo135789->[158,379]
Tauo123456->[135,246]
(3) After the digits, an acronym of 3 is presented. I want to print this separately.
Example:
INPUT: dsa2wtasfwTaeo135789konsadfa241
OUTPUT: (Taeo135789kon)
Taeo
[158,379]
kon
I already tried:
def first_rule(str_encript):
vowels = "aeiou"
str_encript = str(str_encript)
for s in str_encript:
if "T" in s:
(next three characters must be lowercase vowels.)
else:
print("Error in the encrypted str\n")
You can use a reqular expression to extract all the examples of this pattern from a string:
import re
pat = re.compile(r'(T[aeiou]{3})(\d{6})([a-z]{3})')
def first_rule(encrypted):
for match in pat.finditer(encrypted):
t_str, nums, acro = match.group(1, 2, 3)
coordinates = [int(''.join(nums[x::2])) for x in range(2)]
print(t_str, coordinates , acro, sep='\n')
first_rule('dsa2wtasfwTaeo135789konsadfa241')
# Taeo
# [158, 379]
# kon
If you really can't use the re module (which is a built-in library distributed with Python), then you can achieve a similar result scanning the string with enumerate:
def first_rule(encrypted):
for i, c in enumerate(encrypted):
if c == 'T':
t_str = encrypted[i+1:i+4]
if len(t_str) != 3 or any(x not in 'aeiou' for x in t_str):
continue
t_str = 'T' + t_str
nums = encrypted[i+4:i+10]
if len(nums) != 6 or any(x not in '0123456789' for x in nums):
continue
coordinates = [int(''.join(nums[x::2])) for x in range(2)]
acro = encrypted[i+10:i+13]
if len(acro) != 3 or any(x not in 'qwertyuiopasdfghjklzxcvbnm' for x in acro):
continue
print(t_str, coordinates , acro, sep='\n')
By tracking the index we're on in the string, we can look ahead of the T to do our matching.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
is there a way to count letters in this sentence, and print the most used ones?(like: G A D F J N) I know how to count them and sort thwm but cant figure out how to print the letters instead of th ordered numbers.(btw all letters need to be printed in the result)
#example
input: Hello you!
Output: O L H E Y U # <-at least 1 letter# A B C D#<- The rest of the letters
What im trying:
Pismenka = [0] *26
Veta = input()
For i in veta:
Pismenka[ord(i-97)]+=1
Here is an example for you;
import re
text = "Hello you!"
# I lowered capitalized characters because if there was 'H' and 'h',
# the program would have counted these two as two different letters.
text = text.lower()
letters = {}
#We search for '\w' which means only latin characters.
for i in re.findall(r"\w", text):
if i not in letters:
letters[i] = 1
else:
letters[i] += 1
# We sort the items according to the count of letters.
sortedByCount = dict(sorted(letters.items(), key=lambda x: x[1], reverse=True))
# We get only the keys, 'letters' out of the dictionary and concatnate with spaces.
output = " ".join(sortedByCount.keys())
Output:
l o h e y u
First I would look for a magic optimized function already coded in the Python jungle. I'm sure this question was already raised and optimized.
If I had to do it myself from a preliminary unoptimized thought I would do something like this:
testString = 'Hello sss Test'
from collections import OrderedDict
alreadyTested = OrderedDict()
for c in testString:
if c not in alreadyTested:
alreadyTested[c] = testString.count(c)
for c in sorted(alreadyTested,key=alreadyTested.__getitem__,reverse=True):
print(c,alreadyTested[c])
the use of an ordered dictionary is required if you want letters with the same occurrence number to remain in appearance order. Otherwise you can use a basic dictionary.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Is it possible do like that with list comprehension. For example, if I call function f4(5), it should show like: [[[[[]]]]]. So each time append empty list in previous list.
You can append a list to itself, which since lists are mutable, sets off a recursion that leads to an infinitely nested list that can be indexed up until the recursion limit. Python uses the elipisis placeholder to display this:
>>> lst = []
>>> lst.append(lst)
>>> lst
[[...]]
>>> lst[0][0][0][0][0]
[[...]]
However, I can imagine no practical use for this at all.
def f(x):
if x == 1:
return []
return [f(x-1)]
print(f(5))
Output:
[[[[[[]]]]]]
I don't see any real use for that, but of course it's possible.
def f(n):
return [f(n - 1)] if n > 1 else []
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
How can I find the smallest odd number in a list of integers, if the problem statement says that I can't use for and if?
You can use filter and min:
s = [4, 2, 3, 4, 7, 1]
smallest_odd = min(filter(lambda x:x%2 != 0, s))
Output:
1
Why should anyone consider using for or if?
min(numbers, key=lambda n: (n&1==0, n))
you can use
ints = [2,6,8,4,6 ]
srt = sorted(ints)
while len(srt) > 0 and not srt[0] % 2:
srt = srt[1:]
s = None
while len(srt):
s = srt[0]
srt=[]
print(s)
to circumvent the rules. You sort the list, discard any even values from front.
The resulting list is either empty or has the value at front.
The second while is only entered if the list contains elements, and the list is reset to empty (which is false and will not renter the while).
It will print "None" or the lowest not even number.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How can I find the index of an element of a list which may contain duplicate items?
This is my code:
def as_str(L):
string = "("
for element in L:
string += str(element)
if L.index(element) < len(L) - 1:
string += ", "
string += ")"
return string
which doesn't work if the list contains duplicate items.
You could simply use join, e.g.:
def as_str(L):
return "({})".format(", ".join([str(x) for x in L]))
Addressing your comment, L.index takes optional 'start' and 'stop' parameters that you could use to search a range of indexes (e.g. in a loop).