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
Related
1.7 LAB: Adjust values in a list by normalising
When analysing data sets, such as data for human heights or for human weights, a common step is to adjust the data. This can be done by normalising to values between 0 and 1, or throwing away outliers.
Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Then, adjust each integer in the list by subtracting the smallest value from all the integers.
Ex: If the input is:
5
30
50
10
70
65
the output is:
20
40
0
60
55
The 5 indicates that there are five integers in the list, namely 30, 50, 10, 70, and 65. The smallest value in the list is 10, so the program subtracts 10 from all integers in the list.
Anyone can solve this question in python?
This is my code.
arr1 = []
input = int()
for i in range(0,input):
e = int(intput())
arr1.append(e)
k = min(arr1)
for i in range(0,val):
arr1[i] = arr1[i] - k
for i in range(0,val):
print(arr1[i])
Here is the error.
Traceback (most recent call last):
File "main.py", line 8, in <module>
arr1.append(e)
NameError: name 'e' is not defined
You could use list comprehension:
input = [5,30,50,10,70,65]
input = input[1:]
output = [i - min(input) for i in input]
print(output)
[20, 40, 0, 60, 55]
This is the way I solved it
list = []
values = int(input())
for n in range(values):
number = float(input())
list.append(number)
largest = max(list)
for number in list:
number = number / largest
print(f'{number:.2f}')
def get_minimum_int(nums):
low = min(nums)
return low
if __name__ == '__main__':
num = int(input())
nums = []
while num != -1:
nums.append(num)
num = int(input())
l = get_minimum_int(nums)
for n in nums:
print(n - l)
idk if your question ever got answered but I also had the same type of task.
Mine was:
"For this program, adjust the values by dividing all values by the largest value. The input begins with an integer indicating the number of floating-point values that follow.
Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
print('{:.2f}'.format(your_value))
Ex: If the input is:
5
30.0
50.0
10.0
100.0
65.0
the output is:
0.30
0.50
0.10
1.00
0.65
The 5 indicates that there are five floating-point values in the list, namely 30.0, 50.0, 10.0, 100.0, and 65.0. 100.0 is the largest value in the list, so each value is divided by 100.0."
So this is how I solved mine:
x = int(input())
dislist = []
i = 1
while i <= x:
y = float(input())
dislist.append(y)
i += 1
q = max(dislist)
for item in dislist:
item = item / q
print('{:.2f}'.format(item))
Tell me what you think :)
A few problems I can see with your code.
input = int()`
input in the name of a function that gets an input string from the user. int() simply returns 0. You are assigning the value 0 to a variable named input, making the input function no longer accessible.
for i in range(0,input):
e = int(intput())
Because input is 0, this is an empty range. The loop never runs. Which is good because it would have no idea what intput is.
Because the loop never runs, e is never defined, which is why you get the error you do.
Another style note: arr1 is a list so using a name that suggests it's an array is misleading.
You likely wanted something like the following tweaked version of your code.
n = int(input())
vals = []
for _ in range(0, n):
e = int(input())
vals.append(e)
k = min(vals)
for i in range(0, n):
arr1[i] = -= k
for i in range(0, n):
print(arr1[i])
Gathering the input numbers could be simplified using a list comprehension.
vals = [int(input()) for _ in range(0, n)]
This may be helpful for your lab:
user_int = []
while True:
user_input = int(input())
user_int.append(int(user_input))
if len(user_int) > (int(user_int[0])):
break
user_int.pop(0)
vals = min(user_int)
for user_vals in user_int:
my_vals = user_vals - vals
print(my_vals)
I'm writing a program that writes two lists of five numbers between 0-9. I need the program to compare the lists to find how many numbers the lists have in common, but I'm not sure how.
Edit: I just need the program to write the amount of numbers in common, I don't need the numbers themselves
import random
X = 0
while X<2000:
House_deal = [random.randint(0,9) for House_deal in range(5)]
Player_deal = [random.randint(0,9) for House_deal in range(5)]
print("House numbers: ", House_deal)
print("Player numbers: ", Player_deal)
print(" ")
X += 1
Assuming we have l_one and l_two for two randomly generated lists.
counter = [0] * 10
answer = 0
for x in l_one:
counter[x] += 1
for x in l_two:
if counter[x] > 0:
counter[x] -= 1
answer += 1
print(answer)
This algorithm works in O(n) compared to O(n^2) solutions posted before.
A solution similar to others already posted, but using Counter:
import random
from collections import Counter
for _ in range(2000):
House_deal = [random.randint(0,9) for _ in range(5)]
Player_deal = [random.randint(0,9) for _ in range(5)]
hc = Counter(House_deal)
pc = Counter(Player_deal)
common = hc.keys() & pc.keys() #get the intersection of both keys
counts = 0
for cel in common:
counts += min(hc[cel], pc[cel])
print("House numbers: ", House_deal)
print("Player numbers: ", Player_deal)
print("Common numbers: ", counts)
I also changed the while loop into a for loop.
You could define a function like the ones here and use the len() function to get the number of elements in the list. The functions cast the lists to sets and get the intersections of them, which would be all the elements in common. That way you can also see the elements that are incommon between them if you decide you want to as well, or you can even modify this to subtract one list from the other to get the elements they don't have in common like here. Let me know if this is what you're looking for.
You can use a function as follows:
def compare(list1 , list2):
common_list = []
for i in list1:
if i in list2:
common_list.append(i)
print(len(common_list)) # Number of common elements
Its work:
import random
list_one = random.sample(range(9), 4)
list_two = random.sample(range(9), 4)
print(list_one)
print(list_two)
count = 0
for item_one in list_one:
for item_two in list_two:
if item_one == item_two:
count +=1
print(count)
Ps.: The instruction for item_two in list_two: maybe change by if item_one in list_two:, but as you seem to be a beginner, I put it even more explicitly.
A variant of the previous answer.
counter_1 = {k, 0 : k in l_one}
counter_2 = {k, 0 : k in l_two}
answer = 0
for x in l_one:
counter_1[x] = counter_1[x] + 1
for x in l_two:
counter_2[x] = counter_2[x] + 1
for x, v1 in counter_1.items():
v2 = counter_2.get(x, 0)
answer = answer + min (v1, v2)
print(answer)
You can use the set data type in Python, and do something like
In [1]: from random import randint
In [2]: import random
In [3]: random.seed(123)
In [4]: x = set([randint(0,9) for x in range(5)])
In [5]: y = set([randint(0,9) for x in range(5)])
In [6]: x
Out[6]: {0, 1, 4, 6}
In [7]: y
Out[7]: {0, 1, 6, 8}
In [8]: cnt = len(x & y) # return the amount of numbers in common, e.g. {0, 1, 6}
In [9]: cnt
Out[9]: 3
Hope it helps.
I haven't found anything even relevant to my question, so i may be asking it wrong.
I am working on an exercise where I am given sequential values starting at 1 and going to n, but not in order. I must find a missing value from the list.
My method is to add the full 1 => n value in a for loop but I can't figure out how to add n - 1 non-sequential values each as its own line of input in order to subtract it from the full value to get the missing one.
I have been searching modifications to for loops or just how to add n inputs of non-sequential numbers. If I am simply asking the wrong question, I am happy to do my own research if someone could point me in the right direction.
total = 0
for i in range (1 , (int(input())) + 1):
total += i
print(total)
for s in **?????(int(input()))**:
total -= s
print(total)
sample input:
5
3
2
5
1
expected output: 4
To fill in the approach you're using in your example code:
total = 0
n = int(input("How long is the sequence? "))
for i in range(1, n+1):
total += i
for i in range(1, n):
total -= int(input("Enter value {}: ".format(i)))
print("Missing value is: " + str(total))
That first for loop is unnecessary though. First of all, your loop is equivalent to the sum function:
total = sum(range(1,n+1))
But you can do away with any iteration altogether by using the formula:
total = int(n*(n+1)/2) # division causes float output so you have to convert back to an int
I don't know if you are supposed to create the initial data (with the missing item), so I added some lines to generate this sequence:
import random
n = 12 # or n = int(input('Enter n: ')) to get user input
# create a shuffled numeric sequence with one missing value
data = list(range(1,n+1))
data.remove(random.randrange(1,n+1))
random.shuffle(data)
print(data)
# create the corresponding reference sequence (without missing value)
data2 = list(range(1,n+1))
# find missing data with your algorithm
print("Missing value =", sum(data2)-sum(data))
Here is the output:
[12, 4, 11, 5, 2, 7, 1, 6, 8, 9, 10]
Missing value = 3
I have to create a program that shows the arithmetic mean of a list of variables. There are supposed to be 50 grades.
I'm pretty much stuck. Right now I´ve only got:
for c in range (0,50):
grade = ("What is the grade?")
Also, how could I print the count of grades that are below 50?
Any help is appreciated.
If you don't mind using numpy this is ridiculously easy:
import numpy as np
print np.mean(grades)
Or if you'd rather not import anything,
print float(sum(grades))/len(grades)
To get the number of grades below 50, assuming you have them all in a list, you could do:
grades2 = [x for x in grades if x < 50]
print len(grades2)
Assuming you have a list with all the grades.
avg = sum(gradeList)/len(gradeList)
This is actually faster than numpy.mean().
To find the number of grades less than 50 you can put it in a loop with a conditional statement.
numPoorGrades = 0
for g in grades:
if g < 50:
numPoorGrades += 1
You could also write this a little more compactly using a list comprehension.
numPoorGrades = len([g for g in grades if g < 50])
First of all, assuming grades is a list containing the grades, you would want to iterate over the grades list, and not iterate over range(0,50).
Second, in every iteration you can use a variable to count how many grades you have seen so far, and another variable that sums all the grades so far. Something like that:
num_grades = 0
sum_grades = 0
for grade in grades:
num_grades += 1 # this is the same as writing num_grades = num_grades + 1
sum_grades += sum # same as writing sum_grades = sum_grades + sum
Now all you need to do is to divide sum_grades by num_grades to get the result.
average = float(sum_grade)s / max(num_grades,1)
I used the max function that returns the maximum number between num_grades and 1 - in case the list of grades is empty, num_grades will be 0 and division by 0 is undefined.
I used float to get a fraction.
To count the number of grades lower than 50, you can add another variable num_failed and initialize him to 0 just like num_counts, add an if that check if grade is lower than 50 and if so increase num_failed by 1.
Try the following. Function isNumber tries to convert the input, which is read as a string, to a float, which I believe convers the integer range too and is the floating-point type in Python 3, which is the version I'm using. The try...except block is similar in a way to the try...catch statement found in other programming languages.
#Checks whether the value is a valid number:
def isNumber( value ):
try:
float( value )
return True
except:
return False
#Variables initialization:
numberOfGradesBelow50 = 0
sumOfAllGrades = 0
#Input:
for c in range( 0, 5 ):
currentGradeAsString = input( "What is the grade? " )
while not isNumber( currentGradeAsString ):
currentGradeAsString = input( "Invalid value. What is the grade? " )
currentGradeAsFloat = float( currentGradeAsString )
sumOfAllGrades += currentGradeAsFloat
if currentGradeAsFloat < 50.0:
numberOfGradesBelow50 += 1
#Displays results:
print( "The average is " + str( sumOfAllGrades / 5 ) + "." )
print( "You entered " + str( numberOfGradesBelow50 ) + " grades below 50." )
I'm writing a script that takes a bowling score.
The Rules
-If you get a STRIKE you get 10 points plus the next two balls you score.
My question: Is there a way to add the next two numbers in a list after 10 appears. so far my code just takes the users score and stores it in a list.
def f54():
total_pins= 10
max_score= 300
frames= 20
count= 1
score=0
zval = []
yval = []
for i in range(1,11):
2_ahaed = i+2
1_ahead = i+1
z=int(input('What was your score for ball 1 frame ' +str(i)+':'))
if z != 10:
y=int(input('What was your score for ball 2 frame ' +str(i)+':'))
if z > total_pins:
print('this number is too large, re enter all scores')
f54()
if z < 10:
zval.append(z)
if z == 10:
print('Strike!')
if y > total_pins:
print('this number is too large, re enter all scores')
f54()
if y < 10:
yval.append(y)
if y == 10-z:
print('spare!')
I am not too familiar with bowling scoring rules but this should do what you are asking:
scores = [1,2,10,3,4,5,10,1]
ret = [0 for x in (scores)]
for i in xrange(len(scores)):
ret[i] = sum(scores[i:i+3]) if scores[i] == 10 else scores[i]
print "Final score", sum(ret)
Yes You can. .
List[index:] represents all of the values that comes After the given index number. .
List[:index] represents all of the values that comes Before the given index number. .
in this Case,
zval = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for val in zval:
if val==7:
`print zval[val:]`
print sum(zval[val:])