python skipping for loop - python

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.

Related

Why The Variable Didn't Change?

I try to make a calculator but when i run it it just show 0. Why my the result variable doesn't change?
MathSlice = list("1 + 2")
i = 0
Number1 = []
Operation = ""
Number2 = []
Result = 0
while not (str(MathSlice[i]) == "+" or "-" or "*" or "/"):
Number1.append(MathSlice[i])
i += 1
Number1 = ''.join(Number1)
Operation = MathSlice[i]
while not i > len(MathSlice):
Number2.append(MathSlice[i - 1])
i += 1
Number2.pop(1)
Number2 = ''.join(Number2)
if Operation == "+":
Result = int(Number1) + int(Number2)
elif Operation == "-":
Result = int(Number1) - int(Number2)
elif Operation == "*":
Result = int(Number1) * int(Number2)
elif Operation == "/":
Result = int(Number1) / int(Number2)
print(Result)
I expect it to printing 3 but the variable result doesn't change and printing 0.
Changes made: while not (str(MathSlice[i]) == "+" or "-" or "*" or "/"): to while not MathSlice[i] in ("+", "-", "*", "/"):
Code:
MathSlice = list("1 + 2")
#print(MathSlice)
i = 0
Number1 = []
Operation = ""
Number2 = []
Result = 0
while not MathSlice[i] in ("+", "-", "*", "/"):
Number1.append(MathSlice[i])
i += 1
Number1 = ''.join(Number1)
Operation = MathSlice[i]
while not i > len(MathSlice):
Number2.append(MathSlice[i - 1])
i += 1
Number2.pop(1)
Number2 = ''.join(Number2)
if Operation == "+":
Result = int(Number1) + int(Number2)
elif Operation == "-":
Result = int(Number1) - int(Number2)
elif Operation == "*":
Result = int(Number1) * int(Number2)
elif Operation == "/":
Result = int(Number1) / int(Number2)
print(Result) #3
what you have done is assume that or statements only act on the second part of the evaluation, however they act on both. Basically this means you are saying is str(MathSlice[i]) == "+" or "-" == True etc. This then instantly cancels the while not loop as strings with characters evaluate as true in python.
The simple fix is to change your while loop from this:
while not (str(MathSlice[i]) == "+" or "-" or "*" or "/"):
to this
while not str(MathSlice[i]) == "+" or str(MathSlice[i]) == "-" or str(MathSlice[i]) == "/" or str(MathSlice[i]) == "*":
which is unfortunately a little bit uglier but it fixes your problem :)

The result is not what I expected, python console problem

new to coding, when enter an equation of 1 * 5, I get "You are ...lazy". But I need to get "You are ...very lazy". Can you help me finding the problem?
Expected:
You are ... lazy ... very lazy
5.0
Do you want to store the result? (y / n):
Found:
You are ... lazy
5.0
Do you want to store the result? (y / n):
msg_0 = "Enter an equation"
msg_1 = "Do you even know what numbers are? Stay focused!"
msg_2 = "Yes ... an interesting math operation. You've slept through all classes, haven't you?"
msg_3 = "Yeah... division by zero. Smart move..."
msg_4 = "Do you want to store the result? (y / n):"
msg_5 = "Do you want to continue calculations? (y / n):"
msg_6 = " ... lazy"
msg_7 = " ... very lazy"
msg_8 = " ... very, very lazy"
msg_9 = "You are"
memory = 0
def is_one_digit(v):
v = float(v)
if -10 < v < 10 and v.is_integer():
return True
else:
return False
def check(v1, v2, v3):
msg = ""
if is_one_digit(v1) and is_one_digit(v2):
msg = msg + msg_6
if (v1 == 1 or v2 == 1) and v3 == "*":
msg = msg + msg_7
if (v1 == 0 or v2 == 0) and (v3 == "*" or v3 == "+" or v3 == "-"):
msg = msg + msg_8
if msg != "":
msg = msg_9 + msg
print(msg)
while True:
calc = input(msg_0)
try:
x = calc.split()[0]
oper = calc.split()[1]
y = calc.split()[2]
if x == "M":
x = memory
if y == "M":
y = memory
float(x)
float(y)
if oper in ["+", "-", "*", "/"]:
check(x, y, oper)
if oper == "+":
result = float(x) + float(y)
print(result)
elif oper == "-":
result = float(x) - float(y)
print(result)
elif oper == "*":
result = float(x) * float(y)
print(result)
elif oper == "/":
if float(y) != 0:
result = float(x) / float(y)
print(result)
else:
print(msg_3)
continue
user_input = input(msg_4)
if user_input == "y":
memory = result
user_i = input(msg_5)
if user_i == "y":
continue
elif user_i == "n":
break
else:
user_i = input(msg_5)
elif user_input == "n":
user_i = input(msg_5)
if user_i == "y":
continue
elif user_i == "n":
break
else:
user_i = input(msg_5)
else:
user_input = input(msg_5)
else:
print(msg_2)
except ValueError:
print(msg_1)
continue
You call float(x) and float(y), but this is not saved anywhere, so v1 and v2 will be '1' and '5', instead of 1 and 5.
If you set
x = float(x)
y = float(y)
, it should work.

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

How could I clean up my code? [closed]

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 += " "

Categories