Related
0
I'm making a simple text based adventure game. My code uses an adjacency matrix as a map. I would like to navigate the map by direction ex(N,E,S,W) my current attempt can only navigate via the name of the location
current output
You are currently in Foyer.
From this location, you could go to any of the following:
Living Room
Where would you like to go? Living Room
You are currently in Living Room.
From this location, you could go to any of the following:
Foyer
Bedroom 2
Powder Room
Kitchen
Where would you like to go? -__________________________________________________
I would like an output like
You are currently in Foyer.
From this location, you could go to any of the following:
South
Where would you like to go? South
You are currently in Living Room.
From this location, you could go to any of the following:
North
West
South
East
Where would you like to go?
import pygame
Inventory = []
names = ["Foyer", "Living Room", "Bedroom 2", "Full Bath", "Bedroom 3","Powder Room","Dinning", "Home Office", "Kitchen","Walkin Closet", "Hallway", "Bedroom1", "Sitting Room","Balcony", "Storage", "Garage", "Supply Closet", "Utility Closet", "Front Yard", "Sidewalk"]
graph = [[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0],[0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]]
directions =["North", "East", "South", "West"]
curr_location = "Foyer"
while True:
print("You are currently in ", curr_location, ".", sep = '')
print()
exits = []
print("From this location, you could go to any of the following:")
indx_location = names.index(curr_location)
for each in range(len(graph[indx_location])):
if graph[indx_location][each] == 1:
print("\t", names[each])
exits.append(names[each])
print()
next_location = input("Where would you like to go? ")
if not (next_location in exits):
print()
print("You cannot go this way.")
else:
curr_location = next_location
print()
Maybe add North, South, East, West to exits conditionally if it's possible to move in that direction?
As a beginner I have a few doubts about this project I'm working on
The general idea of this project is to allow users to be able to detect a certain disease through symptoms
I want the program to match the input with the provided lists and pick out the best match and print output.
The problem here is that the list provided with symptoms of diseases shares few common symptoms with each other. So the program must evaluate the entire set of lists and print the best match
I tried something
import re
input1 = input("Enter Your Symptoms: ".lower())
x = re.split("\s", input1) #used to seprate the words in the string and create a list out of it
# Symptoms
cadsym = ['chest pain' , 'body pain' , 'falling sick' , 'feeling faint' , 'shortness of breath']
vhdsym = ['swollen ankles' , 'fanting' , 'shortness of breath']
hasym = ['racing heartbeat', 'slow heartbeat', 'chest pain' , 'anxiety', 'sweating']
mhasym = ['cold sweat', 'heartburn', 'sudden dizziness', 'discomfort in joints']
jsym = ['itching', 'abdominal pain', 'weight loss', 'yellow eyes' , 'yellow nails', 'vomiting']
cpsym = ['rashes on skin' , 'fever' , 'sore throat' , 'brown spots' , 'itching']
msym = ['fever', 'runny nose' , 'sneezing' , 'pink eye' , 'skin rash', 'diarrhoea']
dsym = ['Eye pain' , 'fever' , 'muscle pain' , 'nausea' , 'joint pain', 'rash on thigh']
masym = ['pain in muscle' , 'pain in abdomin' , 'Night sweat' , 'shivering', 'fast heart rate' , 'mental confusion']
tcsym = ['chest pain','Night sweats','shortness of breath','blood cough']
disym = ['increase thirst','frequent urination','hunger','blurred vision','slow healing']
pnsym = ['fever','chills','sharp pain in chest','clammy skin']
htsym = ['nose bleeds','dizziness','morning headaches','irregular heart rhythms','vision changes','buzzing in the ears']
emsym = ['lot of mucus','tight chest','whistle sound while breathing']
cysym = ['bluish colour in sikn',' lips','nail beds']
hysym = ['itchy','red and watery eyes','rod of mouth being itchy','runny or blocked nose']
ansym = ['unusual headache','memory loss','slurred speech','forgotten words','trouble in walking','trouble in moving arms','trouble in moving legs']
hcsym = ['anxiety','shortness of breath','headache','daytime sleep even after sleeping a lot at night','daytime sluggishness']
bcsym = ['sleeping difficulty','sore throat','chest pressure','shortness of breath','runny nose']
asym = ['wheezing','anxiety','early awakening','shortness of breath at night','cough','throat irritation']
if x in cadsym:
print("You Might Have Coronary Artery Disease")
elif x in vhdsym:
print("You Might Have Vulvar Heart Disease")
elif x in hasym:
print("You Might Have Heart Arrhythmia ")
elif x in mhasym:
print("You Might Have Minor Heart Attack")
elif x in jsym:
print("You Might Have Jaundice")
elif x in cpsym:
print("You Might Have Chickenpox")
elif x in msym:
print("You Might Have Measles")
elif x in dsym:
print("You Might Have Dengue")
elif x in masym:
print("You Might Have Malaria")
elif x in tcsym:
print("You Might Have Tuberculosis")
elif x in disym:
print("You Might Have Diabetes")
elif x in pnsym:
print("You Might Have Pneumonia")
elif x in htsym:
print("You Might Have Hypertension")
elif x in emsym:
print("You Might Have Emphysema")
elif x in cysym:
print("You Might Have Cyanosis")
elif x in hysym:
print("You Might Have Hay Fever")
elif x in ansym:
print("You Might Have Anoxia")
elif x in hcsym:
print("You Might Have Hypercapnia")
elif x in bcsym:
print("You Might Have Bronchitis")
elif x in asym:
print("You Might Have Asthama")
else:
print("Not Registered")
As the response for each case is the same sentence with just the disease name changing, why not use a dict where the key is the disease name and the value is the list of symptoms.
A bigger challenge here might be that many of the symptoms include spaces, so any split of the full input string is going to prevent you from finding matches. For example, if the user enters shortness of breath, then x is going to contain ['shortness', 'of', 'breath']
There are two possible work arounds for this:
Ask the user to input one symptom at a time and put all of the symptoms into a list
Split of the symptom lists to all be single words only, but that's going to get a lot more false positives.
Here's my solution using sets, prompting the user for separate symptoms, and putting all of the disease data into a single constant dictionary.
# Use a set for user symptoms to prevent duplicates, and so we can compare
# against our database easily later.
user_symptoms = set()
print("Enter your symptoms one at a time. Leave the entry blank to stop.")
while True:
# .lower() needs to be OUTSIDE the input() call,
# otherwise it changes the prompt, not the input
x = input("Enter a symptom: ").lower()
if len(x):
user_symptoms.add(x)
else:
break
# Dict of diseases with symptoms as sets.
# We can use sets instead of lists as ordering is not important.
DIAGNOSES = {
"coronary artery disease": {'chest pain', 'body pain', 'falling sick', 'feeling faint', 'shortness of breath'},
"vulvar heart disease": {'swollen ankles', 'fanting', 'shortness of breath'},
"heart arrhythmia": {'racing heartbeat', 'slow heartbeat', 'chest pain', 'anxiety', 'sweating'},
"minor heart attack": {'cold sweat' 'heartburn', 'sudden dizziness', 'discomfort in joints'},
"jaundice": {'itching', 'abdominal pain', 'weight loss', 'yellow eyes', 'yellow nails', 'vomiting'},
"chickenpox": {'rashes on skin', 'fever', 'sore throat', 'brown spots', 'itching'},
"measles": {'fever', 'runny nose', 'sneezing', 'pink eye', 'skin rash', 'diarrhoea'},
"dengue": {'Eye pain', 'fever', 'muscle pain', 'nausea', 'joint pain', 'rash on thigh'},
"malaria": {'pain in muscle', 'pain in abdomin', 'Night sweat', 'shivering', 'fast heart rate', 'mental confusion'},
"tuberculosis": {'chest pain', 'Night sweats', 'shortness of breath', 'blood cough'},
"diabetes": {'increase thirst', 'frequent urination', 'hunger', 'blurred vision', 'slow healing'},
"pneumonia": {'fever', 'chills', 'sharp pain in chest', 'clammy skin'},
"hypertension": {'nose bleeds', 'dizziness', 'morning headaches', 'irregular heart rhythms', 'vision changes', 'buzzing in the ears'},
"emphysema": {'lot of mucus', 'tight chest', 'whistle sound while breathing'},
"cyanosis": {'bluish colour in sikn', ' lips', 'nail beds'},
"hay fever": {'itchy', 'red and watery eyes', 'rod of mouth being itchy', 'runny or blocked nose'},
"anoxia": {'unusual headache', 'memory loss', 'slurred speech', 'forgotten words', 'trouble in walking', 'trouble in moving arms', 'trouble in moving legs'},
"hypercapnia": {'anxiety', 'shortness of breath', 'headache', 'daytime sleep even after sleeping a lot at night', 'daytime sluggishness'},
"bronchitis": {'sleeping difficulty', 'sore throat', 'chest pressure', 'shortness of breath', 'runny nose'},
"asthma": {'wheezing', 'anxiety', 'early awakening', 'shortness of breath at night', 'cough', 'throat irritation'},
}
# Find any possible matches using set.intersection(). Put matches in a list.
matches = []
for dx, dx_symptoms in DIAGNOSES.items():
if user_symptoms.intersection(dx_symptoms):
matches.append(dx)
# Now print all the possible matches.
for match in matches:
print(f"You might have {match}.")
else:
print("No matching symptoms registered.")
Example run:
Enter your symptoms one at a time. Leave the entry blank to stop.
Enter a symptom: chest PAIN
Enter a symptom: anxiety
Enter a symptom: hunger
Enter a symptom: SORE throat
Enter a symptom:
You might have coronary artery disease.
You might have heart arrhythmia.
You might have chickenpox.
You might have tuberculosis.
You might have diabetes.
You might have hypercapnia.
You might have bronchitis.
You might have asthma.
I am trying to create an online shopping cart system in python to understand list better but have come across some struggles.
I am having difficulties with displaying information using a list. I have already created a list where the person writes in the product the code into an empty list as shown below.
else:
code_input.append(i)
quan_input.append(s)
code_inputed.append(code_input)
quan_inputed.append(quan_input)
I want to use the list with the product codes to find the correlating name and price by using trying to use the code_input list as an index to find the items in the other list.
I have written the simple code to try to find if it works but it comes up with TypeError: list indices must be integers or slices, not list
The code
def display():
index = code_inputed
for i in code_inputed: # and index in range(len(productList)):
print(index)
print(productList[index], quan_inputed[index])
Any help would be greatly appreciated and I'm sorry if none of this makes any sense I am only new.
Thank you
It is a bit unclear what you want, but do you perhaps mean:
def display():
index = code_inputed
for i in code_inputed: # and index in range(len(productList)):
print(i) #CHANGED TO i!
print(productList[i], quan_inputed[i])
Incorporate this code based on your needs. But you get the idea on how to do that. I made list of dicts using 3 lists you provided (productList, priceList, code_of_product) And everything else is just straight forward :)
productList = ["Salad Server Set", "Party Serviette Holder", "Tea Set", "Mixing Bowl Set", "Knife Block Set",
"Coffee Capsule Holder", "Plastic Sensor Soap Pump", "Storage Bucket", "Oven Glove", "Apron",
"Biscuit Barrel", "Chopping Board", "Carioca Cups", "Soup Bowls", "Elevate Wood Turner",
"Pasta Machine", "Teapot", "Cake Pop Scoop", "Cookbook Stand", "Chocolate Station", "Coffee Maker",
"Pepper Mill", "Salt Mill", "Glass Storage Jar", "Measuring jug", "Kitchen Scale", "Tenderiser",
"Pizza Docker", "Knife Sharpener", "Steel Cork Opener", "Steel Garlic Press", "Steel Can Opener",
"Stainless Steel Crank Flour Sifter", "Mineral Stone Mortar and Pestle", "Citrus Cather",
"Cherry & Olive Pitter", "Multi Grater-Detachable", "Stainless Steel Colander", "Steel Pizza Pan",
"Pop Container"]
priceList = [18.70, 11.95, 39.95, 49.95, 99.95, 29.95, 79.95, 24.95, 9.95, 29.95, 39.95, 12.95, 54.95,
43.00, 19.95, 144.95, 29.95, 9.95, 29.95, 34.95, 29.00, 84.94, 84.95, 4.95, 19.95, 39.95, 34.95,
19.95, 79.95, 36.95, 34.95, 36.95, 33.95, 74.95, 19.95, 27.95, 26.95, 44.95, 12.95, 22.95];
code_of_product = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,
38,39]
# Generate a list of dicts from 3 lists productList, priceList, code_of_product
products = [ {'product_name': productList[i], 'price': priceList[i], 'code': code_of_product[i] } for i in range(len(productList)) ]
def catalogue():
global productList, priceList, code_of_product
print('{:<12}\t{:<40}{:<20}'.format("code", "product", "Price $"))
print('{:<12}\t{:<40}{:<20}'.format("----", "------------------------------------", "-------"))
for prod in range(len(products)):
print('{:<12}\t{:<40}{:<20}'.format(products[prod]["code"], products[prod]["product_name"], products[prod]["price"]))
catalogue()
code = int(input("Please input code?"))
quantity = int(input("Please input quntity?"))
def showRecord(cd, qty):
price = products[cd]["price"]
total = float(price)*float(qty)
print(f"Product name: {products[cd]['product_name']}")
print(f"Price: ${price}")
print(f"Total: {total}")
showRecord(code, quantity)
I am trying to write a function that, given a dictionary of restaurants, allows you to randomly pick a restaurant based on your choice of one of the values. For example, if you say you want a bakery then it will only give you bakeries.
I have only worked on the code for choosing the type of restaurant so far, and I am struggling with how to generate a random list. So I am checking for a value and, if it has it, would want to add the key to a list. Does anyone have any suggestions on how to do this?
import random
Restaurants ={
"Eureka": ["American", "$$", "Lunch", "Dinner"],
"Le_Pain": ["Bakery", "$$", "Breakfast", "Lunch", "Dinner"],
"Creme_Bakery": ["Bakery", "$", "Snack"]
}
list=[]
def simple_chooser():
print('Would you like to lock a category or randomize? (randomize, type, price, or meal)')
start= input()
if start=="randomize":
return #completely random
elif start=="type":
print("American, Bakery, Pie, Ice_Cream, Bagels, Asian, Chocolate, Italian, Pizza, Thai, Mexican, Japanese, Acai, Mediterranean, or Boba/Coffee?")
type=input()
for lst in Restaurants.values():
for x in lst:
if x==type:
list.append(x)
return(random.choice(list))
To return completely random restaurant suggestions you need to create a list of all the types first and then you can choose one and return the names of the restaurants.
import random
Restaurants ={
"Eureka": ["American", "$$", "Lunch", "Dinner"],
"Le_Pain": ["Bakery", "$$", "Breakfast", "Lunch", "Dinner"],
"Creme_Bakery": ["Bakery", "$", "Snack"]
}
types = ['American', 'Bakery', 'Pie', 'Ice_Cream', 'Bagels', 'Asian', 'Chocolate', 'Italian',
'Pizza', 'Thai', 'Mexican', 'Japanese', 'Acai', 'Mediterranean','Boba/Coffee']
def simple_chooser():
l=[]
print('Would you like to lock a category or randomize? (randomize, type, price, or meal)')
start= input()
if start=="randomize":
type_random = random.choice(types)
for k,v in Restaurants.items():
if v[0] == type_random:
l.append(k)
elif start=="type":
print("American, Bakery, Pie, Ice_Cream, Bagels, Asian, Chocolate, Italian, Pizza, Thai, Mexican, Japanese, Acai, Mediterranean, or Boba/Coffee?")
type_chosen=input()
for k,v in Restaurants.items():
if v[0] == type_chosen:
l.append(k)
return(random.choice(l))
Also, you don't need to return in if-else statements. Once you have your list of Restaurants you can randomly choose a restaurant and return it.
In your loop, you don't have the restaurant name, as you iterate on the values, you would have need something like
for name, props in Restaurants.items():
if props[0] == type:
list.append(name)
return (random.choice(list)) # wait for the whole list to be constructed
With a better naming (don't use type and list that are builtin methods)
def simple_chooser():
start = input('Would you like to lock a category or randomize? (randomize, type, price, or meal)')
if start == "randomize":
return # completely random
elif start == "type":
restaurant_type = input("American, Bakery, Pie, Ice_Cream, Bagels, Asian, Chocolate, Italian, "
"Pizza, Thai, Mexican, Japanese, Acai, Mediterranean, or Boba/Coffee?")
matching_names = [name for name, props in Restaurants.items() if props[0] == restaurant_type]
return random.choice(matching_names)
You make processing difficult because of the design of your data structures.
Here's an idea which should be easily adapted to future needs.
import random
from operator import contains, eq
Restaurants = [
{'name': 'Eureka', 'type': 'American', 'price': '$$', 'meal': ('Dinner',)},
{'name': 'Le_Pain', 'type': 'Bakery', 'price': '$$', 'meal': ('Lunch', 'Dinner')},
{'name': 'Creme_Bakery', 'type': 'Bakery', 'price': '$', 'meal': ('Snack',)}
]
def get_attr(k):
s = set()
for r in Restaurants:
if isinstance(r[k], tuple):
for t in r[k]:
s.add(t)
else:
s.add(r[k])
return s
def choose_restaurant():
categories = ', '.join(Restaurants[0])
while True:
choice = input(f'Select by category ({categories}) or choose random: ')
if choice == 'random':
return random.choice(Restaurants)
if choice in Restaurants[0]:
choices = get_attr(choice)
if (v := input(f'Select value for {choice} from ({", ".join(choices)}): ')) in choices:
op = contains if isinstance(Restaurants[0][choice], tuple) else eq
return [r for r in Restaurants if op(r[choice], v)]
print('Invalid selection\x07')
print(choose_restaurant())
Restaurants is now a list of dictionaries which is easy to extend. You just need to make sure that each new restaurant has the same structure (keys). Also note that the 'meal' value is a tuple even if there's a single value
I am learning python so this question may be a simple question, I am creating a list of cars and their details in a list as bellow:
car_specs = [("1. Ford Fiesta - Studio", ["3", "54mpg", "Manual", "£9,995"]),
("2. Ford Focous - Studio", ["5", "48mpg", "Manual", "£17,295"]),
("3. Vauxhall Corsa STING", ["3", "53mpg", "Manual", "£8,995"]),
("4. VW Golf - S", ["5", "88mpg", "Manual", "£17,175"])
]
I have then created a part for adding another car as follows:
new_name = input("What is the name of the new car?")
new_doors = input("How many doors does it have?")
new_efficency = input("What is the fuel efficency of the new car?")
new_gearbox = input("What type of gearbox?")
new_price = input("How much does the new car cost?")
car_specs.insert(len(car_specs), (new_name[new_doors, new_efficency, new_gearbox, new_price]))
It isnt working though and comes up with this error:
Would you like to add a new car?(Y/N)Y
What is the name of the new car?test
How many doors does it have?123456
What is the fuel efficency of the new car?23456
What type of gearbox?234567
How much does the new car cost?234567
Traceback (most recent call last):
File "/Users/JagoStrong-Wright/Documents/School Work/Computer Science/car list.py", line 35, in <module>
car_specs.insert(len(car_specs), (new_name[new_doors, new_efficency, new_gearbox, new_price]))
TypeError: string indices must be integers
>>>
Anyones help would be greatly appreciated, thanks.
Just append the tuple to the list making sure to separate new_name from the list with a ,:
new_name = input("What is the name of the new car?")
new_doors = input("How many doors does it have?")
new_efficency = input("What is the fuel efficency of the new car?")
new_gearbox = input("What type of gearbox?")
new_price = input("How much does the new car cost?")
car_specs.append(("{}. {}".format(len(car_specs) + 1,new_name),[new_doors, new_efficency, new_gearbox, new_price]))
I would use a dict to store the data instead:
car_specs = {'2. Ford Focous - Studio': ['5', '48mpg', 'Manual', '\xc2\xa317,295'], '1. Ford Fiesta - Studio': ['3', '54mpg', 'Manual', '\xc2\xa39,995'], '3. Vauxhall Corsa STING': ['3', '53mpg', 'Manual', '\xc2\xa38,995'], '4. VW Golf - S': ['5', '88mpg', 'Manual', '\xc2\xa317,175']}
Then add new cars using:
car_specs["{}. {}".format(len(car_specs)+1,new_name)] = [new_doors, new_efficency, new_gearbox, new_price]
You are not setting the first element go your tuple correctly. You are appending the name to the length of car specs as you expect.
Also new_name is as string, when you do new_name[x] your asking python for the x+1th character in that string.
new_name = input("What is the name of the new car?")
new_doors = input("How many doors does it have?")
new_efficency = input("What is the fuel efficency of the new car?")
new_gearbox = input("What type of gearbox?")
new_price = input("How much does the new car cost?")
car_specs.insert(str(len(car_specs + 1))+'. - ' + name, [new_doors, new_efficency, new_gearbox, new_price])