im trying to do letter sorting according to this example :
Input:
people enjoy programming
Output:
[(set(['e', 'o']), set(['l']), set(['p'])),
(set(['e', 'o']), set(['j']), set(['n', 'y'])),
(set(['o', 'a', 'i']), set(['g', 'm']), set(['p', 'r', 'n']))]
So here is my code :
lista=[[[0],[0],[0]],[[0],[0],[0]],[[0],[0],[0]]]
x=raw_input('please enter 3 words: ')
words=x.split()
if len(words)!=3:
print('error!!! enter 3 words ')
else:
i=0
c=0
while i<3:
for m in range(len(words[i])):
if words[i][m] in ['a','e','i','o','u']:
lista.insert([i][0][c],words[i][m])
lista.insert([i][0][-1],0)
c=c+1
elif words[i][m] in ['b','c','d','f','g','h','j','k','l','m']:
lista.insert([i][1][c],words[i][m])
lista.insert([i][1][-1],0)
c=c+1
else:
lista.insert([i][2][c],words[i][m])
lista.insert([i][2][-1],0)
c=c+1
i=i+1
lista=(set(lista[1][1],lista[1][2],lista[1][3],lista[2][1],lista[2][2],lista[2][3],lista[3][1],lista[3][2],lista[3][3]))
lista=(tuple(lista[1],lista[2],lista[3]))
print lista
And when i try to run it i get this error :
Traceback (most recent call last): File "C:/Python27/ex7.py", line 22, in
lista.insert([i][2][c],words[i][m]) IndexError: list index out of range
Someone see what i did wrong?
I don't think the line lista.insert([i][1][c],words[i][m]) (and the similar lines with other indexes) do what you seem to be intending. Rather than inserting words[i][m] into lista[i][1][c], you're getting an error when trying to evaluate [i][1][c]. That subexpression creates an one element list ([i], then tries to access the value at index 1, which doesn't work.
I think you may want to use something like lista[i][1].append(words[i][m]).
However, it would be much easier if you directly iterated over your lists and strings, rather than using ranges and indexing:
output = []
for word in words:
vowels = set()
consonants1 = set()
consonants2 = set()
for character in word:
if character in "aeiou":
vowels.add(character)
elif character in "bcdfghjklm":
consonants1.add(character)
else:
consonants2.add(character)
output.append([vowels, consonants1, consonants2])
words = []
output = []
desired_output = [(set(['e', 'o']), set(['l']), set(['p'])), (set(['e', 'o']), set(['j']), set(['n', 'y'])),
(set(['o', 'a', 'i']), set(['g', 'm']), set(['p', 'r', 'n']))]
while True:
# words = raw_input('please enter 3 words: ').split()
words = "people enjoy programming".split()
if len(words) != 3:
print('error!!! enter 3 words ')
else:
break
for word in words:
vow = set()
con1 = set()
con2 = set()
for char in word:
if char in "aeiou":
vow.add(char)
elif char in "bcdfghjklm":
con1.add(char)
else:
con2.add(char)
output.append([vow, con1, con2])
print output
print desired_output
Output:
[[set(['e', 'o']), set(['l']), set(['p'])], [set(['e', 'o']), set(['j']), set(['y', 'n'])], [set(['a', 'i', 'o']), set(['m', 'g']), set(['p', 'r', 'n'])]]
[(set(['e', 'o']), set(['l']), set(['p'])), (set(['e', 'o']), set(['j']), set(['y', 'n'])), (set(['a', 'i', 'o']), set(['m', 'g']), set(['p', 'r', 'n']))]
Replace the words = "people enjoy programming".split() for the one above it to make it interactive.
Your use of range and index to access items is very common among anyone who already had a past programming experience(perhaps C++?), in Python most of the things are iterable. You can use a for loop over a list, and it will return each item, you can iterate over a string and it will return each character.
Related
I am doing this code wars kata https://www.codewars.com/kata/57eb8fcdf670e99d9b000272/train/python
you have to return the highest scoring word within a string. letters are scored based on position in the alphabet
a =1, z= 26
I've created a list :
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
I want to iterate through the words, which will be in the string (x) passed as a parameter, and if the letter being checked is in the alphabet list, which it of course will be, then to a sperate variable: score, increment score by the number at which the current letter being checked is indexed within the alphabet list.
Is it possible to use list indexes in this way?
Here's my code soo far:
def high(x):
alphabet = []
scores = [] # ignore
score = 0
for letter in range(97,123):
alphabet.append(chr(letter))
word_list = x.split()
for word in word_list:
for letter in word:
if letter in alphabet:
score += # find way to use alphabet list index number as integer here
Thanks.
From what I can see the list of letters isn't needed at all :
import string
def high(x):
score = 0
for word in x.split():
for letter in word:
if letter in string.ascii_lowercase:
score += ord(letter)-96
return score
or even simpler :
import string
def high(x):
# Sum expression on multiple lines for clarity
return sum( ord(letter)-96
for word in x.split()
for letter in word
if letter in string.ascii_lowercase)
Use list comprehensions and dictionary score to keep track of each letter and its score. Notice that the input string is lowercased - I assume that upper- and lowercase letters are scored the same.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
score = dict(zip(list(alphabet), [i + 1 for i in range(len(alphabet))]))
x = 'aB, c'
score = sum([score[c] for c in list(x.lower()) if c in score])
print(score)
# 6
#AlanJP, would you like to try this program:
# simple word scoring program
import string
characters = string.ascii_lowercase
ranking = {c: i for i, c in enumerate(characters, 1)}
#print(ranking)
word_list = 'abba is great'.split()
for word in word_list:
score = 0 # reset the score for each incoming word
for char in word:
score += ranking[char]
print(word, score)
Output:
abba 6
is 28
great 51
>>>
Yes. alphabet.index(letter) + 1 will give you what you want.
index() you're going also want to +1 to account for index [0]
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index)
No imports allowed (it's a school assignment).
Wish to split a random string into a list of sublists. Words in a sublist, all other characters (including whitespace) would be in a sublist containing only one item. Anyone have some advice on how to do this;
part = "Hi! Goodmorning, I'm fine."
list = [[H,i],[!],[_],[G,o,o,d,m,o,r,n,i,n,g],[,],[_],[I],['],[m],[_],[f,i,n,e],[.]]
This does the trick:
globalList = []
letters = "abcdefghijklmnopqrstuvwxyz"
message = "Hi! Goodmorning, I'm fine."
sublist = []
for char in message:
#if the character is in the list of letters, append it to the current substring
if char.lower() in letters:
sublist.append(char)
else:
#add the previous sublist (aka word) to globalList, if it is not empty
if sublist:
globalList.append(sublist)
#adds the single non-letter character to the globalList
globalList.append([char])
#initiates a fresh new sublist
sublist = []
print(globalList)
#output is [['H', 'i'], ['!'], [' '], ['G', 'o', 'o', 'd', 'm', 'o', 'r', 'n', 'i', 'n', 'g'], [','], [' '], ['I'], ["'"], ['m'], [' '], ['f', 'i', 'n', 'e'], ['.']]
Try this out :
part = "Hi! Goodmorning, I'm fine."
n = part.count(" ")
part = part.split()
k = 0
# Add spaces to the list
for i in range(1,n+1):
part.insert(i+k, "_")
k += 1
new = [] # list to return
for s in part:
new.append([letter for letter in s])
part = "Hi! Goodmorning, I'm fine."
a = []
b = []
c = 0
for i in part:
if i.isalpha():
if c == 1:
a.append(b)
b=[]
b.append(i)
c = 0
else:
b.append(i)
else:
a.append(b)
b=[]
b.append(i)
c = 1
a.append(b)
print a
I have a text file , which reads this.
a,b,c,d,e,f,g,h
a,b,c,i,j,k,l,m
f,k
Now, I want to store the first line as a list, second list in other list. But the third two values, I want to store in some particular variables say a=f, b=k.
I have made the code, but its showing error during reading the third line.
Please someone help this.
Here is my code.
filename = 'input.txt'
fin=open(filename,'r')
n=fin.readline()
m=fin.readline()
a,b=fin.readline()
UPDATE:
with open('input.txt') as fin:
n=fin.readline().split()
m=fin.readline().split()
line=(fin.readline())
a,b=line[0],line[2]
i=0
for i in range(0,len(n)):
if n[i]!=a:
i+=1
cp=i-1
i=0
for i in range(0,len(n)):
if n[i]!=a:
i+=1
posa=i-1
i=0
for i in range(0,len(n)):
if m[i]!=b:
i+=1
posb=i-1
while(posa>cp):
posa-=1
while(posa>cp):
posb-=1
if(cp<0):
print("No Common Predecessor")
elif (posa<posb):
if(posa<0):
posa=0
print("Common Predecessor: %s" %n[posa])
else:
if(posb<0):
posb=0
print("Common Predecessor: %s" %m[posb])
Method readline() returns string. To get a list you have to use:
m=fin.readline().strip().split(',')
n=fin.readline().strip().split(',')
a,b=fin.readline().strip().split(',')
Use with open;
with open('my.txt') as f:
lines = f.read().splitlines()
# lines[0] == 'a,b,c,d,e,f,g,h'
# lines[1] == 'a,b,c,i,j,k,l,m'
# lines[2] == 'f,k'
# lines[3] == '.'
n = list(lines[0].split(','))
m = list(lines[1].split(','))
a, b = lines[2].split(',')
# n == ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h ']
# m == ['a', 'b', 'c', 'i', 'j', 'k', 'l', 'm ']
# a == f
# b == k
Then you can do what you want with each line.
Your problem lies with the fact that a,b=fin.readline() would execute fin.readline() twice, giving you a = 'f,k' and b = '.' (which is the following line that is read)
To prevent this, you could assign the previous line to a variable and then split it into variables a and b.
For example:
filename = 'input.txt'
fin = open(filename )
n=fin.readline().split()
m=fin.readline().split()
line=(fin.readline())
a,b=line.split(',')
b=b.strip()
Or a more simplified approach using with open:
with open('input.txt') as fin:
n=fin.readline().split()
m=fin.readline().split()
line=(fin.readline())
a,b=line.split(',')
b=b.strip()
Both of these approches would yield the output:
>>> n
['a,b,c,d,e,f,g,h']
>>> m
['a,b,c,i,j,k,l,m']
>>> a
'f'
>>> b
'k'
I'm working on a definition tester (you enter in words, their part of speeches, and synonyms for each, and it tests you on them). Problem I have is with the part that gets the word:
def get_word(): # this is in another function, that's why it is indented
import easygui as eg
word_info = eg.multenterbox(msg = 'Enter in the following information about each word.'
, title = 'Definition Tester'
, fields = ['Word: ', 'Part of Speech: ', 'Synonyms (separated by spaces): ']
, values = []
)
return word_info
for i in range(n):
my_list = get_word()
print my_list # for testing
word, pOS, synonyms = my_list[0], my_list[1], my_list[2]
word = word.capitalize()
synonyms = synonyms.split(', ')
words_list += word
print word # for testing
test_dict[word] = [pOS, synonyms]
print words_list # for testing
However, words_list ends up being the word(s) after the list(word) function is applied to them--- I'm not sure why.
For example: if the only word was 'word', words_list turns out to be ['w', 'o', 'r', 'd']. If there were two words ('dog', 'cat'), words_list turns out to be ['d', 'o', 'g', 'c', 'a', 't'].
Here is my input (into get_word()): Word: 'myword', Part of Speech: 'n', Synonyms: 'synonym, definition'.
This is the output I get:
['myword', 'n', 'synonym, definition']
Myword
['M', 'y', 'w', 'o', 'r', 'd'] # Why does this happen?
This is the only thing wrong with my program... If I could get some input on how to fix this and what is wrong, it would be much appreciated. Thanks!
It's because of this line:
words_list += word
+= on a list is for adding all the elements in another list. As it happens, Python strings also function like lists of characters, so you are adding each character to the list as its own element.
You want this:
words_list.append(word)
which is for adding a single element to the end.
After messing around with it, I figured out the problem myself, so I thought I should put it here for anyone who has something similar:
Instead of doing words_list += word, it should be: words_list.append(word).
Or, which is what I did, you can do: words_list += [word]. Now, word is a list object, so it will add onto the previous list.
I'm trying to see if a word or sentence has each letter of the alphabet and I can't get it to print all the letters that isn't in the sentence/word.
alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t'
,'u','v','w','x','y','z']
x = raw_input('')
counter = 0
counter2 = 0
for i in range(len(x))
counter += 1
for o in range(26):
counter2 += 1
if alpha[counter2] not in x[counter]:
and I'm stuck there...
alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t'
,'u','v','w','x','y','z'}
input_chars = set(raw_input())
print alphabet - input_chars
All we do is set difference between the set of alphabet characters and the set of characters in our input. Note that the difference operation can take as a second operand any iterable, so we don't even really have to turn our input into a set if we don't want to, although this will speed up the difference a small amount. Furthermore, there is a built-in string which gives us the ascii letters so we could do it like this:
import string
print set(string.ascii_lowercase) - raw_input()
using set difference:
import string
x=raw_input()
not_found=set(string.ascii_lowercase) - set("".join(x.split()))
print (list(not_found))
output:
>>>
the quick brown fox
['a', 'd', 'g', 'j', 'm', 'l', 'p', 's', 'v', 'y', 'z']
Since you're already iterating over both strings, there is no need to use counter and counter2.
You were almost there. Python makes list operations simple, so there's no need to iterate over the lists element-by-element using indices:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
sentence = raw_input('Enter a sentence: ').lower() # Because 'a' != 'A'
letters = []
for letter in sentence:
if letter in alphabet and letter not in letters:
letters.append(letter)
print(letters)
Much easier:
import string
x = raw_input()
print [c for c in string.ascii_lowercase if c not in x]