So yes I know that there is an answer on how to fix this but can someone explain to me what the hell it means?Because I don't know where it comes from and I also don't know what indented means in programming (as you can understand dear reader English is not my native tongue).
P.S I found that error from a for-loop I was trying to execute, and the code was similar to this:
img = img.resize((basewidth,hsize), PIL.Image.ANTIALIAS)
j='.jpg'
s='somepic'
p=img.save(s+'1'+j)
for i in range(2, 659):
if i==21:
i = i + 1
elif i==36:
i=i+1
elif i==45:
i = i + 1
elif i==51:
i = i + 1
elif i==133:
i = i + 1
elif i==163:
i = i + 1
elif i==263:
i = i + 1
elif i==267:
i = i + 1
elif i==272:
i = i + 1
elif i==299:
i = i + 1
elif i==300:
i = i + 1
elif i==312:
i = i + 1
elif i==313:
i = i + 1
elif i==314:
i = i + 1
elif i==320:
i = i + 1
elif i==323:
i = i + 1
elif i==362:
i = i + 1
elif i==390:
i = i + 1
elif i==432:
i = i + 1
elif i==445:
i = i + 1
elif i==455:
i = i + 1
elif i==459:
i = i + 1
elif i==460:
i = i + 1
elif i==461:
i = i + 1
elif i==477:
i = i + 1
elif i==487:
i = i + 1
elif i==493:
i = i + 1
elif i==496:
i = i + 1
elif i==500:
i = i + 1
elif i==510:
i = i + 1
elif i==519:
i = i + 1
elif i==522:
i = i + 1
elif i==545:
i = i + 1
elif i==547:
i = i + 1
elif i==562:
i = i + 1
elif i==597:
i = i + 1
elif i==599:
i = i + 1
elif i==615:
i = i + 1
elif i==638:
i = i + 1
elif i==654:
i=i+1
else:
p= img + "i".save(s+i+j)
i=i+1
Which means a for-loop, an if-statement, a couple of elifs (or ORs inside the first if-statement) and then I am closing my if-statement with a save and a step forward.
EDITED: So the code above is what I have written and before that are a bunch of image inputs.But although I manage to fix the code with what you said at the end I have another error which says ['str' object has no attribute 'save'] but that is a problem for another time.
In python syntax, if statements, loops, and functions must be followed by indented lines. It's just python syntax. You have to put 4 spaces or use a tab before each line to indent them. In many other scripting languages, { } are used to enclose the code blocks. Without correct indenting, python doesn't know when a block of code ends.
An indent in Python is 4 spaces. Would have commented this, but I don't have enough reputation. Here's a link: Python: using 4 spaces for indention. Why?
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'm trying to do the polish notation challenge on kattis.com. Thing is, I feel I have done everything they asked for and I've tried fixing everything I could think of. I even looked up some other's solutions and while theirs are more clean I want to continue on mine as I am learning.
Why is it that for example this person's code works but not mine?
Here is my current code:
import sys
case = 1
valid_ints = set([str(i) for i in range(-10,11)])
def simplify(index, myLine, processed):
while index+1 > 0:
if (myLine[index] == "+" or myLine[index] == "-" or myLine[index] == "*") and index < len(myLine)-2:
if myLine[index+1] in valid_ints and myLine[index+2] in valid_ints:
try:
processed = myLine[index+3:] + processed
a = str(myLine[index+1] + myLine[index] + myLine[index+2])
processed.insert(0, str(eval(a)))
del myLine[index:]
except:
processed = [myLine[index], myLine[index+1], myLine[index+2]] + processed
del myLine[index:]
elif len(myLine) < 3:
processed = myLine + processed
del myLine[index]
index -= 1
processed = myLine + processed
return processed
for line in sys.stdin:
myLine = line.split()
processed = []
index = len(myLine)-1
savedprocessed = []
processed = simplify(index, myLine, processed)
while True:
if savedprocessed == processed:
break
else:
savedprocessed = []
savedprocessed += processed
processed = simplify(len(processed)-1, processed, [])
result = " ".join(savedprocessed)
print("Case " + str(case) + ": " + result)
case += 1
if case > 5:
break
You're bringing some other language style to Python, that's unnecessary because Python is more flexible.
I've simplified as much as I can here.
Split the input string on white spaces and iterate over the tokens.
For every operator in the expression, push a list onto the stack and append the operator and its operands to the list.
Now pop each list off the stack and process the list
def simplify(exp):
stack1 = []
ops = set('+*-')
for token in exp.split():
if token in ops:
stack1.append([])
stack1[-1].append(token)
stack2 = []
while stack1:
top = stack1.pop()
while len(top) < 3 and stack2:
top.append(stack2.pop())
if any(x.isalpha() for x in top):
simplified = ' '.join(top)
else:
top[0], top[1] = top[1], top[0]
simplified = str(eval(''.join(top)))
stack2.append(simplified)
return simplified
exp = '* - 6 + x -6 - - 9 6 * 0 c'
print(exp)
simplify(exp)
Output;
* - 6 + x -6 - - 9 6 * 0 c
* - 6 + x -6 - - 3 * 0 c
With the display I want the Banking command: input to start on a new string but when it gets to the display elif it does not. I know why, its because of the end= '' but I need to have the display be in one line for the assignment and I cant figure out a solution. Thanks for the help.
def main():
number_of_accounts = int(input("Number of accounts:\n"))
accounts = [0.0] * number_of_accounts
banking_command(accounts)
def banking_command(accounts):
from os import _exit as exit
active = True
while active:
banking_command = input('Banking command:\n')
banking_command = banking_command.split(' ')
if banking_command[0] == 'add':
monetary_amount = float(banking_command[2])
account_being_changed = int(banking_command[1])
accounts[account_being_changed - 1] += monetary_amount
elif banking_command[0] == 'subtract':
monetary_amount = float(banking_command[2])
account_being_changed = int(banking_command[1])
accounts[account_being_changed - 1] -= monetary_amount
elif banking_command[0] == 'move':
monetary_amount = float(banking_command[3])
transfer_money_out = int(banking_command[1])
transfer_money_in = int(banking_command[2])
accounts[transfer_money_out - 1] -= monetary_amount
accounts[transfer_money_in - 1] += monetary_amount
elif banking_command[0] == 'display':
i = 0
while i < len(accounts):
account_number = i + 1
print(str(account_number) + ":$" + str(accounts[i]) + " ", end= '')
i += 1
elif banking_command[0] == 'exit':
exit(0)
main()
Add a print() after the while loop.
elif banking_command[0] == 'display':
i = 0
while i < len(accounts):
account_number = i + 1
print(str(account_number) + ":$" + str(accounts[i]) + " ", end= '')
i += 1
print() # <-- end the line with the account display
I am making some practice code for a game similar to the board game, MasterMind-- and It keeps coming out with this error, and I can't figure out why it's doin it. Here's the code:
def Guess_Almost (Guess, Answer):
a = ''.join([str(v) for v in Answer])
g = str(Guess)
n = 0
am = 0
while n < 5:
if g[n] == a[0]:
am = am + 1
if g[n] == a[2]:
am = am + 1
if g[n] == a[3]:
am = am + 1
if g[n] == a[3]:
am = am + 1
n = n + 1
return(am)
Okay, the Guess is specified to be 4 integers, and the Answer is a list containing 4 numbers. They both have the same 'len' after the code, so i don't have a clue.
The point of this code is to turn the Answer into a string of 4 numbers, and see if any of those numbers match thoise of the guess, and return how many total matches there are.
See if this helps
def Guess_Almost (Guess, Answer):
a = ''.join([str(v) for v in Answer])
g = str(Guess)
n = 0
am = 0
if len(g) >= 5 and len(a) >=4:
while n < 5:
if g[n] == a[0]:
am = am + 1
if g[n] == a[2]:
am = am + 1
if g[n] == a[3]:
am = am + 1
if g[n] == a[3]:
am = am + 1
n = n + 1
return(am)