The result I'm getting after running the code in powershell is three numbers and then a freeze.
The numbers are
1.09861228867,
1.60943791243,
1.94591014906
#summing up all the logs of the first 10 primes, excluding 2.
from math import * # library imports
import math # " "
count = 1 #1-9 gives us 9 primes in total
numb = 3 #3 is the second prime number.
logy_of_prime_sum_total = 0 #sum of log of primes starts at zero
logy = 0 #first value of log is zero
while count != 10: #loops 9 times, for a total of 9 primes.
for k in range(2,numb): #from 2 up to but not including numb.
if numb%k == 0: #purpose is to skip the else if not prime.
break #break takes us out of the for/else disj.
else:
logy_of_prime_sum_total = logy+logy_of_prime_sum_total
logy = math.log(numb) #when the else activates, we are
print(logy) #dealing with a prime, getting a value
numb += 2 #the log of it, incr. numb. by two,
count += 1 #because primes have to be odd,
#increase the count
print logy_of_prime_sum_total #print the sum of all the logs after the
#while end.
The only issue you have is you are not increasing numb if numb happens to be composite. Just move numb += 2 to the end of the loop and unindent. When numb is composite, e.g. 9 (4th number) you are breaking out of the for loop and never incrementing numb (else on a for loop only executes if you don't break):
while count != 10:
for k in range(2,numb): #from 2 up to but not including prime.
if numb%k == 0:
break
else:
logy_of_prime_sum_total = logy+logy_of_prime_sum_total
logy = math.log(numb)
print(logy)
count += 1
numb += 2
print(logy_of_prime_sum_total)
Output:
1.0986122886681098
1.6094379124341003
1.9459101490553132
2.3978952727983707
2.5649493574615367
2.833213344056216
2.9444389791664403
3.1354942159291497
3.367295829986474
18.529951519569238
BTW: You need to start the count = 0 to get 10 numbers, you will currently only get 9.
I just need ideas on how would i add up the odd positional numbers only. For example, if i had 012345678905, i would only need to add 0, 2,4, 6, 8 etc. What I currently have is basically a module (yet to be completed), and this program is asking me valadiate UPC-12 numbers. Im completly confused, as im not entirely sure what i'm doing. I haven't learned "len" (somthing like that) yet.
# Gets the digit of the number using the specified position
def get_digit(number, position):
return number / (10**position) % 10
def is_UPC12(number):
sum_odd = 0
sum_even = 0
#loops through the UPC code and checks every odd position and adds the numbers
for num in range(1, 13, 2):
sum_odd += get_digit(number, num)
sum_odd *= 3
#loops through the UPC code and checks every even position and adds the numbers
for num in range(2, 13, 2):
sum_of_even += even
sum_even += get_digit(number, num)
Sum = sum_of_odd + sum_of_even_two
#subtracts 10 from the last digit of the sum, and if it's equal to the last digit of number then it returns True.
if 10 - get_digit(Sum , 0) == get_digit(number , 0):
return True
elif 10 - get_digit(Sum , 0) == 10 and get_digit(number , 0) == 0:
return True
else:
return False
Have you considered using the modulus % operator? Ex. x % 2 = 0 is an even number.
One approach (not necessarily the best) is:
# get the number to be tested
test_number = raw_input("Enter number to validate: ")
# set an initial 'sum' value at zero
sum = 0
# iterate through the characters in the input string, only selecting odd position characters
for i in range((len(test_number)+1)/2):
# a test print statement to check that it's working
print test_number[i*2]
# add the value of the character (as int) to 'sum'
# note that this doesn't deal with exceptions
# (if the input is not numeric, it will throw an error)
sum += int(test_number[i*2])
# get the final sum
print "sum: " + str(sum)
EDITED - alternate approach
Another way is:
test_number = raw_input("Enter number to validate: ")
sum = 0
odd_numbers = test_number[::2]
for char in odd_numbers:
sum += int(char)
print "sum: " + str(sum)
where "odd_numbers" is a new string composed of the alternate characters from the original string (using the slice method with a step-size of 2).
I feel like I am constantly having this problem when I am writing a program, what I want to do is iterate over every value in my nested list and say that if it's not a zero, make it one.
Here is the error I am getting:
Traceback (most recent call last):
File "C:\Users\ryry3\Desktop\Python Projects\Games\Pygame Experiment\Sprint2.py", line 65, in <module>
resetBoard()
File "C:\Users\ryry3\Desktop\Python Projects\Games\Pygame Experiment\Sprint2.py", line 49, in resetBoard
if board[i][j] != 0:
IndexError: list index out of range
Here is my full code:
import random
grid = [100,100]
board = [[0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,5,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]]
playerX = None
playerY = None
randX = 0
randY = 0
def getRandomGridPos():
global randX, randY
randX = int(random.uniform(0, grid[0]))
randY = int(random.uniform(0, grid[1]))
def main():
pass
def printBoard():
print str(board[0]).replace(',', '')
print str(board[1]).replace(',', '')
print str(board[2]).replace(',', '')
print str(board[3]).replace(',', '')
print str(board[4]).replace(',', '')
print str(board[5]).replace(',', '')
print str(board[6]).replace(',', '')
print str(board[7]).replace(',', '')
print str(board[8]).replace(',', '')
print str(board[9]).replace(',', '')
def resetBoard():
i = 0
j = 0
while i < 10:
if board[i][j] != 0:
board[i][j] = 0
j += 1
print "Looping"
if j == 10:
j = 0
i += 1
print "J == 10"
if i == 10:
j = 0
i = 0
print "I == 10"
else:
j += 1
resetBoard()
Can someone help me find a solution and also help me not get this error anymore (explain why it happens)?
You've already gotten several pointers to the cause of your error, but I just wanted to point out a clearer pattern to iterate multi-dimensional arrays:
for x in range(0, 10):
for y in range(0, 10):
# you will now have all values for a 10x10 array in x & y
if board[x][y] != 0:
board[x][y] = 0
If you really just want to make sure all board fields (10 x 10) are zeros, the following is even more consice:
# zero out a 10 x 10 multi-dimensional array
board = [[0] * 10] * 10
Your for reset board doesn't work for the following reasons:
"if i == 10" ,i never actually reaches 10, since it is in a while loop which states "while i < 10". The loop would exit before i actually reaches 10
no nested while loop. You need two while loops to reset the board.
When j reaches 10 this line raises an index error: if board[i][j] != 0: , because j equals 10, and the maximum index you can take of a 10 element list is 9(since index starts at 0)
I recommend reading the following
http://introtopython.org/lists_tuples.html
I would add that one of the best ways to achieve what you want in python with loops is:
for row in board: # runs the following once for every item in board
for item in row: # runs the following for every item in row.
# A second for statement is required because
# multidimensional lists are lists of lists.
if(item != 0)
item = 0 #sets items to 0 if the item isn't equal to 0
UPDATE:
Sorry but I also encoutered another problem, my bad for not checking the code:
The final code should be:
while i < 10:
if j == 10:
j = 0
i += 1
print ("J == 10")
elif board[i][j] != 0:
board[i][j] = 0
j += 1
print ("Looping")
else:
j += 1
The problem I missed was that you should have checked the j boundary before trying to access the array, only then you should start the loop again.
The problem is in this part:
if j == 10:
j = 0
i += 1
print "J == 10"
if i == 10:
j = 0
i = 0
if i = 9, j= 10 then we enter into the first if which changes i,j to be 10,10
Then the code continues and we enter the second if, thus reseting i and j making the loop go again and again...
Solve it by deleting the second if part, since the while condition will make sure we will never go to that case in the first place.
import math
def is_prime(num):
if num < 2:
return False
for i in range(2, int(math.sqrt(num))+ 1):
if num % i == 0:
return False
return True
Primes seems to be a popular topic but in the book in which I am learning Python, I am on chpt 6 out of 21 and in the iteration chapter which it teaches while loops. I have not learned for loops yet although I understand what they do. So, let's say I have not learned for loops yet and am given only if/elif/else statements and the while loops as my tools. How can I change the for line of code into something more simple using the above tools? While asking this question I quickly came up with this code:
def formula(num):
i = 2
while i >= 2:
return int(math.sqrt(num)+ 1)
def is_primetwo(num):
i = 2
if num < 2:
return False
formula(num)
if num % i == 0:
return False
return True
It works but would this be a simple version of the for loop or is there something even more simple where I do not have to wrap a function within a function?
Absolutely, you do not need a function to replace a for loop.
So you've got this
for i in range(2, int(math.sqrt(num))+ 1):
which is your for loop. Take a second to think what it's doing.
1.) It's taking the variable i, and it's starting it at a value of 2.
2.) It's checking whether to do the loop every time by checking if i is less than the (square root of num) plus 1
3.) Every time through the loop, it adds one to i.
We can do all of these things using a while loop.
Here's the original
for i in range(2, int(math.sqrt(num))+ 1):
if num % i == 0:
return False
let's rename the second and third lines loop contents just so we're focusing on the looping part, not what logic we're doing with the variables i and num.
for i in range(2, int(math.sqrt(num))+ 1):
loop contents
ok, now let's just rearrange it to be a while loop. We need to set i to 2 first.
i = 2
Now we want to check that i is in the range we want
i = 2
while i <= int(math.sqrt(num) + 1):
loop contents
Now we're almost set, we just need to make i actually change, instead of staying at a value of 2 forever.
i = 2
while i <= int(math.sqrt(num) + 1):
loop contents
i = i + 1
Your example seemed to do some of these elements, but this way is a simple way to do it, and no extra function is necessary. It could be the range() function that is confusing. Just remember, the for loop is doing three things; setting a variable to an initial value, checking a condition (one variable is less than another), and incrementing your variable to be one large than previously to run the loop again.
How about something like:
from math import sqrt
def is_prime(num):
if (num < 2):
return False
i = 2
limit = int(sqrt(num) + 1)
while (i <= limit):
if num % i == 0:
return False
i = i + 1
return True
Not sure if this is what you want, but the for loop:
for i in range(2, int(math.sqrt(num))+ 1):
if num % i == 0:
return False
return True
can be expressed as:
i = 2
while i < int(math.sqrt(num))+ 1):
if num % i == 0:
return False
i += 1
return True
Probably a good idea to determine int(math.sqrt(num))+ 1) once:
i = 2
n = int(math.sqrt(num))+ 1)
while i < n:
if num % i == 0:
return False
i += 1
return True
I keep getting this error:
line 4, in timesTwo
IndexError: list index out of range
for this program:
def timesTwo(myList):
counter = 0
while (counter <= len(myList)):
if myList[counter] > 0:
myList[counter] = myList[counter]*2
counter = counter + 1
elif (myList[counter] < 0):
myList[counter] = myList[counter]*2
counter = counter + 1
else:
myList[counter] = "zero"
return myList
I'm not exactly sure how to fix the error. Any ideas?
You are setting the upper-bound of the while loop to the length of myList, which means that the final value of counter will be the length. Since lists are indexed starting at 0, this will cause an error. You can fix it by removing the = sign:
while (counter < len(myList)):
Alternatively, you could do this in a for loop that may be a bit easier to handle (not sure if this fits your use case, so the above should work if not):
def timesTwo(myList):
for index, value in enumerate(myList):
if value is not 0:
myList[index] *= 2
else:
myList[index] = 'zero'
return myList