Using list instead of dictionary for organized results - python-3.x

I'm trying to get my code below working to have the results organized rather than random.
This is what's happening now.
sum = 9 count = 117
sum = 6 count = 142
sum = 3 count = 58
sum = 7 count = 172
sum = 8 count = 129
sum = 5 count = 109
sum = 4 count = 87
sum = 11 count = 53
sum = 12 count = 31
sum = 10 count = 72
And what I'm trying to achieve is
sum = 1 count = 117
sum = 2 count = 142
sum = 3 count = 58
sum = 4 count = 172
sum = 5 count = 129
sum = 6 count = 109
sum = 7 count = 87
sum = 8 count = 53
sum = 12 count = 31
etc. While omitting any number that hasn't been rolled.
I'd ideally like to use a list instead of a dictionary but any time I try it I get varying errors.
Currently this outputs the amount but not in order.
import random
print("results")
occurrences = []
for i in range(1000):
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
roll = die1 + die2
current = occurrences[roll, ]
occurrences[roll] = current + 1
for roll, count in occurrences[]
print(f"sum = {roll} count = {count}")

A recipe for dictionary-based roll occurrence counting would be:
First initialize all roll possibilities within a dictionary (the example below makes use of dictionary comprehension) where the dict keys are the roll value and the dict values are the corresponding occurence.
Count each time a roll happens with the +=1 statement (in-place add up 1).
Sort the dictionary with another dictionary comprehension operated on the sorted dictionary values (here, the occurrence of each roll).
Loop over the dictionary keys (rolls) and corresponding values (occurrences) in order to show the output.
Here is your code with the above statements included:
import random
print("results")
occurrences = {k: 0 for k in range(2, 13)}
for i in range(10000):
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
roll = die1 + die2
occurrences[roll] += 1
occurrences = {k: v for k, v in sorted(occurrences.items(), key=lambda item: item[1], reverse=True)}
for roll, count in occurrences.items():
print(f"sum = {roll} count = {count}")
which outputs the following result with 10,000 rolls:
sum = 7 count = 1653
sum = 6 count = 1398
sum = 8 count = 1325
sum = 5 count = 1162
sum = 9 count = 1142
sum = 10 count = 842
sum = 4 count = 812
sum = 11 count = 578
sum = 3 count = 540
sum = 2 count = 295
sum = 12 count = 253

Related

Printing 6 first numbers from -20 to 20 using while loop

How can I print numerical interval from -20 to 20 using loop "while" and then print 6 first elements
I tried this to print numbers from -20 to 20 but still don't know how to print first six numbers.
x = -21
while x < 20:
x = x + 1
print(x)
Assign count = 6, decrease count after increasing and printing x, then use break if count is 0 or False:
x = -21
count = 6
while x < 20:
if not count: break
x += 1
count -= 1
print(x)
If you don't want to use if and break:
x = -21
count = 6
while x < 20 and count:
x += 1
count -= 1
print(x)
Or using count = 0 and increase it until 6:
x = -21
count = 0
while x < 20 and count < 6:
x += 1
count += 1
print(x)

Why do I get duplicate output when using a for loop over a list?

Hello I have problem looping when printing data in a list.
def inputScore(scor) :
for i in range(len(scor)) :
scor[i] = int(input("Enter Score Number : "))
def Display(scr) :
for i in scr:
if i >= 86 and i <= 100 :
x = "A"
elif i >= 70 and i < 86 :
x = "B"
elif i >= 60 and i < 70 :
x = "C"
elif i >= 50 and i < 60 :
x = "D"
elif i >= 0 and i < 50 :
x = "E"
else :
print("Invalid Score")
for i in range(0,3) : # If I remove this code "for..", it will error "IndexError: list index out of range"
print("Score Number",scr[i],"Letter Grades", x)
def main () :
scor = [int]*3
inputScore(scor)
Display(scor)
main()
Example:
# Input :
85
60
40
# Output that I want :
Score Number 85 Letter Grades A
Score Number 60 Letter Grades C
Score Number 40 Letter Grades E
# Output that I got :
Score Number 85 Letter Grades A
Score Number 60 Letter Grades A
Score Number 40 Letter Grades A
Score Number 85 Letter Grades C
Score Number 60 Letter Grades C
Score Number 40 Letter Grades C
Score Number 85 Letter Grades E
Score Number 60 Letter Grades E
Score Number 40 Letter Grades E
There are 3 looping for Letter Grades (A = 3 times, C = 3 times and E = 3 times), I tried to give for i in range(0,3) for stop looping but it doesn't work, Letter Grades always prints 9 times with 3 A, 3 C, and 3 E. How to solve it and make it output like in the example above?
The inner for loop is unnecessary. The outer for loop already iterates through the scores. In each iteration, i is a score, not an index -- to get an index, you use range. Therefore, there's no need to index the scr list at all -- you would print i itself rather than scr[i].
Also, with the current code, the grade for 85 would be B rather than A. Perhaps you need to adjust the bounds for the A and B grades.
Another issue is that for an invalid score, it would still attempt the final print. This would fail if an invalid score occurred as the first score (since x wouldn't be defined). If an invalid score occurred as a subsequent score, the print would show you the grade for the previous score, which you don't want. You can get around this by setting x to be the empty string at the start of each iteration and checking if it has a non-empty value before doing the final print of the grade.
The following code resolves the issues discussed:
def inputScore(scor):
for i in range(len(scor)):
scor[i] = int(input("Enter Score Number: "))
def display(scr):
for i in scr:
x = ""
if i >= 85 and i <= 100:
x = "A"
elif i >= 70 and i < 85:
x = "B"
elif i >= 60 and i < 70:
x = "C"
elif i >= 50 and i < 60:
x = "D"
elif i >= 0 and i < 50:
x = "E"
else:
print("Invalid Score")
if x:
print("Score Number:", i, "Letter Grade:", x)
def main():
scor = [int] * 3
inputScore(scor)
display(scor)
main()

Finding unique triangles given in n number of triangles in python

Given n-number of triangles, we are required to find how many triangles are unique out of given triangles. For each triangle we are given three integers a, b and c (the sides of a triangle).
A triangle is said to be unique if there is no other triangle with same set of sides.
Sample Input:
7 6 5
5 7 6
8 2 9
2 3 4
2 4 3
Sample Output:
1
Explanation:
Each line is a triangle with 3 sides given. The first two triangles are identical since they have similar sides (just the orders are different). ie. the sum of all the sides for both triangles are equal.
The third triangle '8 2 9' is unique since no other triangle has the exact similar sides. So the output is 1 (total number of unique triangles)
Sample Input:
34 5 32
15 20 6
4 2 3
5 6 9
15 20 6
34 5 32
Sample Output:
2
Here the triangles '423' and '560' are unique. So the output is 2 (total number of unique triangles)
This is what I did...
n = int(input())
arr = [list(map(int, input().split())) for x in range(n)]
def uniqueTriangle(arr):
row = len(arr)
col = len(arr[0])
mp = {}
hel = {}
for i in range(row):
tri = arr[i]
tri.sort()
strA = [str(x) for x in tri]
strB = ''
strB = strB.join(strA)
if strB not in mp.values():
mo[i] = strB
else:
hell[i] = strB
count = 0
for i in range(row):
if i in mp:
val = mp.get(i)
if val not in hel.values():
count = count + 1
print (count)
Apologize for the ugly code. But how can I make this code better?
from collections import Counter
arr = [[7, 6, 5],[5, 7, 6],[8, 2, 9],[2, 3, 4],[2, 4, 3]]
def unique_triangles(arr):
counter = Counter([frozenset(a) for a in arr])
return len([res for res in counter if counter[res] == 1])
Use frozenset to mark each unique set of triangle
use collections.Counter to count the number of unique sets found in the input array
return the set appeared only once
This is what I did :
n = int(input())
l=[]
for i in range(n):
t = [int(side) for side in input().split()]
l.append(set(t))
ans=[]
for j in l:
count=0
for i in l:
if i==j:
count+=1
if count==1:
ans.append(j)
print(len(ans))

How do I get my python function to properly apply an IF-ELIF-ELSE statements correctly to all rows in my pandas dataframe?

I am trying to calculate the CGPA of a number of students. The idea here is that each student takes N courses (in this case, N = 3). Every course has its course load which is an integer and can range from 1 to 6. At the end of the semester, the CGPA is calculated based on the unit load of all the courses taken by each student and the grades obtained.
I am trying to do this using a for statement to loop through the entire dataset a row at a time and then an if suite to determine the number of units to assign to each student according to the grade scored. The problem here is that the code works but it doesn't follow through. So if the first student in the dataframe had an A in course1, the code gives him 15units and all other students also get 15units irregardless of if they score a D or an F.
I really want to know what I am doing wrong and how I can fix it. I would also appreciate it if you can suggest smarter ways of accomplishing this task. Thanks.
I have added breaks in the first course section but I am afraid the code is still not generalizing well.
A = 5; B = 4; C = 3; D = 2; E = 1; F = 0;
course1_cl = 3; course2_cl = 3; course3_cl = 3
def calculate_CGPA(dataframe, a, b, c, d):
for row in dataframe[d]:
if dataframe[a].any()=='A':
dataframe['units'] = A * course1_cl
break
elif dataframe[a].any()=='B':
dataframe['units'] = B * course1_cl
break
elif dataframe[a].any()=='C':
dataframe['units'] = C * course1_cl
break
elif dataframe[a].any()=='D':
dataframe['units'] = D * course1_cl
break
elif dataframe[a].any()=='E':
dataframe[units] = E * course1_cl
else:
dataframe[units]= 0
print("Done generating units for: "+ format(a))
for row in dataframe[d]:
if dataframe[b].any()=='A':
dataframe['units2']=A * course2_cl
elif dataframe[b].any()=='B':
dataframe['units2'] = B*course2_cl
elif dataframe[b].any()=='C':
dataframe['units2'] = C*course2_cl
elif dataframe[b].any()=='D':
dataframe['units2'] = D*course2_cl
elif dataframe[b].any()=='E':
dataframe['units2'] = E*course2_cl
else:
dataframe['units2'] = 0
print("Done generating units for: "+format(b))
for row in dataframe[d]:
if dataframe[c].any()=='A':
dataframe['units3']= A * course3_cl
elif dataframe[c].any()=='B':
dataframe['units3'] = B*course3_cl
elif dataframe[c].any()=='C':
dataframe['units3'] = C*course3_cl
elif dataframe[c].any()=='D':
dataframe['units3'] = D*course3_cl
elif dataframe[c].any()=='E':
dataframe['units3'] = E*course3_cl
else:
dataframe['units3'] = 0
print("Done generating units for: "+format(c))
df['CGPA'] = (dataframe['units'] + dataframe['units2'] + dataframe['units3'])/(course1_cl + course2_cl + course3_cl)
The resulting dataframe should have 4 newly added columns: One units column for each of the three courses and a CGPA column as seen below. The values in the units and CGPA columns should change dynamically based on the grades scored by the individual.
S/N,Name,ExamNo,Course1,Course2,Course3,Units,Units2,Units3,CGPA
1,Mary Beth,A1,A,A,B,15,15,12,4.67
2,Elizabeth Fowler,A2,B,A,A,12,15,15,4.67
3,Bright Thompson,A12,C,C,B,9,9,12,3.33
4,Jack Daniels,A24,C,E,C,9,3,9,2.33
5,Ciroc Brute,A31,A,B,C,15,12,9,4.0
I do not know how complicated you actual data is but for your sample data you do not need the if statements:
from io import StringIO
# sample data
s = """S/N,Name,ExamNo,Course1,Course2,Course3
1,Mary Beth,A1,A,A,B
2,Elizabeth Fowler,A2,B,A,A
3,Bright Thompson,A12,C,C,B
4,Jack Daniels,A24,C,E,C
5,Ciroc Brute,A31,A,B,C"""
df = pd.read_csv(StringIO(s))
# create a dict
d = {'A':5, 'B':4, 'C':3, 'D':2, 'E':1, 'F':0}
# replace the letter grade with number and assign it to units cols
df[['Units', 'Units2', 'Units3']] = df[['Course1','Course2','Course3']].replace(d) * 3
# calc CGPA with sum div 3
df['CGPA'] = df[['Course1','Course2','Course3']].replace(d).sum(1) / 3
S/N Name ExamNo Course1 Course2 Course3 Units Units2 Units3 \
0 1 Mary Beth A1 A A B 15 15 12
1 2 Elizabeth Fowler A2 B A A 12 15 15
2 3 Bright Thompson A12 C C B 9 9 12
3 4 Jack Daniels A24 C E C 9 3 9
4 5 Ciroc Brute A31 A B C 15 12 9
CGPA
0 4.666667
1 4.666667
2 3.333333
3 2.333333
4 4.000000

Python3 numpy array

I have a data file containing random values(without equal spacing) ranging between -5.07 to +6.01(390 values in total). I have to seperate these values according to some conditions like;
-5 to -4 as A
-4 to -3 as B etc.,
and finally add how many A/B/C... are present in total.
The codes are given below. On execution they are printing 'A' 390 times as output. Where is the error?
file = "86M"
v = np.loadtxt(file, delimiter = "\n")
A = B = C = 0
i = 0
while i < len(v):
if -5 < v[i] >= -4:
A = A+1
print (A)
i += 1

Resources