How could I clean up my code? [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
How could I clean up my python code? I basically want to get rid of this huge If statement I have and need to know how I can shortern it down, also could you please explain to me how the code works if you change any of the code. Thanks
global alpha
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']
print("Welcome to Caesar Cipher")
print("How to use Caesar Cipher : \n 1. Select a number from 1 - 26 \n 2. Enter a Sentence/Word/Phrase to encrypt \n 3. Read the encryption.")
def main():
global un_coded
global turn
turn = input("Please enter a number between 1-26 \n")
if int(turn) > 26 or int(turn) < 1:
print("Please only enter a number between 1-26")
main()
global un_coded
un_coded = input("Input the Word/Phrase/Sentence you would like to code : \n")
global x
x = len(un_coded)
global coded
coded = ""
def change():
global x
global turn
global coded
global un1_coded
un1_coded = un_coded.upper()
y = 0
for p in range(0, int(x)):
if un1_coded[y] == "A":
z = 1
letter = int(z) + int(turn)
letter = int(letter) - 1
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "B":
z = 2
letter = int(z) + int(turn)
letter = int(letter) - 1
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "C":
z = 3
letter = int(z) + int(turn)
letter = int(letter) - 1
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "D":
z = 4
letter = int(z) + int(turn)
letter = int(letter) - 1
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "E":
z = 5
letter = int(z) + int(turn)
letter = int(letter) - 1
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "F":
z = 6
letter = int(z) + int(turn)
letter = int(letter) - 1
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "G":
z = 7
letter = int(z) + int(turn)
letter = int(letter) - 1
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "H":
z = 8
letter = int(z) + int(turn)
letter = int(letter) - 1
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "I":
z = 9
letter = int(z) + int(turn)
letter = int(letter) - 1
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "J":
z = 10
letter = int(z) + int(turn)
letter = int(letter) - 1
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "K":
z = 11
letter = int(z) + int(turn)
letter = int(letter) - 1
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "L":
z = 12
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "M":
z = 13
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "N":
z = 14
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "O":
z = 15
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "P":
z = 16
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "Q":
z = 17
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "R":
z = 18
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "S":
z = 19
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "T":
z = 20
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "U":
z = 21
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "V":
z = 22
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "W":
z = 23
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "X":
z = 24
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "Y":
z = 25
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == "Z":
z = 26
letter = int(z) + int(turn)
letter = int(letter) - 27
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == " ":
coded += " "
y = int(y) + 1
main()
change()
print("Your Code Is - ")
print(str(un1_coded))
print(str(coded))

You can change your if statements in this way.
if un1_coded[y].isupper():
z = ord(un1_coded[y]) - 64
letter = z + int(turn)
letter = int(letter) - 1
letter_one = alpha[int(letter)]
coded += str(letter_one)
elif un1_coded[y] == ' ':
coded += " "

Related

Python and global declaration

I'm having trouble trying to resolve this error:
SyntaxWarning: name 'meaning5' is assigned to before global declaration
Basically my program needs to allow the user to input their name, the program then calculates the users lucky number based on the assignment of a=1, b=2 etc.
This is my code so far:
from time import sleep
tempNumb = 0
tempLNN1a = 0
tempLNN1b = 0
tempLNN2a = 0
tempLNN2b = 0
varLNN1 = 0
varLNN2 = 0
LNN = 0
tempLNNa = 0
tempLNNb = 0
templetter = "nothing"
meaning1 = "Natural leader"
meaning2 = "Natural peacemaker"
meaning3 = "Creative and optimistic"
meaning4 = "Hard worker"
meaning5 = "Value freedom"
meaning6 = "Carer and a provider"
meaning7 = "Thinker"
meaning8 = "Have diplomatic skills"
meaning9 = "Selfless and generous"
global templetter
global tempNumb
global tempLNN1a
global tempLNN1b
global tempLNN2a
global tempLNN2b
global varLNN1
global varLNN1
global LNN
global tempLNNa
global tempLNNb
global meaning1
global meaning2
global meaning3
global meaning4
global meaning5
global meaning6
global meaning7
global meaning8
global meaning9
def mainprogram():
sleep(1)
print("-----------------------")
print("Welcome to LUCKY NAME \n NUMBERS")
print("-----------------------")
sleep(1)
firstname = input("Please input your first \nname in all capitals\n")
if firstname == firstname.upper():
print("-----------------------")
sleep(1)
surname = input("Please input your surname \nin all capitals\n")
if surname == surname.upper():
print("-----------------------")
print("Calculating your Lucky \nName Number...")
for i in range(len(firstname)):
templetter = firstname[i]
calculate()
tempfirstname()
for i in range(len(surname)):
templetter = surname[i]
calculate()
tempsurname()
finalcalculate()
def calculate():
if templetter == "A":
tempNumb = 1
elif templetter == "B":
tempNumb = 2
elif templetter == "C":
tempNumb = 3
elif templetter == "D":
tempNumb = 4
elif templetter == "E":
tempNumb = 5
elif templetter == "F":
tempNumb = 6
elif templetter == "G":
tempNumb = 7
elif templetter == "H":
tempNumb = 8
elif templetter == "I":
tempNumb = 9
elif templetter == "J":
tempNumb = 1
elif templetter == "K":
tempNumb = 2
elif templetter == "L":
tempNumb = 3
elif templetter == "M":
tempNumb = 4
elif templetter == "N":
tempNumb = 5
elif templetter == "O":
tempNumb = 6
elif templetter == "P":
tempNumb = 7
elif templetter == "Q":
tempNumb = 8
elif templetter == "R":
tempNumb = 9
elif templetter == "S":
tempNumb = 1
elif templetter == "T":
tempNumb = 2
elif templetter == "U":
tempNumb = 3
elif templetter == "V":
tempNumb = 4
elif templetter == "W":
tempNumb = 5
elif templetter == "X":
tempNumb = 6
elif templetter == "Y":
tempNumb = 7
elif templetter == "Z":
tempNumb = 8
else:
"You managed to break it."
mainprogram()
def tempfirstname():
varLNN1 = varLNN1 + tempNumb
def tempsurname():
varLNN2 = varLNN2 + tempNumb
def finalcalculate():
varLNN1 = str(varLNN1)
varLNN2 = str(varLNN2)
tempLNN1a = varLNN1[0]
tempLNN1b = varLNN1[1]
tempLNN2a = varLNN2[0]
tempLNN2b = varLNN2[1]
varLNN1 = int(tempLNN1a) + int(tempLNN1b)
varLNN2 = int(tempLNN2a) + int(tempLNN2b)
LNN = varLNN1 + varLNN2
LNN = str(LNN)
tempLNNa = LNN[0]
tempLNNb = LNN[1]
LNN = int(tempLNNa) + int(tempLNNb)
if LNN == 1 or "1":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you are a " + meaning1)
loop()
elif LNN == 2 or "2":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you are a " + meaning2)
loop()
elif LNN == 3 or "3":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you are " + meaning3)
loop()
elif LNN == 4 or "4":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you are a " + meaning4)
loop()
elif LNN == 5 or "5":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you " + meaning5)
loop()
elif LNN == 6 or "6":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you are a " + meaning6)
loop()
elif LNN == 7 or "7":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you are a " + meaning7)
loop()
elif LNN == 8 or "8":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you " + meaning8)
loop()
elif LNN == 9 or "9":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you are " + meaning9)
loop()
else:
print("Somehow your lucky name number is too high...")
mainprogram()
Python is different than C, you don't have to declare a variable global, if you are using a global variable in a function, there you need to use global keyword.
For example:
meaning5 = "Value freedom"
def somefunction():
global meaning5
print meaning5
and as linsug has said use lists.
Simply define all the global variable in a single function like :
def global_variables():
global var_1
global var_2
global var_3
global var_4
.
global var_n
And before calling anything else in main, call this function first:
if __name__ == "__main__":
global_variables()
# Rest of your code.
Might it help!. Thanx

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'

Logic Error in Most Common Letter Finder

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

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