I'm trying to translate this pseudocode and can't do it accurately. In particular, I can't seem to figure out what real here means. This is the pseudocode:
Function Real average(Real values[], Integer size)
Declare Real total = 0.0
Declare Integer counter = 0
While counter < size
Set total = total + values[counter]
Set counter = counter + 1
End While
Return total / size
End Function
Declare Real scores[6] = 90, 80, 70, 100, 60, 80
Display average(scores, 6)
And this is what I've come up with:
def average(values[], int(size))
total = 0.0
counter = 0
while counter < size:
total = total + values[counter]
counter = counter + 1
return total / size
scores[6] = 90, 80, 70, 100, 60, 80
print(average(scores, 6))
Some languages use the term "real" in place of "float" etc. Therefore, in Python, with this bit of code you can leave it out.
..but there are a few things wrong with your code other than that. For example you just want
scores=[90,80, 70, 100, 60, 80]
then just give average "scores" and 6
Like this
def average(values ,size):
total = 0.0
counter = 0
while counter < size:
total = total + values[counter]
counter = counter + 1
return total / size
scores = [90, 80, 70, 100, 60, 80]
print(average(scores, 6))
Whilst clearly it is not necessary to do this in this way, I presume you are just learning Python...
Related
This question already has answers here:
Sum of elements of subarrays is equal to a target value in Python
(4 answers)
Closed 1 year ago.
I have the following variables:
arr = [50, 100, 100, 100, 200, 200]
inp = 450
in the inp variable, I receive data from the user, the user can enter any value between the minimum array and the maximum amount of values in the array (50 and 750).
I want to return the values in the array that make up the amount equal to the value in the variable inp
In this situation inp = 450 there are two variants: 50 + 100 + 100 + 200 or 50 + 200 + 200. I'm only interested in one of them.
how can i continue the following code:
import sys
arr = [50, 100, 100, 100, 200, 200]
inp = 450
sum = 0
res = []
for x in arr:
if x == inp:
res = x
print(res)
sys.exit()
sum = sum+x
res.append(x)
if sum == inp:
print(res)
sys.exit()
I can solve the problem if I make six loops, but if the length of the array changes I have to intervene on the source code. I'm looking for a recursive solution.
I would use the itertools.combinations API. You could also use a generator to allow finding all of the values, or choose to stop at the first:
import itertools
def find_comb_for_sum(data, total):
for i in range(len(data)):
for comb in itertools.combinations(data, i + 1):
if sum(comb) == total:
yield comb
This will find all combinations of the array starting from least amount of entries per combination to most. Reverse the range range(len(data))[::-1] if you'd like to do the opposite.
Some test cases:
arr = [50, 100, 100, 100, 200, 200]
inp = 450
comb = find_comb_for_sum(arr, inp)
print(f"Matching combination for {arr} summing to {inp} is: {next(comb, None)}")
arr = [50, 100, 100, 100, 200, 200]
inp = 444
comb = find_comb_for_sum(arr, inp)
print(f"Matching combination for {arr} summing to {inp} is: {next(comb, None)}")
Matching combination for [50, 100, 100, 100, 200, 200] summing to 450 is: (50, 200, 200)
Matching combination for [50, 100, 100, 100, 200, 200] summing to 444 is: None
I have this code here and I'm looking for a way to check if min_score and max_score changes, and count how many times it changes. I can't seem to find a way to do it:
games = int(input())
score = list(input().split())
score = [int(x) for x in score]
for y in range(1, len(score) + 1):
min_score = (str(min(score[:y])) + " MIN")
max_score = (str(max(score[:y])) + " MAX")
print(min_score)
print(max_score)
This is a sample test case for reference:
9
10 5 20 20 4 5 2 25 1
First number is the size of the array, which in my code I never use because I make an array just from the string of numbers below ( in fact I don't even know why they give the size).
Basically I need to find how many times the max and min values change. I'm still a beginner in programming and I don't really know what to do..
you could just keep track of the lowest and highest number encountered and check if the current score is just below or above. A simple script could look like this:
scores = [10,5,20,20,4,5,2,25,1]
countChanges = 0
limitLow = float("inf")
limitHigh = -float("inf")
for s in scores:
if(s < limitLow):
countChanges += 1
limitLow = s
if(s > limitHigh):
countChanges += 1
limitHigh = s
print("current score: %3d limits: [%2d .. %2d] changes:%d" % (s, limitLow, limitHigh, countChanges))
spam = [10, 5, 20, 20, 4, 5, 2, 25, 1]
print(sum(n < min(spam[:idx]) for idx, n in enumerate(spam[1:], start=1)))
print(sum(n > max(spam[:idx]) for idx, n in enumerate(spam[1:], start=1)))
output
4
2
if you also want to account for initial value - add 1.
Looks like a hankerrank problem? They often give the length of the input to allow solutions without knowing about built-in methods like len().
Anyway,
You can initialise min and max to the first element of the array (if it exists, check the specification), or some suitably small and large values (again, check the possible values).
Then you can count the number of times min and max changes as you go.
Should be easy enough to adapt for the case that you just want to track any change, not min and max separately. It wasn't clear from your question.
scores = [10, 5, 20, 20, 4, 5, 2, 25, 1]
min_score = scores[0]
max_score = scores[0]
min_score_changes = 0
max_score_changes = 0
for score in scores:
if score < min_score:
min_score = score
min_score_changes += 1
if score > max_score:
max_score = score
max_score_changes += 1
I solved it like this after some thinking:
games = int(input())
score = list(input().split())
score = [int(x) for x in score]
min_score_list, max_score_list = [] , []
for y in range(1, len(score) + 1):
min_score = (min(score[:y]))
max_score = (max(score[:y]))
if min_score not in min_score_list:
min_score_list.append(min_score)
if max_score not in max_score_list:
max_score_list.append(max_score)
print((len(max_score_list) - 1), len(min_score_list) - 1)
I know it's not perfect code but at least I did myself :D
I need to generate a random number between a min and a max. This number should be a multiple of 10.
This is the solution I have come to.
import random
BLOCK = 10
def random_excluding_values(_min, _max, exclude_list):
while True:
random_number = round(random.randrange(_min, _max - BLOCK) / BLOCK) * BLOCK
if random_number not in exclude_list:
return random_number
There is a way to obtain the same result using list list comprehension or something else?
Lower bound includes multiples of 10 when calculating range.Skipping while loop makkes sure that you will not be stuck in infinite loop. Conversion to sets make sure that you know what you can get .
import random
def random_excluding_values(_min, _max, exclude_list, num_of_elems):
lower_bound = round(_min+4, -1)
all_nums = {num for num in range(lower_bound, _max+1, 10)}
exclude_set = set(exclude_list)
valid_choices = all_nums - exclude_set
return random.sample(valid_choices, num_of_elems)
_min = 9
_max = 103
exclude_list = [40,50,60,70]
#valid_list = [10,20,30,80,90,100]
num_elems = 3
for i in range(5):
print(f'run = {i}; result = {random_excluding_values(_min, _max, exclude_list, num_elems)}')
Outputs:
run = 0; result = [80, 30, 20]
run = 1; result = [10, 20, 80]
run = 2; result = [10, 80, 30]
run = 3; result = [100, 90, 10]
run = 4; result = [10, 20, 100]
random.sample returns a list of choices from valid set of numbers. So you can easily modify to get you single number.
return random.sample(valid_choices, 1)[0]
I have the following code, but when i run it I get type 'NoneType'. I pinpointed to my "summation" variable being the one that has Nonetype, why is that? and how can i change it? I tried making into a float() but it did not work for me. Any insights would be welcome.
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def grades_sum(scores):
total = 0
for item in scores:
total = item + total
print total
grades_sum(grades)
def grade_average(grades):
summation = grades_sum(grades)
average = summation / float(len(grades))
return average
print grade_average(grades)
Change the print to a return.
def grades_sum(scores):
total = 0
for item in scores:
total = item + total
return total
Well summation just calls the function, nothing else, so it is equal to a NoneType or basically nothing. Change print total to return total to allow summation to be equal to whatever total is.
def grades_sum(scores):
total = 0
for item in scores:
total = item + total
return total
When you define grades_sum(), you don't return anything, you just print it. Change it to this:
def grades_sum(scores):
total = 0
for item in scores:
total = item + total
print total
return total
I have a function defined below that prints each integer in the list, and it works perfectly. What I would like to do is create a second function that would call on or reutilize the int_list() function to display a sum of the list that's been generated.
I am not sure if that has been inherently performed by the code itself - I am rather new to the Python syntax.
integer_list = [5, 10, 15, 20, 25, 30, 35, 40, 45]
def int_list(self):
for n in integer_list
index = 0
index += n
print index
In your code, you're setting index=0 in every loop, so it should be initialized before the for loop:
def int_list(grades): #list is passed to the function
summ = 0
for n in grades:
summ += n
print summ
output:
int_list([5, 10, 15, 20, 25, 30, 35, 40, 45])
5
15
30
50
75
105
140
180
225
To get the sum of a list of integers you have a few choices. Obviously the easiest way is sum, but I guess you want to learn how to do it yourself. Another way is to store the sum as you add it up:
def sumlist(alist):
"""Get the sum of a list of numbers."""
total = 0 # start with zero
for val in alist: # iterate over each value in the list
# (ignore the indices – you don't need 'em)
total += val # add val to the running total
return total # when you've exhausted the list, return the grand total
A third option is reduce, which is a function that itself takes a function and applies it to the running total and each consecutive argument.
def add(x,y):
"""Return the sum of x and y. (Actually this does the same thing as int.__add__)"""
print '--> %d + %d =>' % (x,y) # Illustrate what reduce is actually doing.
return x + y
total = reduce(add, [0,2,4,6,8,10,12])
--> 0 + 2 =>
--> 2 + 4 =>
--> 6 + 6 =>
--> 12 + 8 =>
--> 20 + 10 =>
--> 30 + 12 =>
print total
42
integer_list = [5, 10, 15, 20, 25, 30, 35, 40, 45] #this is your list
x=0 #in python count start with 0
for y in integer_list: #use for loop to get count
x+=y #start to count 5 to 45
print (x) #sum of the list
print ((x)/(len(integer_list))) #average
list = [5, 10, 15, 20, 25, 30, 35, 40, 45]
#counter
count = 0
total = 0
for number in list:
count += 1
total += number
#don'n need indent
print(total)
print(count)
# average
average = total / count
print(average)
You can used reduce function from functools module
from functools import module
s=reduce(lambda x,y:x+y, integer_list)
output
225