Logic Error in Most Common Letter Finder - python

So, this program simply lets the user enter a string, and counts the occurrence of each character, then displayed the most frequent.
I enter "AABBCCC", and it tells me that the max is 7, and that the most frequent is "Q".
countList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 \
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 \
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 \
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 \
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
index = 0
for character in userInput:
if character == "Q" or "q":
countList[0] += 1
elif character == "W" or "w":
countList[1] += 1
elif character == "E" or "e":
countList[2] += 1
elif character == "R" or "r":
countList[3] += 1
elif character == "T" or "t":
countList[4] += 1
elif character == "Y" or "y":
countList[5] += 1
elif character == "U" or "u":
countList[6] += 1
elif character == "I" or "i":
countList[7] += 1
elif character == "O" or "o":
countList[8] += 1
elif character == "P" or "p":
countList[9] += 1
elif character == "A" or "a":
countList[10] += 1
elif character == "S" or "s":
countList[11] += 1
elif character == "D" or "d":
countList[12] += 1
elif character == "F" or "f":
countList[13] += 1
elif character == "G" or "g":
countList[14] += 1
elif character == "H" or "h":
countList[15] += 1
elif character == "J" or "j":
countList[16] += 1
elif character == "K" or "k":
countList[17] += 1
elif character == "L" or "l":
countList[18] += 1
elif character == "Z" or "z":
countList[19] += 1
elif character == "X" or "x":
countList[20] += 1
elif character == "C" or "c":
countList[21] += 1
elif character == "V" or "v":
countList[22] += 1
elif character == "B" or "b":
countList[23] += 1
elif character == "N" or "n":
countList[24] += 1
elif character == "M" or "m":
countList[25] += 1
elif character == "`":
countList[26] += 1
elif character == "~":
countList[27] += 1
elif character == "1":
countList[28] += 1
elif character == "!":
countList[29] += 1
elif character == "2":
countList[30] += 1
elif character == "#":
countList[31] += 1
elif character == "3":
countList[32] += 1
elif character == "#":
countList[33] += 1
elif character == "4":
countList[34] += 1
elif character == "$":
countList[35] += 1
elif character == "5":
countList[36] += 1
elif character == "%":
countList[37] += 1
elif character == "6":
countList[38] += 1
elif character == "^":
countList[39] += 1
elif character == "7":
countList[40] += 1
elif character == "&":
countList[41] += 1
elif character == "8":
countList[42] += 1
elif character == "*":
countList[43] += 1
elif character == "9":
countList[44] += 1
elif character == "(":
countList[45] += 1
elif character == "0":
countList[46] += 1
elif character == ")":
countList[47] += 1
elif character == "-":
countList[48] += 1
elif character == "_":
countList[49] += 1
elif character == "=":
countList[50] += 1
elif character == "+":
countList[51] += 1
elif character == "[":
countList[52] += 1
elif character == "{":
countList[53] += 1
elif character == "]":
countList[54] += 1
elif character == "}":
countList[55] += 1
elif character == "\\":
countList[56] += 1
elif character == "|":
countList[57] += 1
elif character == ";":
countList[58] += 1
elif character == ":":
countList[59] += 1
elif character == "'":
countList[60] += 1
elif character == "\"":
countList[61] += 1
elif character == ",":
countList[62] += 1
elif character == "<":
countList[63] += 1
elif character == ".":
countList[64] += 1
elif character == ">":
countList[65] += 1
elif character == "/":
countList[66] += 1
elif character == "?":
countList[67] += 1
mostFrequent = max(countList)
print(mostFrequent)
characterKey = ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A" \
, "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M" \
, "`", "~", "1", "!", "2", "#", "3", "#", "4", "$", "5", "%", "6", "^", "7" \
, "&", "8", "*", "9", "(", "0", ")", "-", "_", "=", "+", "[", "{", "]", "}" \
, "\\", "|", ";", ":", "'", "\"", ",", "<", ".", ">", "/", "?"]
index = 0
for character in countList:
if character == mostFrequent:
print(characterKey[index], "is most frequent.")
index += 1

One of the issues that you are dealing with is that
elif character == "T" or "t"
does not work the way you think it does. You must restate the left-handed side of the expression again, like this:
elif character == "T" or character == "t"
or you can use the in operator:
elif character in ("T,"t")
However, changing this is not going to completely fix your issue.
One thing that would help your code be cleaner and faster would be to look into translating the character value that you receive into an integer value, and then using the integer value as a means of putting the character into the right index of the array. I'll leave that exercise to you :)

I think the use of a dict would save you some code. .lower() can prevent you having to check each as I'm assuming that for your puposes 't is eqivalent to 'T'. Note that helper function is expecting a string that is not Null. Hope this can help
def get_character_frequency(user_input):
'''return dictionary of frequencies to characters'''
char_freq_dict = {}
freq_char_dict = {}
#create dict with characters as keys and freqs as values
for character in user_input:
char_freq_dict[character] = char_freq_dict.get(character, 0) + 1
#invert dict
for character, freq in char_freq_dict.items():
if freq in freq_char_dict.keys():
freq_char_dict[freq].append(character)
else:
freq_char_dict[freq] = [character]
return freq_char_dict
def main():
#you could add some code to ensure some text is entered, or
#modify to error check for this
userInput = input("Enter String: ").lower()
freq_char_dict = get_character_frequency(userInput)
max_freq, max_char = sorted(freq_char_dict.items(), reverse=1)[0]
print('\n{} characters were entered'.format(len(userInput)))
print('Most frequent character(s) {}'.format(max_char), end=" ")
print('Ocurring {} time(s)'.format(max_freq))
main()

This will help you.
import re
import itertools
import operator
def most_common(L):
# get an iterable of (item, iterable) pairs
SL = sorted((x, i) for i, x in enumerate(L))
# print 'SL:', SL
groups = itertools.groupby(SL, key=operator.itemgetter(0))
# auxiliary function to get "quality" for an item
def _auxfun(g):
item, iterable = g
count = 0
min_index = len(L)
for _, where in iterable:
count += 1
min_index = min(min_index, where)
# print 'item %r, count %r, minind %r' % (item, count, min_index)
return count, -min_index
# pick the highest-count/earliest item
return max(groups, key=_auxfun)[0]
user_input = [_.lower() for _ in raw_input("Enter String: ")]
frequent = most_common(list(user_input))
print "Most frequent entry:",frequent
print "Number of Occerences:",user_input.count(frequent)
OUTPUT:
Enter String: aAbBBcccC12309u/.,;'/*
Most frequent entry: c
Number of Occerences: 4

Related

Using if statements

I am attempting to make a simple Python code that replaces numbers with roman numerals. In order to do this, I need to get the position of each number to replace it with the roman numeral equivalent. However, my code doesn't seem to work.
number = range(1,21)
number = list(number)
number = str(number)
for i in number:
for x in i:
if i.index(x) == 0:
if x == "1":
x.replace(x, "X")
elif x == "2":
x.replace(x, "XX")
else:
if x == 1:
x.replace(x, "I")
elif x == 2:
x.replace(x, "II")
elif x == 3:
x.replace(x, "III")
elif x == 4:
x.replace(x, "IV")
elif x == "5":
x.replace(x, "V")
elif x == "6":
x.replace(x, "VI")
elif x == "7":
x.replace(x, "VII")
elif x == "8":
x.replace(x, "VIII")
elif x == "9":
x.replace(x, "IX")
else:
x.replace(x, "")
print number
I suspect that it has to do with the way that my if statements work, but I'm not sure. Any advice would be appreciated.
A long sequence of if and elif clauses is usually a sign that one should be using one or more dicts.
numstrings = [str(i) for i in range(1, 100)]
d0 = {'0':'', '1':'I', '2':'II', '3':'III', '4':'IV',
'5':'V', '6':'VI', '7':'VII', '8':'VIII', '9':'IX'}
d10 = {'0':'', '1':'X', '2':'XX', '3':'XXX', '4':'XL',
'5':'L', '6':'LX', '7':'LXXX', '8':'LXXX', '9':'XC'}
for s in numstrings:
if len(s) == 1:
r = d0[s]
elif len(s) == 2:
r = d10[s[0]] + d0[s[1]]
else:
r = '??'
print(r)

python skipping for loop

So my problem is that my code is skipping the last three "for" loops. here is my full code:
import os
import os.path
clear = lambda: os.system('cls')
def RNA2ENZ(RNA, number):
if RNA[0][number:number + 3] == "UUU" or RNA[0][number:number + 3] == "UUC":
letter = "F"
return letter
elif RNA[0][number:number + 3] == "UUA" or RNA[0][number:number + 3] == "UUG":
letter = "L"
return letter
elif RNA[0][number:number + 3] == "CUU" or RNA[0][number:number + 3] == "CUC" or RNA[0][number:number + 3] == "CUG" or RNA[0][number:number + 3] == "CUA":
letter = "L"
return letter
elif RNA[0][number:number + 3] == "AUU" or RNA[0][number:number + 3] == "AUC" or RNA[0][number:number + 3] == "AUA":
letter = "I"
return letter
elif RNA[0][number:number + 3] == "AUG":
letter = "M"
return letter
elif RNA[0][number:number + 3] == "GUU" or RNA[0][number:number + 3] == "GUC" or RNA[0][number:number + 3] == "GUA" or RNA[0][number:number + 3] == "GUG":
letter = "V"
return letter
elif RNA[0][number:number + 3] == "UCU" or RNA[0][number:number + 3] == "UCC" or RNRNA[0][number:number + 3] == "UCA" or RNA[0][number:number + 3] == "UCG":
letter = "S"
return letter
elif RNA[0][number:number + 3] == "CCG" or RNA[0][number:number + 3] == "CCC" or RNA[0][number:number + 3] == "CCA" or RNA[0][number:number + 3] == "CCU":
letter = "P"
return letter
elif RNA[0][number:number + 3] == "ACG" or RNA[0][number:number + 3] == "ACA" or RNA[0][number:number + 3] == "ACC" or RNA[0][number:number + 3] == "ACU":
letter = "T"
return letter
elif RNA[0][number:number + 3] == "GCU" or RNA[0][number:number + 3] == "GCC" or RNA[0][number:number + 3] == "GCA" or RNA[0][number:number + 3] == "GCG":
letter = "A"
return letter
elif RNA[0][number:number + 3] == "UAU" or RNA[0][number:number + 3] == "UAC":
letter = "Y"
return letter
elif RNA[0][number:number + 3] == "UAA" or RNA[0][number:number + 3] == "UAG":
letter = "."
return letter
elif RNA[0][number:number + 3] == "CAU" or RNA[0][number:number + 3] == "CAC":
letter = "H"
return letter
elif RNA[0][number:number + 3] == "CAA" or RNA[0][number:number + 3] == "CAG":
letter = "Q"
return letter
elif RNA[0][number:number + 3] == "AAU" or RNA[0][number:number + 3] == "AAC":
letter = "N"
return letter
elif RNA[0][number:number + 3] == "AAA" or RNA[0][number:number + 3] == "AAG":
letter = "K"
return letter
elif RNA[0][number:number + 3] == "GAU" or RNA[0][number:number + 3] == "GAC":
letter = "D"
return letter
elif RNA[0][number:number + 3] == "GAA" or RNA[0][number:number + 3] == "GAG":
letter = "E"
return letter
elif RNA[0][number:number + 3] == "UGU" or RNA[0][number:number + 3] == "UGC":
letter = "C"
return letter
elif RNA[0][number:number + 3] == "UGA":
letter = "."
return letter
elif RNA[0][number:number + 3] == "UGG":
letter = "W"
return letter
elif RNA[0][number:number + 3] == "CGU" or RNA[0][number:number + 3] == "CGC" or RNA[0][number:number + 3] == "CGA" or RNA[0][number:number + 3] == "CGG":
letter = "R"
return letter
elif RNA[0][number:number + 3] == "GGU" or RNA[0][number:number + 3] == "GGC" or RNA[0][number:number + 3] == "GGA" or RNA[0][number:number + 3] == "GGG":
letter = "G"
return letter
elif RNA[0][number:number + 3] == "AGU" or RNA[0][number:number + 3] == "AGC":
letter = "S"
return letter
elif RNA[0][number:number + 3] == "AGA" or RNA[0][number:number + 3] == "AGG":
letter = "R"
return letter
else:
letter = "-"
return letter
def DNA2RNA(Strand, numb):
if Strand[0][numb] == "G":
letter = "G"
return letter
elif Strand[0][numb] == "C":
letter = "C"
return letter
elif Strand[0][numb] == "T":
letter = "U"
return letter
elif Strand[0][numb] == "A":
letter = "A"
return letter
def DNAfilp(DNA, num):
if DNA[0][num] == "G":
letter = "C"
return letter
elif DNA[0][num] == "C":
letter = "G"
return letter
elif DNA[0][num] == "T":
letter = "A"
return letter
elif DNA[0][num] == "A":
letter = "T"
return letter
clear()
print("please delete the 5' and 3' from the file")
filename = raw_input("please enter file name to convert:")
clear()
intron = raw_input("are there any introns? If so enter 'yes' else enter 'no':")
if intron == "yes":
clear()
intronfile = raw_input("please enter the file name with the introns and please make sure there is a space inbetween each intron (tip:max of five):")
else:
print("")
clear()
outputfileDNA = raw_input("please enter outputfile for DNA name:")
clear()
outputfileRNA = raw_input("please enter outputfile for RNA name:")
clear()
outputfileENZ = raw_input("please enter outputfile for ENZ name:")
clear()
prime = input("which is first 5' or 3' (tip: just enter the number):")
clear()
file = open(filename, 'r')
DNA = file.read()
DNAlength = len(DNA)
DNA = DNA.split()
intfile = open(intronfile, 'r')
introns = intfile.read()
introns = introns.split()
print(introns)
num = 0
code = ""
raw_input()
clear()
for number in range(0, DNAlength):
code = code + DNAfilp(DNA, num)
num = num + 1
if prime == 5:
realcode = "3'" +code + "5'"
elif prime == 3:
realcode = "5'" + code + "3'"
else:
realcode = code
if prime == 5:
DNAtop = "5'" + DNA[0] + "3'"
elif prime == 3:
DNAtop = "3'" + DNA[0] + "5'"
else:
DNAtop = DNA[0]
outputDNAstrand = DNAtop + " " + realcode
DNAstrand = code + " " + DNA[0]
realcode = realcode.split()
code = code.split()
RNA = ""
numb = 0
if prime == 5:
Strand = DNA
elif prime == 3:
Strand = code
else:
Strand = DNA
for number in range(0, DNAlength):
RNA = RNA + DNA2RNA(Strand, numb)
numb = numb + 1
count = 0
raw_input()
RNA = str(RNA)
for number in range(0, len(introns)):
RNA = RNA.replace(introns[count], "")
count = count + 1
RNA = RNA.split()
print(RNA[0])
ENZlength = len(RNA)/3
number1 = 0
number2 = 1
number3 = 2
ENZ1 = ""
ENZ2 = ""
ENZ3 = ""
raw_input()
for number in range(0, ENZlength):
ENZ1 = ENZ1 + RNA2ENZ(RNA, number1)
number1 = number1 + 3
raw_input()
raw_input()
for number in range(0, ENZlength):
ENZ2 = ENZ2 + RNA2ENZ(RNA, number2)
number2 = number2 + 3
for number in range(0, ENZlength):
ENZ3 = ENZ3 + RNA2ENZ(RNA, number3)
number3 = number3 + 3
outputENZ = " ENZ1: " + ENZ1 + " ENZ2: " + ENZ2 + " ENZ3: " + ENZ3
outputRNA = "RNA: " + str(RNA[0])
if os.path.isfile(outputfileDNA) == True:
os.remove(outputfileDNA)
out_file = open(outputfileDNA, "w")
out_file.write(outputDNAstrand)
out_file.close()
if os.path.isfile(outputfileRNA) == True:
os.remove(outputfileRNA)
out_file = open(outputfileRNA, "w")
out_file.write(outputRNA)
out_file.close()
if os.path.isfile(outputfileENZ) == True:
os.remove(outputfileENZ)
out_file = open(outputfileENZ, "w")
out_file.write(outputENZ)
out_file.close()
raw_input("all done!")
this code was working all fin before I added these lines:
RNA = str(RNA)
for number in range(0, len(introns)):
RNA = RNA.replace(introns[count], "")
count = count + 1
RNA = RNA.split()
I do not know why this would change anything but it did. What I am trying to do is to convert one strand of DNA to RNA then to an Enzyme code (the DNA is a cipher in which certain enzymes equal certain letters). my code creates the DNA and RNA fine but it skips the last 3 for loops for unknown reason. Any help would be great.
[EDIT] The code finishes normally but it does not run the loop. It even bypasses the raw_input in the loops themselves. Also the
I actually figured out what my problem was when looking over #Austin Hastings question. ENZlength which is defining how long the for loop is is actually finding the wrong length. It is doing len(RNA) which is 1 because it is reading how many lists there are when the actual answer should be len(RNA[0]) which is how many characters are in the first item.

Having trouble with an index Error

I am doing an assignment for my first computer programming course, and I am running into a problem. Basically this program is supposed to take a phonetically Hawaiian word, and produce a string that shows how to prounce it. However when I run the program, this happens:
stopProgram = 1
while stopProgram == 1:
validWord = 0
while validWord == 0:
#this while loop is has the user enter a word until it means Hawaiian syntax.
userWord = input("Please enter a valid hawaiian word.")
userWordEval = userWord.lower()
#changed the case for easier comparisons
validInput = 0
for j in range (len(userWordEval)):
#Test every character in the word to see if it meets the requirements. If it does, valid word is added 1.
if userWordEval[j] == "a" or userWordEval[j] == "e" or userWordEval[j] == "i" or userWordEval[j] == "o" or userWordEval[j] == "u" or userWordEval[j] == "p" or userWordEval[j] == "k" or userWordEval[j] == "h" or userWordEval[j] == "l" or userWordEval[j] == "m" or userWordEval[j] == "n" or userWordEval[j] == "w" or userWordEval[j] == "'" or userWordEval[j] == " ":
validInput += 1
if validInput == len(userWordEval):
#if the number in validWord is equal to the length of the word the user put in, that means that all the charaters were accepted. Otherwise, that means that something wasn't allowed, and will have to be reentered.
validWord = 1
else:
print("Invalid input. The accepted characters are: a, e, i, o, u, p, k, h, l, m, n, w, and '")
proWord = "" #Using this for the pronunciation string.
q = 0
while q <= len(userWordEval):
if userWordEval[q] == "a":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "i":
proWord += "-eye"
q += 2
elif userWordEval[q+1] == "e":
proWord += "-eye"
q += 2
elif userWordEval[q+1] == "o":
proWord += "-ow"
q += 2
elif userWordEval[q+1] == "u":
proWord += "-ow"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-ah"
q += 2
else:
proWord += "-ah"
q += 1
else:
proWord += "-ah"
q += 1
elif userWordEval[q] == "e":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "i":
proWord += "-ay"
q += 2
elif userWordEval[q+1] == "u":
proWord += "-ow"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-eh"
q += 2
else:
proWord += "-eh"
q += 1
else:
proWord += "-eh"
q += 1
elif userWordEval[q] == "i":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "u":
proWord += "-ay"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-ee"
q += 2
else:
proWord += "-ee"
q += 1
else:
proWord += "-ee"
q += 1
elif userWordEval[q] == "o":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "i":
proWord += "-oy"
q += 2
elif userWordEval[q+1] == "u":
proWord += "-ow"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-oh"
q += 2
else:
proWord += "-oh"
q += 1
else:
proWord += "-oh"
q += 1
elif userWordEval[q] == "u":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "i":
proWord += "-ooey"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-oo"
q += 2
else:
proWord += "-oo"
q += 1
else:
proWord += "-oo"
q += 1
else:
q + 1
print(proWord)
stopProgram = 0
Output:
Please enter a valid hawaiian word.aeae Traceback (most recent call last):
File "C:/Users/Kristopher/Documents/Programming HW/Program
3.py", line 26, in <module>
if userWordEval[q] == "a": IndexError: string index out of range
string's index is from 0 to length-1. So change the while loop condition in line 24 to:
while q < len(userWordEval):
Your problem is that you are looping while q <= len(userWordEval). First of all, it is important to know that in python lists use zero-based indexing (see description on Wikipedia). This means that if there are 5 elements in a list, the last element will have index 4. The function len returns the number of elements in a list, so if you use that number as an index it will be too large. You can easily fix this by changing to q < len(userWordEval).
Remember list, string, tuple or other types which support indexing will raise IndexError if you try to access element past the index.
>>> a = 'apple'
>>> a[0]
'a'
>>> a[4]
'e'
>>> a[5]
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
a[5]
IndexError: string index out of range
So always use len(s)-1
>>> a[len(a)-1]
'e'
>>>
One nice bit of gotcha here. However during slicing you won't get that error. It will simple return an empty string/list.
>>> a[5:]
''
>>> a[:11]
'apple'

How to find certain letters in a string when there are multiple?

I want to be able to pick out certain letters in a string but need to be able to get the place of multiple rather then just the first (Python). I currently have this code:
word=apple #just and example
character=input("Take a guess")
if character == "a":
place=word.find("a")
elif character == "b":
place=word.find("b")
elif character == "c":
place=word.find("c")
elif character == "d":
place=word.find("d")
elif character == "e":
place=word.find("e")
elif character == "f":
place=word.find("f")
elif character == "g":
place=word.find("g")
elif character == "h":
place=word.find("h")
elif character == "i":
place=word.find("i")
elif character == "j":
place=word.find("j")
elif character == "k":
place=word.find("k")
elif character == "l":
place=word.find("l")
elif character == "m":
place=word.find("m")
elif character == "n":
place=word.find("n")
elif character == "o":
place=word.find("o")
elif character == "p":
place=word.find("p")
elif character == "q":
place=word.find("q")
elif character == "r":
place=word.find("r")
elif character == "s":
place=word.find("s")
elif character == "t":
place=word.find("t")
elif character == "u":
place=word.find("u")
elif character == "v":
place=word.find("v")
elif character == "x":
place=word.find("w")
elif character == "w":
place=word.find("x")
elif character == "y":
place=word.find("y")
else:
place=word.find("z")
This works to find the place of one letter, but if I wanted to find both p's it wouldn't work, it'd only tell me the position of the first. So what I'm really wondering is if there is some loop I can put it through to find the letters and set them as two different variables such as "place" and "place2" or do I have to have this same thing multiple different times for each separate starting point.
You can use re.finditer() to get all occurrences of the substring:
>>> import re
>>> word = "apple" #just and example
>>> character = input("Take a guess: ")
>>> for occurrence in re.finditer(character, word):
... print('character: {}, {}'.format(character, occurrence.start()))
Regular expressions are a powerful tool. However, there is a considerable overhead in using regexps for a trivial string literal search.
Here is a simple alternative repeatedly calling str.find until all occurrences are found:
def findall(mainstring, substring):
pos = -1
while True:
pos = mainstring.find(substring, pos+1)
if pos == -1:
break
yield pos
for occurence in findall("apple", "p"):
print(occurence)
# prints: 1 2

Project Euler 22, off by 18,609

I'm working on problem 22 of Project Euler:
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?
My code (below) gets the answer 871179673. The correct answer should be 871198282, which makes me off by about 18k.
def score(name, pos):
score = 0
for letter in name:
if letter == "A": score += 1
elif letter == "B": score += 2
elif letter == "C": score += 3
elif letter == "D": score += 4
elif letter == "E": score += 5
elif letter == "F": score += 6
elif letter == "G": score += 7
elif letter == "H": score += 8
elif letter == "I": score += 9
elif letter == "J": score += 10
elif letter == "K": score += 11
elif letter == "L": score += 12
elif letter == "M": score += 13
elif letter == "N": score += 14
elif letter == "O": score += 15
elif letter == "P": score += 16
elif letter == "Q": score += 17
elif letter == "R": score += 18
elif letter == "S": score += 19
elif letter == "T": score += 20
elif letter == "U": score += 21
elif letter == "V": score += 22
elif letter == "W": score += 23
elif letter == "X": score += 24
elif letter == "Y": score += 25
elif letter == "Z": score += 26
else: score += 0
# end for loop.
return score * pos
#end def score.
f = open('names.txt')
string = f.readlines()
f.close()
names = sorted(str(string).split(","))
tscore = 0
pos = 1
for name in names:
tscore += score(name, pos)
pos += 1
#end for loop.
print tscore
If I run the 'Colin' example through my score function, I get the right result. I've tested a few other names from the list, and they score correctly as well. I googled the question and got various solutions, but since I'm new to python I'd like to learn what I did wrong. Thanks for your time!
Change this line:
names = sorted(str(string).split(","))
to:
names = sorted(string[0].split(','))
File contains just one line, so you need to access that line using string[0]. file.readlines returns a list containing all lines from the file, it's better to do something like:
names = f.read().split(',')
names.sort()
A shorter version of your program:
from string import ascii_uppercase
def score(word):
return sum(ascii_uppercase.index(c) + 1 for c in word.strip('"'))
with open('names.txt') as f:
names = f.read().split(',')
names.sort()
print sum(i*score(x) for i, x in enumerate(names, 1))
Note: string is a built-in module, don't use it as a variable name
import string
with open("names.txt",'r') as f:
d=f.read()
d=d.replace('"','')
#print(d)
names=d.split(',')
#print(names)
names.sort()
print(names)
gro=dict()
result=string.ascii_uppercase
count=1
for i in result:
gro[i]=count
count+=1
#print(gro)
sum=0
for ind,value in enumerate(names):
#print(ind,value)
temp=0
for x in value:
temp+=gro[x]
print(temp)
sum+=temp*(ind+1)
print(sum)
my way:
splitted = open('names.txt').read().replace('","',',').replace('"','').split(',')
description:
open the file, then read it, after that remove double qoutes by repalce them with none and at the end split the whole string by comma (,)
good luck

Categories