what I have to do to complete this Dynamic Programming problem? - python-3.x

I have a homework that tells this:
A hawker has to decide what products to take on his next trip. Unfortunately, you have a weight limit that you can carry, and having this in mind, you have to choose the best combination of products with at most this weight that will allow you to have maximum revenue.
You will receive the weight limit that the seller can carry, followed by a list of products from which he can choose (assume you have an unlimited stock of each product at your disposal). For each product will be listed its name, its value, and its weight. You should print the maximum revenue you can get if you sell all the products you choose to carry, followed by the list of products you should take to get that revenue (including replicates, if appropriate), sorted alphabetically. If there are 2 products with the same profitability / weight should give priority to the products that appear first in the entry list.
I am reading the input from a file.
Input:
14
bible 20 2
microwave 150 10
television 200 15
toaster 40 3
Output: 190 bible bible microwave
I have made this code to reach the maximum value the hawker can carry with him:
import sys
def knapsack(list_values,list_weight,limit_weight,n):
matrix = [[0 for x in range(limit_weight+1)] for y in range (n+1)]
res = []
for i in range(n+1):
for j in range(limit_weight+1):
if i == 0 or j == 0:
matrix[i][j] = 0
elif list_weight[i-1]<= j:
matrix[i][j] = max(list_values[i-1] + matrix[i-1][j-list_weight[i-1]], matrix[i-1][j])
else:
matrix[i][j] = matrix[i-1][j]
return matrix[n][limit_weight], matrix
def main():
txt = sys.stdin.readlines()
limit_weight = int(txt[0])
list_names = []
list_values = []
list_weight = []
picked = []
for lines in txt[1:]:
lines = lines.split()
list_weight.append(int(lines[2]))
list_values.append(int(lines[1]))
list_names.append(lines[0])
result, matrix = knapsack(list_values,list_weight, limit_weight, len(list_values))
print(result)
main()
I can not figure out which items are chosen.
Can you help me?

Related

How would I integrate input() within iterative loop?

I'm a beginner at python and wanted to have a crack at my first personal project which is a score calculator for a student's subjects. I wanted to run a for loop that asks the user to input their scores for each of the individual subjects through an input() within a for loop. However, it would only take a singular string argument.
scores = {}
total = 0
years = int(input("How subjects have you completed? "))
for sub in range(0, years):
scores = input("Score for subject?",x)
total += int(scores)
Any help would be great, thanks!
If you wanted to keep track of scores by subject and find total score then...
subjects = dict( Math = 0, English = 0, Science = 0, History = 0 )
scores = dict()
total = 0
for sub in subjects.keys():
score = input( f"Score for {sub}? >" )
if score:
total += int( score )
scores[sub] = score
print( total )
for sub,tot in scores.items():
if tot > 0:
print( sub, tot )
The variable x never defined and used, just remove it may solve your problem.
scores first defined as a dict, then you re-define it without using it.Remove it make code more clear.
code:
total = 0
years = int(input("How subjects have you completed? "))
for sub in range(years):
scores = input("Score for subject?")
total += int(scores)
print(total)
result:
How subjects have you completed? 5
Score for subject?1
Score for subject?2
Score for subject?3
Score for subject?4
Score for subject?5
15
In the code sample:
x is an undefined variable.
scores = {} the 'scores' dictionary is useless as later you redefine it as a string.
Just removing the ,x in line 5 will make the code execute properly.
>>> total = 0
>>> for i in range(int(input("How many subjects have you completed? "))):
... total += int(input("Score for subject? "))
...
How many subjects have you completed? 3
Score for subject? 70
Score for subject? 80
Score for subject? 90
>>> total
240

Python- Reading two n-spaced sequences as a list, subtracting the lists and printing the greatest difference.[CodeChef]

I was working with a problem on CodeChef and I am stuck with one of the sub task being incorrect.
Problem statement:
https://www.codechef.com/AUG19B/problems/MSNSADM1
You are given two sequences. For each valid i, player i scored
Ai
goals and committed
Bi
fouls. For each goal, the player that scored it gets
20
points, and for each foul,
10
points are deducted from the player that committed it. However, if the resulting number of points of some player is negative, this player will be considered to have
0
points instead.
You need to calculate the total number of points gained by each player and tell Alex the maximum of these values.
Input:
The first line of the input contains a single integer
T
denoting the number of test cases. The description of
T
test cases follows.
The first line of each test case contains a single integer
N
.
The second line contains
N
space-separated integers (for no. of goals).
The third line contains
N
space-separated integers (for no. of fouls).
Output:
For each test case, print a single line containing one integer ― the maximum number of points.
Constraints:
1≤T≤100
1≤N≤150
0≤Ai≤50
for each valid
i
0≤Bi≤50
for each valid
i
My approach to this was to create 2 lists and multiply each element of first by 20, second by 10 and then create a list c, which has the difference of each elements.
try:
t= int(input())
while(t != 0):
t -= 1
n = int(input())
a_i = list(map(int, input().split()))
b_i = list(map(int, input().split()))
a = [i * 20 for i in a_i]
b = [i * 10 for i in b_i]
for i in range(0 , len(a)):
if a[i] < 0:
a[i] = 0
for i in range(0 , len(b)):
if b[i] < 0:
b[i] = 0
c = [i - j for i, j in zip(a, b)]
print(max(c))
except:
pass
All the tasks seems to be showing correct answer except one. I can't seem to understand what I am doing wrong here.
With the given indentation you are only printing the last testcase.
You create lots of list's in between that are not needed but take time to create/instantiate etc.
You loop over your data twice to eleminate the negative values - also not needed.
Use generators instead:
try:
for _ in range(int(input())):
n = int(input())
a_i = map(int, input().split()) # dont list(...) this
b_i = map(int, input().split()) # dont list(...) this
# get the max - negatives are irrelevant, they are removed when printing
m = max(goals * 20 - fouls*10 for goals, fouls in zip(a_i,b_i))
# if _all values_ are negative, print 0 else print the max value
# you need to print _each_ testcase, not only the last as your code does
print(max( (m,0) ))
except:
pass
t= int(input())
while(t != 0):
t -= 1
n = int(input())
a_i = list(map(int, input().split()))
b_i = list(map(int, input().split()))
c=[]
a = [i * 20 for i in a_i]
b = [i * 10 for i in b_i]
c =list(map(int.__sub__, a, b))
for line in c:
if line < 0:
line = 0
print(max(c))enter code here

Lazy Sorting HackerRank Python

I am new to coding and so the following code I wrote may be incorrect or sub-optimal. However, the problem I have is that I do not understand the input and thus cannot get the code to run (I only tested it with custom inputs).
The essence of the problem is that you have some sequence of numbers and you want to arrange the sequence monotonically (nondecreasing or nonincreasing). You do this by a random shuffle. How many shuffles does it take for you to get to the monotonic sequence via a random shuffle? You can find the problem here and here is my code below:
#!/bin/python3 ------ The following import is given in the prompt
import os
import sys
# Complete the solve function below. Here is my code below
def solve(P):
P.sort()
correct = P
count = []
i = 0
# Here I am trying to calculate the number of ways to get the desired monotonic sequence
# I count the number of repeated numbers in the sequence as separate items in a list
for j in range(i,len(correct)):
if correct[i] != correct[j] or i == len(correct) - 1:
count.append(j-i)
i = j
j = len(correct)
else:
j = j + 1
summ = 0
for k in range(len(count)):
summ = summ + count[k]
if summ == len(correct):
i = len(correct)
poss = [1]*len(count)
for k in range(len(count)):
for l in range(1,count[k]+1):
poss[k] = poss[k]*l
possible = 1
for x in poss:
possible = possible * x
# This is calculating the number of different permutations of n distinct elements
total = 1
n = len(correct)
for i in range(1,n+1):
total = total * i
# Calculating the probability to the 6th decimal place
probability = float(possible / total)
expected = round(1/probability, 6)
print(expected)
# The following code is given in the prompt to input the test cases
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
P_count = int(input())
P = list(map(int, input().rstrip().split()))
result = solve(P)
fptr.write(str(result) + '\n')
fptr.close()
In my code, I just assumed that P is the sequence of numbers you receive from the input.

Loop only adds the last result to a list

I am trying to run a small casino roulette betting outcome simulator. As a result I want to understand how big of a bank the casino should have in order not to go bankrupt in relation to the players betting size.
Please see code below:
from random import choices
bankroll = 500
bet = 50
lose = -50
population = [bet, lose]
weights = [0.4865, 0.5135]
game_count = 1
winning_game_count = []
bankrupt_game_count = []
for i in range(10000):
while bankroll != 0 and game_count < 5000:
result = int(choices(population, weights)[0])
bankroll -= result
game_count += 1
if game_count > 4999:
winning_game_count.append('won')
elif bankroll == 0:
bankrupt_game_count.append('lost')
print(winning_game_count)
print(bankrupt_game_count)
I am getting the result of the last iteration only, whereas I want to get the total sum of all games (5000 games) and the number of games where bankroll resulted in 0. I am lost.
You only get the result of the last iteration because you only run 1 iteration.
You need to reset the variables that control your loop condition between each iteration:
for i in range(10000):
bankroll=500
game_count = 1
while bankroll != 0 and game_count < 5000:

Validating user input program syntax eror

How does one answer this question.
1. A dramatic society wants to record the number of tickets sold for each of their four performances. Ask the user to enter the number of tickets sold for each performance. The number must be between 0 and 120. Print an error message if an invalid number is entered and ask them to re-enter until they enter a valid number. Print the total number of tickets sold and the average attendance for a performance.
import re
affirm = False
p = 0
total = 0
for p in range(4):
p = input("Please enter the total number of tickets sold for the performance.")
while affirm != True:
try:
int(p)
except ValueError:
print("This is not a number")
else:
valid = re.match("[0-120]",p)
if valid:
total += p
affirm = True
else:
p = input("Please enter the total number of tickets sold for the performance.")
average = (total/480) * 100
average = round(average,2)
print("""
The total number of tickets sold is: """,total"""
The average attendance is : """,average)
My python book didn't really explain the correct syntax for the re module and the try except else function. Can someone point out if there is anything wrong with the code. This was my first go at validating user input.
You cannot use regular expression to see whether a number is between a certain range, and even if you did, it would be silly considering how easy it is to check if a number is between numbers in Python:
valid = 0 < p < 120
Here is your code after the fix:
affirm = False
p = 0
total = 0
for p in range(4):
p = input("Please enter the total number of tickets sold for the performance.")
while affirm != True:
try:
int(p)
except ValueError:
print("This is not a number")
else:
valid = 0 < p < 120
if valid:
total += p
affirm = True
else:
p = input("Please enter the total number of tickets sold for the performance.")
average = (total/480) * 100
average = round(average,2)
print("""
The total number of tickets sold is: """,total"""
The average attendance is : """, average)
More on: Expressions in Python 3

Resources