Printing total using for loop - python-3.x

I am trying to get the total of 1,2,3,4 which I am able to achieve through code 1 but not code 2. Could someone please point out why is code 2 returning 4 and not 10?
CODE 1:
total = 0
for i in range(1,5):
total = total + i
print(total)
10
CODE 2:
total = 0
for i in range(1,5):
newtotal = total + i
print(newtotal)
4

This is because in code2 total is not updating ,it always is zero because you initialised it to 0 so every time in for loop i gets updated like
newtotal = 0+1 = 1
next time
newtotal = 0+2 = 2
nex time
newtotal = 0+3 = 3
nex time
newtotal = 0+4 = 4
But in code 1 you are updating the value of total everytime with the statement
total = total + i
first time
total = 0+1 = 1
//now total is 1
next time
total = 1+2 = 3
next time
total = 3+3 = 6
next time
total = 6+4 = 10
Hence the answer 10

Because in CODE 2, in each iteration total is 0.
total = 0
newtotal = 0
for i in range(1,5):
total = newtotal
newtotal = total + i
print(newtotal)
Now here we are updating the value of total

Related

Using list instead of dictionary for organized results

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

How to Vectorise index insertion in Python?

I have this problem with a very large data set which I can finished in Excel in less than a minute but it takes way too long on Python.
Objective: To give each row an ID based on information in column X and Y of the data set.
In Excel:
Initialize counter to 1
For each row i:
If both X = 0 and Y = 0, row ID = counter, followed by counter += 1
[edited] Else row ID = ID in the previous row.
Next i
My pd dataframe is large. Doing it in for loop takes more than an hour. I don't know how to vectorise my problem to avoid a for loop.
Hope someone can help me.
To find an efficient Pandas solution, you should rephrase your problem. Your counter is essentially the number of the previous all-zero rows (plus 1):
df = pd.DataFrame({'X': [0,2,1,0,0,1,2,0],
'Y': [0,2,1,3,0,0,1,2]})
df['counter'] = (((df.X==0) & (df.Y==0)).cumsum().shift() + 1)\
.fillna(1).astype(int)
# X Y counter
#0 0 0 1
#1 2 2 2
#2 1 1 2
#3 0 3 2
#4 0 0 2
#5 1 0 3
#6 2 1 3
#7 0 2 3

Return values based on the sum of array indeces

I would like to return all values in an array where the row number plus the column number is a multiple of 5.
I feel like I'm close, but I can't seem to get the (i + j) % 5 == 0 part working as a condition.
using:
(i + j) % 5 == 0
I have constructed a random 8 x 9 array using:
arr2 = np.random.normal(size = (8,9), loc=1, scale=0.5)
a = np.empty([100,100])
for i in range(0,len(a)):
for j in range(0,len(a[0])):
if (i+j)%5 == 0:
print(i,j,i+j a[i][j])
output
0 0 0 0.0
0 5 5 0.0
0 10 10 0.0
0 15 15 0.0
0 20 20 0.0
.
.
.
I don't know what you did wrong you have the correct logic. Its a simple loop where you use the index itself as a test rather than than contents at that index.
Awesome thanks. I actually tweaked this a little to get the mean of all values that meet this criteria:
def arrmean5 (arr):
total = 0
count = 0
for i in range(0,len(arr)):
for j in range(0,len(arr[0])):
if (i+j) % 5 == 0:
total = total + (arr[i][j])
count += 1
return(total/count)
I appreciate the help Sam!

How can I avoid duplicate digit in the cicle result

The result of the code includes separetly "min" and "max" values. Can't get how I can print only result of cicle?
For examle, whan I set min = 1, max = 3 the result is:
1
3
1
2
3
And I need 1 2 3 without first 1 3.
min = int(input())
max = int(input())
while min <= max:
print(min)
min = min + 1
That depends entirely on the ide or python environment you are using. May I know which environment you are using?
Because when I ran here https://ideone.com/lUmjKL everything seems fine.
min = int(input())
max = int(input())
while min <= max:
print(min)
min = min + 1
Let me know.

How to use nested while loops

I'm trying to make a function that uses a nested while loop that prints something like this.
ranges(5,2)
5
0 1 2 3 4
4
0 1 2 3
3
0 1 2
2
0 1
my code that i have so far looks like this
def ranges(high,low):
while high >= low:
print(high)
high = high - 1
y = 0
x = high
while x > y:
print (y, end = " ")
y = y + 1
The output is like this
5
0 1 2 3 4
0 1 2 3
0 1 2
0
I'm pretty sure I missed up in calling the nested while loop because when i split up the code to just print 5,...,2 in a column it works and so does the code for printing the numbers in a row. Any help would be cool
Add print("") right after the while loop, and modify the condition of the while loop to >=:
def ranges(high,low):
while high >= low: # <-- change the condition otherwise you'll miss the last number in every line
print(high)
high = high - 1
y = 0
x = high
while x >= y:
print (y, end = " ")
y = y + 1
print("") # <-- this
ranges(5, 2)
OUTPUT
5
0 1 2 3 4
4
0 1 2 3
3
0 1 2
2
0 1

Resources