Faster "switch-case" implementation in python - python-2.7

I made the script below to read a string buffer and distribute the numbers in 6 different variables. I found an example doing the same in C# using switch-case method, and when I tried a similar method in python (as shown below) I got the desired result but it takes too much time to read the buffer (more than a second). This script is just a way to test the method, and it will be a part of a bigger open-loop control code, so the loop time is really important. Is there any faster way to do in in python? I use python 2.7. Thank you in advance.
Julio = '123.5,407.4,21.6,9.7,489.2,45.9/\n'
letter = ''
x_c = ''
y_c = ''
z_c = ''
theta_c = ''
ux_c = ''
uy_c = ''
variable_number = 1
def one():
global x_c
x_c += letter
def two():
global y_c
y_c += letter
def three():
global z_c
z_c += letter
def four():
global theta_c
theta_c += letter
def five():
global ux_c
ux_c += letter
def six():
global uy_c
uy_c += letter
def string_reader(variable_number):
switcher = {
1: one,
2: two,
3: three,
4: four,
5: five,
6: six
}
# Get the function from switcher dictionary
func = switcher.get(variable_number, lambda: 'Invalid variable number')
# Execute the function
print func()
for letter in Julio:
if (letter != '/') and (letter != ',') and (letter != '\n'):
string_reader(variable_number)
elif (letter == '/'):
break
elif (letter == '\n'):
break
else:
variable_number = variable_number + 1
print x_c, y_c, z_c, theta_c, ux_c, uy_c

Err... Aren't you overcomplicating things ?
>>> Julio = '123.5,407.4,21.6,9.7,489.2,45.9/\n'
>>> x_c, y_c, z_c, theta_c, ux_c, uy_c = Julio.strip().rstrip("/").split(",")[:6]

Related

Really weird issue with CodeHS

I am doing some CodeHS for my computer science class at my school and for some reason my program doesnt meet the criteria of the grader, and maybe someone can assist me.
The autograder is looking for this:
The things it tests with are here:
and every result returns a runtime error in the autograder but not in the console.
Heres my code:
def get_letter():
while True:
letter = str(input("Enter a letter:\n> "))
if letter.isupper() == True:
print("Character must be a lowercase letter!")
continue
if len(letter) > 1 or len(letter) < 1:
print("Must be 1 character!")
elif letter.islower() == True:
return letter
break
def get_index():
while True:
try:
index = int(input("Enter an index (-1 to quit):\n> "))
if index == -1:
break
if index > len(word) or index < 0:
print "Invalid index"
continue
if index <= len(word):
global letter
letter = get_letter()
return index
break
except ValueError:
print "Please enter a number"
continue
word = input("Enter a word\n> ")
words = list(word)
while True:
try:
indexes = get_index()
splitword = words[:indexes] + [letter] + words[indexes +1:]
joinedword = ''.join(splitword)
print joinedword
except NameError:
break
and here are the instructions:
The CodeHS lesson is 8.3.8 Word Latter
This might be a little too late. I just came up to this question on CodeHS and had trouble myself. But I found it somewhere else, not to CodeHS's requirements so I had to fix it up myself. Here it is all fixed
def get_index(Inital_Word1):
User_Input = int(input("Enter an index (-1 to quit): "))
DexNav = len(Inital_Word1)
while User_Input > DexNav or User_Input<-1:
print "Invalid index"
User_Input = input("Enter an index (-1 to quit):")
DexNav = len(Inital_Word1)
return User_Input
def get_letter():
User_Input = input("Enter a letter: ")
DexNav = len(User_Input)
while DexNav > 1:
print "Must be exactly one character!"
User_Input = input("Enter a letter: ")
DexNav = len(User_Input)
while User_Input.isupper():
print "Character must be a lowercase letter!"
User_Input = input("Enter a letter: ")
return User_Input
def replace_at_index(User_Input, num, replacement):
return User_Input[0:num] + replacement + User_Input[num + 1:]
for i in range(1):
Inital_Word = input("Enter you inital word here: ")
Index = get_index(Inital_Word)
while Index != -1:
Letter = get_letter()
Inital_Word = replace_at_index(Inital_Word, Index, Letter)
print (Inital_Word)
Index = get_index(Inital_Word)

Python 2.7.4, does anyone know why this is not working?

The following code is for one of my excercises to pass the subject,
This is my code:
rot13=raw_input("Please write your text! ")
This is where i ask the user for a text
for i in range(len(rot13)):
And in this part I check the text letter by letter with for.
if rot13[i]=="a":
rot13[i]="n"
elif rot13[i]=="b":
rot13[i]="o"
elif rot13[i]=="c":
rot13[i]="p"
elif rot13[i]=="d":
rot13[i]="q"
elif rot13[i]=="e":
rot13[i]="r"
elif rot13[i]=="f":
rot13[i]="s"
elif rot13[i]=="g":
rot13[i]="t"
elif rot13[i]=="h":
rot13[i]="u"
elif rot13[i]=="i":
rot13[i]="v"
elif rot13[i]=="j":
rot13[i]="w"
elif rot13[i]=="k":
rot13[i]="x"
elif rot13[i]=="l":
rot13[i]="y"
elif rot13[i]=="m":
rot13[i]="z"
elif rot13[i]=="n":
rot13[i]="a"
elif rot13[i]=="o":
rot13[i]="b"
elif rot13[i]=="p":
rot13[i]="c"
elif rot13[i]=="q":
rot13[i]="d"
elif rot13[i]=="r":
rot13[i]="e"
elif rot13[i]=="s":
rot13[i]="f"
elif rot13[i]=="t":
rot13[i]="g"
elif rot13[i]=="u":
rot13[i]="h"
elif rot13[i]=="v":
rot13[i]="i"
elif rot13[i]=="w":
rot13[i]="j"
elif rot13[i]=="x":
rot13[i]="k"
elif rot13[i]=="y":
rot13[i]="l"
elif rot13[i]=="z":
rot13[i]="m"
print rot13
Does anyone knows why this is not working? I do not want to do it with encode.
There are a couple of issues with your code.
First, you're trying to assign a character to a string, but strings are immutable, so you can't swap out chars using =. Second, you don't need to hardcode each character and its mapping. You should use the modulus operator (%).
The basic solution is to loop through each char, turn it into a number, add 13 to it, and turn it back into a character. You'll have to consider the case where your input is "z" and the resulting character lies beyond the alphabet. That's where you'll have to use the modulus operator to force the character to wrap around.
Here's an example:
def rot13(string):
result = []
for char in string:
shiftBy = 65 # uppercase 'A'
if char.islower():
shiftBy = 97 # lowercase 'a'
newChar = chr(((ord(char) + 13 - shiftBy) % 26) + shiftBy)
result.append(newChar)
return ''.join(result)
print rot13("abcXYZ")
ord converts a character to its numeric representation (e.g. 'a' becomes 97)
chr does the reverse computation (e.g. 97 becomes 'a')

Converting python string to pig latin

def isAlpha(c):
return (ord(c) >= 65 and ord(c) <= 95) or \
(ord(c) >= 97 and ord(c) <= 122)
# testing first function
print isAlpha("D")
print isAlpha("z")
print isAlpha("!")
s = "AEIOUaeiou"
def isVowel(c):
return s.find(c) > -1
# testing second function
print isVowel("A")
print isVowel("B")
print isVowel("c")
print isVowel(" ")
print isVowel("a")
def convPigLatin_word(word):
if isVowel(word[0]):
word += "way"
while not isVowel(word[0]):
word = word[1:] + word[0]
if isVowel(word[0]):
word += "ay"
return word
# testing third function
print convPigLatin_word("This")
print convPigLatin_word("ayyyyyylmao")
def translate(phrase):
final = ""
while phrase.find(" ") != -1:
n = phrase.find(" ")
final += convPigLatin_word(phrase[0:n]) + " "
phrase = phrase[n+1:]
if phrase.find(" ") == -1:
final += convPigLatin_word(phrase)
return final
print translate("Hello, this is team Number Juan") #Should be "elloHay, isthay isway eamtay umberNay uanJay"
I tried to create a code that transform a string into pig latin. But I got stuck on the non-alphanumeric character. The while loop only works up to the comma. How can I resolve that? I don't know where to implement the isAlpha code to check for non alphanumeric character. Any advice is helpful.
You can iterate through the words of a phrase by using .split(' '). Then you can test them for special characters using .isalpha()
pigLatin = lambda word: word[1:]+ word[0]+"ay"
def testChars(word):
text = ""
for char in list(word):
if char.isalpha():
text += char
else:
return pigLatin(text)+ char
def testWords(lis):
words = []
lis = lis.split(' ')
for word in lis:
if not word.isalpha():
words.append( testChars(word) )
else:
words.append(pigLatin(word))
return (' ').join(words)
phrase = "I, have, lots of! special> characters;"
print testWords(phrase)

I have found most of everything I need and have a "mostly" working game

I having issues with the def check guess. It's the format my teacher specifically gave. You guys are great. Thanks for the help!!!! Sorry for the format this is my first time on this site.
# # Global variables
wrong_guesses = []
target_phrase = ""
current_phrase = ""
def clear_display():
for i in range(20):
print "\n"
def string_with_dashes(str):
global target_phrase
new_phrase = ""
for i in str:
if i.isalpha():
new_phrase += "-"
else:
new_phrase += i
return new_phrase
def check_guess(letter):
global current_phrase
replacement_list = [""]
for i in range(len(target_phrase)):
if target_phrase[i] == letter:
replacement_list[i] = target_phrase[i]
current_phrase = replacement_list
return current_phrase
else:
wrong_guesses.append(letter)
return False
def process_input():
user_letter = raw_input("Guess a letter: ").upper()
if user_letter in wrong_guesses:
print "You already guessed that letter"
user_letter = raw_input("Guess again : ")
else:
return check_guess(user_letter)
def one_turn():
global wrong_guesses
print "=================================================="
print current_phrase
print "Wrong guesses:", ' '.join(wrong_guesses)
print "Guesses remaining:", (8 - len(wrong_guesses))
display_robot(8 - len(wrong_guesses))
print "String to guess:", current_phrase
print "=================================================="
process_input()
print "\n\n"
def setup_phrase():
global target_phrase, current_phrase
target_phrase = raw_input("Dear friend, enter a phrase for the user to guess: ").upper()
current_phrase = string_with_dashes(target_phrase)
setup_phrase()
clear_display()
while True:
one_turn()
if len(wrong_guesses) > 7:
print "GAME OVER! You Lose"
breack
if current_phrase == target_phrase:
print "You WIN!!"
break
(why won't stackoverflow let me fix your code?)
I'm not sure exactly what you are trying to do, but it sounds like you want to create a string where the guessed letters replace blanks as they are guessed? Try something like this:
hidden_phrase = "abracadabra"
current_list = ["."]*len(hidden_phrase)
def check_guess(letter):
for i in range(len(hidden_phrase)):
if hidden_phrase[i] == letter:
current_list [i] = hidden_phrase[i]
print("before", "".join(current_list ))
check_guess("a")
print("guess1", "".join(current_list))
check_guess("z")
print("guess2", "".join(current_list))
check_guess("b")
print("guess3", "".join(current_list))
Output:
before ...........
guess1 a..a.a.a..a
guess2 a..a.a.a..a
guess3 ab.a.a.ab.a
In Python strings are immutable, and can't be updated, so it seems easier to me to keep the 'replacement' word (with blanks, which I represent with .) as a list, and join it back together for display.
The two global variables don't need to be explicitly specified as global, because the variable is not assigned to in the function, only accessed.
If you prefer to have a string current_phrase and update that, of course that's possible too:
hidden_phrase = "abracadabra"
current_phrase = "."*len(hidden_phrase )
def check_guess(letter):
global current_phrase
i = -1
while True:
i = hidden_phrase.find(letter, i+1)
if i<0:
break
current_phrase = current_phrase[0:i]+letter + current_phrase[i+1:]
print("before", current_phrase)
check_guess("a")
print("guess1", current_phrase)
check_guess("z")
print("guess2", current_phrase)
check_guess("b")
print("guess3", current_phrase)
This time you need the global again to prevent current_phrase = ... from creating a local variable.
My previous answer was to the first, more general, version of your question. Several things were wrong with your check_guess(). Here's a fixed version:
def check_guess(letter):
global current_phrase
replacement_list = list(current_phrase)
found=False
for i in range(len(target_phrase)):
if target_phrase[i] == letter:
replacement_list[i] = target_phrase[i]
found = True
if found:
current_phrase = "".join(replacement_list)
else:
wrong_guesses.append(letter)
Comments to show problems with your version:
def check_guess(letter):
global current_phrase
replacement_list = [""] # list has only 1 element, can't assign above index zero
for i in range(len(target_phrase)):
if target_phrase[i] == letter:
replacement_list[i] = target_phrase[i]
current_phrase = replacement_list # assigning a list to what was previously a string
return current_phrase # returns before checking 2nd character
else:
wrong_guesses.append(letter) # only the first character has been checked
return False # returns False or current_phrase, inconsistent
Also near the end you wrote breack instead of break, it's a shame that Python doesn't check these things by default, waiting instead for you to hit that line.

Python 2.7: Variable defined in previous function, receiving undefined error

So my variable is clearly defined in inputnfo(), why am I getting an undefined error? The try & except perhaps? I've added removed... swapped it all around and cannot seem to find the solution, and answers online seem very situation based... Thanks in advance :)
Super New & improved edit: now getting UnboundLocalError
import random
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']
strgen = []
retry = 0
### Defining
def inputnfo():
global much
much = input('how long do you want your random word/lucky number to be: ')
global which
which = raw_input('would you like letters or numbers?(let,num, or mix?):').lower
def generate():
while much > 0:
if which == 'let':
strgen.append(random.choice(alpha))
much -= 1
print '.'
elif which == 'num':
strgen.append(random.randint(1,9))
much -= 1
print '.'
elif which == 'mix':
mixer = random.choice([0,1])
if mixer == 0:
strgen.append(random.choice(alpha))
much -= 1
print '.'
elif mixer == 1:
strgen.append(random.randint(1,9))
much -= 1
print '.'
def finish():
finito = ''.join(strgen)
print 'Generation Completed!\n'
if which == 'let':
print 'Your randomly generated string is:' + finito
elif which == 'num':
print 'Your randomly generated number is:' + finito
elif which == 'mix':
print 'Your randomly generated Alpha-Numerical string is:' + finito
### Running
inputnfo()
while much != 0:
generate()
finish()
Its because the variable "much" in the function inputnfo() is local to that function alone. that is why you are getting an undefined error in the while loop. there is two solution
1. Make the variable "much" global by including the line
def inputnfo():
global much
try:
and then removing the argument of generate function
Or
2. Let the function inputnfo() return much and use this return value in the while loop and generate function
do the same for variable "which"
and put a line which = "" befor
which = ""
def inputnfo():
global much