I am trying to improve my run time of my python code.
The code should inputs as the following:
3
5 1
6 1
8 2
4
7
1
7
3
The first number (3) represents the number of following box sizes as well as how many are on hand for each size
The next number (4) tells us the size of each order. We are not allowed to use a box to pack a specific item, if a smaller box can be used or ordered instead and the box has to strictly be bigger than the product.
The code should return:
5 1
I have working code to do this. It is attached. However I want to speed up my run time using binary search and I was wondering if anyone could help me with this as I am running into errors.
def amount_of_boxes_to_order(boxes, orders, orders_to_place):
for order in orders:
for box in orders_to_place:
if box[0] > order:
box[1] += 1
break
final_return = []
for i in range(len(orders_to_place)):
if orders_to_place[i][0] == boxes[i][0]:
diff = orders_to_place[i][1] - boxes[i][1]
if diff > 0:
new_tuple = [orders_to_place[i][0], diff]
final_return.append(new_tuple)
for answer in final_return:
print(str(answer[0]) + ' ' + str(answer[1]))
n = input()
boxes_input = []
orders_to_place_input = []
for q in range(int(n)):
user_input = [int(x) for x in input().split()]
boxes_input.append(user_input)
orders_to_place_input.append([user_input[0], 0])
orders_input = []
x = input()
for p in range(int(x)):
input_from_user = [int(x) for x in input().split()]
orders_input.append(input_from_user[0])
amount_of_boxes_to_order(boxes_input, orders_input, orders_to_place_input)
Any help is greatly appreciated!
Related
I made this program trying to solve a problem which is fliping a number. For example, when the number 123 is the number inputed the number 321 should be the output.
#function to swap number positions on the array
def swapPositions(list, pos1, pos2):
i = list[pos1]
list[pos1] = list[pos2]
list[pos2] = i
myList = []
theNum = int(input("enter the value"))
theNumInString = str(theNum)
#loop to separate numbers on the integer into each position of the array
for char in theNum2:
myList.append(char)
#this variable is to know how many times we should swap the positions
numofSwaps = len(myList) % 2
posi1 = 0
posi2 = len(myList) - 1
while numofSwaps != 0:
swapPositions(myList, posi1, posi2)
#I add one and subtract one from the positions so they move further to the middle to swap other positions
posi1 += 1
posi2 -= 1
numofSwaps -= 1
number = "".join(myList)
print(number)
what happens when I run the code and try for example 123 it returns 321 as expected
BUT here comes the problem... when I input 12345 the output is 52341 which only swaps the outer two numbers.
this can be done without converting the number to a string, for example
# note: this example works for positive numbers only
def reverseNum(x):
y = 0
while x > 0:
y = y*10 + x%10
x //= 10
return y
>>> reverseNum(3124)
4213
I have been trying to write code for the activity selection problem. I am not using the greedy algorithm method but I just wrote this code on my own. My cod is able to find the max number of activities possible, but in my code, I am having a problem with the input. Here's my code:
i = int(input("How many activities are there? Please enter as an integer. "))
list_of_lists = [[[]], [], []]
def check(space):
x = space.split(" ")
for b in range(2):
x[b] = int(x[b])
if (x[0] >= x[1]):
space = input("Incorrect start and end times. Please enter a start time which is less than the end time. ")
check(space)
return space
return space
#ab = space
#return ab
for a in range(1, i + 1):
arr = input("Please enter the start time and end time. There should be a space between the two integers. ")
abc = check(arr)
print(abc)
list_of_lists[a].append(list(map(int, abc.split(' '))))
list_of_lists[0].append(list(map(int, abc.split(' '))))
print(list_of_lists)
count = [0] * i
inn = 0
for ii in range(1, i + 1):
for jj in range(1, i + 1):
if (ii != jj):
if (list_of_lists[ii][0][0] <= list_of_lists[0][jj][0]):
a = list_of_lists[ii][0][1]
b = list_of_lists[0][jj][0]
else:
a = list_of_lists[0][jj][1]
b = list_of_lists[ii][0][0]
if (a <= b):
count[inn] += 1
else:
count[inn] += 1
inn += 1
count.sort()
print(count[i - 1])
So there is a problem with the check function. It is working perfectly when I have the correct type of input. But say, if someone inputs the wrong type of input, then there is a problem. Let me describe with an example.
If I input 2 4 to arr = ..., then it is working properly. If I input 6 5 to arr = ... and then if I input 2 4 to space = input(..., it is working properly. However, if say I input 6 5 to arr = ..., then I input 5 4 to space = input(..., and then I input 2 4 to space = input(..., then it is not working properly. check function is returning 5 4. I know the problem is with the return but I really do not know how to solve this issue so that it works in the right way.
I have this task I need to complete:
"There are N athletes competing in a hammer throw. Each of them made M
throws. The athlete with the highest best throw wins. If there are
several of them, then the one with the best sum of results for all
attempts wins. If there are several of them, the athlete with the
minimum number is considered the winner. Determine the number of the winner of the competition."
I can find highest best throw wins, but I can't find the athlete with the minimum number.
Sample Input:
4 3
4 2 7
1 2 7
1 3 5
4 1 6
Sample Output:
1
My code so far:
row,columns = map(int,input().split())
matrix = [[int(i) for i in input().split()] for j in range(row)]
numbers = []
suma = []
for i in range(row):
numbers.append(matrix[i][0])
sumaa = sum(matrix[i]) - matrix[i][0]
suma.append(sumaa)
new_matrix = [numbers,suma]
print(new_matrix.index(max(new_matrix)))
input = """4 3
4 2 7
1 2 7
1 3 5
4 1 6
"""
def winner(input):
athletes = input.split("\n")
best_throw = max(" ".join(athletes).split(" "))
best_total = max(map(lambda s: sum(list(map(lambda n: int(n) if n != '' else 0, s.split(" ")))), athletes))
best_athletes_indexes = []
for i, athlete in enumerate(athletes):
if best_throw in athlete.split(" ") and sum(map(int, athlete.split(" "))) == best_total:
best_athletes_indexes.append(i)
best_athletes_attempts = list(map(lambda i: len(athletes[i].split(" ")), best_athletes_indexes))
return best_athletes_indexes[best_athletes_attempts.index(min(best_athletes_attempts))]
print(winner(input))
please please please do not ask me to explain this this is the first python i hav written in 2 years. i come from a world of type safety wth
my search history is literally "remove item from list python" the python standard library is strange
It's answer
a = []
b = []
row, columns = map(int, input().split())
for i in range(row):
a.append(list(map(int, input().split())))
for i in range(row):
b.append([max(a[i]), sum(a[i])])
print(b.index(max(b)))
Try this code:
row, columns = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(row)]
matrix_max_sum_elms = [[max(row), sum(row)] for row in matrix]
best_athlete_ind = matrix_max_sum_elms.index(max(matrix_max_sum_elms)) + 1
print(best_athlete_ind)
Explanation:
First, we create a list of lists with an input value,
then we create a new list of lists, in which each list contains the maximum value and the sum of the elements of the input values. As a result, we take the index of the list that contains the maximum value and add 1, since indexing starts from 0
Now I'm using while loops to try and do this because I'm not too good at using for loops. As the title reads, I'm trying to print out a table which has the line number next to the length of each line.
Error: When I hit run all I get is the above print out (line and number of words with dashes below). I do not get a series of printouts of y and z
Note: I'm probably making this way harder than it needs to be
Code:
list1 = ['Lets go outside','pizza time','show me the money']
list2 = []
print('line number of words')
print('---- ---------------')
x = 0
len_l1 = len(list1)
while len_l1 > 0:
split_lis1 = list1[0+x].split(' ')
list2.append(split_lis1)
len_l1 -= 1
x += 1
while len_l1 > 0:
q = 1
y = len(list1) - len(list1) + q(x)
z = len(list2[0+x])
print(y, z)
len_l1 -= 1
x += 1
what I want the print out to look like:
line number of words
---- ---------------
0 3
1 2
2 4
Thanks.
Yes, you might have overcomplicated the solution as there are out of the box Python methods that help you easily solve problems like this. For iteration with indexes, use enumerate, in the example below we set the index to start at 1. We can also use some simple string formatting defined in fmt to ensure consistent spacings.
li = ['Lets go outside','pizza time','show me the money']
print('line number of words')
print('---- ---------------')
fmt = ('{} {}')
for idx, sentence in enumerate(li,1):
no_of_words = len(sentence.split())
print(fmt.format(idx, no_of_words))
Then simple use split to split the whitespaces and get the total number of words and let enumerate manage the whole thing for you.
>>
line number of words
---- ---------------
1 3
2 2
3 4
list1 = ['Lets go outside','pizza time','show me the money']
print('line number of words')
print('---- ---------------')
for i in range(0, len(list1)):
length = len(list1[i].split(" "))
print(i + 1, " ", length)
Check out python docs for range and for details.
I'm currently trying to do some of the Project Euler questions. I'm currently on question 8 and I'm using python to solve it.
I made some code and got an answer, which turns out to be incorrect. I'm not sure what the problem is with my code, so I'd be grateful is someone could tell me what the issue is. I'm getting an answer of 56435097600, which is the 13 numbers multiplied together on the 30th column with an offset of 6, so it starts 7894... Here's my code, it's not very efficient or neat, but I just want to know what the issue is, not change my code to make it neater/more effective.
rows = ['73167176531330624919225119674426574742355349194934','96983520312774506326239578318016984801869478851843','85861560789112949495459501737958331952853208805511',
'12540698747158523863050715693290963295227443043557','66896648950445244523161731856403098711121722383113','62229893423380308135336276614282806444486645238749',
'30358907296290491560440772390713810515859307960866','70172427121883998797908792274921901699720888093776','65727333001053367881220235421809751254540594752243',
'52584907711670556013604839586446706324415722155397','53697817977846174064955149290862569321978468622482','83972241375657056057490261407972968652414535100474',
'82166370484403199890008895243450658541227588666881','16427171479924442928230863465674813919123162824586','17866458359124566529476545682848912883142607690042',
'24219022671055626321111109370544217506941658960408','07198403850962455444362981230987879927244284909188','84580156166097919133875499200524063689912560717606',
'05886116467109405077541002256983155200055935729725','71636269561882670428252483600823257530420752963450',]
columns = []
def createcolumns():
global rows,columns
for x in range(0,50):
tempvalue = ''
for j in range(0,20):
tempvalue = tempvalue + rows[j][x]
columns.append(tempvalue)
def multiply(string):
tempvalue = 1
for letters in string:
tempvalue *= int(letters)
return tempvalue
def highestnumber():
global rows,columns
highest = 0
# 37 ways per row * 20 + 7 ways per column * 50
for x in range(0,20):
for g in range(0,37):
tempvalue = ''
for j in range(0,13):
tempvalue = tempvalue + rows[x][j+g]
tempvalue = multiply(tempvalue)
if(tempvalue > highest):
highest = tempvalue
for x in range(0,50):
for g in range(0,7):
tempvalue = ''
for j in range(0,13):
tempvalue = tempvalue + columns[x][j+g]
tempvalue = multiply(tempvalue)
if(tempvalue > highest):
highest = tempvalue
return highest
createcolumns()
print(highestnumber())
Output:
>> 56435097600
Well, the purpose is to solve this yourself.
However, I would like to point out the flaw in your understanding of this question and you can pick up from there.
The question talks about a "1000 digit" number.
That means, all the 20 rows of 50 digits need to be merged into 1 single number of 1000 digits.
It's been given in a matrix form just for good visibility.
So approaching this problem with rows X columns may not help.
Your logic would work well for the 4 digit number since it is all in 1 row.
And since your logic's failing for a 13 digit number, my guess is that the 13 digits do not fall in 1 single row.
If I'm not wrong.