Unable to copy list to set. 'float' object is not iterable - python-3.x

lst,score_set,final_lst = [],[],[]
if __name__ == '__main__':
for _ in range(int(input())):
name = input()
score = float(input())
score_set.append(score)
lst.append(([name,score]))
new_set = set()
for i in range(0,len(score_set)):
item = score_set[i]
print (item)
new_set.update(item)
I am trying to copy a list into a set to remove duplicates. In my code, if I remove the last line, the code runs fine. Could you guys please help ?

If you want to add a single value, use add() instead of update():
new_set.add(item)

Related

grocery list in python 3

I'm confused about how to compare user input and a set list on python. For this problem, I have to create a program that asks the user for a list of ingredients. As the user enters the ingredients, I then need to store them in a list. Once the user is done entering their list, I need to pass this list to a function that will compare the ingredients to an already existing list of pantry items. If all items are available in the pantry, it should print out "you don’t need to go shopping". If any item is missing, it should print out "you need to go shopping" and list the missing ingredients. I've tried several ways of doing it but I can't figure it out.
So basically my function has to have:
1: A pre-created list for pantry items
2: User input into an ingredient list
3: Pass the ingredient list to a method
4: Use a conditional and loop in the method
5: Print out the results of whether the user needs to go shopping based on the items in the ingredient list that are not in the pantry.
This is what I have right now. Whenever I run it, it allows me to type in an item but then says <function end at 0x7fec87bf58b0> :
shopping_list = []
set_list = ['bread', 'jelly', 'peanut butter', 'chips']
#prints out what I need or if I have everything on my list
def end():
for item in shopping_list:
if shopping_list == set_list:
print("you have everything")
else:
print("You have to go grocery shopping! You need:" + str(new_list))
while True:
#asks for new items and removes them from the set list to return a new list
try:
new_item = input("Item? : ")
except ValueError:
print("Oops! That was no valid item. Try again...")
new_list = set_list.remove(new_item)
print(new_list)
if new_item == 'done':
print(end)
end is a function. When you write print(end) you ask python to print info about function. So it prints <function end at 0x7fec87bf58b0>. To print a result of a function you should call it first
So the end of your script will look like
if new_item == 'done':
result = end() # calling a function
print(result)
There you go:
pantry_items = ["apple", "banana", "eggs"]
ingridient_list = []
shopping_list = []
def compare_lists():
for item in pantry_items:
if item not in ingridient_list:
shopping_list.append(item)
userinput = ""
while (len(ingridient_list) < len(pantry_items)):
userinput = input("Enter smth.: ")
if (userinput == "done"):
compare_lists()
if len(shopping_list) > 0:
print("You need:")
print(shopping_list)
else:
print("You dont need to go shopping")
break
ingridient_list.append(userinput)
My python is a bit rusty, but this will do the job

Python Try Except when a list is null

I've been searching for my problem here, but i can't find the exact answer to my problem.
I call a sympy function ( solve() ). This function can return a full list or an empty list.
I call this piece of code inside a while:
try:
sol = solve([eq1,eq2],[r,s])
rB = bin(abs(sol[0][0]))
sB = bin(abs(sol[0][1]))
stop = True
r = rB[2:len(rB)]
s = sB[2:len(sB)]
P = int("0b"+r+s,2)
Q = int("0b"+s+r,2)
print(P*Q == pubKey.n)
print("P = {}".format(P))
print("Q = {}".format(Q))
break
except ValueError:
pass
What i want is:
if the solve() returns an empty list, just pass. And if the solve() returns a full list, keep with the execution. The solve will be returning empty list until i find the right value.
This can be reached by checking sol[0][0], if there's a non-empty list this will work, but if the list is empty, this will throw an error (null pointer) i want try to flag it and pass.
What i'm having now is that when sol is empty, it tries to get sol[0][0], and ofc this throws an error that's not being catched by the try, and the whole code stops.
Anyone knows a solution for that? I'm not using try correctly?
Set sol in the beginning of each loop to some value and check it in the except clause
about else
try/except has an else which will be run the try block did not raise an Exception
and for has an else clause for when it was not broken out of!
for foo in iterable:
# set value so the name will be available
# can be set prior to the loop, but this clears it on each iteration
# which seems more desirable for your case
sol = None
try:
"logic here"
except Exception:
if isinstance(sol, list):
"case where sol is a list and not None"
# pass is implied
else: # did not raise an Exception
break
else: # did not break out of for loop
raise Exception("for loop was not broken out of!")

How to implement python dictionaries into code to do the same job as list functions

I need to be able to implement dictionaries into this code. Not all needs to be changed just were i can change it and it still does the same job.
In a test file I have a list of three strings (1, once),(2,twice).(2, twice).
I'm guessing the number will represent the value.
This code passes the tests but I am struggling to understand how I can use dictionaries to make it do the same job.
If any one can help it'll be grateful.
The current is:
The list items are in a test file elsewhere.
class Bag:
def __init__(self):
"""Create a new empty bag."""
self.items = []
def add(self, item):
"""Add one copy of item to the bag. Multiple copies are allowed."""
self.items.append(item)
def count(self, item):
"""Return the number of copies of item in the bag.
Return zero if the item doesn't occur in the bag.
"""
counter = 0
for an_item in self.items:
if an_item == item:
counter += 1
return counter
def clear(self, item):
"""Remove all copies of item from the bag.
Do nothing if the item doesn't occur in the bag.
"""
index = 0
while index < len(self.items):
if self.items[index] == item:
self.items.pop(index)
else:
index += 1
def size(self):
"""Return the total number of copies of all items in the bag."""
return len(self.items)
def ordered(self):
"""Return the items by decreasing number of copies.
Return a list of (count, item) pairs.
"""
result = set()
for item in self.items:
result.add((self.count(item), item))
return sorted(result, reverse=True)
I have been scratching my head over it for a while now. I can only use these also for dictionaries.
Items[key] = value
len(items)
dict()
items[key]
key in items
Del items[key]
Thank you
Start with the simplest possible problem. You have an empty bag:
self.items = {}
and now a caller is trying to add an item, with bag.add('twice').
Where shall we put the item?
Well, we're going to need some unique index.
Hmmm, different every time, different every time, what changes with each .add()?
Right, that's it, use the length!
n = len(self.items)
self.items[n] = new_item
So items[0] = 'twice'.
Now, does this still work after a 2nd call?
Yes. items[1] = 'twice'.
Following this approach you should be able to refactor the other methods to use the new scheme.
Use unit tests, or debug statements like print('after clear() items is: ', self.items), to help you figure out if the Right Thing happened.

Passing string variable value in Pandas dataframe

I have been trying to use variables for passing the string value in dataframe for various column operations, but the code is giving me wrong results. See the code below, I am using in Jupyter Notebook:
first_key = input("key 1: ")
second_key = input("ket 2: ")
third_key = input("ket 2: ")
These receive the values "Russia", "China", "Trump" for the operation in next cell as below:
tweets['{first_key}'] = tweets['text'].str.contains(r"^(?=.*\b{first_key}\b).*$", case=False) == True
tweets['{second_key}'] = tweets['text'].str.contains(r"^(?=.*\b'{second_key}'\b).*$", case=False) == True
tweets['{third_key}'] = tweets['text'].str.contains(r"^(?=.*\b'{third_key}'\b).*$", case=False) == True
But results are wrong. Any idea how to get the correct results. A small snapshot of the results is like this.
I've tried cleaning up your code. You can leverage f-strings (using python-3.6+) with a tiny change to your code:
def contains(series, key):
return series.str.contains(rf"^(?=.*\b{key}\b).*$", case=False)
If you're working with an older version of python, use str.format:
def contains(series, key):
return series.str.contains(r"^(?=.*\b{}\b).*$".format(key), case=False)
Next, call this function inside a loop:
for key in (first_key, second_key, third_key):
tweets[key] = contains(tweets['text'], key)

How to check all variables created by class function and use them?

In short; I started coding a few days ago and thought trying to make a simple text based adventure will let me face a lot of problems that I will encounter in other harder projects as well. My class init function produces items with some variables, one of which is it's equipment slot position [0-6]. I would like to unequip a slot, but the way I have it set up at the moment requires me to know which item is in that particular slot.
In english: unequip("mainhand"), mainhand has slotnumber 0. Get the info of all equipped items and check which one has the corresponding slotnumber, then remove that particular item.
(Some items have 2 slotnumbers ("althand") which means I will have to find a way to make sure I remove the right item from the list, but that is something I can do later). For now, I can't seem to figure out how to dynamically call items and do stuff with them.
PS. I am pretty sure I can do this in a way more phytonic manner and any suggestions are welcome, but regardless of this, I would still like to know how to dynamically call the function.
The code with which I try this:
def Unequip(Slotname): #Slotname is just a string, so I could say: unequip("Mainhand")
for count,i in enumerate(Item.slotname): #Item.slotname is a list of strings for slots which corresponds with Item.Slot which are the values determining the which slot is occupied.
if Slotname == Item.slotname[count]: #so when the name I put into the function equals the Item.slotname, I know which number in Item.Slot I need.
for items in Item: #Here we enter the problem (again, I understand that this code could be a lot better and would love some suggestions).
#Item is a object, but it's __init__ functions produces items, such as item1, item2 etc. I would like to check if any of these items is currently in my Item.Equipped and has the Item.Slot value I want to remove.
#I tried global(), locals() and dir(Item) but none give me what I need. I really hope this makes it clear.
if Item.Slot[count] == items.slot and items.name == Item.Equipped: #I need a susbtitute for the items variable which will represent item1, item2 or item3 etc. So I can do Item.Slot.remove(item2.slot).
Slot = Item.Slot.remove(items.slot)
Equipped = Item.Equipped.remove(items.name)
Player.stats = list(map(operator.sub,list(Player.stats),self.itemstats))
elif Item.Slot[i] == items.altslot and Items.name == items.Equipped:
pass
Full code (I tried using self etc, but it may not be super readable, my apologies), it includes a item.unequip function but this requires me to select the particular item instead of just the slot from which I want my item to be removed
Edit1: Removed all unneeded stuff per request:
import random
import operator
class Item:
Equipped = []
Slot = []
Inventory = []
num_of_items = 0
statnames = ["Strength", "Agility", "Dexterity", "Wisdom", "Constitution", "Intelligence"]
slotname = ["MainHand","Offhand","Head", "Necklace","Chest","Legs", "Cape" ]
def __init__(self, name, itemstats, slot, altslot = None, atk = None, Def = None):
self.itemstats = itemstats #itemstats in order: S, A, D, W, C, I
self.name = name
Item.num_of_items += 1
self.slot = slot
self.altslot = altslot
if atk != None and atk != 0:
self.atk = atk
if Def != None and Def != 0:
self.Def = Def
def Unequip(Slotname):
for count,i in enumerate(Item.slotname):
if Slotname == Item.slotname[count]:
for items in dir(Item):
if Item.Slot[count] == items.slot and items.name == Item.Equipped:
Slot = Item.Slot.remove(items.slot)
Equipped = Item.Eqiupped.remove(items.name)
Player.stats = list(map(operator.sub,list(Player.stats),self.itemstats))
elif Item.Slot[i] == items.altslot and Items.name == items.Equipped:
pass
class Player:
stats= [8,8,8,8,8,8]
item1 = Item("Sword of damaocles",[5, 1, 0,1,2,-2],0,1,20)
item2 = Item("Helmet of steel",[9,9,9,9,9,9],2,None,0,20)

Resources