Python - can i recall a list name from raw_input? - python-2.7

I'm trying to create a game using python, but in my 'class Character:', i would like to do something like:
answer = raw_input('Which class do you want to play')
if answer = list_name[0]
self.stats = list_name
Thank you!

First note that your if statement should have an == instead of =
Also this type of situation is a great time to use python's in statement which will check if a value matches any of the items in your list! You could try something like this:
list_name = ['classA','classB','classC','classD']
answer = raw_input('Which class do you want to play: ')
#Check if the answer is one of the options in your list
if answer in list_name:
my_stats = answer
print 'great, your class is '+my_stats
else:
print 'sorry, ['+answer+'] is not an ok class'

Related

Groovy: Accessing class fields via list

First, I'm sorry for asking such a dumb question, but quick googling didn't help me much...
I'm a Java delevoper and very new to Groovy. Consider the following code snippet:
class Person {
public String name
}
​def jack = new Person()
jack.name = "Jack"
​
def bob = new Person()
bob.name = "Bob"
def list = new java.util.ArrayList()
list.add(jack)
list.add(bob)
println list.name​
Executing it gives the following output (list of name field values for each Person in the list):
[Jack, Bob]
So my question is what the corresponding java code for calling list.name?
My assumption is that it translates to something like:
list.stream().map(person -> person.name).collect(Collectors.toList())
Can somebody explain what exactly happens when i call list.name?
Thanks in advance!
Your code
list.property
is the shortest way to write this. What groovy implies here is the use of the spread operator:
list*.property
(note the * there). And .property could be short here for .getProperty(), for an implicit call to the getter).
So your assumption is correct, that this is the eager collection of the values .getProperty() returns into an ArrayList.

Partial match in a list, from a user input

Trying to get a partial match in a list, from a user input.
I am trying to make a simple diagnostic program. The user inputs their ailment and the program will output a suggested treatment.
print("What is wrong with you?")
answer=input()
answer=answer.lower()
problem=""
heat=["temperature","hot"]
cold=["freezing","cold"]
if answer in heat:
problem="heat"
if answer in cold:
problem="cold"
print("you have a problem with",problem)
I can get it to pick an exact match from the list but I want it to find partial matches from my input. For example if the user types they are "too hot".
Try the code below. The key is the split() method.
answer = input('What is wrong with you?')
answer = answer.lower()
heat = ['temperature', 'hot']
cold = ['freezing', 'cold']
for word in answer.split():
if word in heat:
problem = 'heat'
if word in cold:
problem = 'cold'
print('you have a problem with', problem)
I would recommend you use something like this which might be a bit more "pythonic"
answer = input()
cold = ["freezing", "cold"]
if any(answer in c for c in cold):
problem = "cold"

Concatenate queryset in django

I want to concatenate two queryset obtained from two different models and i can do it using itertools like this:
ci = ContributorImage.objects.all()
pf = Portfolio.objects.all()
cpf = itertools.chain(ci,pf)
But the real fix is paginating results.If i pass a iterator(cpf, or our concatenated queryset) to Paginator function, p = Paginator(cpf, 10), it works as well but fails at retrieving first page page1 = p.page(1) with an error which says:
TypeError: object of type 'itertools.chain' has no len()
What can i do in case like this ?
The itertools.chain() will return a generator. The Paginator class needs an object implementing __len__ (generators, of course do not support it since the size of the collection is not known).
Your problem could be resolved in a number of ways (including using list to evaluate the generator as you mention) however I recommending taking a look at the QuerySetChain mentioned in this answer:
https://stackoverflow.com/a/432666/119071
I think it fits exactly to your problem. Also take a look at the comments of that answer - they are really enlightening :)
I know it's too late, but because I encountered this error, I would answer to this question.
you should return a list of objects:
ci = ContributorImage.objects.all()
pf = Portfolio.objects.all()
cpf = itertools.chain(ci,pf)
cpf_list = list(cpf)

Python - Changing Class Variable Value in Function

I'm building a python class to encapsulate a drop-down list and its buttons in one convenient widget and I ran across a problem.
class DropDownMenu(DropDown):
def __init__(self, **kwargs):
super(DropDownMenu, self).__init__(**kwargs)
self.The_Menu = DropDown()
self.The_Btns = []
self.Num_Btns = 0
def Set_Num_Btns(self):
self.Num_Btns = len(self.The_Btns)
def Create_Menu(self, Btn_Names):
# Populate List Size Property
if (self.Num_Btns == 0):
self.Set_Num_Btns()
# Add Buttons to the Drop-Down
for i in range(0, self.Num_Btns):
self.The_Btns.append(Button(text = Btn_Names[i], size_hint_y = None, height = 20))
self.The_Menu.add_widget(self.The_Btns[i])
It compiles fine and when I try to create a drop-down menu, I get what I want:
self.File_Menu = DropDownMenu()
self.File_Menu.Create_Menu(self.File_Menu_Names)
self.add_widget(self.File_Menu)
But, if I try to bind any of the buttons to anything, like so:
self.File_Menu.The_Btns[0].bind(on_release = self.Insert_File_Menu.open)
The compiler throws an exception saying the list was out-of-bounds. On further inspection, I realized that even though I'm calling the Create_Menu function, the value of The_Btns is not being changed from an empty list. So, my question is: how do I fix this problem?
Any help would be appreciated. Thanks!
First of all, python doesn't "compile" in the sense that you refer to, and doesn't have a compiler. Also, have a look at PEP8.
To answer your question, You are iterating over a range, 0 to Num_Btns. However, in Set_Num_Btns, you set the variable to len(self.The_Btns), which is an empty list, i.e. you are iterating over range(0, 0). I suspect you mean to do soemthing like this:
for name in Btn_Names:
self.The_Btns.append(Button(text=name, ...))
....

Using a HavePropertyMatcher for collection elements in ScalaTest?

I've been using ScalaTest's FeatureSpec for a couple of days now and I'm trying to understand if it's possible to define the following spec using the built-in matchers (and if not, how I can write a suitable custom matcher).
Suppose I have the class Book:
case class Book(val title: String, val author: String)
and in my test I have a List of books:
val books = List(Book("Moby Dick", "Melville"))
Now, I would like to specify that the books list should contain a book with the title "Moby Dick". I would like to write something like:
books should contain (value with title "Moby Dick")
I can't seem to figure out from the docs and code if it's possible to express this requirement in ScalaTest. Has anyone ran into a similar situation?
In the meantime here's a custom matcher you can use:
def containElement[T](right: Matcher[T]) = new Matcher[Seq[T]] {
def apply(left: Seq[T]) = {
val matchResults = left map right
MatchResult(
matchResults.find(_.matches) != None,
matchResults.map(_.failureMessage).mkString(" and "),
matchResults.map(_.negatedFailureMessage).mkString(" and ")
)
}
}
Then you can use the full power of the ScalaTest Have matcher to inspect the fields of your object:
val books = List(Book("Moby Dick", "Melville"),
Book("Billy Budd", "Melville"),
Book("War and Peace", "Tolstoy"))
books should containElement(have('title("Moby Dick")))
books should containElement(have('title("Billy Budd"), 'author("Melville")))
books should containElement(have('title("War and Peace"), 'author("Melville")))
The last one is a failure producing this output:
The title property had value "Moby Dick", instead of its expected value "War and Peace", on object Book(Moby Dick,Melville) and The title property had value "Billy Budd", instead of its expected value "War and Peace", on object Book(Billy Budd,Melville) and The author property had value "Tolstoy", instead of its expected value "Melville", on object Book(War and Peace,Tolstoy)
You can also combine matchers with and or or, use not, etc.
Not currently, though you will be able to do something like this very soon in the future. What you can do now is something like:
books.exists(_.title == "Moby Dick") should be (true)