Please am very new in python, and I am trying to do a Binary CSP instance, where it generates variables based on the number of variables the user wants. So if the user wants 4 variables, it generates X1, X2, X3, X4 and then appends to a list. I have tried working on it, still can't place it
class CSP:
def __init__(self, variables):
self.variables = list(variables)
def get_variables(self):
return self.variables
class Map(CSP):
n = input("Enter number of variables: ")
for i in range(n):
vare = 'X' + 'i'
def __init__(self):
super().__init__(self._collect_variables())
def _collect_variables(self):
variables = []
variables.append(self.vare) #list the user appends to
def main():
Map()
if __name__ == '__main__':
main()
Your code is not working for a simple reason: it does not generate several variables. Instead of it, it updates single variable 'vare'.
I should do it in the following way:
class Map(CSP):
self._vare = []
def __init__(self):
n = input("Enter number of variables: ")
for i in range(n):
vare.append ('X' + 'i')
super().__init__(self._get_variables())
def _get_variables(self):
return self._vare
Related
I am just a newbie in Python and trying to write this program. So far, my code looks like this.
class Investment:
def _init_(self,p,i):
self.p = p
self.i = i
def value_after(self,value,n):
value = (1+i) ** n
return p * value
def _str_(self):
return "Principal:"(p),"Investment:"(I),"%"
pr = Investment(98,3)
print(pr.value_after())
I expect to print Principal and Interest rate separately. At this point, I am getting the following Error
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\principalandinterest.py", line 10, in
pr = Investment(98,3)
TypeError: Investment() takes no arguments
{class Investment(object):
def __init__(self,p,i):
self.p = p
self.i = i
def value_after(self,value,n):
value = (1+self.i) ** n
return (self.p * value)
def _str_(self):
return ("Principal:"(self.p),"Investment:"(self.i),"%")}
pr = Investment(98,3)
print(pr.value_after(2,1))
i and p are class attributes and can not be called like this in your methods, they should be called like self.i
Self.p
I am working on my undergraduate project and this is my first time using Python to control a parrot bebop 2 drone. I have a variable x(an int) and I want to read its value from a file. In the mean time I want the program to read this file continuously; what I mean is that my text file input will be changed each time and I want the Python code to catch this change and change the value x.
For example:
if x is assigned 1 from the text file --> then the drone takes off.
in the mean time after x is assigned the value 1, I want it to be assigned 2 automatically and do the second command, for example: move to the left (but without disconnecting the drone "the first command")
here is my code, but I had a lot of problems with it, it checks the value, but no commands work after it knows the value of x:
bebop = Bebop()
print("connecting")
success = bebop.connect(10)
print(success)
f = open('EEGresults.txt')
lines = f.readlines()
list_of_elements = []
for line in lines:
list_of_elements += map(int, line.split())
f.close()
print (list_of_elements)
x = list_of_elements[1]
bebop.smart_sleep(5)
if x == 1:
print ("Yay! This number is = 1")
bebop.safe_takeoff(3)
else:
if x == 2:
print ("Yay! This number is = 2")
bebop.move_relative(0,0,0,1.6)
I expect that the code will read the value of x from text file directly and continuously and at the same time it will run the commands depending what the value of x that it receives.
I don´t know how to use Bebop but I whould use something like this...
First I would create an object to store the data from your file. So you need something like an onValueChanged callback. You have to define this object on your own:
class NotifierVariable():
def __init__(self):
self.__value = 0
self.__Listener = list()
#NotifierVariable.setter
def set(self, value):
if(value != self.__value):
self.__value = value
for callback in self.__Listener:
callback(self.__value)
#property
def get(self):
return self.__value
def addListener(self, callback):
self.__Listener.append(callback)
You can use it in the following way:
class NotifierVariable():
def __init__(self):
self.__value = 0
self.__Listener = list()
def set(self, value):
if(value != self.__value):
self.__value = value
for callback in self.__Listener:
callback(self.__value)
def get(self):
return self.__value
def addListener(self, callback):
self.__Listener.append(callback)
def Func(value):
print(value)
if __name__ == '__main__':
x = NotifierVariable()
x.addListener(Func)
x.set(10)
Now you have to read the file periodicly:
while(True):
with open('EEGresults.txt') as File:
lines = File.readlines()
list_of_elements = []
for line in lines:
list_of_elements += map(int, line.split())
print (list_of_elements)
x.set(list_of_elements[1])
time.sleep(10)
You use the callback to send the command to your drone. The file is periodicly read out every 10 seconds (you can change it) and update your x variable. A callback is triggered if the value got changed and then you can send a command, based on the input, to your drone.
I'm having trouble understanding how to instantiate a class, and update that instances variables. If I __init__ a series of self.x variables, then instance that class, I want to update self.x = 40. However, self.x always stays constant.
I have a feeling I'm not wrapping my head around the class variable, init variable, and instanced class variables. I can always access them, I just can't seem to change them. I have coded an example of what I am trying to do.
class Engine(object):
def __init__(self, board):
self.board = board
def play_game(self):
print(self.board.sheet[0])
number_one = int(input("Please enter a number."))
self.board.a = number_one
number_two = int(input("Please enter another number."))
self.board.b = number_two
number_three = int(input("Please enter a third number."))
self.board.c = number_three
number_four = int(input("Please enter a final number."))
self.board.d = number_four
print("Thank you! List updated.")
print(self.board.sheet[0])
class ScoreBoard(object):
def __init__(self):
self.a = "_____"
self.b = "_____"
self.c = "_____"
self.d = "_____"
self.sheet = [f"""
1. Number One: {self.a}
2. Number Two: {self.b}
3. Number Three: {self.c}
4. Number Four: {self.d}
"""]
new_board = ScoreBoard()
new_game = Engine(new_board)
new_game.play_game()
When I print self.board.sheet[0] I would like to show the numbers instead of the lines for self.a through self.d.
You need to recompute self.sheet after self.a through self.d are set. After self.sheet is assigned it just contains a simple string. That string isn't automatically updated when the fields are changed; you have to do it yourself.
Better yet, make sheet a method rather than a static variable.
class ScoreBoard(object):
def __init__(self):
self.a = "_____"
self.b = "_____"
self.c = "_____"
self.d = "_____"
def sheet(self):
return f"""
1. Number One: {self.a}
2. Number Two: {self.b}
3. Number Three: {self.c}
4. Number Four: {self.d}
"""
I am trying to understand object oriented programming. I am doing this by creating a small poker like program. I have come across a problem whose minimal working example is this:
For this code:
import random
class superthing(object):
def __init__(self,name,listthing=[]):
self.name = name
self.listthing = listthing
def randomlyadd(self):
self.listthing.append(random.randint(1,50))
def __str__(self):
return '\nName: '+str(self.name)+'\nList: '+str(self.listthing)
Aboy = superthing('Aboy')
Aboy.randomlyadd()
print(Aboy)
Anotherboy = superthing('Anotherboy')
Anotherboy.randomlyadd()
print(Anotherboy)
I expect this output :
Name: Aboy
List: [44]
(some number between 1 and 50)
Name: Anotherboy
List: [11]
(again a random number between 1 and 50)
But what I get is:
Name: Aboy
List: [44]
(Meets my expectation)
Name: Anotherboy
List: [44,11]
(it appends this number to the list in the previous instance)
Why is this happening? The context is that two players are dealt a card from a deck. I am sorry if a similar question exists, if it does, I will read up on it if you can just point it out. New to stack overflow. Thanks in advance.
For the non minimal example, I am trying this:
import random
class Card(object):
def __init__(self, suit, value):
self.suit = suit
self.value = value
def getsuit(self):
return self.suit
def getval(self):
return self.value
def __str__(self):
if(self.suit == 'Clubs'):
suitstr = u'\u2663'
elif(self.suit == 'Diamonds'):
suitstr = u'\u2666'
elif(self.suit == 'Hearts'):
suitstr = u'\u2665'
elif(self.suit == 'Spades'):
suitstr = u'\u2660'
if((self.value<11)&(self.value>1)):
valuestr = str(self.value)
elif(self.value == 11):
valuestr = 'J'
elif(self.value == 12):
valuestr = 'Q'
elif(self.value == 13):
valuestr = 'K'
elif((self.value == 1)|(self.value == 14)):
valuestr = 'A'
return(valuestr+suitstr)
class Deck(object):
def __init__(self,DeckCards=[]):
self.DeckCards = DeckCards
def builddeck(self):
suits = ['Hearts','Diamonds','Clubs','Spades']
for suit in suits:
for i in range(13):
self.DeckCards.append(Card(suit,i+1))
def shuffle(self):
for i in range(len(self)):
r = random.randint(0,len(self)-1)
self.DeckCards[i],self.DeckCards[r] = self.DeckCards[r],self.DeckCards[i]
def draw(self):
return self.DeckCards.pop()
def __str__(self):
return str([card.__str__() for card in self.DeckCards])
def __len__(self):
return len(self.DeckCards)
class Player(object):
def __init__(self,Name,PlayerHandcards = [],Balance = 1000):
self.Name = Name
self.Hand = PlayerHandcards
self.Balance = Balance
def deal(self,deck):
self.Hand.append(deck.draw())
def __str__(self):
return 'Name :'+str(self.Name)+'\n'+'Hand: '+str([card.__str__() for card in self.Hand])+'\n'+'Balance: '+str(self.Balance)
deck1 = Deck()
deck1.builddeck()
deck1.shuffle()
Alice = Player('Alice')
Alice.deal(deck1)
print(Alice)
Bob = Player('Bob')
Bob.deal(deck1)
print(Bob)
And after dealing to Bob they both have the same hands. If you have some other suggestions regarding the code, you are welcome to share that as well.
This is a duplicate of “Least Astonishment” and the Mutable Default Argument as indicated by #Mad Physicist. Closing this question for the same.
I have been trying to alter a list in class Inventory from class Pod, but I get an error that I am popping from an empty set. Is there anyway that I can pop from a list from an Inventory instance that I know is populated? Essentially, I am trying to transfer widgets from Inventory to Pod.
class Widget():
def __init__(self):
self.cost = 6
self.value = 9
class Inventory():
def __init__(self):
self.widgets_inv = []
self.cost_inv = 0
self.value_inv = 0
def buy_inv(self):
x = int(input("How many widgets to you want to add to inventory? "))
for i in range(0, x):
self.widgets_inv.append(Widget())
def get_inv(self):
print("You have " + str(len(self.widgets_inv)) + " widgets in inventory.")
def cost_of_inv(self):
cost_inv = len(self.widgets_inv) * Widget().cost
print("The current cost of your inventory is: " + cost_inv + " USD.")
def value_of_inv(self):
val_inv = len(self.widgets_inv) * Widget().value
print("The current value of your inventory is: " + val_inv + " USD.")
class Pod():
"""A pod is a grouping of several widgets. Widgets are sold in pods"""
def __init__(self):
self.pod = []
def creat_pod(self):
x = int(input("How many widgets would you like to place in this pod? "))
for i in range(0, x):
self.pod.append(Widget())
Inventory().widgets_inv.pop()
You should modify the creat_pod-method, so that you can handover the Inventory-object. This allows you to add widgets to the inventory-object before calling creat_pod-method:
def creat_pod(self, inventory):
x = int(input("How many widgets would you like to place in this pod? "))
for i in range(0, x):
self.pod.append(Widget())
inventory.widgets_inv.pop()
In your original code you create always a new Inventory-object, which has therefore and empty widget-list:
Inventory().widgets_inv.pop()