How can i get enumerate object inside on screen - python

I want to write screen Capital letters and index numbers in word="WElCMMerC".For example [(0,W),(1,E),(3,C),(4,M),(5,M)...]
def cap(word):
w=list(enumerate(i) for i in word if i!=i.lower())
print (w)
print(cap("WElCMMerC"))

You can loop over the result of enumerate, and keep only those which have an uppercase letter (using isupper to check for that), and return the list w, don't print inside the function:
def cap(word):
w = [i for i in enumerate(word) if i[1].isupper()]
return w
print(cap("WElCMMerC"))
Output:
[(0, 'W'), (1, 'E'), (3, 'C'), (4, 'M'), (5, 'M'), (8, 'C')]

You made a list of enumerate objects. Read the documentation: enumerate is an iterator, much like range. Rather, you need to use the enumeration.
return [(idx, letter)
for idx, letter in enumerate(word)
if letter.isupper()]
In English:
Return the pair of index and letter
for each index, letter pair in the word
but only when the letter is upper-case.

Related

Ngram in python with start_pad

i'm know in python i'm take some basic thing about list and tuple but my not full understand the my cod i want create list have three index in each index have tuple with tow index like this [('~','a'),('a','b'),('b','c')] the first index in tuple have tow char or the length context when have like this [('~a','a'),('ab','b'),('bc',' c')] can any one help my ? Her my code
def getNGrams(wordlist, n):
ngrams = []
padded_tokens = "~"*(n) + wordlist
t = tuple(wordlist)
for i in range(3):
t = tuple(padded_tokens[i:i+n])
ngrams.append(t)
return ngrams
IIUC, You can change the function like below and get what you want:
def getNGrams(wordlist, n):
ngrams = []
padded_tokens = "~"*n + wordlist
for idx, i in enumerate(range(len(wordlist))):
t = tuple((padded_tokens[i:i+n], wordlist[idx]))
ngrams.append(t)
return ngrams
print(getNGrams('abc',1))
print(getNGrams('abc',2))
print(getNGrams('abc',3))
Output:
[('~', 'a'), ('a', 'b'), ('b', 'c')]
[('~~', 'a'), ('~a', 'b'), ('ab', 'c')]
[('~~~', 'a'), ('~~a', 'b'), ('~ab', 'c')]

turning a list back into a string python

The first function is able to separate each letter of a string and list how many times that letter appears. For example:
print(rlencode("Hello!"))
[('H', 1), ('e', 1), ('l', 2), ('o', 1), ('!', 1)]
How do I get rldecode(rle): do the the complete opposite of rlencode(s) so that rldecode(rlencode(x)) == x returns True
def rlencode(s):
"""
signature: str -> list(tuple(str, int))
"""
string=[]
count=1
for i in range(1,len(s)):
if s[i] == s[i-1]:
count += 1
else:
string.append((s[i-1], count))
count=1
if i == len(s)-1:
string.append((s[i], count))
return string
def rldecode(rle):
"""
#signature: list(tuple(str, int)) -> str
#"""
string=" "
count=1
for i in rle:
if i == rle:
string += i
return string
You can use the fact that you can multiply a string by a number to repeat it and use `''.join() to bring the elements of the list together.
To show the effect of string multiplication, I multiplied "a" by 5
"a"*5 #'aaaaa'
Using that in a comprehension will give you
str = [char[0]*char[1] for char in rle] #['H', 'e', 'll', 'o', '!']
Then add in the ''.join() and you have your answer.
l = [('H', 1), ('e', 1), ('l', 2), ('o', 1), ('!', 1)]
str = ''.join(char[0]*char[1] for char in rle) #'Hello!'
So your function would be
def rldecode(rle):
"""
signature: list(tuple(str, int)) -> str
"""
return ''.join(char[0]*char[1] for char in rle)
Also, if you would like to make your rlencode a little cleaner, you can simplify it a little bit by using enumerate to help you keep your position in the string and check if you're about to hit either a new character or the end of the string. You just have to increment the counter on each loop.
def rlencode(s):
output = []
count = 0
for i, char in enumerate(s):
count += 1
if (i == (len(s)-1)) or (char != s[i+1]):
output.append((char, count))
count = 0
return output
Use join:
b = [('H', 1), ('e', 1), ('l', 2), ('o', 1), ('!', 1)]
''.join([c[0] * c[1] for c in b])
Hello!
You can also use list comprehensions for your initial function.
You can use collections.Counter.elements():
from collections import Counter
l = [('H', 1), ('e', 1), ('l', 2), ('o', 1), ('!', 1)]
print(''.join(Counter(dict(l)).elements()))
This outputs:
Hello!
A simple, readable solution is to iterate over all of the tuples in the list returned by rlencode and construct a new string from each letter (and it's frequency) like so:
def rldecode(rle):
string = ''
for letter, n in rle:
string += letter*n
return string
An answer that's easy to read but also accounts for ordering in the problem:
def rlencode(s):
"""
signature: str -> list(tuple(str, int, list(int)))
"""
result=[]
frequency=1
for i in range(len(s)):
letters = [item[0] for item in result]
if s[i] in letters:
idx = letters.index(s[i])
frequency=result[idx][1]
frequency+=1
positions= result[idx][2]
positions.append(i)
result[idx] = (s[i],count,lst)
else:
result.append((s[i],1,[i]))
return result
def rldecode(rle):
"""
#signature: list(tuple(str, int, list(int))) -> str
#"""
frequencies = [i[1] for i in rle]
total_length = sum(frequencies)
char_list=[None]*total_length
for c in rle:
for pos in c[2]:
char_list[pos] = c[0]
return "".join(char_list)
text = "This is a lot of text where ordering matters"
encoded = rlencode(text)
print(encoded)
decoded = rldecode(encoded)
print(decoded)
I adapted it from the answer posted by #Brian Cohan
It should be noted that the answer is computationally expensive because of .index() if letter grows really long as explained in this SO post

Compare List of Tuples and Return Indices of Matched Values

I'm new to programming and am having some trouble with this exercise. The goal is to write a function that returns a list of matching items.
Items are defined by a tuple with a letter and a number and we consider item 1 to match item 2 if:
Both their letters are vowels (aeiou), or both are consonants
AND
The sum of their numbers is a multiple of 3
NOTE: The return list should not include duplicate matches --> (1,2) contains the same information as (2,1), the output list should only contain one of them.
Here's an example:
***input:*** [('a', 4), ('b', 5), ('c', 1), ('d', 3), ('e', 2), ('f',6)]
***output:*** [(0,4), (1,2), (3,5)]
Any help would be much appreciated!
from itertools import combinations
lst = [('a', 4), ('b', 5), ('c', 1), ('d', 3), ('e', 2), ('f',6)]
vowels = 'aeiou'
matched = [(i[0],j[0]) for (i,j) in combinations(enumerate(lst),2) if (i[1][0] in vowels) == (j[1][0] in vowels) and ((i[1][1] + j[1][1]) % 3 == 0)]
print(matched)
Sorry, I'm high enough rep to comment, but i'll edit / update once I can.
Im a little confused about the question, what is the purpose of the letters, should we be using their positon in the alphabet as their value? i.e a=0, b=1?
what are we comparing one tuple to?
Thanks
You can use itertools.combinations with enumerate to iterate all combinations and output indices. Combinations do not include permutations, so you will not see duplicates.
from itertools import combinations
lst = [('a', 4), ('b', 5), ('c', 1), ('d', 3), ('e', 2), ('f',6)]
def checker(lst):
vowels = set('aeiou')
for (idx_i, i), (idx_j, j) in combinations(enumerate(lst), 2):
if ((i[0] in vowels) == (j[0] in vowels)) and ((i[1] + j[1]) % 3 == 0):
yield idx_i, idx_j
res = list(checker(lst))
# [(0, 4), (1, 2), (3, 5)]

Trying to create python program, but simplified with def

I'm trying to create a program without importing anything. The program lets the user input a passage, then prints how many A's there are in the message, how many B's, etc.
So it works...it's just VERY long. I'm new to coding, and I know that there is a way to simplify the code below with def but I'm not really sure how. Can anyone help?
You need no methods, but you can definately cut it short:
String can be used as an array of characters.
You can use the index method to determine what is the position of the letter in the alphabet.
You can iterate a zipped list of pairs from the alphabet and the counter list, to produce the output.
Use if letter in alphabet as a guard to ensure the letter is valid for the alphabet, instead of hard coding the alphabet. That way you can even expand your alphabet. (Note that the counter is set to the length of the alphabet).
Here is a suggestion:
message = input('what is your message? ').upper()
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
counter = [0] * len(alphabet)
for letter in message:
if letter in alphabet:
counter[alphabet.index(letter)] += 1
for letter, count in zip(alphabet, counter):
print(letter, ':', count)
One can do it with a one line instruction, where we make use of:
count method of string that returns the numbers of element contained in a string
chr function that gives a character from an int. chr(65) gives a A, chr(66) gives a B, ...
join function that concatenates strings of a list
The result looks like
message = input('what is your message? ').upper()
print('\n'.join([chr(65+i)+':'+str(message.count(chr(65+i))) for i in range(26)]))
For a very short and elegant solution use the Counter unit from the collections module:
from collections import Counter
message=raw_input("what is your message?")
message=message.upper()
c = Counter(message)
print c.most_common()
This counts every kind of letter in the message. And it can even sort the result for you quickly. Here is a sample dialog:
"what is your message?Hi there, new Pythonist!
[(' ', 3), ('E', 3), ('H', 3), ('T', 3), ('I', 2), ('N', 2), ('!', 1), (',', 1), ('O', 1), ('P', 1), ('S', 1), ('R', 1), ('W', 1), ('Y', 1)]"

Python:Update list of tuples

I have a list of tuples like this:
list = [(1, 'q'), (2, 'w'), (3, 'e'), (4, 'r')]
and i am trying to create a update function update(item,num) which search the item in the list and then change the num.
for example if i use update(w,6) the result would be
list = [(1, 'q'), (6, 'w'), (3, 'e'), (4, 'r')]
i tried this code but i had error
if item in heap:
heap.remove(item)
Pushheap(item,num)
else:
Pushheap(item,num)
Pushheap is a function that push tuples in the heap
any ideas?
You can simply scan through the list looking for a tuple with the desired letter and replace the whole tuple (you can't modify tuples), breaking out of the loop when you've found the required item. Eg,
lst = [(1, 'q'), (2, 'w'), (3, 'e'), (4, 'r')]
def update(item, num):
for i, t in enumerate(lst):
if t[1] == item:
lst[i] = num, item
break
update('w', 6)
print(lst)
output
[(1, 'q'), (6, 'w'), (3, 'e'), (4, 'r')]
However, you should seriously consider using a dictionary instead of a list of tuples. Searching a dictionary is much more efficient than doing a linear scan over a list.
As noted in the comments, you are using an immutable data structure for data items that you are attempting to change. Without further context, it looks like you want a dictionary, not a list of tuples, and it also looks like you want the second item in the tuple (the letter) to be the key, since you are planning on modifying the number.
Using these assumptions, I recommend converting the list of tuples to a dictionary and then using normal dictionary assignment. This also assumes that order is not important (if it is, you can use an OrderedDict) and that the same letter does not appear twice (if it does, only the last number will be in the dict).
>>> lst = [(1, 'q'), (2, 'w'), (3, 'e'), (4, 'r')]
>>> item_dict = dict(i[::-1] for i in lst)
>>> item_dict
{'q': 1, 'r': 4, 'e': 3, 'w': 2}
>>> item_dict['w'] = 6
>>> item_dict
{'q': 1, 'r': 4, 'e': 3, 'w': 6}
Tuples are an immutable object. Which means once they're created, you can't go changing there contents.
You can, work around this however, by replaceing the tuple you want to change. Possibly something such as this:
def change_item_in_list(lst, item, num):
for pos, tup in enumerate(lst):
if tup[1] == item:
lst[pos] = (num, item)
return
l = [(1, 'q'), (2, 'w'), (3, 'e'), (4, 'r')]
print(l)
change_item_in_list(l, 'w', 6)
print(l)
But as #brianpck has already said, you probably want a (ordered)-dictionary instead of a list of tuples.

Categories