The goal of the code is to add ub before any vowel (klinker) to a new sentence (nieuwe_zin). or to decode sentences.
I want to add a feature where if the last 2 characters in the zin(sentence) are "ub" they will not be deleted when decoded. So that words like club dont become cl.
from pcinput import getString
while True:
zin = getString("Give a sentence")
cd = getString("Coding or decoding (c/d)")
cd = cd.lower()
klinkers = ("eaiou")
nieuwe_zin = ("") zin= zin.lower()
if cd == "c":
for i in range (len(zin)):
if zin[i] in klinkers:
nieuwe_zin += "ub" + zin[i]
else:
nieuwe_zin += zin[i]
print (nieuwe_zin)
break
if cd == "d":
i = 0
while i < len(zin):
if zin[i:i+2] == "ub":
i += 2
if zin[i:i+4] == "ubub":
i += 0
else:
nieuwe_zin += zin[i]
i += 1
print(nieuwe_zin)
break
else:
print ("C or D")
I tried
if zin[i:-2] =="ub":
i = -1
nieuwe_zin = zin + "ub"
EDITED: To account for multiple instances of "ub" as in "clubub"
from pcinput import getString
while True:
zin = getString("Give a sentence")
cd = getString("Coding or decoding (c/d)")
cd = cd.lower()
klinkers = ("eaiou")
nieuwe_zin = ("")
zin= zin.lower()
if cd == "c":
for i in range (len(zin)):
if zin[i] in klinkers:
nieuwe_zin += "ub" + zin[i]
else:
nieuwe_zin += zin[i]
print (nieuwe_zin)
break
if cd == "d":
i = 0
while i < len(zin):
if zin[i:i+3] == "ubub":
i += 3
nieuwe_zin += zin[i]
i += 1
print(nieuwe_zin)
break
else:
print ("C or D")
Cleaned up and optimized version:
from pcinput import getString
while True:
zin = getString("Give a sentence").lower()
cd = getString("Coding or decoding (c/d)").lower()
nieuwe_zin = ""
klinkers = "eaiou"
if cd == "c":
nieuwe_zin = "".join(["ub" + char if char in klinkers else
char for char in zin])
print(nieuwe_zin)
break
elif cd == "d":
i = 0
while i < len(zin):
if zin[i:i+3] == "ubub":
i += 3
nieuwe_zin += zin[i]
i += 1
print(nieuwe_zin)
break
else:
print("Please enter either 'c' or 'd'.")
Related
So I have a file "game.txt" which consist of an instruction and a number. The instruction is either "coin," "jump," or "none." "Coin" stores the number following the instruction, "jump" will jump to a new instruction relative to itself and do whatever that instructions says, and "none" will do nothing. However, "jump +2" would continue to the instruction two lines below, and "jump -5" causes the instruction 5 lines above to be executed next.
I want to be able to iterate through the file, write the number on a new file, and count how many "coins" there are at the end. I already have a decent function that gets me somewhat close to this, but I have some bugs that I can't seem to figure out.
ex.)
I have 533 as my total, but only 528 entries in my new file
I would also like to simplify the code if possible (looks redundant in some parts)
game.txt file game.txt file link
def counting_coins(file):
count = 0
game_list = [] # list of all game steps
valid_coins = [] # list of all coin values
try:
coins = open("coins.txt", "x")
except FileExistsError:
coins = open("coins.txt", "w") # if file already exists
with open(file, "r") as cc:
### LOOPS ###
for line in cc:
game_list.append(line[0:-1]) # append each line to list to index and iterate
for i in range(len(game_list)):
current = game_list[i] # keep track of current step
if "coin" == current[0:4]:
count += 1
if game_list[i][5:6] == "+":
valid_coins.append(current[6:] + "\n")
# count += 1
elif game_list[i][5:6] == "-":
valid_coins.append("-" + current[6:] + "\n")
# count += 1
elif "jump" == current[0:4]:
if current[5:6] == "+":
num = int(current[6:])
jump = game_list[i + num]
elif current[5:6] == "-":
num = int(current[6:])
num = -num
jump = game_list[i + num]
if "coin" == jump[0:4]:
count += 1
if jump[5:6] == "+":
valid_coins.append(jump[6:] + "\n")
# count += 1
elif jump[5:6] == "-":
valid_coins.append("-" + jump[6:] + "\n")
# count += 1
elif "jump" == jump[0:4]:
if jump[5:6] == "+":
new_num = int(jump[6:])
new_jump = game_list[(i + num) + new_num]
elif jump[5:6] == "-":
new_num = int(jump[6:])
new_num = -new_num
new_jump = game_list[(i + num) + new_num]
if "coin" == new_jump[0:4]:
count += 1
if new_jump[5:6] == "+":
valid_coins.append(new_jump[6:] + "\n")
# count += 1
elif new_jump[5:6] == "-":
valid_coins.append("-" + new_jump[6:] + "\n")
# count += 1
elif "jump" == new_jump[0:4]:
if new_jump[5:6] == "+":
new_num2 = int(new_jump[6:])
new_jump2 = game_list[(i + num) + new_num + new_num2]
elif new_jump[5:6] == "-":
new_num2 = int(new_jump[6:])
new_num2 = -new_num2
new_jump2 = game_list[(i + num) + new_num + new_num2]
if "coin" == new_jump2[0:4]:
count += 1
if new_jump2[5:6] == "+":
valid_coins.append(new_jump2[6:] + "\n")
# count += 1
elif new_jump2[5:6] == "-":
valid_coins.append("-" + new_jump2[6:] + "\n")
# count += 1
elif "none" == current[0:4]:
continue
for i in range(len(valid_coins)):
if valid_coins[i] == valid_coins[-1]: # if last entry
coins.write(valid_coins[i][:-1]) # removes preceding newline
else:
coins.write(valid_coins[i])
coins.close()
return coins, count
file, count = counting_coins("game.txt")
print(f"Total coins collected: {count}")
Don't use all those nested if statements for jumping. Just reset the current index of the main loop to the element that you're jumping to.
You'll need to use a while loop instead of looping over range() so you can reset the index.
Instead of all that slicing, use split() to split each line into a command and argument.
i = 0
while i < len(game_list):
current = game_list[i].split()
if current[0] == "coin":
count += 1
valid_coins.append(current[1])
elif current[0] == "jump"
i += int(current[1])
elif current[0] = "none":
pass
else:
print(f"invalid line {game_list[i]}")
with open("coins.txt", "w") as coins:
coins.write("\n".join(valid_coins))
There's no need for the try/except. Opening in w mode will create the file if it doesn't already exist, you don't need x for that.
My Problem is on line 25 when it says
if conformation == 1:
for i in range(l, len(lines[k]), 1):
if lines[k][i].isdigit() or lines[k][i].istitle():
f += lines[k][i]
if f in var:
print(var[f])
What my issue is is that the "f" string isn't being added to and its value stays as "". For context, I'm trying to make my own sort of mini programming language, and I'm trying to make prints read for variables. Every time it loops to set f to the variable name, nothing happens. The only way I get remotely close to finding the variable name is by doing "print(lines[k][i])" before the "if lines[k][i]" condition.
Note: I was using a debugger, and I'm not sure if the "if f in var" condition is even being checked.
Python code that reads my custom programming language:
⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄
code = open("HelloWorld.sabo", 'r')
lines = code.readlines()
var = {}
for k in range(0, len(lines), 1):
conformation = 0
temp = ""
temp2 = ""
if lines[k][0:5] == "print":
r = 0
l = 0
p = False
f = ""
for i in lines[k]:
r += 1
if not p:
l += 1
if i == "(":
p = True
conformation += 1
if i == "\"" and conformation == 1:
conformation += 1
if conformation == 2:
break
if conformation == 1:
for i in range(l, len(lines[k]), 1):
if lines[k][i].isdigit() or lines[k][i].istitle():
f += lines[k][i]
if f in var:
print(var[f])
if conformation == 2:
for i in range(r, len(lines[k]), 1):
if not lines[k][i] == "\"":
f += lines[k][i]
else:
break
print(f)
elif lines[k][0:4] == "var ":
for i in range(4, len(lines[k]), 1):
if not lines[k][i] == " ":
temp += lines[k][i]
else: break
for i in range(4, len(lines[k])):
if lines[k][i] == "=":
conformation = 1
elif conformation == 1:
if not lines[k][i] == " ":
temp2 += lines[k][i]
elif not temp2 == "":
break
var[temp] = temp2.strip()
Code that is being read by the above script:
⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄
var val = hello
print(val)
So, I was being a bit dumb with this, but I found out that if I just account for Uppercase and Lowercase characters, then it will work.
if lines[k][i].islower() or lines[k][i].isdigit() or lines[k][i].isnumeric() or lines[k][i].istitle():
f += lines[k][i]
I might have gone overboard with the security though I'm just not sure about the difference isdigit and isnumeric.
I am making a game in python and I get this error:
UnboundLocalError: local variable 'playerY' referenced before assignment
The code is:
import voyager200librarys
playerY = 1
playerX = 0
amountOfRows = 3
command = voyager200librarys.menu ("P Y C R A F T", ["Play", "Quit"])
if (command == "Play"):
world = [0,0,0,0,-1,0,1,1,1]
def printWorld ():
index = 0
indexCheck = 0
for x in range(len (world)):
voyager200librarys.printWithoutNewLine (" ")
if (world [index] == 0):
voyager200librarys.printWithoutNewLine (" ")
if (world [index] == 1):
voyager200librarys.printWithoutNewLine ("D")
if (world [index] == -1):
voyager200librarys.printWithoutNewLine ("&")
indexCheck += 1
if (indexCheck == 3):
print ("")
indexCheck = 0
index += 1
def mainMenu ():
print ("")
whatToDo = voyager200librarys.menu ("What To Do?", ["Move"])
if (whatToDo == "Move"):
movementControls ()
def movementControls ():
print ("")
print ("Movement Controls:")
print ("< > Ʌ")
print ("")
print ("| | |")
print ("V V V")
print ("")
print ("1 2 3")
print ("")
command = input ("Plase Pick An Option: ")
command = int (command)
if (command != 1):
if (command != 2):
if (command != 3):
print ("Plase Pick A Valid Option Next Time.")
if (command == 1):
world [playerY * amountOfRows + playerX] = 0 #(The problem occurs here)
playerX -= 1
if (command == 2):
world [playerY * amountOfRows + playerX] = 0
playerX += 1
if (command == 3):
world [playerY * amountOfRows + playerX] = 0
playerY -= 0
while (True):
printWorld()
mainMenu()
world [playerY * amountOfRows + playerX] = -1
and I've tried swapping "playerX" and "playerY" but it doesn't fix it! Btw the game itself is a ripoff of minecraft, and if your missing any information ask me.
If anyone has answers please help!
P.S. A quick answer would be great.
P.S. It's python.
I have a little problem who block me, I've a work where I must to convert a number to Shadocks (base 4 it seems), and I must to make a decrypter.
So I made the first part, but my code won't work on the second.
Here it's :
def Base10toShadocks(n):
q = n
r = 0
Base4=[]
Shads=["GA","BU","ZO","MEU"]
if q == 0:
Base4.append(0)
else:
while q > 0:
q = n//4
r = n%4
n = q
Base4.append(r)
Base4.reverse()
VocShad = [Shads[i] for i in Base4]
print(VocShad)
def ShadockstoBase10(n):
l=len(n)
Erc_finale=[]
for i in range(l):
Sh=(n[i])
i=i+1
if Sh =="a":
Erc_finale.append(0)
elif Sh =="b":
Erc_finale.append(1)
elif Sh =="o":
Erc_finale.append(2)
elif Sh =="e":
Erc_finale.append(3)
print(Erc_finale)
F=str(Erc_finale)
print(F)
F=F.replace("[","")
F=F.replace("]","")
F=F.replace(",","")
F=F.replace(" ","")
L2=len(F)
F=int(F)
print(L2)
print(F)
r=0
while f < 4 or F ==4:
d=(F%4)-1
F=F//4
print(d)
r=r+d*(4**i)
print(r)
inp = 0
inp2 = 0
print("Tapez \"1\" pour choisir de traduire votre nombre en shadock, ou \"2\" pour inversement")
inp = int(input())
if inp == 1:
print("Quel est le nombre ?")
inp2 = int(input())
if inp2 != None:
Base10toShadocks(inp2)
elif inp == 2:
print("Quel est le nombre ?")
inp2 = str(input())
if inp2 != None:
ShadockstoBase10(inp2)
It blocks at the F=int(F), I don't understand why.
Thanks for your help.
First, some errors in your code:
for i in range(l):
Sh=(n[i])
i=i+1 #### Won't work. range() will override
##### Where do "a","b","o","e" come from
##### Shouldn't it be "G","B","Z","M" ("GA","BU","ZO","MEU")?
if Sh =="a":
Erc_finale.append(0)
elif Sh =="b":
Erc_finale.append(1)
elif Sh =="o":
Erc_finale.append(2)
elif Sh =="e":
Erc_finale.append(3)
print(Erc_finale)
F=str(Erc_finale) ### Not how you join an array into a string
Here's a corrected way:
def ShadockstoBase10(n):
n = n.upper(); # Convert string to upper case
l = len(n)
Erc_finale = "" # Using a string instead of an array to avoid conversion later
i = 0
while i < l: # while loop so we can modify i in the loop
Sh = n[i:i+2] # Get next 2 chars
i += 2 # Skip 2nd char
if Sh == "GA":
Erc_finale += "0"
elif Sh == "BU":
Erc_finale += "1"
elif Sh == "ZO":
Erc_finale += "2"
elif Sh =="ME" and "U" == n[i]:
Erc_finale += "3"
i += 1; # MEU is 3 chars
else:
break; # bad char
return int(Erc_finale, 4) # Let Python do the heavy work
Like everything in Python, there are other ways to do this. I just tried to keep my code similar to yours.
The closest thread I could find to my problem was this: Python setter does not change variable
It didn't really help, the volume and the channels are not changing at all. The first fucntion which is to "watch TV" works perfectly fine.
class TV(object):
def __init__(self, channel, volume):
self.__channel = channel
self.__volume = volume
def __str__(self):
out = ""
out += "You're on channel #" + str(self.__channel) + ", " + self.channelNetwork()
out += "\nVolume is currently at: " + str(self.__volume) + "/20"
return out
# a method that determines the name for each channel from 1-10
def channelNetwork(self):
c = self.__channel
if c == 1:
return "CBS"
elif c==2:
return "NBC"
elif c==3:
return "ABC"
elif c==4:
return "Fox"
elif c==5:
return "ESPN"
elif c==6:
return "PBS"
elif c==7:
return "CNN"
elif c==8:
return "Comedy Central"
elif c==9:
return "Cartoon Network"
elif c==10:
return "Nicklodeon"
# a volume slider that has a range from 0-20
def volumeSlider(self, newVolume):
v = self.__volume
if newVolume == "+":
v += 1
else:
v -= 1
if v < 0:
v = 0
if v > 20:
v = 20
def channelChanger(self, newChannel):
c = self.__channel
if newChannel == "+":
c += 1
else:
c -= 1
if c < 0:
c = 0
if c > 10:
c = 10
def main():
import random
randomChannel = random.randint(1,10)
randomVolume = random.randrange(21)
televsion = TV(randomChannel, randomVolume)
choice = None
while choice != "0":
print \
("""
TV Simulator
0 - Turn off TV
1 - Watch TV
2 - Change channel
3 - Change volume
""")
choice = input("Choice: ")
print()
# exit
if choice == "0":
print("Have a good day! :)")
elif choice == "1":
print("You relax on your couch and watch some TV")
print(televsion)
elif choice == "2":
newChannel = None
while newChannel not in ('+', '-'):
newChannel = input("\nPress '+' to go up a channel and press '-' to go down a channel: ")
televsion.channelChanger(newChannel)
elif choice == "3":
newVolume = None
while newVolume not in ('+', '-'):
newVolume = input("\nPress '+' to increase volume and press '-' to decrease volume: ")
televsion.volumeSlider(newVolume)
else:
print("\nSorry, but", choice, "isn't a valid choice.")
main()
input("\n\nPress enter to exit.")
The problem is, that when you do:
v = self.__volume
In:
def volumeSlider(self, newVolume):
v = self.__volume
if newVolume == "+":
v += 1
else:
v -= 1
if v < 0:
v = 0
if v > 20:
v = 20
Assigning to v won't affect self.__volume. You need to use self.__volume = 20 or whatever.
As an aside, don't use double-underscore name-mangling unless you actually need it. E.g. self.volume is fine.