There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.
Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.
Example 1:
Input: rooms = [[1],[2],[3],[]]
Output: true
Explanation:
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.
Example 2:
Input: rooms = [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
hkey=[]
count=0
status=[False for i in range(len(rooms))]
for i in rooms:
for j in i:
status[j]=True
for i in range(len(status)):
if status[i]==True:
count+=1i
if count==len(status)-1:
return True
else:
return False
Initially, it passes the basic test cases but only few test cases are being handled by this....what else could be done inorder to make it perfect?
Store an integer for the number of rooms total, an integer for number of rooms visited, iterate the entire thing and if your visited is smaller than total return false.
Related
I have just started learning python and i have been given an assignment to create a list of players and stats using different loops.
I cant work out how to create a function that searches the player list and gives an output of the players name and the players stat.
Here is the assignment:
Create an empty list called players
Use two input() statements inside a for loop to collect the name
and performance of each player (the name will be in the form of a
string and the performance as an integer from 0 – 100.) Add both
pieces of information to the list (so in the first iteration of the
loop players[0] will contain the name of the first player and
players[1] will contain their performance.) You are not required to
validate this data.
Use a while loop to display all the player information in the
following form:
Player : Performance
Use a loop type of your choice to copy the performance values from
the players list and store these items in a new list called results
Write a function that accepts the values “max” or “min” and
returns the maximum or minimum values from the results list
Write a function called find_player() that accepts a player name
and displays their name and performance from the players list, or an
error message if the player is not found.
Here is what I have so far:
print ("Enter 11 Player names and stats")
# Create player list
playerlist = []
# Create results list
results = []
# for loop setting amount of players and collecting input/appending list
for i in range(11):
player = (input("Player name: "))
playerlist.append(player)
stats = int(input("Player stats: "))
playerlist.append(stats)
# While loop printing player list
whileLoop = True
while whileLoop == True:
print (playerlist)
break
# for loop append results list, [start:stop:step]
for i in range(11):
results.append(playerlist[1::2])
break
# max in a custom function
def getMax(results):
results = (playerlist[1::2])
return max(results)
print ("Max Stat",getMax(results))
# custom function to find player
def find_player(playerlist):
list = playerlist
name = str(input("Search keyword: "))
return (name)
for s in list:
if name in str(s):
return (s)
print (find_player(playerlist))
I have tried many different ways to create the find player function without success.
I think I am having problems because my list consists of strings and integers eg. ['john', 6, 'bill', 8]
I would like it to display the player that was searched for and the stats ['John', 6]
Any help would be greatly appreciated.
PS:
I know there is no need for all these loops but that is what the assignment seems to be asking for.
Thank you
I cut down on the fat and made a "dummy list", but your find_player function seems to work well, once you remove the first return statement! Once you return something, the function just ends.
All it needs is to also display the performance like so:
# Create player list
playerlist = ["a", 1, "b", 2, "c", 3]
# custom function to find player
def find_player(playerlist):
name = str(input("Search keyword: "))
searchIndex = 0
for s in playerlist:
try:
if name == str(s):
return ("Player: '%s' with performance %d" % (name, playerlist[searchIndex+1]))
except Exception as e:
print(e)
searchIndex += 1
print (find_player(playerlist))
>>Search keyword: a
>>Player: 'a' with performance 1
I also added a try/except in case something goes wrong.
Also: NEVER USE "LIST" AS A VARIABLE NAME!
Besides, you already have an internal name for it, so why assign it another name. You can just use playerlist inside the function.
Your code didn't work because you typed a key and immediately returned it. In order for the code to work, you must use the key to find the value. In this task, it is in the format of '' key1 ', value1,' key2 ', value2, ...]. In the function, index is a variable that stores the position of the key. And it finds the position of key through loop. It then returns list [index + 1] to return the value corresponding to the key.
playerlist = []
def find_player(playerlist):
list = playerlist
name = str(input("Search keyword: "))
index = 0
for s in list:
if name == str(s):
return ("This keyword's value: %d" % (list[index+1]))
index+=1
print (find_player(playerlist))
My program should get a random name from a list every time a key is pressed, and then delete that name from the list. With the code I have now a random name is selected, but the list is emptied completely.
I have tried both a for and a while loop, but I'm uncertain as what to use in this situation.
x = win.getKey()
while len(members) > 0:
if x:
name = random.choice(members)
members.remove(name)
As mentioned above I want to draw a random name and delete that name from the list every time a key is pressed, until the list is empty.
You'll need to put your key prompt in the loop to cause the loop to pause and wait for input for each element, otherwise the loop will run to completion and instantly empty the entire list.
import random
members = [1,2,3,4,5,6,7,8,9]
while members:
if win.getKey():
choice = random.choice(members)
members.remove(choice)
print(choice)
Output:
8
4
2
3
7
6
9
5
1
If the list is very large, remove is a slow linear operation that needs to inspect each element in the list one by one to find a match. Consider using a fast (amortized) constant time pop operation which uses an index to find the target element without searching:
import random
members = [1,2,3,4,5,6,7,8,9]
while members:
if win.getKey():
choice = members.pop(random.randint(0, len(members) - 1))
print(choice)
I have a problem.
I want to make a shopping list who asking to the user what item does it want and how many.
The list will evolve on each time the loop "reboot" by adding the name of the item (a string) and the number it is associated with (an integer).
The only problem is that when the loop "reboot", the contents of the list is reset.
Here is the code:
def shopping(n):
x=0
while x<n:
item={}
nb={}
shopping_cart={}
item[x]=str(input("item?")) #We asking the user the name of the item he wants.
nb[x]=int(input("nb?")) #We asking the user the number he wants.
shopping_cart[x] = item[x],nb[x]
shopping_cart+=shopping_cart[x] #We try to add what the user has entered to a dictionary to not reset what he has entered before.
x+=1
print(shopping_cart)
shopping(2) #To simplify, in this exemple, we imagine that the customer want to buy two differents items.
But, on the console I have this:
TypeError: unsupported operand type(s) for +=: 'dict' and 'tuple'
I don't find a way to not reset what the customer said before...
Ps: Sorry for my English, I'm French... :)
The below function will return a dictionary of the items the user wants to purchase to the number of each item they want.
def shopping(n):
cart = {}
for _ in range(n):
item = input("What would you like to buy?")
amount = int(input("How many would you like?"))
cart[item] = cart.get(item, 0) + amount
return cart
I am having issues with creating this program I don't know whether I should use elif or something else.
Here is the question: In the cell below, use the try/except control structure to create a program which looks up a price in a dictionary.
shop_prices = {
'eggs': 1.99,
'milk': 0.99,
'ham': 4.99,
}
# take two inputs - what the customer wants, and how many of the items they want
# always greet the customer
# see if they sell the item and calculate the price
# otherwise say "We don't sell XXX", where XXX is the item
# always say goodbye to the customer
This may be what you're looking for. It asks what you want, and if it isn't available, it asks again. After that, it asks you how many of that item you want, and if that input is valid, it prints out the cost and exits.
shop_prices = { 'eggs': 1.99, 'milk': 0.99, 'ham': 4.99, }
request = input("Hello, what would you like?\n")
while request not in shop_prices.keys():
request = input("That item isn't currently available, please choose another item.\n")
while True:
try:
numof = int(input("How many of that item would you like?\n"))
break
except ValueError:
print("That isn't an integer, please enter an integer.\n")
print("That will be $"+str(numof*shop_prices[request])+". Thank you for shopping here today.\n")
add name, where is a string denoting a contact name. This must store as a new contact in the application.
find partial, where is a string denoting a partial name to search the application for. It must count the number of contacts starting with and print the count on a new line.
Given sequential add and find operations, perform each operation in order.
Input:
4
add hack
add hackerrank
find hac
find hak
Sample Output
2
0
We perform the following sequence of operations:
1.Add a contact named hack.
2.Add a contact named hackerrank.
3.Find and print the number of contact names beginning with hac.
There are currently two contact names in the application
and both of them start with hac, so we print 2 on a new line.
4.Find and print the number of contact names beginning with hak.
There are currently two contact names in the application
but neither of them start with hak, so we print 0 on a new line.
i solved it but it is taking long time for large number of string. my code is
addlist =[]
findlist=[]
n = int(input().strip())
for a0 in range(n):
op, contact = input().strip().split(' ')
if(op=='add'):
addlist.append(contact)
else:
findlist.append(contact)
for item in findlist:
count=0
count=[count+1 for item2 in addlist if item in item2 if item==item2[0:len(item)]]
print(sum(count))
is there any other way to avoid the long time to computation.
As far as optimizing goes I broke your code apart a bit for readability and removed a redundant if statement. I'm not sure if its possible to optimize any further.
addlist =[]
findlist=[]
n = int(input().strip())
for a0 in range(n):
op, contact = input().strip().split(' ')
if(op=='add'):
addlist.append(contact)
else:
findlist.append(contact)
for item in findlist:
count = 0
for item2 in addlist:
if item == item2[0:len(item)]:
count += 1
print(count)
I tested 10562 entries at once and it processed instantly so if it lags for you it can be blamed on your processor