For example, if your niece is turning 4 years old, and the cake will have 4 candles of height 4, 4, 1, 3, she will be able to blow out 2 candles successfully, since the tallest candles are of height 4 and there are such
2 candles.
Sample Input
4
3 2 1 3
Sample Output
2
Here's my code
def birthdayCakeCandles(ar):
candle = []
for i in ar:
if ar[i] == max(ar):
candle.append(ar[i])
print(len(candle))
In Pycharm, there's something trouble in """if[i] == max(ar)"""
It says index error but I don't know why it causes index error..
You are confusing two concepts on how to iterate through a list.
Also we don't need a list, we just need a variable candles which keeps count of number of valid candles
The first way is to pick each element in the list and use it, we do it by doing for elem in list, where elem=4,4,1..
def birthdayCakeCandles(ar):
candles = 0
#Maximum value in array
max_arr = max(ar)
#a in an element in ar
for a in ar:
if a == max_arr:
candles+=1
print(candles)
The second method is to get the indexes of the list and use those indexes to iterate, i.e. for i in range(len(ar)) where i=0,1,2... etc.
def birthdayCakeCandles(ar):
candles = 0
max_arr = max(ar)
#i is the index in ar
for i in range(len(ar)):
if ar[i] == max_arr:
candles+=1
print(candles)
In both cases, the output is 2
Related
names = ["jeremy","johnathon"]
average = 4
def longestNames(names,average):
newlist = []
for i in names:
if len(names) > average:
return newlist.append(len(names))
z = longestNames(names,average)
print(z)
Ive been trying to figure this out but I either get an error or none. I basically want to place all names longer than average the new list.
There is no error. the code returns None because both jack and john has a length smaller than average
Edit :
Use this code:
names = ["veryyyyyyyy","sml"]
average = 4
def longestNames(names,average):
newlist = []
for i in names:
if len(i) > average:
newlist.append(i)
return newlist
z = longestNames(names,average)
print(z)
Note list.append() returns None. You have to return the list itself
The names that you have already selected have the length equal to 4, but you are checking the average bigger than 4. Thus, the returned value would be none. It is better to try other names with the length of 5 or bigger or change the initial average to less than 4.
I am doing an online code challenge. I have an array which I need to sort and record to minimum number of iterations required to be sorted. I have the following code.
def minSwap(ar):
c = 0
for i in range(0, len(ar)):
if ar[i] == i+1:
continue
else:
for k in range(i+1, len(ar)):
if ar[k] == i+1:
ar[k] = ar[i]
ar[i] = i+1
c = c+1
break
return c
This code passes majority of test cases, however for really huge number of case such as where array size is beyond (let's say 50000) it gets timeout.
How can I identify the faulty block of code? I can't see a way to tweak it further.
Looking at the problem statement, it looks like you want to sort a list that has numbers starting from 1 thru n.
If you are trying to sort the list, and the final list is expected to be [1, 2, 3, 4, 5, 6, 7 , 8, .....], then all you need to do is to insert the i+1 to the current position and pop the value of i+1 from its current position. That will reduce the number of iterations you need to sort or swap.
Here's the code that does this with least number of moves. At least that's what I found based on my tests.
def minSwap(ar):
c=0
for i in range(0, len(ar)):
if ar[i] != i+1:
#find the value of i+1 from i+1th position
temp = ar.index(i+1,i+1)
ar.insert(i,i+1) #insert i+1 in the ith position
ar.pop(temp+1) #remove the value of i+1 from the right
c+=1 #every time you do a swap, increment the counter
print (ar) #if you want to check if ar is correct, use this print stmt
return c
a = [1,3,4,5,6,7,2,8]
print (minSwap(a))
The total number of swaps for the above example is 1. It just inserts 2 in the second place and pops out 2 from position 6.
I ran the code for a = [1,6,5,4,3,8,2,7] and it swapped in 5 moves.
I ran the code for a = [1,3,5,4,6,8,2,7] and it swapped in 3 moves.
If you are trying to figure out how this works, use a print statement right after the if statement. It will tell you the element being swapped.
From your code I take it that sorting isn't the issue here, since you know you'll end up with ar[i] == i+1. Given that, why not change your else block to swap the current element into its slot, and repeat until you ar[i] is correct.
else:
while ar[i] != i+1:
temp = ar[i]
ar[i] = ar[temp - 1]
ar[temp - 1] = temp
You don't actually need to do a sort on this array. You just need to figure out the minimum number of swaps needed. If we just look at the following pattern, we can form a hypothesis to be tested:
1234 = 0
1324 = 1, swap 2 and 3
1423 = 2, swap 2 and 4, swap 3 and 4
4213 = 2, swap 1 and 4, swap 3 and 4
4123 = 3, swap 4 and 1, swap 4 and 2, swap 4 and 3
Based on these observations, I think we can work on the hypothesis that the answer will be max(0, n - 1) where n is the count of the number of "out of place" elements.
Then the code becomes simplified to:
def minSwap(ar):
c = 0
for i in range(0, len(ar)):
if ar[i] != i+1:
c = c + 1
return c < 0 ? 0 : c
Note that I don't actually know python so don't know if that last ternary is valid in python.
We have unlimited coins of different values - Calculate the unique combinations of how these coins can make up a specific amount. For example:
n = 4 (say, 4 cents)
coins_list = [1,2] - we have 1-cent coins, and 2-cent coins
The different combinations would be 112, 1111, and 22. (121 and 211 should be excluded since it's not unique - using one 2-cent coin and two 1-cent coin)
I have watched this video: https://www.youtube.com/watch?v=k4y5Pr0YVhg
countless number of times, and edited my codes countless number of times, but I cannot manage to get rid of the same combination of different orders.
def make_change(n, coinlist_index=None):
coin_list = [1, 2]
if coinlist_index == None:
coinlist_index = 0
#coin index position in coin_list; starts at index 0 and cycles through all the coins
if n == 0:
return 1
if n < 0:
return 0
ways = 0
# if I use for i in range(len(coin_list)), it returns an error message saying that index is out of range
for coinlist_index in range(len(coin_list)):
ways += make_change((n - coin_list[coinlist_index]), coinlist_index)
coinlist_index += 1
return ways
make_change(4)
Output: 5
My output was 5 (different ways to make change for 4 cents with 1 and 2-cent coins), instead of 3 (which is what I want).
I'm sure it has to do with the for loop toward the end, but when i change "for coinlist_index in range..." to a different iterator, i, I get an error that says index is out of range.
What is going on, and more importantly, how can I fix it?
EDIT: P.S. This is just a simple example that I'm working through to solve the actual assignment - Which is with 6 types of coins, in cents, (1, 5, 10, 25, 50, 100), and calculate how many ways to make change for 200 dollars. I have seen and tried the dynamic programming method out there, which worked, but we have to use recursion for assignment purposes.
Looks like I got it working. In each recursive pass you want to make sure that you aren't double counting possible ways to make the change. My thought to do this was to make sure that you never go backwards in the coin_list. So for the coin_list [1,2] if we ever use the 2 cent coin we never want the option to use the 1 cent coin afterwards. I made sure it follows this order by changing your for loop a bit:
for i in range(len(coin_list)-coinlist_index):
ways += make_change((n - coin_list[i+coinlist_index-1]), coinlist_index)
In the for loop I subtracted coinlist_index from the upper bound so we don't cycle over all coins once the index reaches 1, then added the index to where you pull from the coin_list, making sure once coinlist_index is 1 or more, we NEVER usecoin_list[0]. This got me to 3 in your sample case, hopefully it works for all cases. Full code:
def make_change(n, coinlist_index=None):
coin_list = [1, 2]
if coinlist_index == None:
coinlist_index = 0
#coin index position in coin_list; starts at index 0 and cycles through all the coins
if n == 0:
return 1
if n < 0:
return 0
ways = 0
# if I use for i in range(len(coin_list)), it returns an error message saying that index is out of range
for i in range(len(coin_list)-coinlist_index):
ways += make_change((n - coin_list[i+coinlist_index-1]), coinlist_index)
coinlist_index += 1
return ways
print(make_change(4))
I feel 5 is actually the correct answer.
1 1 1 1
1 1 2
1 2 1
2 1 1
2 2
Or if you want distinct result, you may store results in the list and remove the duplicate result.
def make_change(n, coinlist_index=0):
coin_list = [1, 2]
if n == 0:
return [[]]
if n < 0:
return []
ways = []
for coinlist_index in range(len(coin_list)):
res = make_change((n - coin_list[coinlist_index]), coinlist_index)
ways += list(map(lambda x : x + [coin_list[coinlist_index]], res))
return ways
def remove_dup(lolist):
res = []
for lst in lolist:
lst.sort()
if lst not in res:
res.append(lst)
return res
print remove_dup(make_change(4))
This is one of the lab questions: I try to create a program that generates a list of N random integers between 0 and 19 and computes the element strictly less than 5, 10, 15 and 20. I want to print all of the 'There are {} elements between x and y' statements.
When I run the program, it only shows the first one, and not the others. How do I correct it?
from random import randint
import sys
while True:
nb_of_elements = input('How many element do you want to generate? ')
try:
nb_of_elements = int(nb_of_elements)
break
except ValueError:
print('Input is not an integer, try again...')
L = [randint(0, 19) for _ in range (nb_of_elements)]
print('The list is :', L)
number = [0] * 4
for i in range (nb_of_elements):
number[L[i] // 5]+=1
for i in range(4):
if number[i] < 5:
print('There are {} elements between 0 and 4'.format (number[i]))
elif 5<= number[i] < 10:
print('There are {} elements between 5 and 9'.format(number[i]))
elif 10<= number[i] < 15:
print('There are {} elements between 10 and 14'.format(number[i]))
else:
print('There are {} elements between 15 and 20'.format(number[i]))
Your mistake is that you're attempting to count numbers in a range twice.
First, you use the trick with integer division:
for i in range (nb_of_elements):
number[L[i] // 5]+=1
So, number already contains the count of elements in the ranges 0--4, 5--9, 10--14 and 15--19 (inclusive).
Then, in your if-elif-elif-else block, you look at the value of number, whether it fits in any of these ranges. number, however, contains counts. On average, it will contain about nb_of_elements / 5 counts for each element.
You don't need the if-elif-elif-else block. Instead, loop through range(4) as you do know, and print each element number[i]. Each time, it'll correspond to the next range (you may need some smart thing to print the range. 5*i and 5*i+4 may do that).
It's kind-of interesting that you came up with a smart way to count the numbers in a range (number[L[i]//5] += 1), and then fell back to standard range comparison in an if-elif-else chain. I guess one can outsmart oneself.
You already have found a smart way to count fill the nb_of_elements list. Now you may want a smart way to print it. You can use enumerate to get the current index in the for loop: with this index, you can create the 'between X and Y' variables.
counts = [0] * 4
for i in range (nb_of_elements):
counts[L[i] // 5]+=1
# Loop the counts, and keep track of the index for enumerate
for i,count in enumerate(counts):
# i * 5 will be [0,5,10,15] and i * 5 + 5 will be [5,10,15,20]
print('There are {} elements between {} and {}'.format (count, i*5, i*5 + 5))
#The list is : [7, 10, 5]
#There are 0 elements between 0 and 5
#There are 2 elements between 5 and 10
#There are 1 elements between 10 and 15
#There are 0 elements between 15 and 20
In Python, a range is exclusive, meaning 'between 0 and 5' is [0,1,2,3,4]. I have chosen this notation for the print function as well: it now states 'between 0 and 5' (exclusive) instead of 'between 0 and 4' (inclusive) like you used in your code. This can of course be easily changed: i*5 + 5 > i*5 + 4.
So I have a matrix like:
1 2 3 4
0 3 4 1
7 3 4 5
And I want to select a row,then use this row to do stuff on it such as sorting it with some algorithms;I made this so far:
def row_management(matrix):
theline = input('wich line?') #enter row number
thelist = [matrix[theline]] #go take the right row of the matrix
menu_thelist(thelist) #supossed to use the row and take it to the list management menu
However, when I run this, it always return an error "[matrix[theline]] TypeError: list indices must be integers, not str" and I don't get it.
The input call returns a str type, so it can not be used directly as index to the list inmatrix[theline], which is also what the error message says. Instead do:
matrix[int(theline)]
Needed to convert to int
theline = int(input('wich line?'))
And also
thelist = matrix[theline]
the have [1,2,3] and not [[1,2,3]](wich cause further problem)