Python: Using a list to execute arguements [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Sorry if this is basic question I'm new to python and i couldn't find the proper way to do this within the api docs.
I have a list that contains stack arguments in the fashion
[push,3][push,2][push,1][pop][add]... so on
I also have a StackMachine.py file that created a class Stack:with the member functions push pop add sub mul div mod
I imported it into my main.py file and i want to go through my list and execute the arguments using the functions i made in my StackMachine.py file.
My question is how to analyze the list and use my member functions from the Stack class.
my main.py looks like
from StackMachine import Stack
import sys
toks = []
f = open(sys.argv[1])
for line in f.readlines():
tokens = line.split()
toks.append(tokens)
f.close()

It may not work because one you forgot the colon after the if statement, if i == "push": and if i == "pop":. For the push, 1 and push, 2 part you would be checking a tuple which is a data structure that is similar to a list but is immutable. So to check what the number is or what the first argument is you would do if i[0] == "push" and i[1] == 1: but before this if statement you would have to check if that object is a tuple so you would do if type = tuple:

Related

Find name in textfile [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
im new to python (I started yesterday) and wanted to make a program, in which you can enter a name, and then searches for the name in a text file and displays if the name exists or not. If I run the program and enter a existing name, it still shows "no" and I have no idea why. Can anyone help me out?
Here's a small code snippet which performs this logic:
def find_name_in_file(name, filename):
with open(filename, "r") as fd:
for line in fd.readlines():
if name in line:
return True # or print "YES"
return False # or print "NO"
Two things you need to keep in mind:
This code does not take into account case sensitivity, if name equals "Mark" and in the file the name is "mark" you will not find it (this can easily be resolved by using the "lower" function).
The function returns true also in cases where the file contains the word "SHMark" or "MarkSH". If you can't rely on the file having the exact name you are looking for you can add additional logic to check the word is surrounded by whitespace. I'll leave it to you to find out how to do it.

Python Logical Error in Loop while reading Dictionary [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am new to python and OOPS.I am expecting my module add_book to increment if book is already present in dictionary. Please help me .Not sure why for loop is not working as expected.
https://github.com/amitsuneja/Bookstore/commit/4aefb378171ac326aacb35f355051bc0b057d3be
You should not append to the list while you are still iterating it. Also, your code will append the new item for each item already in the list that has a different name. Instead, you should use a for/else loop. Here, the else case will only be triggered if you do not break from the loop.
for recordlist in self.mybooksinventory:
if self.name == recordlist['name']:
recordlist['quantity'] += 1
break # break from the loop
else: # for/else, not if/else !
self.mybooksinventory.append({'name':self.name,'stuclass':self.stuclass,'subject':self.subject,'quantity':1})

How to read lists and int from a file? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to make a coding system based on Enigma but I'd like to add a twist to it. In order to make to program customizable by the user id like to create "files" wich contains parameters that my prgramm will use to then crypt the message. It includes lists as well as integers. How can I read them?
I have tried using a split method and seperating my lists with "/" but the lists are considered as strings.
Here is an example of the paramaters I would like to assign to, in order, list1, list2, list3, list4, trigger1, trigger2, trigger3 that I tried to seperate with "/":
[6,18,20,12,17,26,19,4,10,22,13,7,14,1,21,9,2,16,3,23,24,8,15,11,25,5]/[1,-5,6,3,-4,2,-4,-4,-3,5,-1,1,-2,-2,-1,3,4,2,5,-4,-4,-4,2,-2,1,5]/[5,-1,-1,-1,-1,1,4,-3,-1,4,1,1,-4,2,-5,4,0,-3,-1,1,-2,0,2,2,-1,-3]/[2,-1,2,0,-3,2,-1,-1,0,2,-1,2,-2,-1,1,4,2,0,-2,-5,2,-1,3,0,-3,-1]/11/5/17
f=open("param.txt")
param=f.read()
list_tbl,param=param.split("/",1)
list_pattern1,param=param.split("/",1)
list_pattern2,param=param.split("/",1)
list_pattern3,param=param.split("/",1)
trigger1,param=param.split("/",1)
trigger2,param=param.split("/",1)
trigger3=param
When I try using the lists, they cannot be used because they are strings.
Have a look at ast.literal_eval which will basically do what you want i.e. make a list out of a string such as this:
from ast import literal_eval
my_string = '[0, 1, 2, 3]'
my_list = literal_eval(my_string)
To create multiple variables you can use a dictionary instead and then just fetch it by a key e.g.:
my_dict = {}
for i in range(10):
my_dict['list' + str(i)] = <some value>
which is definitely prettier than wasting lines on creating each variable.

Can't edit a tuple from inside a function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am programming an application in python. Here is the function:
def aircraftListBoxRefresh():
sqlConnect=sqlite3.connect("fglconfdb")
sqlCursor=sqlConnect.cursor()
sqlCursor.execute("SELECT fgAircraftDir FROM fglconfig")
adl=sqlCursor.fetchall()
global aircraftDirectories
for x in adl:
aircraftDirectories=aircraftDirectories+(x,)
I put print(aircraftDirectories) to test whether the value changes. It changes in side the function. But outside the function it is null.
I am trying to access the value with this:
aircraftDirectories=()
aircraftDir=StringVar(value=aircraftDirectories)
aircraftListBox=Listbox(mainframe,height=7,width=100,listvariable=aircraftDir)
aircraftListBox.place(x=170,y=170)
But I can't.
Any help greatly appreciated.
Regards.
You can't modify tuples anywhere, inside a function or outside, they're immutable. Maybe you want lists:
def aircraftListBoxRefresh():
sqlConnect=sqlite3.connect("fglconfdb")
sqlCursor=sqlConnect.cursor()
sqlCursor.execute("SELECT fgAircraftDir FROM fglconfig")
adl=sqlCursor.fetchall()
for x in adl:
aircraftDirectories.append(x)
aircraftDirectories=[]
aircraftDir=StringVar(value=aircraftDirectories)
aircraftListBox=Listbox(mainframe,height=7,width=100,listvariable=aircraftDir)
aircraftListBox.place(x=170,y=170)
With this approach, since you're modifying the list and not re-assigning to the variable, you don't need global.
You can't modify a tuple, but you can replace it. In this example M[] is a list of tuples, each tuple contains two numbers. I want to replace the first number of a tuple to 0, but keep the second number.
M[j] = (0, M[j][1])

Combine variable with variable and text in Python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I wondering what i am doing wrong here..
The issue is this line *final = 'PAT_' SID '.txt'*
where SID is a variable
Can anybody have a quick look, I am sure I am doing something stupid.
Below is the complete code...
#!/usr/bin/env python
import os
global SID
global final
with open ('sampleID.txt', 'r') as inF:
for line in inF:
if 'Sample ID:' in line:
SID = line.split(':')[1]
final = 'PAT_' SID '.txt'
os.rename("sampleID.txt",final)
To concatenate variables, you need to add (+) them:
final = 'PAT_' + SID + '.txt'
You can also use the built-in function str.format() here:
final = 'PAT_ {} .txt'.format(SID)
Or even the old way of string formatting, which is still compatible in Python 3 (but str.format is much better to use):
final = 'PAT_ %s .txt' % SID
By the way, your global statements aren't needed. A with statement does not introduce a new scope, hence everything defined in a with statement is a global variable.
use + to concat strings in python

Categories

Resources